mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
Resilience sits behind Oura's `stress` scope, not `heart_health`, so a
connection that granted every scope HealthLog asked for still answered 401
on `daily_resilience`. `src/lib/oura/scope.ts` now maps every collection the
sync reads to the scope the live API enforces and is the one source for the
authorize request, the per-collection permission detection, the reconnect
hint and the settings card. The request asks for `stress` as well.
Oura names a missing scope in its 401 body ("Token is not authorized access
stress scope."), while a dead token reads differently. A collection refusal
now carries that scope: it spends no token refresh, never counts toward the
reconnect threshold and marks only the collections it names. A 403 (a lapsed
membership) is a persistent failure rather than a reconnect. The callback
also records what the token response says was granted, so an unticked
permission shows on the card before the first sync.
A browser can deliver an OAuth callback twice with the same code. Both
requests exchanged it, and Oura answers a reused code by revoking the token
the first exchange issued. Every connect callback (Oura, Polar, Strava,
WHOOP, Withings, Fitbit, Google Health) now claims its state in
`oauth_callback_claims` before the exchange: one request exchanges, the
duplicate waits for it and redirects to the same page without touching any
token. The ledger flows claim inside the transaction that consumes their
state row. A failed exchange settles with its error page, and a new connect
mints a new state.
Oura token refreshes are serialised per user with an advisory lock, so
overlapping syncs no longer spend the same single-use refresh token, and the
write stays conditional so a reconnect's new grant is never overwritten by a
refresh of the old one.
130 lines
4.2 KiB
TypeScript
130 lines
4.2 KiB
TypeScript
/**
|
|
* S-1 — the Strava OAuth callback enqueues the self-converging history backfill
|
|
* at connect time (mirroring the WHOOP / Fitbit callbacks) so deep history
|
|
* lands within the hour instead of waiting for the next worker reboot. A missing
|
|
* boss instance is a warning, never a failure — boot discovery is the net.
|
|
*/
|
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
|
import { NextRequest } from "next/server";
|
|
|
|
const {
|
|
bossSend,
|
|
getGlobalBossMock,
|
|
exchangeCodeMock,
|
|
getCredsMock,
|
|
userFindUnique,
|
|
userUpdate,
|
|
markReconnectedMock,
|
|
} = vi.hoisted(() => ({
|
|
bossSend: vi.fn(async () => "job-id"),
|
|
getGlobalBossMock: vi.fn(),
|
|
exchangeCodeMock: vi.fn(),
|
|
getCredsMock: vi.fn(),
|
|
userFindUnique: vi.fn(),
|
|
userUpdate: vi.fn(async () => ({})),
|
|
markReconnectedMock: vi.fn(async () => {}),
|
|
}));
|
|
|
|
// Single-use claiming is covered against Postgres in
|
|
// tests/integration/oauth-callback-single-use.test.ts; here every callback
|
|
// is the first and only one.
|
|
vi.mock("@/lib/oauth/callback-claim", () => ({
|
|
runOAuthCallbackOnce: (
|
|
_p: string,
|
|
_s: string,
|
|
_o: unknown,
|
|
run: () => Promise<unknown>,
|
|
) => run(),
|
|
settleOAuthCallback: (_p: string, _s: string, run: () => Promise<unknown>) =>
|
|
run(),
|
|
consumeLedgerState: async (
|
|
_p: string,
|
|
_s: string,
|
|
consume: (tx: unknown) => Promise<unknown>,
|
|
) => consume((await import("@/lib/db")).prisma),
|
|
duplicateOAuthCallback: async () => null,
|
|
}));
|
|
|
|
vi.mock("@/lib/api-handler", () => ({
|
|
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
|
}));
|
|
vi.mock("@/lib/db", () => ({
|
|
prisma: { user: { findUnique: userFindUnique, update: userUpdate } },
|
|
}));
|
|
vi.mock("@/lib/auth/session", () => ({ getSession: vi.fn(async () => null) }));
|
|
vi.mock("@/lib/logging/context", () => ({
|
|
annotate: vi.fn(),
|
|
getEvent: () => ({
|
|
setAuth: vi.fn(),
|
|
setError: vi.fn(),
|
|
addWarning: vi.fn(),
|
|
}),
|
|
}));
|
|
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn(async () => {}) }));
|
|
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc(${s})` }));
|
|
vi.mock("@/lib/strava/client", () => ({ exchangeCode: exchangeCodeMock }));
|
|
vi.mock("@/lib/strava/credentials", () => ({
|
|
getStravaClientCredentials: getCredsMock,
|
|
}));
|
|
vi.mock("@/lib/oauth/signed-state", () => ({
|
|
oauthStateCookieName: () => "strava_oauth_state",
|
|
stateMatchesCookie: () => true,
|
|
verifySignedState: () => ({ userId: "u1" }),
|
|
}));
|
|
vi.mock("@/lib/integrations/status", () => ({
|
|
markReconnected: markReconnectedMock,
|
|
}));
|
|
vi.mock("@/lib/jobs/strava-backfill", () => ({
|
|
STRAVA_BACKFILL_QUEUE: "strava-backfill",
|
|
}));
|
|
vi.mock("@/lib/jobs/boss-instance", () => ({
|
|
getGlobalBoss: getGlobalBossMock,
|
|
}));
|
|
|
|
import { GET } from "../route";
|
|
|
|
process.env.NEXT_PUBLIC_APP_URL = "https://app.example";
|
|
|
|
function callback(): Promise<{ headers: { get(k: string): string | null } }> {
|
|
const req = new NextRequest(
|
|
"http://localhost/api/strava/callback?code=abc&state=signed-state",
|
|
{ headers: { cookie: "strava_oauth_state=signed-state" } },
|
|
);
|
|
return (GET as unknown as (r: NextRequest) => Promise<never>)(req);
|
|
}
|
|
|
|
beforeEach(() => {
|
|
vi.clearAllMocks();
|
|
getCredsMock.mockResolvedValue({ clientId: "c", clientSecret: "s" });
|
|
exchangeCodeMock.mockResolvedValue({
|
|
access_token: "at",
|
|
refresh_token: "rt",
|
|
athlete: { id: 42 },
|
|
});
|
|
userFindUnique.mockResolvedValue({ stravaAthleteId: null });
|
|
getGlobalBossMock.mockReturnValue({ send: bossSend });
|
|
});
|
|
|
|
describe("GET /api/strava/callback — S-1 backfill enqueue", () => {
|
|
it("enqueues one STRAVA_BACKFILL_QUEUE job for the connecting user", async () => {
|
|
const res = await callback();
|
|
|
|
expect(res.headers.get("location")).toContain("strava=connected");
|
|
expect(markReconnectedMock).toHaveBeenCalledWith("u1", "strava");
|
|
expect(bossSend).toHaveBeenCalledTimes(1);
|
|
expect(bossSend).toHaveBeenCalledWith(
|
|
"strava-backfill",
|
|
expect.objectContaining({ userId: "u1" }),
|
|
);
|
|
});
|
|
|
|
it("still connects when the boss instance is unavailable (warning, not failure)", async () => {
|
|
getGlobalBossMock.mockReturnValue(null);
|
|
|
|
const res = await callback();
|
|
|
|
expect(res.headers.get("location")).toContain("strava=connected");
|
|
expect(bossSend).not.toHaveBeenCalled();
|
|
});
|
|
});
|