mirror of
https://github.com/MBombeck/HealthLog.git
synced 2026-11-08 20:42:43 +00:00
The legacy OAuth state shape `${user.id}:${random16}` (v1.4.42-) put
the user id on both the URL state param and the `withings_state`
cookie. httpOnly + Secure + sameSite:lax shut the XSS exfiltration
surface, but the user id still leaked into any request-log entry
where the cookie is not redacted and into network-traffic captures
of the redirect. Cosmetic today; a future refactor flipping the
cookie to non-httpOnly would silently expose it.
The v1.4.43 security audit (L-1) recommended switching the state to
a fully-random nonce backed by a short-lived `(nonce -> userId)`
ledger row, with the callback resolving the user via the row rather
than parsing it out of the cookie. This change lands the migration
end-to-end:
- New `WithingsOAuthState` table (migration `0076`): nonce PK, userId
FK with cascade, createdAt default-now, expiresAt + index for the
cleanup sweep.
- `withings/connect` mints a 22-char base64url nonce
(`randomBytes(16).toString("base64url")` — 128 bits, OAuth 2.0
§10.10 recommended threshold), persists the row with a 10-minute
TTL, and sets the cookie to JUST the nonce (no user id).
- `withings/callback` verifies the cookie/URL pair byte-for-byte
(timing-safe), then looks up the row, asserts `expiresAt > now()`
AND `row.userId === session.user.id` (defence-in-depth — the audit
rec was to resolve user identity from the row; cross-checking it
against the session covers a stolen-cookie + cross-user scenario),
and deletes the row on every exit branch (single-use semantics, so
a replay of the same nonce fails the second time).
- Daily cleanup cron at 03:20 Europe/Berlin slots between the
audit-log cleanup (:15) and the mood-reminder cleanup (:25); the
helper module mirrors the audit-log-cleanup shape so the worker
contract is symmetric.
Tests:
- 3 unit cases pin the cleanup helper contract (deleteMany shape,
default-now branch, idempotent re-run).
- 2 unit cases pin the mint helper + constants (22-char base64url,
10-minute TTL, cookie name preserved across the deploy window).
- 5 integration cases pin the connect -> callback ledger lifecycle
end-to-end against real Postgres: row mint, no-credentials short-
circuit, single-use consumption + replay rejection, expired-row
rejection, cross-user mismatch rejection.
- The existing `withings-oauth.test.ts` integration cases updated to
reflect the new state shape; the legacy `${user.id}:${random32}`
assertion was the only test relying on the old contract.
Files: 12. Tests: 5076 -> 5108 (+32 unit; integration adds 5 cases
plus 2 case updates on the existing file).
82 lines
2.5 KiB
TypeScript
82 lines
2.5 KiB
TypeScript
/**
|
|
* Per-test helpers for the integration suite. The Postgres testcontainer
|
|
* is started ONCE in `global-setup.ts` and torn down at the end of the
|
|
* run, so test files only need:
|
|
*
|
|
* import { getPrismaClient, truncateAllTables } from "./setup";
|
|
*
|
|
* beforeEach(async () => { await truncateAllTables(getPrismaClient()); });
|
|
*
|
|
* No beforeAll(startTestDb) / afterAll(stopTestDb) is needed — the
|
|
* container is alive whenever the test file is loaded, and Vitest's
|
|
* worker inherits `process.env.DATABASE_URL` from globalSetup so the
|
|
* application's Prisma singleton (`src/lib/db.ts`) connects to the
|
|
* testcontainer transparently.
|
|
*/
|
|
import { prisma } from "@/lib/db";
|
|
import type { PrismaClient } from "@/generated/prisma/client";
|
|
|
|
/**
|
|
* The application's Prisma singleton. Tests use this so any code
|
|
* imported via `await import("@/lib/...")` shares the exact same client
|
|
* instance — no risk of a divergent connection pool reading stale
|
|
* truncation state.
|
|
*/
|
|
export function getPrismaClient(): PrismaClient {
|
|
return prisma;
|
|
}
|
|
|
|
/**
|
|
* Truncate every user-facing table in dependency-safe order using
|
|
* `TRUNCATE … RESTART IDENTITY CASCADE`. Call from beforeEach() to make
|
|
* tests independent. The list mirrors `prisma/schema.prisma` minus
|
|
* prisma-internal tables (_prisma_migrations).
|
|
*/
|
|
export async function truncateAllTables(client: PrismaClient): Promise<void> {
|
|
// CASCADE means we only need to enumerate the tables; FK chains are
|
|
// handled by Postgres. Listed alphabetically for diff stability.
|
|
const tables = [
|
|
"api_tokens",
|
|
"app_settings",
|
|
"audit_logs",
|
|
"auth_challenges",
|
|
"coach_conversations",
|
|
"coach_messages",
|
|
"coach_usage",
|
|
"data_backups",
|
|
"devices",
|
|
"feedback",
|
|
"host_metrics",
|
|
"idempotency_keys",
|
|
"integration_statuses",
|
|
"measurement_rollups",
|
|
"measurements",
|
|
"medication_intake_events",
|
|
"medication_schedules",
|
|
"medications",
|
|
"mood_entries",
|
|
"notification_channels",
|
|
"notification_preferences",
|
|
"passkeys",
|
|
"personal_records",
|
|
"push_subscriptions",
|
|
"rate_limits",
|
|
"refresh_tokens",
|
|
"reminder_phase_configs",
|
|
"sessions",
|
|
"telegram_reminder_messages",
|
|
"telegram_scheduled_deletions",
|
|
"user_achievements",
|
|
"users",
|
|
"withings_connections",
|
|
"withings_oauth_states",
|
|
"workout_routes",
|
|
"workouts",
|
|
];
|
|
|
|
const quoted = tables.map((t) => `"${t}"`).join(", ");
|
|
await client.$executeRawUnsafe(
|
|
`TRUNCATE TABLE ${quoted} RESTART IDENTITY CASCADE;`,
|
|
);
|
|
}
|