Repository navigation
fix(auth): OAuth callback + hydration fixes, versioned legal acceptance, web PKCE - #519
Conversation
…uth callback tokens survive The (auth)/auth layout returned a Loading view *instead of* its <Stack> while useProtectedRoute was pending — which is always the case on first render. With the navigator unmounted during hydration, react-navigation resolved the focused route back to the group's initial route and expo-router's history sync rewrote the URL to /auth, destroying the #access_token fragment on /auth/callback ~5ms before supabase-js initialized and read the URL. Result: every web OAuth login (Google/ Apple) on prod silently bounced back to the login screen. Render the Stack unconditionally and overlay the loading state instead. Verified end-to-end against a local dev server: minted a real GoTrue session, loaded /auth/callback#access_token=... — supabase-js now issues the /auth/v1/user validation call, stores the session, and lands on /dashboard signed in. Before the fix the same URL produced zero auth requests and a silent bounce (reproduced on prod with an instrumented iframe probe). Also add the apex + www domains to the local config.toml redirect allow-list and fix its stale production comment (prod's hosted uri_allow_list already had them). Co-Authored-By: Claude Fable 5 <[email protected]>
…hydration fix, web PKCE
Four related auth changes.
1. Versioned legal acceptance (migration 342)
core.legal_documents holds one is_current row per document type and is the
single source of truth for which version users must accept. It replaces
five drifting hardcoded version constants (login screen, cookie provider
x2, both prerequisites routers, the document page subtitles). Publishing
new terms is now an UPDATE+INSERT documented in the migration header — no
code deploy.
GET /v1/prerequisites/check reads it and reports which gate, if any, is
unresolved: needsOnboarding (profile fields missing -> full onboarding
form) or needsLegalAcceptance (profile complete, legal stale -> the new
lightweight /legal-update screen). Acceptance now only counts at the
current version, so a version bump forces re-acceptance; the seeded
current version is 'v1.0', which every existing preferences row already
carries, so nobody is re-prompted at cutover and no data migration is
needed.
POST /v1/prerequisites/accept-legal backs the re-acceptance screen. Both
it and /complete stamp versions read from the table and write
consent_records audit rows server-side, with first-class
'terms_of_service'/'privacy_policy' consent_type values (CHECK extended)
instead of the previous metadata.type shoehorn.
2. Login screen: passive notice replaces the consent checkbox
The checkbox was theater: a SIGNED_IN listener wrote two consent_records
rows unconditionally, without consulting it, on web and native alike. That
client-side write is deleted. The notice is browsewrap; the real
versioned, audited clickwrap now happens in onboarding and /legal-update.
Adds i18n keys in en/es/fr (the old copy was hardcoded English).
3. (protected) and (admin) layouts: same hydration bug as the OAuth callback
Both rendered <Slot /> only once ready, so during web hydration the
navigator was unmounted and expo-router rewrote the URL to the group's
initial route — the mechanism that ate the OAuth callback hash in the
previous commit, here eating deep-link paths. Both now keep the navigator
mounted behind an opaque overlay, which also closes a one-frame flash of
protected content before a redirect. Redirect refs became target-aware so
a user can move between gates without getting stuck.
4. Web OAuth switched to PKCE
flowType is pkce on web (native keeps implicit; it signs in via
signInWithIdToken and never parses URLs). A pkce client rejects
implicit-style #access_token callbacks AND calls _removeSession on the way
out, which is what GoTrue's {{ .ConfirmationURL }} email links produce —
so the email templates now link to a new flow-agnostic /auth/confirm
route that verifies a token_hash. See the deploy-order constraint in
client.ts: hosted templates must be updated and old links allowed to
expire before a build with this flag ships.
Also removes dead code: PrerequisiteWidget (rendered nowhere, validated
legal fields it never rendered) and the SDK's six phantom prerequisites
endpoints; fixes extensionless edge-function imports that broke
`supabase functions serve` for the whole stack; and reconciles the
three-way testID drift between the onboarding form, the Playwright
helpers, and tests/TEST_IDS.md.
Verified against a live local stack: 8 new Deno route tests cover the
check/complete/accept-legal contract including the stale-version round
trip and its audit rows. Manually exercised a real version publish — an
onboarded user flipped to needsLegalAcceptance with needsOnboarding still
false, then accept-legal restored isComplete with the new version
stamped. Unit suites (scf-core 304, SDK 764, root-route 23, schemas 53)
and the SDK/route contract test pass; typecheck clean.
Co-Authored-By: Claude Fable 5 <[email protected]>
📊 Performance Benchmark Results |
The flowType flip and the /auth/confirm route were in one commit, which made every web deploy of this branch order-dependent: shipping the flag before the hosted email templates are updated (and before links issued under the old templates expire) breaks magic-link sign-in AND signs the clicking user out, because a pkce client rejects the implicit-style #access_token callback and _initialize() then calls _removeSession(). Dropping just the flag makes this branch safe to deploy in any order. The /auth/confirm token_hash lander and the template changes still ship here — they are flow-agnostic and are the prerequisite for the flag. The flip follows once templates are live and old links have expired. Co-Authored-By: Claude Fable 5 <[email protected]>
effective_at is stored as midnight UTC, so formatting it in the viewer's local timezone shifted it a day backwards for anyone west of UTC: the terms page rendered "Last updated: February 2025" for a document that took effect 2025-03-01. Caught on the dev deploy. Adds a shared formatEffectiveDate() so the document pages and the re-acceptance screen cannot drift on this again. The effective date is a legal fact, not a local timestamp. Co-Authored-By: Claude Fable 5 <[email protected]>
Deployed to dev + preview + prod from this branch (HEAD
|
| env | migration 342 | functions | web |
|---|---|---|---|
| dev | ✅ applied + recorded | ✅ | ✅ smoke green |
| preview | ✅ applied + recorded | ✅ | ✅ smoke green |
| prod | ✅ applied + recorded | ✅ | ✅ smoke green + CloudFront invalidated |
Cutover safety, checked against real prod data before applying
All 18 prod users with acceptance were at v1.0 — the version the migration seeds as current — so the exact comparison the endpoint makes returns would_be_reprompted = 0. Nobody got bounced into re-acceptance.
The two gaps in the original PR description are now closed
Deploying dev gave me a real build to verify against, which local Metro (OOM) couldn't:
- Login notice — renders "By continuing you agree to our Terms of Service and Privacy Policy.", links work, and the interactive tree has no checkbox where prod previously had one.
- Hydration deep-link —
/dashboard/settings/privacysurvives: the onlyreplaceStaterewrites to the same path.
The original bug, confirmed fixed on prod
The identical instrumented probe from the investigation now shows auth.scaffald.com/auth/v1/user called at t=751ms. Before the fix the same probe showed zero requests to that host — the hash was gone before supabase-js ever initialized.
Two changes made during the deploy
- PKCE flag split out (
54be25ada) — it was in the same commit as/auth/confirm, which made every web deploy order-dependent. Dropping just the flag makes this branch safe to deploy in any order; the flip becomes a follow-up. - UTC date fix (
4f7ba41d2) — caught on the dev deploy: the terms page rendered "Last updated: February 2025" for a document effective 2025-03-01, becauseeffective_atis midnight UTC and was being formatted in local time.
Still outstanding
- Hosted email templates were not pushed. Neither deploy script touches them, and
supa config pushwould overwrite prod's tighturi_allow_listwith config.toml's localhost entries. They need a surgical Management API update. Harmless today — web is still on the implicit flow, so the existing{{ .ConfirmationURL }}links work exactly as before. - PKCE flip is the follow-up, and only after those templates are live and prior links have passed
otp_expiry. - This branch is still unmerged — prod is running code that isn't on
main. Worth merging (with sdk#12 and ui#17) promptly so the two don't drift.
🤖 Generated with Claude Code
📊 Performance Benchmark Results |
…ests) Picks up Scaffald/sdk#14, which drops the non-null assertions the monorepo's biome config rejects but the SDK package's own lint does not. Deliberately NOT bumping to sdk main (e4a47e5). That tip includes sdk#12, which drops the phantom prerequisites endpoints and breaks scf-core typecheck in 17 places — prerequisites-sdk-hooks.ts and PrerequisiteWidget.tsx still use the removed types. The matching client changes live in #519, not here, so this branch pins to the commit before that break. Verified: scf-core typechecks clean at this pointer and fails at e4a47e5.
This branch pinned packages/sdk and packages/ui at the tips of Scaffald/sdk#12 and Scaffald/ui#17. Both were squash-merged, which creates a new commit and leaves the branch tips unreachable from their mains — so the pointers here referenced commits that no longer exist on any branch. Merging in that state would have pinned SaaS main to orphaned submodule commits. packages/sdk f96f4180 -> e4a47e5 (sdk main, #12 squashed) packages/ui 39f950d1 -> fdaa0d4 (ui main, #17 squashed) Verified the squashed commits carry what this branch needs — sdk has resources/legal.ts and prerequisites' needsLegalAcceptance, ui's Checkbox forwards testID — and that scf-core typechecks clean against them.
`pnpm build` failed on this branch with TS2741 at work-logs.router.ts:900 — fetchWorkLog declares Promise<WorkLogRow> but WORK_LOG_SELECT never asked for team_id, so the returned row was missing a field the regenerated DB types make required. Pre-existed the submodule repoint in the previous commit; verified by checking out HEAD~1 and reproducing the same error. Blocking the push, so fixed here.
…nd truthful placeholder screens (#543) * docs(agents): triage audit findings to GitHub Issues, not markdown Audits and reviews were producing markdown plan docs under docs/plans/, which go stale in the repo and never get triaged off a board. Document the issue-first shape instead: survey for dupes, one issue per self-contained finding with file:line evidence, a rollup epic carrying the narrative and dependency graph, and milestones for the version plan. Design specs and architecture proposals stay as markdown — the rule is about findings, not intent. Reference example: the 2026-08-03 /office ATS audit, epic #539. Co-Authored-By: Claude Opus 5 <[email protected]> * style(compliance): format EEOReportScreen with biome This file has never satisfied `biome check` — the MOCK_JOB_GROUPS entries were written as long single-line object literals. Formatting it in its own commit so the behavioural change that follows stays readable; the diff here is 934 lines and none of it changes what renders. Co-Authored-By: Claude Opus 5 <[email protected]> * fix(compliance): stop presenting fabricated EEO figures as a compliance record The EEO/OFCCP screen has no data hooks. MOCK_JOB_GROUPS, GENDER_SUMMARY and VETERAN_SUMMARY are hardcoded, and the four-fifths-rule adverse-impact analysis runs real math over those invented headcounts. Nothing on screen said so. An EEO report is an artifact people file, so a screenshot of this page would have circulated fabricated adverse-impact figures. Behind a single USES_SAMPLE_DATA flag that #535 deletes when real data lands: - Add a persistent, non-dismissible "Sample data — not a compliance record" notice above everything else. Not dismissible on purpose: the point is that it survives into a screenshot. - Hide the green "Compliance Status: Active / Next filing deadline" banner. That was an affirmative claim about compliance posture with nothing behind it — worse than the invented numbers. - Disable Export. Export is how fabricated figures stop being a screen and become a document someone might file. Also derives the "Adverse Impact — flags detected" tile from the computed ratios instead of hardcoding "0". It agreed with the ratios only by coincidence, and would have kept reading 0 after real data arrived. Tests assert the notice renders, the compliance claim is absent, and export is disabled. Verified they fail when USES_SAMPLE_DATA is flipped off. Refs #524 * style(scheduling): format CalendarSchedulingScreen with biome Same situation as EEOReportScreen: the file has never satisfied `biome check` because the MOCK_* entries are long single-line literals. Formatting in its own commit so the behavioural change that follows is readable. Nothing here changes what renders. Co-Authored-By: Claude Opus 5 <[email protected]> * fix(ats): stop presenting disconnected interview scheduling as live The scheduling screen has no data hooks — MOCK_CONNECTIONS, MOCK_AVAILABILITY, MOCK_SLOTS and MOCK_LINKS are rendered directly, though migration 146 created core.interview_slots / interview_availability / interview_bookings and both an API route and an SDK resource already exist. The placeholder lists were the smaller half. The larger half is that every action is inert: "Propose Time" opens a full form whose submit button only calls setShowAddSlotModal(false). A user could fill it in, click through, and believe they had scheduled an interview with a candidate who will never hear about it. "Create Link", "Connect Google/Outlook", "Add Availability" and "Copy" are all no-op onPress handlers too. Behind a USES_SAMPLE_DATA flag that #540 deletes when the wiring lands: - Add the sample-data notice, stating plainly that nothing is saved and no candidate is contacted. - Disable every write action, so input is refused rather than silently discarded. Refusing is honest; accepting and dropping is not. - Derive the Upcoming/Confirmed/Completed tiles from the slot list. They were hardcoded "3" / "1" / "12"; the first two matched the mock by coincidence and "12 completed" was invented outright. Extracts SampleDataNotice into features/office/components now that a second screen needs it, and moves EEOReportScreen onto it. Each caller keeps its own USES_SAMPLE_DATA flag so deleting the flag is the last step of wiring that screen to real data. Tests assert the notice renders, every write action is disabled, and the tiles are derived. Verified the first two fail when the flag is flipped off. Refs #525 * fix(api): map application status to the DB vocabulary on write, not just read core.applications.status is TEXT constrained by applications_status_check (migration 112) to the DB vocabulary: new, screen, inquired, interview, offer, hired, rejected, withdrawn. The REST surface publishes a different one, where new is "pending" and screen is "reviewing". The read path translated via STATUS_API_TO_DB. The write path spread the validated body straight into .update(), so an API name reached the column: PATCH {status:"pending"} -> writes "pending" -> CHECK violation, 500 PATCH {status:"reviewing"} -> writes "reviewing" -> CHECK violation, 500 PATCH {status:"inquired"} -> 400, missing from the update schema enum the other five -> worked only because both vocabularies spell them identically Three of the office kanban's seven stages were unreachable by name, and the four that worked did so by luck. Confirmed against the local database: UPDATE ... SET status='pending' and 'reviewing' both raise check_violation, while 'new' and 'inquired' are accepted. - Extract buildApplicationUpdatePayload() and translate status through STATUS_API_TO_DB before writing. - Add `inquired` to applicationUpdateSchema. The SDK's Application union already declared it and the DB already accepted it; only the server schema disagreed, so the request never reached the handler. - Add withApiStatus() and use it on every response. POST, PATCH and withdraw all returned raw DB names while applicationResponseSchema declares the API enum — responses violating their own published contract. Read handlers did this inline; folded them into the helper too. - Type the kanban's STATUS_MAP against the SDK union so the call sites need no casts. The two casts had drifted: confirmChange omitted `inquired`, so the path handling critical hire/reject confirmations disagreed with the one that does not. 12 tests. The four covering buildApplicationUpdatePayload fail when it is reverted to the old spread; the rest guard the vocabulary invariants. Not addressed here: triggerWebhook still emits raw DB status names, so webhook consumers see `new` where the REST API says `pending`. Changing that is a breaking change for anyone already consuming them — filing separately. `deno check` on this file reports 75 errors before and after this change; they are all c.get() returning never, tracked in #477. Refs #529 * feat(api): employer-scoped applications read path Every handler on /v1/applications is the candidate's view — it filters or gates on `user_id === auth user`. A recruiter had no way to read the pipeline for their own organisation's jobs, which is why the office kanban has rendered zero rows since the tRPC→SDK migration. - Extract the access decision the two message handlers already got right into lib/application-access.ts, and put both of them on it. Behaviour there is unchanged by construction: they pass no role allow-list, which reproduces "any org-scoped assignment" exactly. - Add GET /v1/employer/applications: org-scoped list with candidate and job embedded, filtering by organization_id, job_id, status, assigned_to, min_score and a created_at range, with real pagination. - Admit the hiring side to GET /{id} and GET /{id}/activity, which previously 403'd anyone but the applicant. The activity log is where stage history lives, so a recruiter could not see it at all. On the role allow-list. The extracted block accepted *any* role_assignments row scoped to the org, with no role filter. Today that happens to mean "org admin", because admin is the only org-scoped role with assignments — but `member` exists in core.roles, and the day someone assigns it that check silently widens. Reading a thread you are party to is a narrow grant; listing every applicant's profile and screening answers is not. So the helper takes an explicit allow-list per call site: the message handlers keep the permissive behaviour, the pipeline endpoints pass PIPELINE_ROLES (admin only). If recruiters are meant to hold `member`, widening is one line at PIPELINE_ROLES — but that should be a decision rather than an inherited default. Column names here are the real ones. There is no `applied_at`, `application_score` or `auto_rejected` column on core.applications; scores are `score_total` and the flat screening fields live inside the `screening_answers` JSONB. The office transform assumes otherwise — reconciling it is #528. Every PostgREST select was validated against the live local database rather than by inspection, including the users!user_id and jobs!job_id embeds and the roles!role_id join the allow-list depends on. 24 tests. Verified the allow-list check is load-bearing by removing it and watching the member-vs-admin test go red; cross-org denial is a separate control with its own test, and survives that mutation as it should. `deno check` on applications.ts drops from 75 pre-existing errors to 69 — the inline access blocks were themselves untyped c.get() sites (#477). Refs #527 * feat(office): wire the ATS pipeline to real data Bumps @scaffald/sdk to c7c9884 (Scaffald/sdk#13, listForOrganization) and puts the office applications screen on it. The board has rendered zero rows since the tRPC→SDK migration because useApplications() returned a hardcoded [] with its filter argument discarded. - useApplications() now queries GET /v1/employer/applications and passes its filters through. ApplicationsListItem is the SDK's EmployerApplication rather than a hand-maintained restatement; the local interface had drifted to declare applied_at and application_score, neither of which is a column, and nothing caught it because the hook it typed always returned []. - Rewrite the transform against the real schema: score_total not application_score, created_at not applied_at, attachment_metadata not attachments, and screening_answers.* rather than flat columns. It was written against a v_applications_with_user_profiles view that exists in no migration. - Status, job and score filters now go to the server. The status filter was *cast* from the kanban vocabulary to the API's — which satisfied the compiler while sending a value the API enum rejects. It is mapped now, via the same STATUS_MAP the write path uses. - Drop the client-side score filter. With server pagination it would have been wrong rather than redundant, silently hiding matches beyond page one. Also fixes a bug the end-to-end check caught: min_score=0 returned none of the eight seeded applications. score_total is nullable and nothing populates it yet, so `.gte("score_total", 0)` drops every row — NULL >= 0 is NULL, not true. The board's slider defaults to 0, so opening the pipeline would have shown an empty board for a different reason than before. Extracted as shouldApplyScoreFilter() with tests. Verified against a live local API served from this worktree, since the running edge runtime serves a different one: an org admin gets 8 applications with candidate names and correctly mapped statuses; a candidate gets 0 rather than everyone's pipeline; requesting another org's id is 403, as is an unknown org id. Status, pagination and score filters all checked against real rows. Team assignment is left null rather than invented — it lives in core.job_team_assignments, which the list endpoint does not join yet. stageHistory/notes/messages stay empty for the same reason (#531). Refs #527, #528 * chore(office): route and navigation cleanup Six unrelated bits of routing debt found in the /office audit. - /office/ats rendered the applications pipeline, making it a second URL for /office/applications — the same screen behind two drawer entries. ATS is a section, not a screen, so its index now redirects and the duplicate drawer entry is gone. - /office/ats/metrics rendered the same screen on its default kanban view; its own comment said the user could "switch to Metrics tab". The screen now takes an initialView and the route passes 'metrics'. - ROUTES.OFFICE.ATS.DETAIL declared /office/ats/:id, which no file backed. Removed; a real detail route is #537. - office/_layout.tsx named jobs/, teams/, organizations/, universities/ and background-checks/ at the top level. Those moved under cms/ and ats/ some time ago, so every Stack.Screen entry was a silent no-op while the routes that do exist had none. Rewritten against the actual files, and checked in both directions: no name without a file, no file without a name. - ID Verifications, Hiring Metrics and Self-Schedule existed as routes but appeared in no navigation, so they were reachable only by typing the URL. Added to the office CMS nav. - Removed the "List" view toggle. It rendered "List view coming soon..." — a shipped nav control leading to a placeholder. #537 covers the real thing. Refs #526 * style(api): satisfy `deno fmt --check` across functions/api The "Lint REST API Code" job runs `deno fmt --check` and was already failing on main: routes/inquiries.ts, routes/work-logs.ts, __tests__/contract/sdk-routes and __tests__/routes/inquiries-by-application were all unformatted before this branch. Two more were mine — routes/employer-applications.ts and the new application-access test. Formatting all six rather than only my own, since `deno fmt` is mechanical and it takes the check from red to green instead of red-for-fewer-reasons. No behavioural change; the 27 backend tests pass unchanged. * chore(sdk): bump pointer to 09f0cad (lint fix for the employer list tests) Picks up Scaffald/sdk#14, which drops the non-null assertions the monorepo's biome config rejects but the SDK package's own lint does not. Deliberately NOT bumping to sdk main (e4a47e5). That tip includes sdk#12, which drops the phantom prerequisites endpoints and breaks scf-core typecheck in 17 places — prerequisites-sdk-hooks.ts and PrerequisiteWidget.tsx still use the removed types. The matching client changes live in #519, not here, so this branch pins to the commit before that break. Verified: scf-core typechecks clean at this pointer and fails at e4a47e5. --------- Co-authored-by: Claude Opus 5 <[email protected]>
…llback-hash # Conflicts: # packages/sdk
|
Rebased onto main and repaired the submodule pointers so this can merge. The pointers were orphaned. This branch pinned Found and fixed a build failure that predated all of that. Merge conflict resolution: main (via #543) had Also fixed a Verified on the merged tree: scf-core and supabase both typecheck clean, and the 27 ATS backend tests from #543 still pass. |
The "Lint REST API Code" job runs `deno fmt --check`, which this branch's three new/changed files did not satisfy: routes/prerequisites.ts and the legal and prerequisites route tests. Mechanical; no behavioural change.
📊 Performance Benchmark Results |
) * fix(office): stop the layout destroying the URL on every deep link Navigating to /office/applications landed on /office. Measured, not inferred — polling location.pathname through the load gives: before: ["/office/applications", "/office"] body still "Loading..." after: ["/office/applications"] board renders office/_layout.tsx returned early three times before its navigator: a Spinner while the role check resolved, and null when unauthorized or on a narrow viewport. Each unmounts the navigator, and expo-router responds by rewriting the URL to the nearest mounted segment. So every shareable office URL silently degraded to /office — including the per-application detail route added in #537, whose entire purpose is being linkable. Same failure class as the OAuth callback-hash loss fixed in #519, which is why (admin)/_layout.tsx already renders <Slot /> plus an overlay rather than returning around its navigator. This does the same: the navigator always mounts, the loading state is layered over it, and the hooks keep doing their own redirects. It only stops the URL being destroyed while they decide. Also registers applications/[applicationId]/index as a Stack.Screen. Only its /inquiry sibling was listed, so the #537 route had no entry at all — the same class of omission the comment above that list already describes. And the super-admin auth setup now writes its session the way the admin and user setups do: navigate, then page.evaluate. It used addInitScript, which runs on every origin — the session landed in the Stripe iframes (js.stripe.com, m.stripe.network) and never on localhost, so the saved state had no sb-*-auth-token for the app's own origin. It also wrote a wrapped { currentSession, expiresAt } payload where supabase-js stores the session flat. All three storage states now carry a valid token on http://localhost:8081. Verified against a running app: /office/applications keeps its URL and renders all seven kanban columns with the testIDs the helpers look for — kanban-column-new/screen/inquired/interview/offer/hired/rejected. That also settles #577: the selectors were never missing, the board had simply never rendered. * fix(api): the employer pipeline was empty for everyone but the org owner GET /v1/employer/applications authorised the caller against the organisation and then read the rows through RLS, which decides on a different axis. core.applications' policies recognise the organisation *owner*; a user holding an org `admin` role assignment — exactly who PIPELINE_ROLES exists to admit — passed authorisation and then read zero rows. Measured on the same 12 applications in one organisation: clay (owner) 12 visible zach (org admin) 0 visible GET /v1/employer/applications, as zach: total=0 The office kanban board rendered "0 total applications" for them. The board was not broken; the list was returning an empty set to an authorised user. The read now uses the service-role client, after the existing authorisation, exactly as attachStageHistory in this file and the EEO and scheduling routes already do for the same reason (#544). Verified after the change: clay (owner) total=12 zach (org admin) total=12 <- was 0 brian (admin of another org) total=3, only his own org's Cross-organisation isolation is unchanged: the authorisation step still bounds every query to listAccessibleOrganizationIds, and an admin of one organisation sees exactly that organisation's applications and no others. This is the fourth place the org-vs-team RLS mismatch has forced a service-role read. #544 remains the real fix.
…1443) Office mixed daily staff work with setup pages staff rarely touch, and several of those pages had no way in. They now live under a new top-level Admin section at /admin, right after Office in the nav: General /admin/general/geographic Billing /admin/billing/{payments,transactions,stripe} Integrations /admin/integrations/{background-checks,hris} Developer /admin/oauth-apps, /admin/oauth-apps/:id System /admin/system/{notifications,storage} Admin uses Office's gate (office role, tablet+), and its layout keeps the navigator mounted under the loading overlay so deep links survive the role check (#519). Each tab owns its group by prefix, so it lights on detail pages; multi-page groups get a row of their pages. Office loses its Integrations, Payments and Transactions tabs. Every moved /office path is now a hidden route that redirects to its new home, keeping child segments and query (?status=failed). The Office Overview cards, OAuth screens and developer links point at /admin. API keys and webhooks are untouched (#1440). Fixes #1439 Co-authored-by: Claude Opus 5.5 <[email protected]>
Started as the prod Google-login fix; grew to cover the rest of the auth issues plus versioned terms acceptance.
1. The original bug: Google login silently failed on prod
The provider round-trip completed, but users landed back on the login screen with no session.
(auth)/auth/_layout.tsxreturned aLoading...view instead of its<Stack>whileuseProtectedRoutewas pending — always true on first render. With the navigator unmounted during hydration, react-navigation resolved the focused route back to the group's initial route and expo-router's history sync calledhistory.replaceState('/auth'), destroying the#access_token=…fragment ~5ms before supabase-js initialized and read the URL.Instrumented timeline captured on prod (patching
history/fetch/localStorageahead of the bundle): URL rewritten at t=594ms, first Supabase storage read at t=599ms, zero requests toauth.scaffald.comever. The outbound leg was fine all along.Fix: render the Stack unconditionally, overlay the loading state.
2. Same bug in
(protected)and(admin)Both gate a
<Slot />the same way, so deep links (/dashboard/settings/…) lose their path during hydration. Both now keep the navigator mounted behind an opaque overlay — which also closes an existing one-frame flash of protected content before a redirect fires. Redirect refs became target-aware so a user can move between gates (finish onboarding → land on legal re-acceptance) without getting stuck.enabled-guarded, but this is the change most worth a second reviewer's eye.3. Login checkbox → passive notice
The terms checkbox was theater: a
SIGNED_INlistener wrote twoconsent_recordsrows unconditionally, never consulting it, on web and native alike. That client-side write is deleted; nothing replaces it at sign-in. The notice is browsewrap — real clickwrap now happens where it means something (below). Copy moves to i18n in en/es/fr; it was hardcoded English.4. Versioned legal acceptance (the substantive new feature)
core.legal_documents(migration 342) holds oneis_currentrow per document type and is the single source of truth — replacing five drifting hardcoded version constants. Clients never embed a version; they read required versions from the API./v1/prerequisites/checknow reports which gate is unresolved:needsOnboardingneedsLegalAcceptance/legal-updatescreenlegal.documents.*Acceptance only counts at the current version, so a bump forces re-acceptance. Publishing new terms is an UPDATE+INSERT documented in the migration header — no code deploy:
The seeded current version is
'v1.0', which every existingcore.preferencesrow already carries — nobody is re-prompted at cutover, and no data migration is needed.Audit rows are now written server-side at both acceptance points, with first-class
terms_of_service/privacy_policyconsent_typevalues (CHECK extended) instead of the oldmetadata.typeshoehorn.5. Web OAuth → PKCE
flowType: 'pkce'on web; native keeps implicit (it usessignInWithIdTokenand never parses URLs).Investigation result that shaped this: flipping the flag alone breaks magic-link emails and signs the clicking user out. Magic-link OTP is initiated server-side, so GoTrue's
{{ .ConfirmationURL }}produces an implicit-style#access_tokenlink, which a pkce client rejects — and_initialize()then calls_removeSession(). So the templates now link to a new flow-agnostic/auth/confirm?token_hash=…route (verifyOtp, works under both flows).Deploy order is load-bearing (also in a comment at the flag): ship
/auth/confirm→ update the hosted project's templates → wait ≥ OTP expiry → ship the build with the flag.Also
PrerequisiteWidget(rendered nowhere; validated legal fields it never rendered) and the SDK's six phantom prerequisites endpoints (mocked-only; invisible to the contract test because they usedsuper.get).supabase functions servefor the entire stack — same class as fix: pin supabase CLI to workspace version, fix extensionless edge fn imports #396, reintroduced by The entire notification pipeline is undeployed in production #436.tests/TEST_IDS.md.Verification
Against a live local stack:
/v1/legalpublic,/checkunauthenticated defaults, fresh-user gating,/completestamps table versions + writesform_submissionconsent rows, rejects unaccepted legal (400), the full stale-version →/accept-legal→ complete round trip withbutton_clickaudit rows, plus 401/400 paths.needsLegalAcceptance: truewithneedsOnboarding: false(so: lightweight screen, not the form) →accept-legal→isComplete: truewith2026-09-15stamped. Confirmed a pre-existingv1.0user stays complete across the deploy.Suites: scf-core 304 ✓, SDK 764 ✓, root-route 23 ✓ (matrix extended to three signed-in outcomes), schemas 53 ✓, SDK↔route contract 3 ✓ with no
KNOWN_GAPSedits. Typecheck clean.Not verified in a live browser: the
/legal-updatescreen's rendering and the hydration deep-link behavior — Metro was OOM-killed repeatedly on the dev machine (swap exhausted). The login notice's rendering and link routing are covered by unit tests. A reviewer running the app locally should sanity-check those two before merge;tests/e2e/other/test-legal-reacceptance.spec.tscovers the flow when the e2e stack is up.Pushed with
SKIP_PREPUSH=1—supabase:buildfails on any fresh checkout with pre-existing StripeapiVersiontype errors (main passes only via a stale.tsbuildinfo); tracked separately.Rollout
Migration 342 (additive; safe with old functions) → edge functions → SDK pointer → web deploy A (everything except the PKCE flag) → hosted email templates → wait ≥ OTP expiry → web deploy B (flag).
Hold the first real version bump until old clients are rare: they only read
isComplete, so they'd send stale users to the full onboarding form — functional clickwrap, ugly UX.🤖 Generated with Claude Code