feat(whoop): OAuth connect/callback + HMAC-signed webhook + CSP gating

Connect mints the state nonce into the WhoopOAuthState ledger and redirects
to the WHOOP authorize page; callback verifies the nonce (atomic
delete-first consume, four distinguished reason tags), exchanges the code,
fetches the WHOOP profile for the user id, persists the encrypted
WhoopConnection, and enqueues the self-converging history backfill.

The webhook handler rate-limits per source first, verifies the
WHOOP_WEBHOOK_SECRET path segment, then verifies the HMAC-SHA256 body
signature over the raw bytes (timestamp + body, timingSafeEqual, stale
timestamp reject) before any work. Valid *.updated enqueues the matching
per-resource sync; *.deleted soft-deletes (workouts hard-delete, no
soft-delete column). Unknown users return 200 to stop retries.

CSP gates api.prod.whoop.com to the WHOOP settings surface + /api/whoop/*;
the webhook path joins the public-path allowlist and the path-secret redact
registry. Env wiring adds WHOOP_WEBHOOK_SECRET + WHOOP_REDIRECT_URI to the
compose whitelist and .env.production.example.
This commit is contained in:
Marc-André Bombeck committed 2026-06-04 01:40:27 +02:00
1 parent be94e43480
commit dd1071158f
12 files changed
+965 -4

No files matched your search

+15
View File
@@ -36,6 +36,21 @@ API_TOKEN_HMAC_KEY="<openssl rand -hex 32>"
# WITHINGS_WEBHOOK_SECRET=""
# -----------------------------------------------------------------------------
# WHOOP -- optional integration
# -----------------------------------------------------------------------------
# The WHOOP app client id/secret are per-user BYO-keys: each user registers
# their own WHOOP developer app and pastes the client id/secret into Settings
# (stored encrypted in the DB). There is therefore no WHOOP_CLIENT_ID/SECRET.
#
# WHOOP_WEBHOOK_SECRET is the instance-level secret carried as the trailing
# path segment of the webhook URL AND used to verify the WHOOP HMAC body
# signature. WHOOP_REDIRECT_URI overrides the derived
# `${NEXT_PUBLIC_APP_URL}/api/whoop/callback` when the public URL differs.
# WHOOP_WEBHOOK_SECRET="<openssl rand -hex 32>"
# WHOOP_REDIRECT_URI=""
# -----------------------------------------------------------------------------
# APNs -- iOS push (optional, all-or-none)
# -----------------------------------------------------------------------------
+10
View File
@@ -55,6 +55,16 @@ services:
# an operator override in .env actually reaches the container (the
# `environment:` block is a whitelist).
FHIR_MAX_MEDICATION_ADMINISTRATIONS: "${FHIR_MAX_MEDICATION_ADMINISTRATIONS:-}"
# WHOOP integration (optional). The app client id/secret are per-user
# BYO-keys stored encrypted in the DB, so there is no
# WHOOP_CLIENT_ID/SECRET env. WHOOP_WEBHOOK_SECRET is the instance-level
# path-segment + HMAC-verification secret for the webhook;
# WHOOP_REDIRECT_URI overrides the derived
# `${NEXT_PUBLIC_APP_URL}/api/whoop/callback` when the public URL
# differs. Listed here so an operator override in .env reaches the
# container (the `environment:` block is a whitelist).
WHOOP_WEBHOOK_SECRET: "${WHOOP_WEBHOOK_SECRET:-}"
WHOOP_REDIRECT_URI: "${WHOOP_REDIRECT_URI:-}"
depends_on:
db:
condition: service_healthy
@@ -101,3 +101,35 @@ describe("proxy.ts Withings CSP gating (F-5, 2026-05-16)", () => {
expect(csp).not.toMatch(/wbsapi\.withings\.net/);
});
});
describe("proxy.ts WHOOP CSP gating (v1.11.0)", () => {
it("does NOT allow api.prod.whoop.com on a non-WHOOP page", () => {
const res = proxy(makeRequest("/", { healthlog_session: "sess-1" }));
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).not.toMatch(/api\.prod\.whoop\.com/);
});
it("allows api.prod.whoop.com under /settings/integrations/whoop/*", () => {
const res = proxy(
makeRequest("/settings/integrations/whoop", {
healthlog_session: "sess-1",
}),
);
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).toMatch(/connect-src[^;]*https:\/\/api\.prod\.whoop\.com/);
});
it("allows api.prod.whoop.com under /api/whoop/*", () => {
const res = proxy(
makeRequest("/api/whoop/callback", { healthlog_session: "sess-1" }),
);
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).toMatch(/connect-src[^;]*https:\/\/api\.prod\.whoop\.com/);
});
it("never ships the WHOOP host on the auth surface", () => {
const res = proxy(makeRequest("/auth/login"));
const csp = res.headers.get("content-security-policy") ?? "";
expect(csp).not.toMatch(/api\.prod\.whoop\.com/);
});
});
+168
View File
@@ -0,0 +1,168 @@
import { prisma } from "@/lib/db";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { annotate, getEvent } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { encrypt } from "@/lib/crypto";
import {
exchangeCode,
fetchProfile,
WHOOP_OAUTH_SCOPE,
} from "@/lib/whoop/client";
import { getUserWhoopCredentials } from "@/lib/whoop/credentials";
import { WHOOP_OAUTH_STATE_COOKIE } from "@/lib/whoop/oauth-state";
import { WHOOP_BACKFILL_QUEUE } from "@/lib/jobs/whoop-backfill";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
import { markReconnected } from "@/lib/integrations/status";
import { Prisma } from "@/generated/prisma/client";
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.
*
* Reason tags distinguish the four 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).
*
* 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) =>
NextResponse.redirect(
new URL(
`/settings/integrations?whoop=error&reason=${reason}`,
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);
const code = searchParams.get("code");
const state = searchParams.get("state");
const storedState = request.cookies.get(WHOOP_OAUTH_STATE_COOKIE)?.value;
// CSRF leg 1: URL state must match the cookie state byte-for-byte
// (timing-safe). Runs BEFORE the atomic delete so a probe with arbitrary
// state values can't grief legitimate ledger rows.
if (
!state ||
!storedState ||
state.length !== storedState.length ||
!timingSafeEqual(Buffer.from(state), Buffer.from(storedState))
) {
annotate({ meta: { reason: "csrf1" } });
return 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;
try {
stateRow = await prisma.whoopOAuthState.delete({ where: { nonce: state } });
} catch (err) {
if (
err instanceof Prisma.PrismaClientKnownRequestError &&
err.code === "P2025"
) {
annotate({ meta: { reason: "replay" } });
return ERR("replay");
}
const errName = err instanceof Error ? err.name : "unknown";
getEvent()?.addWarning(`oauth-state-delete failed: ${errName}`);
annotate({ meta: { reason: "state" } });
return ERR("state");
}
if (stateRow.expiresAt <= new Date()) {
annotate({ meta: { reason: "expired" } });
return ERR("expired");
}
if (stateRow.userId !== user.id) {
annotate({ meta: { reason: "cross_user" } });
return ERR("cross_user");
}
if (!code) {
return ERR("nocode");
}
try {
const creds = await getUserWhoopCredentials(user.id);
if (!creds) {
return ERR("nocreds");
}
const tokens = await exchangeCode(code, creds);
const profile = await fetchProfile(tokens.access_token);
const whoopUserId = String(profile.user_id);
const expiresAt = new Date(Date.now() + tokens.expires_in * 1000);
await prisma.whoopConnection.upsert({
where: { userId: user.id },
update: {
whoopUserId,
accessToken: encrypt(tokens.access_token),
refreshToken: encrypt(tokens.refresh_token),
tokenExpiresAt: expiresAt,
scope: tokens.scope ?? WHOOP_OAUTH_SCOPE,
backfillCompletedAt: null,
},
create: {
userId: user.id,
whoopUserId,
accessToken: encrypt(tokens.access_token),
refreshToken: encrypt(tokens.refresh_token),
tokenExpiresAt: expiresAt,
scope: tokens.scope ?? WHOOP_OAUTH_SCOPE,
},
});
await auditLog("whoop.connect", {
userId: user.id,
details: { whoopUserId },
});
// Re-completing OAuth clears any prior reauth-required state.
await markReconnected(user.id, "whoop");
// Enqueue the self-converging history backfill. Best-effort: the boot-time
// discovery query (`backfillCompletedAt IS NULL`) is the safety net, so a
// missing boss instance here doesn't strand the connection.
const boss = getGlobalBoss();
if (boss) {
await boss
.send(WHOOP_BACKFILL_QUEUE, {
userId: user.id,
enqueuedAt: new Date().toISOString(),
})
.catch((err) =>
getEvent()?.addWarning(`whoop-backfill enqueue failed: ${err}`),
);
}
const response = NextResponse.redirect(
new URL(
"/settings/integrations?whoop=connected",
process.env.NEXT_PUBLIC_APP_URL!,
),
);
response.cookies.delete(WHOOP_OAUTH_STATE_COOKIE);
return response;
} catch (err) {
getEvent()?.setError(err);
return ERR("token");
}
});
+90
View File
@@ -0,0 +1,90 @@
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError } from "@/lib/api-response";
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 { getUserWhoopCredentials } from "@/lib/whoop/credentials";
import {
WHOOP_OAUTH_STATE_COOKIE,
WHOOP_OAUTH_STATE_TTL_MS,
mintWhoopOAuthStateNonce,
} from "@/lib/whoop/oauth-state";
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).
*
* Mirrors the Withings connect route: a fully-random base64url state nonce
* backed by a 10-minute `WhoopOAuthState` ledger row carries the
* `(nonce → userId)` mapping, so the user id never travels in the OAuth
* `state` param (which can land in request logs / network captures). The
* httpOnly + Secure cookie carries JUST the nonce; the callback resolves the
* user via the row's `userId`.
*
* 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
* 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();
annotate({ action: { name: "whoop.connect" } });
const rl = await checkRateLimit(
`whoop:connect:${user.id}`,
CONNECT_RATE_LIMIT,
CONNECT_WINDOW_MS,
);
if (!rl.allowed) {
annotate({ action: { name: "whoop.connect.rate_limited" } });
return NextResponse.redirect(
new URL(
"/settings/integrations?whoop=error&reason=rate_limited",
req.url,
),
);
}
const creds = await getUserWhoopCredentials(user.id);
if (!creds) {
return apiError(
"Please configure your WHOOP Client ID and Client Secret in Settings first.",
400,
);
}
const nonce = mintWhoopOAuthStateNonce();
try {
await prisma.whoopOAuthState.create({
data: {
nonce,
userId: user.id,
expiresAt: new Date(Date.now() + WHOOP_OAUTH_STATE_TTL_MS),
},
});
} catch (err) {
getEvent()?.setError(err);
annotate({ action: { name: "whoop.connect.create_failed" } });
return NextResponse.redirect(
new URL("/settings/integrations?whoop=error&reason=connect", req.url),
);
}
const url = getAuthorizationUrl(nonce, creds);
const response = NextResponse.redirect(url);
response.cookies.set(WHOOP_OAUTH_STATE_COOKIE, nonce, {
httpOnly: true,
secure: shouldEmitSecureCookie(),
sameSite: "lax",
maxAge: Math.floor(WHOOP_OAUTH_STATE_TTL_MS / 1000),
path: "/",
});
return response;
});
@@ -0,0 +1,208 @@
import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
import { NextRequest } from "next/server";
import { createHmac } from "node:crypto";
// --- Module-boundary mocks must come before importing the route. ---
vi.mock("@/lib/api-handler", () => ({
apiHandler: <T extends (...args: unknown[]) => unknown>(fn: T) => fn,
}));
vi.mock("@/lib/db", () => ({
prisma: {
whoopConnection: { findFirst: vi.fn() },
measurement: { updateMany: vi.fn() },
workout: { deleteMany: vi.fn() },
},
}));
vi.mock("@/lib/jobs/boss-instance", () => ({
getGlobalBoss: vi.fn(),
}));
vi.mock("@/lib/rate-limit", () => ({
checkRateLimit: vi.fn(),
rateLimitHeaders: vi.fn(() => ({})),
}));
vi.mock("@/lib/api-response", () => ({
getClientIp: vi.fn(() => "203.0.113.7"),
}));
vi.mock("@/lib/logging/context", () => ({
annotate: vi.fn(),
getEvent: vi.fn(() => ({
setAuth: vi.fn(),
addWarning: vi.fn(),
})),
}));
import { POST } from "../route";
import { prisma } from "@/lib/db";
import { checkRateLimit } from "@/lib/rate-limit";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
const SECRET = "test-whoop-webhook-secret";
const ORIGINAL_SECRET = process.env.WHOOP_WEBHOOK_SECRET;
const NOW = 1_700_000_000_000;
function signedRequest(
body: object,
opts: { signatureValid?: boolean; timestamp?: number } = {},
): NextRequest {
const rawBody = JSON.stringify(body);
const timestamp = String(opts.timestamp ?? NOW);
const signingSecret = opts.signatureValid === false ? "wrong" : SECRET;
const signature = createHmac("sha256", signingSecret)
.update(timestamp + rawBody, "utf8")
.digest("base64");
return new NextRequest("https://app.example.com/api/whoop/webhook/" + SECRET, {
method: "POST",
headers: {
"content-type": "application/json",
"X-WHOOP-Signature": signature,
"X-WHOOP-Signature-Timestamp": timestamp,
},
body: rawBody,
});
}
const ctx = (token: string) => ({ params: Promise.resolve({ token }) });
beforeEach(() => {
vi.resetAllMocks();
process.env.WHOOP_WEBHOOK_SECRET = SECRET;
vi.useFakeTimers();
vi.setSystemTime(NOW);
vi.mocked(checkRateLimit).mockResolvedValue({
allowed: true,
count: 1,
limit: 60,
remaining: 59,
reset: NOW + 60_000,
} as never);
});
afterEach(() => {
vi.useRealTimers();
process.env.WHOOP_WEBHOOK_SECRET = ORIGINAL_SECRET;
});
describe("POST /api/whoop/webhook/[token]", () => {
it("rate-limits BEFORE any secret/signature work", async () => {
vi.mocked(checkRateLimit).mockResolvedValueOnce({
allowed: false,
count: 61,
limit: 60,
remaining: 0,
reset: NOW + 60_000,
} as never);
const req = signedRequest({
user_id: 42,
id: "abc",
type: "recovery.updated",
});
const res = await POST(req, ctx(SECRET));
expect(res.status).toBe(429);
// No connection lookup happened — the rate limit short-circuited.
expect(prisma.whoopConnection.findFirst).not.toHaveBeenCalled();
expect(getGlobalBoss).not.toHaveBeenCalled();
});
it("rejects a bad path-segment secret with 401, no work done", async () => {
const req = signedRequest({
user_id: 42,
id: "abc",
type: "recovery.updated",
});
const res = await POST(req, ctx("wrong-token"));
expect(res.status).toBe(401);
expect(prisma.whoopConnection.findFirst).not.toHaveBeenCalled();
});
it("rejects a forged HMAC signature with 401, no work done", async () => {
const req = signedRequest(
{ user_id: 42, id: "abc", type: "recovery.updated" },
{ signatureValid: false },
);
const res = await POST(req, ctx(SECRET));
expect(res.status).toBe(401);
expect(prisma.whoopConnection.findFirst).not.toHaveBeenCalled();
});
it("rejects a stale timestamp with 401", async () => {
const req = signedRequest(
{ user_id: 42, id: "abc", type: "recovery.updated" },
{ timestamp: NOW - 10 * 60 * 1000 },
);
const res = await POST(req, ctx(SECRET));
expect(res.status).toBe(401);
});
it("enqueues the matching per-resource sync on a valid `*.updated`", async () => {
const send = vi.fn().mockResolvedValue("job-id");
vi.mocked(getGlobalBoss).mockReturnValue({ send } as never);
vi.mocked(prisma.whoopConnection.findFirst).mockResolvedValue({
userId: "user-1",
} as never);
const req = signedRequest({
user_id: 42,
id: "abc",
type: "recovery.updated",
});
const res = await POST(req, ctx(SECRET));
expect(res.status).toBe(200);
expect(prisma.whoopConnection.findFirst).toHaveBeenCalledWith({
where: { whoopUserId: "42" },
select: { userId: true },
});
expect(send).toHaveBeenCalledWith("whoop-recovery-sync", {
userId: "user-1",
});
});
it("returns 200 unknown_user for an unrecognised WHOOP user (no retry storm)", async () => {
vi.mocked(prisma.whoopConnection.findFirst).mockResolvedValue(null);
const req = signedRequest({
user_id: 99,
id: "abc",
type: "sleep.updated",
});
const res = await POST(req, ctx(SECRET));
expect(res.status).toBe(200);
expect(await res.json()).toEqual({ status: "unknown_user" });
expect(getGlobalBoss).not.toHaveBeenCalled();
});
it("soft-deletes matching rows on a `*.deleted` event", async () => {
vi.mocked(prisma.whoopConnection.findFirst).mockResolvedValue({
userId: "user-1",
} as never);
const req = signedRequest({
user_id: 42,
id: "rec-uuid",
type: "recovery.deleted",
});
const res = await POST(req, ctx(SECRET));
expect(res.status).toBe(200);
expect(prisma.measurement.updateMany).toHaveBeenCalledWith({
where: {
userId: "user-1",
source: "WHOOP",
externalId: { startsWith: "rec-uuid:" },
deletedAt: null,
},
data: { deletedAt: expect.any(Date), syncVersion: { increment: 1 } },
});
});
});
@@ -0,0 +1,86 @@
import { NextRequest, NextResponse } from "next/server";
import { apiHandler } from "@/lib/api-handler";
import { annotate, getEvent } from "@/lib/logging/context";
import {
applyWebhookRateLimit,
processWhoopNotification,
timingSafeStringEqual,
verifyWhoopSignature,
} from "@/lib/whoop/webhook-handler";
/**
* WHOOP webhook entrypoint (v1.11.0). Mirrors the Withings path-segment
* secret shape and adds the HMAC body-signature verification WHOOP supports.
*
* Auth, in order — every leg short-circuits with no work done on failure:
* 1. per-source rate limit (BEFORE secret verify — DoS floor);
* 2. path-segment secret `timingSafeStringEqual` against
* `WHOOP_WEBHOOK_SECRET` (scrubbed from logs by `PATH_SECRET_PATHS`);
* 3. HMAC body signature `timingSafeEqual` over the RAW request bytes +
* a stale-timestamp reject.
*
* The path segment keeps the secret out of the reverse-proxy `query_string`
* access-log column; the HMAC binds the request body so a captured URL alone
* can't forge a delivery.
*/
interface RouteContext {
params: Promise<{ token: string }>;
}
async function verifyTokenSegment(
token: string | undefined,
): Promise<boolean> {
const expected = process.env.WHOOP_WEBHOOK_SECRET;
if (!expected) {
getEvent()?.addWarning("WHOOP_WEBHOOK_SECRET not configured");
return false;
}
if (!token) return false;
return timingSafeStringEqual(expected, token);
}
export const POST = apiHandler(
async (request: NextRequest, context: RouteContext) => {
annotate({ action: { name: "whoop.webhook" } });
// (1) Rate-limit BEFORE any secret / signature work.
const limited = await applyWebhookRateLimit(request);
if (limited) return limited;
// (2) Path-segment secret.
const { token } = await context.params;
if (!(await verifyTokenSegment(token))) {
return NextResponse.json({ status: "unauthorized" }, { status: 401 });
}
// (3) HMAC body signature over the RAW bytes. Read the body as text
// exactly once — `request.json()` would consume it and defeat the
// signature check.
const rawBody = await request.text();
const secret = process.env.WHOOP_WEBHOOK_SECRET;
if (
!secret ||
!verifyWhoopSignature({
rawBody,
signature: request.headers.get("X-WHOOP-Signature"),
timestamp: request.headers.get("X-WHOOP-Signature-Timestamp"),
secret,
})
) {
annotate({ action: { name: "whoop.webhook.bad_signature" } });
return NextResponse.json({ status: "unauthorized" }, { status: 401 });
}
let body: unknown;
try {
body = JSON.parse(rawBody);
} catch {
return NextResponse.json({ status: "ignored" }, { status: 200 });
}
if (typeof body !== "object" || body === null) {
return NextResponse.json({ status: "ignored" }, { status: 200 });
}
return processWhoopNotification(body);
},
);
+4
View File
@@ -47,6 +47,10 @@ export const PATH_SECRET_PATHS: ReadonlyArray<{ prefix: string }> = [
// credential for the share surface, so scrub it from `http.path` /
// `http.route` the same way the Withings webhook secret is scrubbed.
{ prefix: "/c/" },
// v1.11.0 — WHOOP webhook entrypoint: `WHOOP_WEBHOOK_SECRET` travels as
// the trailing path segment (mirrors Withings). Without this rule the
// secret lands in every Wide Event's `http.path` / `http.route`.
{ prefix: "/api/whoop/webhook/" },
];
function redactPathSegments(input: string): string {
+9 -3
View File
@@ -28,9 +28,15 @@ const {
},
refreshAccessTokenMock: vi.fn(),
fetchRecoveriesMock: vi.fn(),
recordSyncFailure: vi.fn(async () => {}),
recordSyncSuccess: vi.fn(async () => {}),
isReauthRequired: vi.fn(async () => false),
recordSyncFailure: vi.fn<(...a: unknown[]) => Promise<void>>(
async () => {},
),
recordSyncSuccess: vi.fn<(...a: unknown[]) => Promise<void>>(
async () => {},
),
isReauthRequired: vi.fn<(...a: unknown[]) => Promise<boolean>>(
async () => false,
),
}));
vi.mock("@/lib/db", () => ({ prisma: prismaMock }));
@@ -0,0 +1,107 @@
import { describe, it, expect } from "vitest";
import { createHmac } from "node:crypto";
import { verifyWhoopSignature } from "../webhook-handler";
const SECRET = "test-whoop-webhook-secret";
function sign(rawBody: string, timestamp: string, secret = SECRET): string {
return createHmac("sha256", secret)
.update(timestamp + rawBody, "utf8")
.digest("base64");
}
describe("verifyWhoopSignature", () => {
const now = 1_700_000_000_000;
const rawBody = JSON.stringify({
user_id: 42,
id: "abc",
type: "recovery.updated",
});
it("accepts a valid signature over `timestamp + rawBody`", () => {
const timestamp = String(now);
expect(
verifyWhoopSignature({
rawBody,
signature: sign(rawBody, timestamp),
timestamp,
secret: SECRET,
now,
}),
).toBe(true);
});
it("rejects a forged signature", () => {
const timestamp = String(now);
expect(
verifyWhoopSignature({
rawBody,
signature: sign(rawBody, timestamp, "wrong-secret"),
timestamp,
secret: SECRET,
now,
}),
).toBe(false);
});
it("rejects a body that doesn't match the signed bytes", () => {
const timestamp = String(now);
const sig = sign(rawBody, timestamp);
expect(
verifyWhoopSignature({
rawBody: rawBody + " tampered",
signature: sig,
timestamp,
secret: SECRET,
now,
}),
).toBe(false);
});
it("rejects a stale timestamp (> 5 min skew)", () => {
const timestamp = String(now - 6 * 60 * 1000);
expect(
verifyWhoopSignature({
rawBody,
signature: sign(rawBody, timestamp),
timestamp,
secret: SECRET,
now,
}),
).toBe(false);
});
it("rejects a missing signature or timestamp", () => {
const timestamp = String(now);
expect(
verifyWhoopSignature({
rawBody,
signature: null,
timestamp,
secret: SECRET,
now,
}),
).toBe(false);
expect(
verifyWhoopSignature({
rawBody,
signature: sign(rawBody, timestamp),
timestamp: null,
secret: SECRET,
now,
}),
).toBe(false);
});
it("rejects a non-numeric timestamp", () => {
expect(
verifyWhoopSignature({
rawBody,
signature: sign(rawBody, "not-a-number"),
timestamp: "not-a-number",
secret: SECRET,
now,
}),
).toBe(false);
});
});
+219
View File
@@ -0,0 +1,219 @@
/**
* Shared body processing + signature verification for the WHOOP webhook
* endpoint (`POST /api/whoop/webhook/[token]`). Mirrors the Withings
* `webhook-handler.ts` shape, with one genuine improvement: WHOOP signs the
* body, so we verify an HMAC-SHA256 signature in addition to the path-segment
* secret (Withings can't sign, so it only has the path secret).
*
* WHOOP webhook contract (API v2):
* - headers `X-WHOOP-Signature` (base64) + `X-WHOOP-Signature-Timestamp`
* (ms epoch);
* - signature = `base64(HMAC-SHA256(timestamp + rawBody, secret))`;
* - body `{ user_id: number, id: string|number, type: string, trace_id }`
* where `type` is e.g. `recovery.updated` / `sleep.updated` /
* `workout.updated` (+ the matching `*.deleted`). Creates arrive as
* `*.updated`. The payload carries NO resource data — the per-resource
* sync job re-fetches by id.
*
* Auth layering, in order (every leg short-circuits before any work):
* 1. per-source rate limit (BEFORE secret verify — DoS floor);
* 2. path-segment secret `timingSafeStringEqual`;
* 3. HMAC body signature `timingSafeEqual` over the raw bytes + a stale
* timestamp reject.
*
* Always returns 200 (even for an unknown WHOOP user) so WHOOP doesn't queue
* retries forever for a disconnected account — same contract as Withings.
*/
import { NextRequest, NextResponse } from "next/server";
import { createHmac, timingSafeEqual } from "node:crypto";
import { prisma } from "@/lib/db";
import { checkRateLimit, rateLimitHeaders } from "@/lib/rate-limit";
import { getClientIp } from "@/lib/api-response";
import { annotate, getEvent } from "@/lib/logging/context";
import { getGlobalBoss } from "@/lib/jobs/boss-instance";
/**
* Maximum age of a webhook timestamp before it is treated as a replay. Five
* minutes comfortably covers clock skew + delivery latency while bounding the
* window an attacker has to replay a captured (signed) body.
*/
const WHOOP_SIGNATURE_MAX_AGE_MS = 5 * 60 * 1000;
/**
* Resource-`type` prefix → pg-boss queue name. The webhook only enqueues a
* per-user job; the worker re-fetches the resource by id. Cycle has no
* webhook (poll-only) so it is intentionally absent.
*/
const WHOOP_RESOURCE_QUEUE: Record<string, string> = {
recovery: "whoop-recovery-sync",
sleep: "whoop-sleep-sync",
workout: "whoop-workout-sync",
};
/**
* Constant-time string comparison. Returns false unless both inputs have the
* same byte length AND match exactly.
*/
export async function timingSafeStringEqual(
expected: string,
received: string,
): Promise<boolean> {
const a = Buffer.from(expected, "utf8");
const b = Buffer.from(received, "utf8");
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
/**
* Apply the per-source rate limit every WHOOP webhook delivery shares.
* Returns a `NextResponse` when the request must be rejected, `null` when it
* should continue. Runs BEFORE secret/signature verification so a flood of
* forged deliveries can't drive unbounded crypto work.
*/
export async function applyWebhookRateLimit(
request: NextRequest,
): Promise<NextResponse | null> {
const ip = getClientIp(request);
const rl = await checkRateLimit(`whoop-webhook:${ip}`, 60, 60 * 1000);
if (!rl.allowed) {
return NextResponse.json(
{ status: "rate_limited" },
{ status: 429, headers: rateLimitHeaders(rl) },
);
}
return null;
}
/**
* Verify the WHOOP HMAC body signature against the raw request bytes.
*
* `secret` is the per-instance `WHOOP_WEBHOOK_SECRET`. The base string is
* `timestamp + rawBody` (timestamp first, per the WHOOP v2 spec). Returns
* true only when the timestamp is fresh AND the recomputed signature matches
* the `X-WHOOP-Signature` header byte-for-byte under a constant-time compare.
*/
export function verifyWhoopSignature(args: {
rawBody: string;
signature: string | null;
timestamp: string | null;
secret: string;
now?: number;
}): boolean {
const { rawBody, signature, timestamp, secret } = args;
if (!signature || !timestamp) return false;
const ts = Number.parseInt(timestamp, 10);
if (!Number.isFinite(ts)) return false;
const now = args.now ?? Date.now();
if (Math.abs(now - ts) > WHOOP_SIGNATURE_MAX_AGE_MS) return false;
const expected = createHmac("sha256", secret)
.update(timestamp + rawBody, "utf8")
.digest("base64");
const a = Buffer.from(expected, "utf8");
const b = Buffer.from(signature, "utf8");
if (a.length !== b.length) return false;
return timingSafeEqual(a, b);
}
interface WhoopWebhookBody {
user_id?: number | string;
id?: number | string;
type?: string;
}
/**
* Process an authenticated + signature-verified WHOOP notification. Resolves
* the `WhoopConnection` by `whoopUserId`, then either enqueues the matching
* per-resource sync job (`*.updated`) or soft-deletes the matching rows
* (`*.deleted`). The caller has already verified rate limit + path secret +
* HMAC signature and parsed the body.
*/
export async function processWhoopNotification(
body: WhoopWebhookBody,
): Promise<Response> {
getEvent()?.setAuth({ auth_method: "webhook_secret" });
const whoopUserId = body.user_id != null ? String(body.user_id) : null;
const type = typeof body.type === "string" ? body.type : null;
const resourceId = body.id != null ? String(body.id) : null;
if (!whoopUserId || !type) {
annotate({ action: { name: "whoop.webhook.ignored" } });
return NextResponse.json({ status: "ignored" }, { status: 200 });
}
const connection = await prisma.whoopConnection.findFirst({
where: { whoopUserId },
select: { userId: true },
});
if (!connection) {
// Unknown / disconnected user. Return 200 so WHOOP stops retrying.
annotate({ action: { name: "whoop.webhook.unknown_user" } });
return NextResponse.json({ status: "unknown_user" }, { status: 200 });
}
const [resource, verb] = type.split(".");
const queue = WHOOP_RESOURCE_QUEUE[resource ?? ""];
if (verb === "deleted") {
// Soft-delete every matching row for this user + WHOOP resource id.
// `externalId` is `<whoop-resource-uuid>:<field-tag>` so a `startsWith`
// match catches every measurement derived from the deleted resource.
if (resourceId) {
const now = new Date();
await prisma.measurement.updateMany({
where: {
userId: connection.userId,
source: "WHOOP",
externalId: { startsWith: `${resourceId}:` },
deletedAt: null,
},
data: { deletedAt: now, syncVersion: { increment: 1 } },
});
if (resource === "workout") {
// The Workout model carries no soft-delete column, so a deleted
// WHOOP workout is removed outright (keyed by the canonical
// `(userId, source, externalId)` unique).
await prisma.workout.deleteMany({
where: {
userId: connection.userId,
source: "WHOOP",
externalId: resourceId,
},
});
}
}
annotate({
action: { name: "whoop.webhook.deleted" },
meta: { resource: resource ?? "unknown" },
});
return NextResponse.json({ status: "ok" }, { status: 200 });
}
if (!queue) {
// A resource type with no webhook-driven sync queue (e.g. cycle is
// poll-only). Acknowledge so WHOOP doesn't retry.
annotate({
action: { name: "whoop.webhook.no_queue" },
meta: { resource: resource ?? "unknown" },
});
return NextResponse.json({ status: "ignored" }, { status: 200 });
}
// `*.updated` (creates arrive as updates too). Enqueue the per-user
// resource sync; the worker re-fetches by id (payload carries no data).
const boss = getGlobalBoss();
if (!boss) {
getEvent()?.addWarning("whoop-webhook: pg-boss not initialised");
return NextResponse.json({ status: "ok" }, { status: 200 });
}
await boss.send(queue, { userId: connection.userId });
annotate({
action: { name: "whoop.webhook.enqueued" },
meta: { resource: resource ?? "unknown" },
});
return NextResponse.json({ status: "ok" }, { status: 200 });
}
+17 -1
View File
@@ -21,6 +21,11 @@ const PUBLIC_PATHS = [
"/api/monitoring/",
"/api/send",
"/api/withings/webhook",
// v1.11.0 — WHOOP webhook (`recovery.updated` / `sleep.updated` /
// `workout.updated`, + `*.deleted`). Authenticated by the path-segment
// secret + the HMAC body signature, never by a session cookie, so it
// must bypass the auth gate (mirrors the Withings webhook entry).
"/api/whoop/webhook",
"/api/telegram/webhook",
"/api/integrations/moodlog/webhook",
"/api/ingest/",
@@ -289,6 +294,17 @@ export function proxy(request: NextRequest) {
const withingsConnectSrc = isWithingsRoute
? " https://wbsapi.withings.net"
: "";
// v1.11.0 — `api.prod.whoop.com` gated to the WHOOP settings surface +
// `/api/whoop/*`, mirroring the Withings gating shape. The WHOOP data
// client lives server-side and the OAuth handshake is a browser
// redirect (not a fetch), so this is belt-and-suspenders parity — no
// other surface ever needs to reach the WHOOP host from the browser.
const isWhoopRoute =
pathname.startsWith("/settings/integrations/whoop") ||
pathname.startsWith("/api/whoop/");
const whoopConnectSrc = isWhoopRoute
? " https://api.prod.whoop.com"
: "";
// v1.5.5 — Gravatar host removed from `img-src`. The /me payload
// used to return `gravatarUrl: https://www.gravatar.com/avatar/<sha256(email)>`,
// which leaked the email digest to Automattic on every authenticated
@@ -297,7 +313,7 @@ export function proxy(request: NextRequest) {
// them.
const csp = isDev
? `default-src 'self'; script-src 'self' 'unsafe-eval' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; font-src 'self';`
: `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'${aiConnectSrc}${withingsConnectSrc}; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; worker-src 'self'; report-uri ${cspReportEndpoint}; report-to csp-endpoint;`;
: `default-src 'self'; script-src 'self' 'nonce-${nonce}'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'${aiConnectSrc}${withingsConnectSrc}${whoopConnectSrc}; font-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'; worker-src 'self'; report-uri ${cspReportEndpoint}; report-to csp-endpoint;`;
response.headers.set("Content-Security-Policy", csp);
// Production-only headers. HSTS carries `preload` so the domain stays