mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-19 00:12:18 +00:00
feat(whoop): native-scheme connect redirect and Bearer connect ticket
Two connect-in-app enhancements for the native client. return_scheme: GET /api/whoop/connect accepts an optional custom scheme, threaded through the server-side OAuth-state row so it survives the round trip without ever riding in the URL or cookie. When a valid scheme is present, the callback's final redirect targets <scheme>://whoop?whoop= connected|error&reason=... so an in-app web session auto-completes on its custom-scheme match; absent or invalid, the web settings redirect is unchanged. Schemes validate against a strict allowlist (custom app scheme only, ^[a-z][a-z0-9.+-]*$, http/https/javascript/data/file/vbscript rejected, pinned to dev.healthlog.app). A rejected scheme falls back to the web redirect and never reflects an arbitrary value. Bearer connect ticket: a purely Bearer-authenticated client holds no web session cookie, so it cannot start the handshake through the cookie-gated connect route. POST /api/whoop/connect/ticket (Bearer) mints a one-time, ~60s, opaque ticket bound to the user; only its HMAC-SHA256 hash is stored (the raw value never persists). GET /api/whoop/connect?ticket=<opaque> accepts the ticket in lieu of a cookie, consumes it atomically (single-use, reuse rejected), sets the nonce cookie, and 302s to WHOOP exactly as the cookie path. Expired, consumed, or invalid tickets return a typed 401. The two combine. The daily WHOOP OAuth-state cleanup also sweeps expired ticket rows. The ticket query param is added to the egress redaction denylist so the opaque value never reaches logs or error reports. Migration 0124 adds whoop_connect_tickets (id, user_id FK cascade, token_hash unique, expires_at, consumed_at, created_at) and a nullable return_scheme column on whoop_oauth_states. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> (cherry picked from commit 221b362011d52dda314139e0be7cc195c47d016e)
This commit is contained in:
1 parent
540abebf09
commit
1a478d3028
17 files changed
+1239
-44
No files matched your search
@@ -0,0 +1,128 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: {
|
||||
whoopOAuthState: { delete: vi.fn() },
|
||||
whoopConnection: { upsert: vi.fn() },
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/session", () => ({
|
||||
// Native ticket path → no web session present.
|
||||
getSession: vi.fn(async () => null),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: () => ({
|
||||
setError: vi.fn(),
|
||||
addWarning: vi.fn(),
|
||||
setAuth: vi.fn(),
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/audit", () => ({ auditLog: vi.fn() }));
|
||||
vi.mock("@/lib/crypto", () => ({ encrypt: (s: string) => `enc:${s}` }));
|
||||
|
||||
vi.mock("@/lib/whoop/client", () => ({
|
||||
WHOOP_OAUTH_SCOPE: "read:recovery",
|
||||
exchangeCode: vi.fn(async () => ({
|
||||
access_token: "at",
|
||||
refresh_token: "rt",
|
||||
expires_in: 3600,
|
||||
scope: "read:recovery",
|
||||
})),
|
||||
fetchProfile: vi.fn(async () => ({ user_id: 42 })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/whoop/credentials", () => ({
|
||||
getUserWhoopCredentials: vi.fn(async () => ({
|
||||
clientId: "cid",
|
||||
clientSecret: "secret",
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/jobs/whoop-backfill", () => ({ WHOOP_BACKFILL_QUEUE: "q" }));
|
||||
vi.mock("@/lib/jobs/boss-instance", () => ({ getGlobalBoss: () => null }));
|
||||
vi.mock("@/lib/integrations/status", () => ({ markReconnected: vi.fn() }));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
const stateDelete = prisma.whoopOAuthState.delete as ReturnType<typeof vi.fn>;
|
||||
const connUpsert = prisma.whoopConnection.upsert as ReturnType<typeof vi.fn>;
|
||||
|
||||
process.env.NEXT_PUBLIC_APP_URL = "https://app.example";
|
||||
|
||||
function makeReq(nonce: string): NextRequest {
|
||||
return {
|
||||
url: `https://app.example/api/whoop/callback?code=auth-code&state=${nonce}`,
|
||||
cookies: { get: (name: string) => (name === "whoop_state" ? { value: nonce } : undefined) },
|
||||
} as unknown as NextRequest;
|
||||
}
|
||||
|
||||
describe("GET /api/whoop/callback custom-scheme redirect", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
connUpsert.mockResolvedValue({});
|
||||
});
|
||||
|
||||
it("redirects to the native custom scheme on success when returnScheme is set", async () => {
|
||||
stateDelete.mockResolvedValue({
|
||||
userId: "ticket-user",
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
returnScheme: "dev.healthlog.app",
|
||||
});
|
||||
|
||||
const res = await GET(makeReq("nonce-abc"));
|
||||
expect(res.headers.get("location")).toBe(
|
||||
"dev.healthlog.app://whoop?whoop=connected",
|
||||
);
|
||||
expect(connUpsert).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("uses the web redirect on success when no returnScheme", async () => {
|
||||
stateDelete.mockResolvedValue({
|
||||
userId: "u1",
|
||||
expiresAt: new Date(Date.now() + 60_000),
|
||||
returnScheme: null,
|
||||
});
|
||||
|
||||
const res = await GET(makeReq("nonce-web"));
|
||||
expect(res.headers.get("location")).toBe(
|
||||
"https://app.example/settings/integrations?whoop=connected",
|
||||
);
|
||||
});
|
||||
|
||||
it("routes an error to the native scheme when returnScheme is set (expired row)", async () => {
|
||||
stateDelete.mockResolvedValue({
|
||||
userId: "u1",
|
||||
expiresAt: new Date(Date.now() - 1000),
|
||||
returnScheme: "dev.healthlog.app",
|
||||
});
|
||||
|
||||
const res = await GET(makeReq("nonce-exp"));
|
||||
expect(res.headers.get("location")).toBe(
|
||||
"dev.healthlog.app://whoop?whoop=error&reason=expired",
|
||||
);
|
||||
expect(connUpsert).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("pre-resolution CSRF rejection always uses the web redirect", async () => {
|
||||
// Cookie/url state mismatch → csrf1, no row consumed.
|
||||
const req = {
|
||||
url: "https://app.example/api/whoop/callback?code=c&state=URLSTATE",
|
||||
cookies: { get: () => ({ value: "DIFFERENT" }) },
|
||||
} as unknown as NextRequest;
|
||||
const res = await GET(req);
|
||||
expect(res.headers.get("location")).toBe(
|
||||
"https://app.example/settings/integrations?whoop=error&reason=csrf1",
|
||||
);
|
||||
expect(stateDelete).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,6 @@
|
||||
import { prisma } from "@/lib/db";
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiHandler } from "@/lib/api-handler";
|
||||
import { getSession } from "@/lib/auth/session";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { auditLog } from "@/lib/auth/audit";
|
||||
import { encrypt } from "@/lib/crypto";
|
||||
@@ -10,6 +11,7 @@ import {
|
||||
} from "@/lib/whoop/client";
|
||||
import { getUserWhoopCredentials } from "@/lib/whoop/credentials";
|
||||
import { WHOOP_OAUTH_STATE_COOKIE } from "@/lib/whoop/oauth-state";
|
||||
import { buildReturnSchemeRedirect } from "@/lib/whoop/return-scheme";
|
||||
import { WHOOP_BACKFILL_QUEUE } from "@/lib/jobs/whoop-backfill";
|
||||
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
|
||||
import { markReconnected } from "@/lib/integrations/status";
|
||||
@@ -18,23 +20,40 @@ import { NextRequest, NextResponse } from "next/server";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
|
||||
/**
|
||||
* OAuth callback from WHOOP (v1.11.0). Mirrors the Withings callback: the
|
||||
* `state` param is a random base64url nonce keyed against the
|
||||
* `WhoopOAuthState` ledger. The in-flight user is resolved via the row's
|
||||
* `userId` (never parsed from the cookie value) and cross-checked against the
|
||||
* session. The row is consumed (deleted) atomically on every exit branch so a
|
||||
* replay of the same nonce fails the second time.
|
||||
* OAuth callback from WHOOP (v1.11.0; native enhancements v1.12.2). Mirrors the
|
||||
* Withings callback: the `state` param is a random base64url nonce keyed
|
||||
* against the `WhoopOAuthState` ledger. The in-flight user is resolved via the
|
||||
* row's `userId` (never parsed from the cookie value) — this is the
|
||||
* authoritative identity, bound at connect time from either the session or the
|
||||
* one-time Bearer connect ticket. The row is consumed (deleted) atomically on
|
||||
* every exit branch so a replay of the same nonce fails the second time.
|
||||
*
|
||||
* Reason tags distinguish the four post-delete branches for the audit trail:
|
||||
* Auth model. The state row's `userId` is the source of truth. When a web
|
||||
* session cookie is ALSO present (the browser/web-login path) we additionally
|
||||
* cross-check it matches the row, so a logged-in user can't complete another
|
||||
* user's in-flight handshake. The cookie is OPTIONAL: the native ticket path
|
||||
* (v1.12.2) carries no web session, and the nonce-cookie CSRF check + atomic
|
||||
* single-use delete already pin the row to the caller who started the flow.
|
||||
*
|
||||
* Reason tags distinguish the post-delete branches for the audit trail:
|
||||
* `csrf1` (URL/cookie mismatch, short-circuit before delete), `replay`
|
||||
* (P2025 — nonce already consumed), `expired` (valid row, TTL elapsed), and
|
||||
* `cross_user` (valid row, session userId mismatch).
|
||||
*
|
||||
* v1.12.2 — when the state row carries a validated `returnScheme` (set by the
|
||||
* connect route from a native `?return_scheme=`), the FINAL redirect targets
|
||||
* `<scheme>://whoop?whoop=connected|error&reason=…` instead of the web settings
|
||||
* URL, so `ASWebAuthenticationSession` auto-completes on its custom-scheme
|
||||
* match. The pre-resolution CSRF rejections (`csrf1`/`replay`/`state`) have no
|
||||
* row yet, so they always use the web redirect.
|
||||
*
|
||||
* On success: exchange the code, fetch the WHOOP profile for `whoopUserId`,
|
||||
* persist the encrypted `WhoopConnection`, clear any prior reauth state, and
|
||||
* enqueue the self-converging history backfill.
|
||||
*/
|
||||
const ERR = (reason: string) =>
|
||||
|
||||
/** Web-URL redirect (default + every pre-row-resolution path). */
|
||||
const WEB_ERR = (reason: string) =>
|
||||
NextResponse.redirect(
|
||||
new URL(
|
||||
`/settings/integrations?whoop=error&reason=${reason}`,
|
||||
@@ -42,8 +61,31 @@ const ERR = (reason: string) =>
|
||||
),
|
||||
);
|
||||
|
||||
/**
|
||||
* Outcome redirect honouring an optional validated native return scheme.
|
||||
* `scheme` null → web URL (unchanged behaviour).
|
||||
*/
|
||||
const outcomeRedirect = (
|
||||
scheme: string | null,
|
||||
outcome: "connected" | "error",
|
||||
reason?: string,
|
||||
) => {
|
||||
if (scheme) {
|
||||
return NextResponse.redirect(
|
||||
buildReturnSchemeRedirect(scheme, outcome, reason),
|
||||
);
|
||||
}
|
||||
return outcome === "error"
|
||||
? WEB_ERR(reason ?? "unknown")
|
||||
: NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings/integrations?whoop=connected",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
};
|
||||
|
||||
export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.callback" } });
|
||||
|
||||
const { searchParams } = new URL(request.url);
|
||||
@@ -61,15 +103,20 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
!timingSafeEqual(Buffer.from(state), Buffer.from(storedState))
|
||||
) {
|
||||
annotate({ meta: { reason: "csrf1" } });
|
||||
return ERR("csrf1");
|
||||
return WEB_ERR("csrf1");
|
||||
}
|
||||
|
||||
// CSRF leg 2: atomically consume the ledger row. `delete` returns the row
|
||||
// on success so the `expiresAt` + `userId` checks run against the consumed
|
||||
// payload. P2025 means the nonce was already consumed (replay) or never
|
||||
// existed. Atomic at the Postgres row level: two concurrent callbacks with
|
||||
// the same nonce can't both pass before either deletes.
|
||||
let stateRow: { userId: string; expiresAt: Date } | null = null;
|
||||
// on success so the `expiresAt` + `userId` + `returnScheme` checks run
|
||||
// against the consumed payload. P2025 means the nonce was already consumed
|
||||
// (replay) or never existed. Atomic at the Postgres row level: two
|
||||
// concurrent callbacks with the same nonce can't both pass before either
|
||||
// deletes.
|
||||
let stateRow: {
|
||||
userId: string;
|
||||
expiresAt: Date;
|
||||
returnScheme: string | null;
|
||||
} | null = null;
|
||||
try {
|
||||
stateRow = await prisma.whoopOAuthState.delete({ where: { nonce: state } });
|
||||
} catch (err) {
|
||||
@@ -78,31 +125,49 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
err.code === "P2025"
|
||||
) {
|
||||
annotate({ meta: { reason: "replay" } });
|
||||
return ERR("replay");
|
||||
return WEB_ERR("replay");
|
||||
}
|
||||
const errName = err instanceof Error ? err.name : "unknown";
|
||||
getEvent()?.addWarning(`oauth-state-delete failed: ${errName}`);
|
||||
annotate({ meta: { reason: "state" } });
|
||||
return ERR("state");
|
||||
return WEB_ERR("state");
|
||||
}
|
||||
|
||||
// The validated native return scheme (if any) is now known; every redirect
|
||||
// below honours it. Identity is the row's userId (bound at connect time from
|
||||
// the session or the one-time ticket).
|
||||
const returnScheme = stateRow.returnScheme;
|
||||
const userId = stateRow.userId;
|
||||
|
||||
const evt = getEvent();
|
||||
if (evt) {
|
||||
// Identity resolved from the consumed state row (bound at connect time
|
||||
// from the session or the one-time ticket); no role is asserted here.
|
||||
evt.setAuth({ user_id: userId, auth_method: "session" });
|
||||
}
|
||||
|
||||
if (stateRow.expiresAt <= new Date()) {
|
||||
annotate({ meta: { reason: "expired" } });
|
||||
return ERR("expired");
|
||||
return outcomeRedirect(returnScheme, "error", "expired");
|
||||
}
|
||||
if (stateRow.userId !== user.id) {
|
||||
|
||||
// Optional session cross-check: only when a web session cookie is present.
|
||||
// The native ticket path carries no session — the nonce cookie + atomic
|
||||
// single-use delete already bind the row to its originator.
|
||||
const sessionData = await getSession();
|
||||
if (sessionData && sessionData.user.id !== userId) {
|
||||
annotate({ meta: { reason: "cross_user" } });
|
||||
return ERR("cross_user");
|
||||
return outcomeRedirect(returnScheme, "error", "cross_user");
|
||||
}
|
||||
|
||||
if (!code) {
|
||||
return ERR("nocode");
|
||||
return outcomeRedirect(returnScheme, "error", "nocode");
|
||||
}
|
||||
|
||||
try {
|
||||
const creds = await getUserWhoopCredentials(user.id);
|
||||
const creds = await getUserWhoopCredentials(userId);
|
||||
if (!creds) {
|
||||
return ERR("nocreds");
|
||||
return outcomeRedirect(returnScheme, "error", "nocreds");
|
||||
}
|
||||
|
||||
const tokens = await exchangeCode(code, creds);
|
||||
@@ -111,7 +176,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
const expiresAt = new Date(Date.now() + tokens.expires_in * 1000);
|
||||
|
||||
await prisma.whoopConnection.upsert({
|
||||
where: { userId: user.id },
|
||||
where: { userId },
|
||||
update: {
|
||||
whoopUserId,
|
||||
accessToken: encrypt(tokens.access_token),
|
||||
@@ -121,7 +186,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
backfillCompletedAt: null,
|
||||
},
|
||||
create: {
|
||||
userId: user.id,
|
||||
userId,
|
||||
whoopUserId,
|
||||
accessToken: encrypt(tokens.access_token),
|
||||
refreshToken: encrypt(tokens.refresh_token),
|
||||
@@ -131,12 +196,12 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
});
|
||||
|
||||
await auditLog("whoop.connect", {
|
||||
userId: user.id,
|
||||
userId,
|
||||
details: { whoopUserId },
|
||||
});
|
||||
|
||||
// Re-completing OAuth clears any prior reauth-required state.
|
||||
await markReconnected(user.id, "whoop");
|
||||
await markReconnected(userId, "whoop");
|
||||
|
||||
// Enqueue the self-converging history backfill. Best-effort: the boot-time
|
||||
// discovery query (`backfillCompletedAt IS NULL`) is the safety net, so a
|
||||
@@ -145,7 +210,7 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
if (boss) {
|
||||
await boss
|
||||
.send(WHOOP_BACKFILL_QUEUE, {
|
||||
userId: user.id,
|
||||
userId,
|
||||
enqueuedAt: new Date().toISOString(),
|
||||
})
|
||||
.catch((err) =>
|
||||
@@ -153,16 +218,11 @@ export const GET = apiHandler(async (request: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
const response = NextResponse.redirect(
|
||||
new URL(
|
||||
"/settings/integrations?whoop=connected",
|
||||
process.env.NEXT_PUBLIC_APP_URL!,
|
||||
),
|
||||
);
|
||||
const response = outcomeRedirect(returnScheme, "connected");
|
||||
response.cookies.delete(WHOOP_OAUTH_STATE_COOKIE);
|
||||
return response;
|
||||
} catch (err) {
|
||||
getEvent()?.setError(err);
|
||||
return ERR("token");
|
||||
return outcomeRedirect(returnScheme, "error", "token");
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "cookie-user" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/db", () => ({
|
||||
prisma: { whoopOAuthState: { create: vi.fn() } },
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({
|
||||
annotate: vi.fn(),
|
||||
getEvent: () => ({ setError: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: vi.fn(async () => ({ allowed: true })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/whoop/client", () => ({
|
||||
getAuthorizationUrl: vi.fn(
|
||||
(nonce: string) => `https://api.prod.whoop.com/oauth/oauth2/auth?state=${nonce}`,
|
||||
),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/whoop/credentials", () => ({
|
||||
getUserWhoopCredentials: vi.fn(async () => ({
|
||||
clientId: "cid",
|
||||
clientSecret: "secret",
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/whoop/connect-ticket", () => ({
|
||||
consumeWhoopConnectTicket: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/auth/secure-cookie", () => ({
|
||||
shouldEmitSecureCookie: () => true,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiError: (error: string, status: number) => ({
|
||||
__apiError: true,
|
||||
error,
|
||||
status,
|
||||
}),
|
||||
}));
|
||||
|
||||
import { GET } from "../route";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireAuth } from "@/lib/api-handler";
|
||||
import { consumeWhoopConnectTicket } from "@/lib/whoop/connect-ticket";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import type { NextRequest } from "next/server";
|
||||
|
||||
const create = prisma.whoopOAuthState.create as ReturnType<typeof vi.fn>;
|
||||
const consume = consumeWhoopConnectTicket as unknown as ReturnType<typeof vi.fn>;
|
||||
const reqAuth = requireAuth as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
function makeReq(url: string): NextRequest {
|
||||
return { url } as NextRequest;
|
||||
}
|
||||
|
||||
describe("GET /api/whoop/connect", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
create.mockResolvedValue({});
|
||||
(checkRateLimit as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
allowed: true,
|
||||
});
|
||||
});
|
||||
|
||||
it("cookie path: 302s to WHOOP and stores the state row (no scheme)", async () => {
|
||||
const res = await GET(
|
||||
makeReq("https://app.example/api/whoop/connect"),
|
||||
);
|
||||
expect(res.status).toBe(307);
|
||||
expect(res.headers.get("location")).toContain(
|
||||
"api.prod.whoop.com/oauth/oauth2/auth",
|
||||
);
|
||||
expect(reqAuth).toHaveBeenCalled();
|
||||
expect(consume).not.toHaveBeenCalled();
|
||||
const data = create.mock.calls[0][0].data;
|
||||
expect(data.userId).toBe("cookie-user");
|
||||
expect(data.returnScheme).toBeNull();
|
||||
// Nonce cookie is set.
|
||||
expect(res.cookies.get("whoop_state")?.value).toBeTruthy();
|
||||
});
|
||||
|
||||
it("ticket path: resolves user from the ticket, NOT requireAuth, and 302s to WHOOP", async () => {
|
||||
consume.mockResolvedValue({ userId: "ticket-user" });
|
||||
const res = await GET(
|
||||
makeReq("https://app.example/api/whoop/connect?ticket=opaque123"),
|
||||
);
|
||||
expect(res.status).toBe(307);
|
||||
expect(res.headers.get("location")).toContain("api.prod.whoop.com");
|
||||
expect(consume).toHaveBeenCalledWith("opaque123");
|
||||
expect(reqAuth).not.toHaveBeenCalled();
|
||||
expect(create.mock.calls[0][0].data.userId).toBe("ticket-user");
|
||||
});
|
||||
|
||||
it("ticket path: invalid/expired/used ticket returns typed 401", async () => {
|
||||
consume.mockResolvedValue(null);
|
||||
const res = (await GET(
|
||||
makeReq("https://app.example/api/whoop/connect?ticket=bad"),
|
||||
)) as unknown as { __apiError: boolean; status: number };
|
||||
expect(res.__apiError).toBe(true);
|
||||
expect(res.status).toBe(401);
|
||||
expect(create).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stores a valid return_scheme on the state row", async () => {
|
||||
const res = await GET(
|
||||
makeReq(
|
||||
"https://app.example/api/whoop/connect?return_scheme=dev.healthlog.app",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(307);
|
||||
expect(create.mock.calls[0][0].data.returnScheme).toBe("dev.healthlog.app");
|
||||
});
|
||||
|
||||
it("rejects http/javascript return_scheme → null (web fallback)", async () => {
|
||||
await GET(
|
||||
makeReq("https://app.example/api/whoop/connect?return_scheme=http"),
|
||||
);
|
||||
expect(create.mock.calls[0][0].data.returnScheme).toBeNull();
|
||||
create.mockClear();
|
||||
await GET(
|
||||
makeReq(
|
||||
"https://app.example/api/whoop/connect?return_scheme=javascript",
|
||||
),
|
||||
);
|
||||
expect(create.mock.calls[0][0].data.returnScheme).toBeNull();
|
||||
});
|
||||
|
||||
it("ticket + return_scheme combine", async () => {
|
||||
consume.mockResolvedValue({ userId: "ticket-user" });
|
||||
const res = await GET(
|
||||
makeReq(
|
||||
"https://app.example/api/whoop/connect?ticket=opaque&return_scheme=dev.healthlog.app",
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(307);
|
||||
const data = create.mock.calls[0][0].data;
|
||||
expect(data.userId).toBe("ticket-user");
|
||||
expect(data.returnScheme).toBe("dev.healthlog.app");
|
||||
});
|
||||
});
|
||||
@@ -4,17 +4,20 @@ import { prisma } from "@/lib/db";
|
||||
import { annotate, getEvent } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { getAuthorizationUrl } from "@/lib/whoop/client";
|
||||
import { consumeWhoopConnectTicket } from "@/lib/whoop/connect-ticket";
|
||||
import { getUserWhoopCredentials } from "@/lib/whoop/credentials";
|
||||
import {
|
||||
WHOOP_OAUTH_STATE_COOKIE,
|
||||
WHOOP_OAUTH_STATE_TTL_MS,
|
||||
mintWhoopOAuthStateNonce,
|
||||
} from "@/lib/whoop/oauth-state";
|
||||
import { validateReturnScheme } from "@/lib/whoop/return-scheme";
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
|
||||
|
||||
/**
|
||||
* Redirect the user to the WHOOP OAuth authorization page (v1.11.0).
|
||||
* Redirect the user to the WHOOP OAuth authorization page (v1.11.0; native
|
||||
* enhancements v1.12.2).
|
||||
*
|
||||
* Mirrors the Withings connect route: a fully-random base64url state nonce
|
||||
* backed by a 10-minute `WhoopOAuthState` ledger row carries the
|
||||
@@ -23,20 +26,54 @@ import { shouldEmitSecureCookie } from "@/lib/auth/secure-cookie";
|
||||
* httpOnly + Secure cookie carries JUST the nonce; the callback resolves the
|
||||
* user via the row's `userId`.
|
||||
*
|
||||
* v1.12.2 — two native-client enhancements:
|
||||
* - `?ticket=<opaque>` lets a purely Bearer-authenticated native client (no
|
||||
* web-session cookie) start the handshake. The connect route resolves the
|
||||
* user from a one-time, unconsumed/unexpired ticket IN LIEU of a cookie,
|
||||
* consumes it, and proceeds exactly as the cookie path. Expired / consumed
|
||||
* / invalid → typed 401. The ticket is minted via the Bearer
|
||||
* `POST /api/whoop/connect/ticket` route.
|
||||
* - `?return_scheme=<custom-scheme>` (validated against a strict allowlist)
|
||||
* is stored on the state row so it survives the OAuth round-trip; the
|
||||
* callback uses it to send its FINAL redirect to a native custom scheme.
|
||||
*
|
||||
* Rate-limited per user (10 calls / 60 s) so a logged-in session can't spam
|
||||
* ledger rows for the full 10-min TTL window. Both the rate-limit and
|
||||
* create-failure paths redirect (not JSON) because the entry point is a
|
||||
* create-failure paths redirect (not JSON) because the cookie entry point is a
|
||||
* browser navigation — a 429 envelope would surface as a blank page.
|
||||
*/
|
||||
const CONNECT_RATE_LIMIT = 10;
|
||||
const CONNECT_WINDOW_MS = 60_000;
|
||||
|
||||
export const GET = apiHandler(async (req: NextRequest) => {
|
||||
const { user } = await requireAuth();
|
||||
const { searchParams } = new URL(req.url);
|
||||
const ticket = searchParams.get("ticket");
|
||||
|
||||
// Resolve the in-flight user. The ticket path is for Bearer-only native
|
||||
// clients whose in-app web session carries no cookie; it must NOT call
|
||||
// requireAuth (which would 401 the cookieless session). The cookie path is
|
||||
// unchanged. The ticket is single-use + consumed atomically here.
|
||||
let userId: string;
|
||||
if (ticket) {
|
||||
annotate({ action: { name: "whoop.connect.ticket.consume" } });
|
||||
const resolved = await consumeWhoopConnectTicket(ticket);
|
||||
if (!resolved) {
|
||||
annotate({ action: { name: "whoop.connect.ticket.invalid" } });
|
||||
// Typed 401 — the in-app session surfaces this; the client re-mints.
|
||||
return apiError(
|
||||
"Connect ticket is invalid, expired, or already used.",
|
||||
401,
|
||||
);
|
||||
}
|
||||
userId = resolved.userId;
|
||||
} else {
|
||||
const { user } = await requireAuth();
|
||||
userId = user.id;
|
||||
}
|
||||
annotate({ action: { name: "whoop.connect" } });
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`whoop:connect:${user.id}`,
|
||||
`whoop:connect:${userId}`,
|
||||
CONNECT_RATE_LIMIT,
|
||||
CONNECT_WINDOW_MS,
|
||||
);
|
||||
@@ -50,7 +87,7 @@ export const GET = apiHandler(async (req: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
const creds = await getUserWhoopCredentials(user.id);
|
||||
const creds = await getUserWhoopCredentials(userId);
|
||||
if (!creds) {
|
||||
return apiError(
|
||||
"Please configure your WHOOP Client ID and Client Secret in Settings first.",
|
||||
@@ -58,13 +95,19 @@ export const GET = apiHandler(async (req: NextRequest) => {
|
||||
);
|
||||
}
|
||||
|
||||
// Validate the optional native return scheme against the strict allowlist.
|
||||
// An invalid/absent value resolves to null → the callback uses the web
|
||||
// redirect (never an arbitrary reflected scheme).
|
||||
const returnScheme = validateReturnScheme(searchParams.get("return_scheme"));
|
||||
|
||||
const nonce = mintWhoopOAuthStateNonce();
|
||||
try {
|
||||
await prisma.whoopOAuthState.create({
|
||||
data: {
|
||||
nonce,
|
||||
userId: user.id,
|
||||
userId,
|
||||
expiresAt: new Date(Date.now() + WHOOP_OAUTH_STATE_TTL_MS),
|
||||
returnScheme,
|
||||
},
|
||||
});
|
||||
} catch (err) {
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
|
||||
vi.mock("@/lib/api-handler", () => ({
|
||||
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
|
||||
requireAuth: vi.fn(async () => ({ user: { id: "u1" } })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/logging/context", () => ({ annotate: vi.fn() }));
|
||||
|
||||
vi.mock("@/lib/rate-limit", () => ({
|
||||
checkRateLimit: vi.fn(async () => ({ allowed: true })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/whoop/connect-ticket", () => ({
|
||||
mintWhoopConnectTicket: vi.fn(async () => "opaque-raw-ticket"),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/whoop/credentials", () => ({
|
||||
getUserWhoopCredentials: vi.fn(async () => ({
|
||||
clientId: "cid",
|
||||
clientSecret: "s",
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api-response", () => ({
|
||||
apiSuccess: (data: unknown) => ({ data, error: null, status: 200 }),
|
||||
apiError: (error: string, status: number) => ({ data: null, error, status }),
|
||||
}));
|
||||
|
||||
import { POST } from "../route";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { getUserWhoopCredentials } from "@/lib/whoop/credentials";
|
||||
import { mintWhoopConnectTicket } from "@/lib/whoop/connect-ticket";
|
||||
|
||||
const rl = checkRateLimit as ReturnType<typeof vi.fn>;
|
||||
const creds = getUserWhoopCredentials as unknown as ReturnType<typeof vi.fn>;
|
||||
const mint = mintWhoopConnectTicket as unknown as ReturnType<typeof vi.fn>;
|
||||
|
||||
const call = () =>
|
||||
(POST as unknown as () => Promise<{ data: unknown; status: number }>)();
|
||||
|
||||
describe("POST /api/whoop/connect/ticket", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
rl.mockResolvedValue({ allowed: true });
|
||||
creds.mockResolvedValue({ clientId: "cid", clientSecret: "s" });
|
||||
});
|
||||
|
||||
it("mints and returns a ticket once", async () => {
|
||||
const res = await call();
|
||||
expect(res.status).toBe(200);
|
||||
expect((res.data as { ticket: string }).ticket).toBe("opaque-raw-ticket");
|
||||
expect(mint).toHaveBeenCalledWith("u1");
|
||||
});
|
||||
|
||||
it("429s when rate-limited", async () => {
|
||||
rl.mockResolvedValue({ allowed: false });
|
||||
const res = await call();
|
||||
expect(res.status).toBe(429);
|
||||
expect(mint).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("400s when WHOOP credentials are not configured", async () => {
|
||||
creds.mockResolvedValue(null);
|
||||
const res = await call();
|
||||
expect(res.status).toBe(400);
|
||||
expect(mint).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,49 @@
|
||||
import { apiHandler, requireAuth } from "@/lib/api-handler";
|
||||
import { apiError, apiSuccess } from "@/lib/api-response";
|
||||
import { annotate } from "@/lib/logging/context";
|
||||
import { checkRateLimit } from "@/lib/rate-limit";
|
||||
import { mintWhoopConnectTicket } from "@/lib/whoop/connect-ticket";
|
||||
import { getUserWhoopCredentials } from "@/lib/whoop/credentials";
|
||||
|
||||
/**
|
||||
* Mint a one-time, short-lived WHOOP connect ticket (v1.12.2).
|
||||
*
|
||||
* Bearer-capable: a purely Bearer-authenticated native client (no web-session
|
||||
* cookie) mints a ticket here, then opens
|
||||
* `GET /api/whoop/connect?ticket=<opaque>` in an in-app web session to start
|
||||
* the WHOOP OAuth handshake. The raw ticket is returned exactly once; only its
|
||||
* hash is stored (see `src/lib/whoop/connect-ticket.ts`).
|
||||
*
|
||||
* Rate-limited per user so a token can't mint an unbounded backlog of tickets.
|
||||
*/
|
||||
const TICKET_RATE_LIMIT = 10;
|
||||
const TICKET_WINDOW_MS = 60_000;
|
||||
|
||||
export const POST = apiHandler(async () => {
|
||||
const { user } = await requireAuth();
|
||||
annotate({ action: { name: "whoop.connect.ticket.mint" } });
|
||||
|
||||
const rl = await checkRateLimit(
|
||||
`whoop:connect:ticket:${user.id}`,
|
||||
TICKET_RATE_LIMIT,
|
||||
TICKET_WINDOW_MS,
|
||||
);
|
||||
if (!rl.allowed) {
|
||||
annotate({ action: { name: "whoop.connect.ticket.rate_limited" } });
|
||||
return apiError("Too many connect-ticket requests. Try again shortly.", 429);
|
||||
}
|
||||
|
||||
// BYO-key gate: a ticket is only useful if the user has WHOOP credentials
|
||||
// configured (the connect route would 400 otherwise). Fail fast with a clear
|
||||
// error rather than minting a ticket that can't complete.
|
||||
const creds = await getUserWhoopCredentials(user.id);
|
||||
if (!creds) {
|
||||
return apiError(
|
||||
"Please configure your WHOOP Client ID and Client Secret in Settings first.",
|
||||
400,
|
||||
);
|
||||
}
|
||||
|
||||
const ticket = await mintWhoopConnectTicket(user.id);
|
||||
return apiSuccess({ ticket });
|
||||
});
|
||||
Reference in new issue
Block a user