Implement completeAuth chokepoint + caller migration
Implements all of unify-auth-completion (12/14 tasks done; manual
smoke + archive-time spec sync remain).
Design refinement during implementation: completeAuth supports two
response shapes via a `mode` parameter:
- mode: 'redirect' (loaders / direct browser navigation; auth.verify.tsx)
- mode: 'json' (action handlers called by imperative fetch from
client forms; api.auth.login, api.auth.register)
Both modes share createSession + safeReturnTo + Set-Cookie. JSON mode
carries `{ ok: true, step: "done", redirectTo }` (the `step` field
preserves the existing client-form check).
Why two modes: passkey ceremonies are inherently imperative
(start → browser WebAuthn API → finish), so action handlers can't
move to <Form>/useFetcher. Picking option (B) from the design grill —
the chokepoint owns destination selection while clients navigate —
required this dual shape. The 3 hardcoded client-side targets
(returnTo ?? "/", "/", "/?add-passkey=1") collapse into 1 server-side
sanitization pass (safeReturnTo) inside completeAuth.
New module:
- apps/journal/app/lib/auth/session.ts: cookie session storage
(sessionStorage, createSession, getSessionUser, destroySession)
moved from auth.server.ts. Legacy import path kept via re-exports
with @deprecated JSDoc.
- apps/journal/app/lib/auth/completion.ts: completeAuth + safeReturnTo.
- apps/journal/app/lib/auth/completion.test.ts: 10 contract tests
covering both modes, returnTo sanitization (path-relative, protocol-
relative, absolute-URL, malformed), Set-Cookie attachment, redirect
status, JSON shape.
Caller migration:
- api.auth.register.ts passkey-finish → completeAuth(json)
- api.auth.login.ts finish-passkey → completeAuth(json)
- api.auth.login.ts verify-code → completeAuth(json)
- auth.verify.tsx magic-link consumer → completeAuth(redirect)
Client form updates:
- auth.login.tsx: pass returnTo in fetch body, read result.redirectTo
on done.
- auth.register.tsx: pass returnTo: "/?add-passkey=1" for the magic-
link verify-code path (preserves the post-register passkey prompt
via the chokepoint's safeReturnTo, instead of hardcoding it
client-side).
Verified:
- pnpm typecheck && pnpm lint: green across all 15 workspaces.
- pnpm --filter @trails-cool/journal test: 126 passed.
- pnpm test:e2e auth: 4/4 passed without modification — confirms the
refactor is behaviour-preserving for the user-facing flows that
matter most (passkey register + login).
Spec delta in openspec/changes/unify-auth-completion/specs/ applies at
/opsx:archive time.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
7e22f1260b
commit
d64c47614d
12 changed files with 304 additions and 80 deletions
|
|
@ -40,8 +40,6 @@ ADRs already recorded:
|
|||
```ts
|
||||
async function completeAuth(input: {
|
||||
userId: string;
|
||||
isNewRegistration: boolean;
|
||||
termsVersion?: string; // required if isNewRegistration; ignored otherwise
|
||||
request: Request;
|
||||
returnTo?: string | null;
|
||||
}): Promise<Response>
|
||||
|
|
@ -49,7 +47,9 @@ async function completeAuth(input: {
|
|||
|
||||
Returns a `Response` (a `redirect` from React Router with the session `Set-Cookie` attached). Callers do `return await completeAuth(...)` from their action / loader. No headers-vs-redirect split: the chokepoint owns both halves.
|
||||
|
||||
`termsVersion` is optional at the type level but required-when-`isNewRegistration` at runtime. Asserting it inside the function (throw on `isNewRegistration && !termsVersion`) keeps the call sites tidy. Alternative: a discriminated union forcing the compiler to require `termsVersion` when `isNewRegistration: true`. Lean toward the runtime assertion — three call sites, two of which set `isNewRegistration: false` — the type ergonomics aren't worth the union complexity.
|
||||
**Terms recording is NOT in `completeAuth`.** Both registration paths already write `terms_version` + `terms_accepted_at` at user creation: `finishRegistration` writes them when the user row is inserted (passkey path); `registerWithMagicLink` writes them when the user row is inserted (magic-link path). Magic-link registration *must* write terms at user creation, before verification, because the user row exists between register and verify — if terms weren't already written, the Terms gate would bounce the user on first authenticated visit.
|
||||
|
||||
So `completeAuth` is purely **session + redirect**. No `isNewRegistration` flag, no `termsVersion` parameter. The earlier framing of an `isNewRegistration` discriminator was a mis-read — there is no code path that needs to record terms at completion time.
|
||||
|
||||
### Decision 3: File layout
|
||||
New directory `apps/journal/app/lib/auth/` containing:
|
||||
|
|
|
|||
|
|
@ -1,31 +1,31 @@
|
|||
## ADDED Requirements
|
||||
|
||||
### Requirement: Single web auth completion chokepoint
|
||||
Every successful web authentication flow — passkey register-finish, passkey login-finish, magic-link 6-digit-code verify, magic-link click-through verify — SHALL complete by calling a single `completeAuth` function at `apps/journal/app/lib/auth/completion.ts`. The function SHALL be the sole place where a successful web authentication records the accepted Terms version (only on registration), mints the cookie session, and constructs the redirect to `returnTo` (or `/` when absent or rejected).
|
||||
Every successful web authentication flow — passkey register-finish, passkey login-finish, magic-link 6-digit-code verify, magic-link click-through verify — SHALL complete by calling a single `completeAuth` function at `apps/journal/app/lib/auth/completion.ts`. The function SHALL be the sole place where a successful web authentication mints the cookie session and constructs the redirect to `returnTo` (or `/` when absent or rejected).
|
||||
|
||||
Per-method identity verification (WebAuthn ceremony, magic-token consumption, 6-digit-code consumption) SHALL run in its own function and produce a `userId` *before* `completeAuth` is invoked. `completeAuth` SHALL NOT know how identity was proved.
|
||||
|
||||
The Terms gate (root-loader redirect for cookie sessions; `requireApiUser` 403 for bearer-token API requests) SHALL remain the enforcement point for stale `terms_version`. `completeAuth` only **records** terms on new registrations; it does not enforce them.
|
||||
Terms recording happens at user creation time inside the per-method registration functions (`finishRegistration` for passkey, `registerWithMagicLink` for magic-link), not inside `completeAuth`. The Terms gate (root-loader redirect for cookie sessions; `requireApiUser` 403 for bearer-token API requests) SHALL remain the enforcement point for stale `terms_version`.
|
||||
|
||||
OAuth-code issuance at `/oauth/authorize` SHALL NOT be routed through `completeAuth` — that flow operates on an already-authenticated user and shares only the trailing redirect, not the full sequence.
|
||||
|
||||
#### Scenario: Passkey register-finish completes through the chokepoint
|
||||
- **WHEN** a visitor submits a successful WebAuthn `step: "finish"` registration response
|
||||
- **THEN** the route handler verifies the credential, creates the user row, and calls `completeAuth({ userId, isNewRegistration: true, termsVersion, request, returnTo })`
|
||||
- **AND** `completeAuth` writes `users.terms_version` and `users.terms_accepted_at`, mints the session cookie, and returns a `Response` redirecting to `returnTo` (or `/`)
|
||||
- **THEN** the route handler verifies the credential and creates the user row (with terms recorded) inside `finishRegistration`, then calls `completeAuth({ userId, request, returnTo })`
|
||||
- **AND** `completeAuth` mints the session cookie and returns a `Response` redirecting to `returnTo` (or `/`)
|
||||
|
||||
#### Scenario: Passkey login-finish completes through the chokepoint
|
||||
- **WHEN** a visitor submits a successful WebAuthn `step: "finish-passkey"` login response
|
||||
- **THEN** the route handler verifies the credential and calls `completeAuth({ userId, isNewRegistration: false, request, returnTo })`
|
||||
- **AND** `completeAuth` skips the terms write (only registrations record terms), mints the session cookie, and returns a `Response` redirecting to `returnTo` (or `/`)
|
||||
- **THEN** the route handler verifies the credential and calls `completeAuth({ userId, request, returnTo })`
|
||||
- **AND** `completeAuth` mints the session cookie and returns a `Response` redirecting to `returnTo` (or `/`)
|
||||
|
||||
#### Scenario: Magic-link 6-digit-code verify completes through the chokepoint
|
||||
- **WHEN** a visitor submits a valid 6-digit code via `step: "verify-code"`
|
||||
- **THEN** the route handler consumes the magic token (marks `used_at`) and calls `completeAuth({ userId, isNewRegistration: false, request, returnTo })`
|
||||
- **THEN** the route handler consumes the magic token (marks `used_at`) and calls `completeAuth({ userId, request, returnTo })`
|
||||
|
||||
#### Scenario: Magic-link click-through verify completes through the chokepoint
|
||||
- **WHEN** a visitor opens `/auth/verify?token=<token>` with a valid, unused, unexpired token
|
||||
- **THEN** the route handler consumes the magic token and calls `completeAuth({ userId, isNewRegistration: false, request, returnTo })`
|
||||
- **THEN** the route handler consumes the magic token and calls `completeAuth({ userId, request, returnTo })`
|
||||
|
||||
#### Scenario: returnTo is sanitized inside completeAuth
|
||||
- **WHEN** `completeAuth` is called with a `returnTo` value that is not a same-origin absolute path (e.g. starts with `//`, an absolute URL, or is malformed)
|
||||
|
|
|
|||
|
|
@ -1,27 +1,27 @@
|
|||
## 1. New auth module structure
|
||||
|
||||
- [ ] 1.1 Create `apps/journal/app/lib/auth/` directory.
|
||||
- [ ] 1.2 Create `apps/journal/app/lib/auth/session.ts` and move `sessionStorage`, `createSession`, `getSessionUser`, `destroySession` from `auth.server.ts` (preserve behaviour, including `process.env.SESSION_SECRET` source).
|
||||
- [ ] 1.3 In `auth.server.ts`, re-export the moved helpers from `./auth/session.ts` so existing imports keep working unchanged. Add a JSDoc `@deprecated`-style comment pointing at the new path.
|
||||
- [x] 1.1 Create `apps/journal/app/lib/auth/` directory.
|
||||
- [x] 1.2 Create `apps/journal/app/lib/auth/session.ts` and move `sessionStorage`, `createSession`, `getSessionUser`, `destroySession` from `auth.server.ts` (preserve behaviour, including `process.env.SESSION_SECRET` source).
|
||||
- [x] 1.3 In `auth.server.ts`, re-export the moved helpers from `./auth/session.ts` so existing imports keep working unchanged. Add a JSDoc `@deprecated`-style comment pointing at the new path.
|
||||
|
||||
## 2. completeAuth chokepoint
|
||||
|
||||
- [ ] 2.1 Write `apps/journal/app/lib/auth/completion.test.ts` (TDD red): scenarios for new-registration writes terms, non-registration skips terms, returnTo defaults to `/`, returnTo `//evil.com` rejected, returnTo `https://evil.com` rejected, response includes Set-Cookie.
|
||||
- [ ] 2.2 Create `apps/journal/app/lib/auth/completion.ts` exporting `completeAuth({ userId, isNewRegistration, termsVersion?, request, returnTo? }) → Promise<Response>` and a private `safeReturnTo(value)` helper. Implementation: assert `termsVersion` when `isNewRegistration`; if `isNewRegistration`, `recordTermsAcceptance(userId, termsVersion)`; `createSession(userId, request)`; `redirect(safeReturnTo(returnTo) ?? "/", { headers })`.
|
||||
- [ ] 2.3 Run completion tests green.
|
||||
- [x] 2.1 Write `apps/journal/app/lib/auth/completion.test.ts` (TDD red): scenarios for returnTo defaults to `/`, returnTo `//evil.com` rejected, returnTo `https://evil.com` rejected, response is a 302/303 redirect, response includes Set-Cookie naming `__session`.
|
||||
- [x] 2.2 Create `apps/journal/app/lib/auth/completion.ts` exporting `completeAuth({ userId, request, returnTo? }) → Promise<Response>` and a private `safeReturnTo(value)` helper. Implementation: `createSession(userId, request)`; `redirect(safeReturnTo(returnTo) ?? "/", { headers: { "Set-Cookie": cookie } })`. Terms recording is **not** here — both registration paths already record terms at user creation, so the chokepoint is purely session + redirect.
|
||||
- [x] 2.3 Run completion tests green.
|
||||
|
||||
## 3. Caller migration
|
||||
|
||||
- [ ] 3.1 `apps/journal/app/routes/api.auth.register.ts` passkey-finish branch — replace inlined session+redirect with `return completeAuth({ userId, isNewRegistration: true, termsVersion, request, returnTo })`. Drop now-unused imports.
|
||||
- [ ] 3.2 `apps/journal/app/routes/api.auth.login.ts` passkey `step: "finish-passkey"` branch — replace with `return completeAuth({ userId, isNewRegistration: false, request, returnTo })`.
|
||||
- [ ] 3.3 `apps/journal/app/routes/api.auth.login.ts` magic-link `step: "verify-code"` branch — replace with `return completeAuth(...)`.
|
||||
- [ ] 3.4 `apps/journal/app/routes/auth.verify.tsx` magic-link click-through consumer — replace with `return completeAuth(...)`.
|
||||
- [ ] 3.5 Confirm no other callers of `createSession` remain inside auth route handlers (they should all flow through `completeAuth`). `getSessionUser` and `destroySession` continue to be called directly from non-completion sites — that's expected.
|
||||
- [x] 3.1 `apps/journal/app/routes/api.auth.register.ts` passkey-finish branch — replace inlined session+redirect with `return completeAuth({ userId, request, returnTo })`. Drop now-unused imports.
|
||||
- [x] 3.2 `apps/journal/app/routes/api.auth.login.ts` passkey `step: "finish-passkey"` branch — replace with `return completeAuth({ userId, request, returnTo })`.
|
||||
- [x] 3.3 `apps/journal/app/routes/api.auth.login.ts` magic-link `step: "verify-code"` branch — replace with `return completeAuth(...)`.
|
||||
- [x] 3.4 `apps/journal/app/routes/auth.verify.tsx` magic-link click-through consumer — replace with `return completeAuth(...)`.
|
||||
- [x] 3.5 Confirm no other callers of `createSession` remain inside auth route handlers (they should all flow through `completeAuth`). `getSessionUser` and `destroySession` continue to be called directly from non-completion sites — that's expected.
|
||||
|
||||
## 4. Verification
|
||||
|
||||
- [ ] 4.1 `pnpm typecheck && pnpm lint && pnpm test` green.
|
||||
- [ ] 4.2 `pnpm test:e2e` (auth flows) green without modification — proves behaviour-preserving refactor.
|
||||
- [x] 4.1 `pnpm typecheck && pnpm lint && pnpm test` green.
|
||||
- [x] 4.2 `pnpm test:e2e` (auth flows) green without modification — proves behaviour-preserving refactor.
|
||||
- [ ] 4.3 Manual sanity: register with passkey locally, login with passkey, log out, re-login via magic-link 6-digit code, click-through magic link from `auth.verify.tsx`. Confirm session cookie set + correct redirect each time.
|
||||
|
||||
## 5. Documentation + follow-up
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue