Auth — Verification & External Approvers
Feature Overview
Three connected concerns that share a single specification because their decisions interact:
- External approver authentication — how off-platform consultants (timesheet approvers, 360 reviewers) authenticate to act on a single item without holding a full PPP account
- AHPRA verification pipeline — how Australian medical registration is confirmed, cached, and re-validated
- Identity model — how a single PPP user maps to multiple sign-in methods (cross-references linked-accounts.md)
For the doctor-facing sign-in flow itself, see linked-accounts.md. For zero-trust route protection, see auth-zero-trust-routing.md.
Source
Rob & Matt call 13 Apr 2026 (transcript timestamps cited per section).
External Approver Authentication
Decision
External approvers authenticate via a time-limited isolation code, NOT username/password (#4827).
Why
- External approvers (consultant department directors, 360-review participants) are typically off-platform — forcing them to register an account creates friction and abandonment
- The previous email-link-only flow had security gaps that required significant lock-down
- A rotating code provides per-action authentication without persistent credentials, and is acceptable for the lighter actions external approvers need to perform
- Source: ~01:02:17 / 01:03:23
Acceptance Criteria
- ✅
auth.external.temp-code-no-password— External approvers (timesheet approvers, 360-review participants) MUST authenticate via a temporary isolation code delivered by email. No username, no password, and no persistent PPP account is required. † - ✅ When a timesheet or WBA is sent to an external approver, the email contains a one-time isolation code plus a deep-link to the action page
- ✅
auth.external.decision-identity— after redeeming a code the approver types their full name (remembered per lower-cased email, pre-filled next time) and approves or declines (a reason of 10+ characters is required to decline); the decision is stored as anaudit_trailrow withactor_type = 'external'carrying the typed name, email, time, IP address, browser, decision and reason. The live 360 reviewer link records the reviewer's typed name the same way. Not built: nothing issues a code for a WBA / 360 request yet, and an approve or decline changes no WBA record — open question: which WBA / 360 request mints a code, and what an approve or decline should change on it. † (#12531) - ✅ The code is valid for a configurable window (default 7 days, single-use) —
EXTERNAL_APPROVER_CODE_TTL_DAYSenv var (#7327) - ✅ The action page asks for the code on first entry, then sets a short-lived signed cookie scoped to that action only —
EXTERNAL_APPROVER_COOKIE_TTL_MIN(#7327) - ✅ No persistent account is created; no password is set
- ⏳ If the user wants to convert to a full PPP account they can do so via standard sign-up — independent flow
- ✅ Audit log captures: code generated, code redeemed, action taken —
external_approver_code_generated/external_approver_code_redeemed/external_approver_action_taken(#7327) - ✅ Codes are stored hashed; rate-limited by IP and recipient email — HMAC-SHA256(
EXTERNAL_APPROVER_CODE_SECRET), per-IP + per-email sliding windows (#7327) - ✅ The approver types their full name when confirming; the latest name is remembered per lower-cased email (
external_approvers) and pre-fills next time. Each confirmation writes anaudit_trailrow withactor_type = 'external'carrying name, email, time, IP and browser, andaudit_trail.user_idis null for it — engineering decision Rob 2026-10-04 (#12528, #12531); whether the approver also confirms email/position is an open question for Matt (#12529) - ✅
auth.profile-non-doctor.tier-level-scope-cross-ref— The org-admin SSO-eligibility set (enterpriseSso.ts § ORG_ADMIN_PERSONAS) and the persona scope checks (checkIsHospitalAdmin.ts, now keyed offgetPersonaTierLevelrather than enum literals) underapi/backend-ppp/src/services/auth/**are auth-domain code, but the underlyingtier_levelinteger hierarchy (re-parentable org tiers, shipped in #7876) is governed byprofile-non-doctor.md. The acceptance criteria for the tier-level model and the org-admin persona tiers are maintained there — seeprofile-non-doctor.md. (#7876)
Session & Token Endpoints — Rate Limiting
Acceptance Criteria
- ✅
auth.api.token-queries-rate-limited— Authenticated session/token read queries (getMobileToken,getLinkedAccounts,getEnterpriseSsoStatus) MUST be rate-limited consistently with sibling auth procedures; a burst beyond the limit returnsTOO_MANY_REQUESTSbefore any DB read. † - ✅
auth.login.inputs-16px-no-ios-zoom— The login / auth inputs (theEmailFieldandPasswordFieldatoms) MUST render at ≥16px so iOS / WKWebView never focus-zooms the first screen a user taps out of frame. The sharedINPUT_STYLES.authLogindesign token (instances/ppp/src/themes/tokens.ts) pins the auth-field text to 16px (FONT_SIZE.md); both fields apply it. The change is scoped to the auth path — the generalINPUT_STYLES.outlinedtoken keeps its 14px sizing so non-auth outlined inputs are unaffected. Mirrors the mobile-side ACmobile.auth.no-ios-zoominmobile.mdand complements the app-widemobile.forms.no-focus-zoom(#8338). †
Email Link Expiry
Acceptance Criteria
- ⏳
auth.links.14-day-expiry— All email links generated by the platform (invitations, verifications, password resets, approvals) MUST carry a 14-day expiry window. The email body MUST inform the recipient how long the link is valid for. Expired links MUST be regenerable via a self-service action (re-request). † - ⏳
auth.links.light-email-same-security— "Light email" variants (sent to external approvers and other off-platform recipients) MUST carry the same security controls and time-expiring link behaviour as standard platform emails. †
Open Questions
| # | Question | Ref | Proposed answer |
|---|
Closed Questions (5) — click to expand
| # | Question | Ref | Proposed answer |
|---|---|---|---|
| Q1 | External approver code lifetime — 7 days, 14 days, or single-session? | #4827 | Answered (transcript 2026-05-06 ~00:08:38): 14 days. Industry standard is 7 days but Matt agreed to 14-day expiry window with ability to regenerate expired links. |
| Q2 | External approver delivery channel — email only, or also SMS? | #4827 | Answered (transcript 2026-05-06): Email only (magic link). No SMS. |
| Q3 | Code expiry behaviour — re-request flow or contact admin? | #4827 | Answered (transcript 2026-05-06 ~00:08:38): Regeneration — user can regenerate an expired link. Super admin can also view and resend. |
| Q4 | Remember Me session lifetime — what should the extended duration be? | #4994 | Answered (Rob, 2026-05-21): 30 days. |
| Q5 | Account status on login — show specific reason (suspended/pending) or generic "contact support"? | #4993 | Resolved 2026-06-03 — RESOLVED-IN-CODE — login shows a SPECIFIC per-status message (pending_approval / suspended / disabled / inactive / deleted) each with a next step + support email, plus a generic fallback. Shipped via #4993. code:instances/ppp/src/slots/CoreAppContainerLogin/CoreAppContainerLogin.tsx INACTIVE_STATUS_MESSAGES. |
AHPRA Verification Pipeline
Decision
PCA (Provider Connect Australia) is not the right tool — it's for providers to update their own business details, not a regulatory lookup (#4630, #4832).
PPP will use a cache-first verification pipeline with annual re-validation (#4842).
Why
- AHPRA's public register is web-based with no free API
- Calling AHPRA on every page load would be expensive AND legally fragile
- Caching makes the second-and-subsequent reads near-zero cost while building up an authoritative PPP-side registry over time
- AHPRA registration is annual, so a cached result must be re-validated at least once per registration cycle to stay accurate
- Source: ~00:31:11 / 00:32:18 / 01:04:06 / 01:05:34
Architecture
ahpra_validation_cache
registrationNumber PK
status valid | invalid | unknown
fullName (denormalised — for cross-check)
lastValidatedAt timestamp
expiresAt timestamp (set to registration renewal date or +1y)Validator service writes to both layers on each lookup: Redis (24h hot cache via PppCache) and the DB table (persistent annual TTL). The scheduler-lambda's annual processRegistrationReCheckNotifications job re-validates all stored registrations and updates the DB cache.
Legal / ToS posture (updated 2026-05-20)
AHPRA's POST /api/Search/GetPredictions endpoint is the same JSON API the AHPRA website calls in-browser — it is a public, unauthenticated endpoint on the public register. PPP makes one per-registration-number request to verify a practitioner the user has claimed. There is no AHPRA API ToS governing third-party use of this endpoint (no API key, no developer agreement). Legal posture: equivalent to a user manually searching the public register at ahpra.gov.au. This is not traditional web scraping — no HTML parsing, no headless browser, no bot detection circumvention. Source: spike findings in ahpraScrapeClient.ts header comments (2026-05-19, #5991).
Acceptance Criteria
- ✅
ahpra_validation_cachetable created —ppp_ahpra_validation_cachein migration 0100 (#4842) - ✅ Validation service: writes to DB cache on every live register lookup; Redis 24h hot cache remains the performance layer
- ✅ Decision recorded: per-user TTL (
lastValidatedAt + 1 year) — no global sweep needed because the annualprocessRegistrationReCheckNotificationsjob provides the sweep (#4842) - ✅ Background job wired:
processRegistrationReCheckNotificationsadded toscheduler-lambda.ts(#4842); updates DB cache on each annual run - ⏳ AHPRA "Verified" badge on profile only renders when the cache says
validANDexpiresAtis in the future — blocked by #6306 (detail-page scraping for actual renewal date) - ✅ Until live verification is wired, the badge MUST NOT say "Verified" — show "Format valid" or hide the badge
- ✅ Legal/ToS posture documented — see section above
- ⏳ Update
docs/features/onboarding.mdanddocs/features/cpd.mdto reference this for the registration-display sections
What NOT To Do
- ❌ Use PCA — wrong tool, confirmed 13 Apr 2026
- ❌ Show a green "Verified" badge for users where validation is only format-checked
- ❌ Cache without expiry — annual registration cycle requires re-validation
GMC Licence Status Enforcement (#5069)
Invariant
For any UK signup where regulatoryBody = 'GMC', the server-side verification gate MUST reject isVerified = true unless the GMC registrant page reports a licence status in the active-licence allow-list. Name-match alone is NOT sufficient.
Why
- The GMC public register exposes
licenceStatusas free-form caption text. Rendering it in the UI without gating the verification decision created a compliance gap: a doctor with "Registered without a licence", "Suspended", "Erased" or "Not registered" could pass name-match and flipisVerifiedto true — despite having no active licence to practise. - PPP certifies the credentials of licensed clinical practitioners. A verified badge on an unlicensed doctor is a safety/regulatory failure, not just a UX bug.
Acceptance Criteria
- ✅ Centralised allow-list of acceptable GMC licence statuses lives in
api/backend-ppp/src/services/gmcRegistrantService/gmcLicenceStatus.ts— currently the single string "Registered with a licence to practise" - ✅
validateConsultantStatusreturnshasAcceptableLicence: booleanand the rawlicenceStatusstring for audit/UI copy - ✅
enforceConsultantStatus(authService) runs the licence gate for ALL GMC-backed signups — not only consultant claims — and setsisVerified = falsewheneverhasAcceptableLicence === false - ✅ When the user also claims consultant status and the licence is unacceptable, the user is downgraded to
non-consultant - ✅ Unit tests cover: "Registered without a licence", "Not registered", "Suspended", "Erased", empty / null, and the canonical active value
- ✅ BDD
@regression @issue-5069scenario proves a revoked-licence response never lands asisVerified = true - ✅ Consultant status is sourced from the registration body, never self-claimed (#7643). The AHPRA (AU) sign-up path now has the same server-side consultant gate as GMC —
enforceAhpraConsultantStatusdowngrades an unconfirmeduserType=consultantclaim tonon-consultant(specialist status comes fromvalidateAhpraNumber.suggestedUserType). A sharedresolveVerifiedUserTyperesolver enforces the same rule on the SSO completion path (completeSsoProfile), which previously hard-codedconsultant. Indeterminate / failed lookups fail safe tonon-consultant. Seedocs/features/medical-registration-verification.mdfor the canonical source-of-truth / no-self-claim ACs.
What NOT To Do
- ❌ Check
licenceStatusinline at each call site — always route throughisAcceptableGmcLicenceStatusso the allow-list stays single-source - ❌ Rely on name-match as a sufficient proxy for verification
- ❌ Treat a 404 / network error / empty status string as acceptable — default to rejection
Session Expiry Handling
Decision
Any tRPC response with HTTP 401 / code UNAUTHORIZED must redirect the user to /login?reason=session-expired and surface a toast explaining the session expired (#5044).
Why
- Before #5044 the tRPC client had no global error handler for
UNAUTHORIZED. When a Better Auth session expired mid-use, every subsequent query returned 401 andUserContextfell through withuser = null. Users saw a blank / broken UI with no explanation and no way to recover. - A single cache-level
onErroron the shared QueryClient guarantees the behaviour fires uniformly for every query and mutation in the app.
Acceptance Criteria
- ✅ A global interceptor exists on the tRPC / React Query client that detects
UNAUTHORIZEDerrors (either tRPCcode === 'UNAUTHORIZED'or HTTP 401) - ✅ On detection, the interceptor navigates to
/login?reason=session-expiredand preserves the originating path via aredirect=query param - ✅ A
notistacktoast is shown informing the user their session expired - ✅ Local auth state is cleared (
authClient.signOut()is called) - ✅ The handler is deduplicated — a burst of concurrent 401s triggers a single redirect, not a storm
Account Types
Four distinct tiers determine which modules a user can access and what they pay. †
Acceptance Criteria
Hospital Email — Link to Personal Account
Acceptance Criteria
- ⏳
auth.account.hospital-email-link-personal— A user may sign up using a hospital email address and subsequently link it to a personal account, enabling multiple logins to reach the same PPP profile. Changing the email address on an existing account must trigger a verification step before the new address is confirmed. †
Identity Model (Cross-Reference)
PPP uses a canonical user ID with multiple linked identities — a single user may link multiple email addresses and SSO providers without being tied to any one address. Email is NOT a primary key. † See linked-accounts.md for the model.
SSO Profile Completion — Account Access Invariant
Invariant
An SSO user must end up on exactly the tier they paid for: never full PPP access by default (#4992), and never a paid tier they did not pay for (#12594).
Superseded mechanism (#12594): this section previously required completeSsoProfile to persist accountAccess exactly as submitted. That let an SSO registrant pick cpdppp without paying. The submitted accountAccess is now only a plan intent. The profile is created on the cpd floor. The paid tier is written only from the verified Stripe PaymentIntent, using its server-set metadata.accountType, which is priced from the same selection. The writers are attachEmbraceIdToPaymentIntent and the payment_intent.succeeded webhook. An honest user ends up on the same tier as before. †
Why
- The frontend (
SsoProfileCompletion.tsx) collectsaccountAccessvia the sharedPaymentFormexactly like the password signup flow, and the Stripe PaymentIntent it issues is priced by that selection. - If the backend writes a different tier from the one paid for, the user's billing and entitlements diverge: they paid the CPD price but receive full PPP access (or vice versa).
- This is a security / billing regression, not a UX preference — the invariant is load-bearing for paid-tier gating.
Acceptance Criteria
- ⏳
completeSsoProfileInputSchemaincludesaccountAccessas a required string constrained to the known values (cpd,cpdppp) - ⏳
completeSsoProfilenever grantscpdpppfrom the submittedaccountAccessalone. It creates the profile on thecpdfloor and hands any supplied PaymentIntent to Stripe verification, whateverpaymentStatusthe client claims (#12594; supersedes the #4992 "pass the submitted value straight intocreateUserProfile" mechanism) - ⏳ An SSO user who selects "CPD only" at profile completion has
accountAccess = 'cpd'on the resultingmb_userrow (NOT'cpdppp') - ⏳ An SSO user who selects "CPD + PPP" and whose Stripe PaymentIntent succeeded has
accountAccess = 'cpdppp', written from the PaymentIntent'smetadata.accountType - ⏳ A service test asserts that a client-selected
cpdpppalone reachescreateUserProfileascpd
Sign-Up — Registrant Field Allowlist (#12594)
Invariant
auth.signUp is reachable before login. Its input is an explicit .strict() allowlist of fields the registrant may supply. Every privilege, billing, verification and lifecycle column on the new users row is set by the server.
Acceptance Criteria
- ✅
auth.signup.no-mass-assignment— a sign-up request can only supply registrant fields: name, email, phone, regulatory body and registration number, country, date of birth, job title, CV, PGY, speciality, medical degree and university, claimed user type, and CPD plan. A request carrying any otheruserscolumn is rejectedBAD_REQUESTand no account is created (#12594). That covers the super-admin and hospital-admin flags, persona and tier level, account status, timesheet-approver status, onboarding completion, downgrade state, the enterprise SSO binding andid. † ‡ - ✅
auth.signup.server-derived-verification-and-tier— the wizard still sendsisVerified,accountAccessandpayment*values. They are accepted for compatibility but never saved.isVerifiedcomes only from the server's own GMC or AHPRA register lookup. The account starts on thecpdtier with no payment recorded. The paid tier andpaymentStatus = 'completed'are written only from a Stripe PaymentIntent that Stripe reports as succeeded and that is not already bound to another account (#12594). † ‡
Password Reset — Expired-Link Recovery
Decision
When a user clicks a password-reset link that has expired (default 1-hour TTL), the /reset-password page MUST offer an inline "request new link" CTA — NOT redirect the user back to /login and force them to re-enter the forgot-password flow from scratch (#4625).
Why
- Matt found in UAT (Randell_06 ticket, 13 Apr 2026) that the original page showed a dead-end "Go to Login" button on expiry. With Hotmail filtering delaying delivery to junk and the link only valid for 1 hour, by the time he found the email and clicked, the link had already expired — and he was bounced to login with no clear path forward.
- Self-service recovery in place avoids a support ticket for a routine failure mode and matches user expectations from other consumer auth flows.
Acceptance Criteria
- ⏳
auth.password-reset-expired-page-has-request-new-cta— When the/reset-passwordpage detects an expired or invalid token (either because the URL has notokenquery param, or becauseauthClient.resetPasswordreturns an expired/invalid-token error), it MUST render an inline form to re-enter the email address and request a new reset link, callingauthClient.requestPasswordResetdirectly. On success the page MUST show a confirmation ("Check your email") in place. It MUST NOT redirect to/loginas the only recovery path.
Link host (#12833). Reset links — emailed or admin-generated ("Generate password reset link", Settings → All Users) — are built on the API's public base URL: BETTER_AUTH_BASE_URL, falling back to API_BASE_URL (the only one NAS deployments set), and only then to the local-dev default. A deployed environment must never emit a localhost reset link.
In-App Change Password (My Profile — Security Section)
Decision
Authenticated users can change their PPP sign-in password from a "Security" accordion on the My Profile page, without leaving the app. Credential users (email + password sign-in) see a Change Password form; SSO-only users (no credential auth account) see a message directing them to their identity provider instead, never the form (#9833/#9857).
Why
- Matt asked for in-app password management alongside CV/profile editing, scoped to the Security accordion on My Profile (#9833).
- A user's set of linked auth methods (
getLinkedAccounts) already distinguishes credential vs SSO-only accounts for the Linked Emails section — the same signal gates which of the two Security states renders, rather than duplicating that check. - Changing the password revokes other active sessions (
revokeOtherSessions: true) so a compromised session is invalidated the moment the user resets their credentials, while the current session stays valid (the user is not immediately logged out of the page they just used).
Acceptance Criteria
- ✅
auth.change-password.credential-user-form— A credential user (has acredential-provider row fromgetLinkedAccounts) expanding the Security accordion sees a Change Password form with current password, new password, and confirm password fields (ChangePasswordForm.tsx, rendered bySecuritySection.tsx). † ‡ - ✅
auth.change-password.success-feedback— Submitting valid current + new password callsauthClient.changePasswordwithrevokeOtherSessions: trueand shows a "Password changed successfully" snackbar on success; the submitting user's own session remains authenticated afterwards, and the new password immediately works for a fresh login. † ‡ - ✅
auth.change-password.sso-only-redirect-message— A user with nocredential-provider row (SSO-only) does NOT see the Change Password form when expanding the Security accordion; instead they see a message directing them to manage their password via their sign-in provider's own account settings. † ‡
Password Reset — Send-Failure Observability
Decision
Azure Communication Services (ACS) sendResetPassword delivery failures MUST be wired to an actual alert (not just a log line), and this MUST NOT change the unauthenticated Forgot Password endpoint's generic anti-enumeration response (#10017).
Why
- Better Auth's own route handler (
runInBackgroundOrAwait) swallows anysendResetPassworderror internally and always returns{ status: true, message: "If this email exists in our system, check your email for the reset link" }— a deliberate anti-enumeration pattern that must never change to leak whether an email exists. - Before #10017, PPP's own
sendResetPasswordhook re-threw for structured logging (#4397), but that log line was never wired to an actual alert — engineering only learned about a silent ACS delivery failure via a user complaint (Matt Randell, #9898), exactly the gap #4397's own AC called for and never shipped. - #4397's infra root cause (unverified ACS sender domain) is confirmed still healthy — SPF/DKIM/DMARC all green — so this closes a different, deeper gap: any transient ACS failure (quota, rate limit, API error) on any critical flow through
sendEmail(password-reset, change-email-verification, etc.) is now alertable, not just logged.
Acceptance Criteria
- ✅
auth.password-reset.acs-failure-alerted— Every ACS send failure (sendEmailinapi/backend-ppp/src/utils/mailer-helper.ts) emits a structuredevent: 'ACS_SEND_FAILURE'log marker. An Azure Monitor Scheduled Query Rule (api/infra-azure/src/index.ts) fires on anyACS_SEND_FAILUREoccurrence within a 5-minute window and notifies the on-call address via the shared login-failure Action Group (#4760) — no user complaint required. † - ✅
auth.password-reset.acs-connectivity-integration-test— A live-ACS integration test (api/backend-ppp/src/utils/mailer-helper.acs-connectivity.integration.test.ts, skipped in CI) sends a real email against the configured environment'sAZURE_COMMUNICATION_CONNECTION_STRINGand fails fast with a clear message if ACS delivery is broken or the connection string is absent — the acceptance criterion #4397 specified but never implemented. † - ✅
auth.password-reset.generic-response-unchanged— The unauthenticated Forgot Password response remains the generic "If this email exists in our system, check your email for the reset link" regardless of ACS delivery outcome. This is a deliberate anti-enumeration pattern and MUST NOT be changed to surface a distinguishable error to the requesting user. †
Login Page
Acceptance Criteria
- ✅ Inactive / pending / suspended accounts show a clear error on login — no silent broken shell (#4993;
code:instances/ppp/src/slots/CoreAppContainerLogin/CoreAppContainerLogin.tsx) - ⚠️
/api/auth/get-sessionpolled at most once per visible-state change — not 40–60× per session (#4995) - ⚠️ Remember Me checkbox wired to session lifetime — currently renders but has no effect (#4994)
- ⚠️ Empty login form shows per-field inline errors, not a combined message (#4997)
- ⚠️ Returning from password-reset flow clears prior error state and pre-filled email (#4996)
- ⚠️ Login page colour contrast meets WCAG 2.1 AA (#5224)
What NOT To Do
- ❌ Poll
/api/auth/get-sessionon a fixed interval — use event-driven state only
SSO Flow
Acceptance Criteria
- ✅
auth.sso.enabled-on-uat-login— SSO sign-in is enabled on the UAT login page via theVITE_ENABLE_SSO=truebuild flag set on theci-gateUAT frontend build (the only build feeding theppp-frontend-uat-buildartifact). A user can sign in via SSO without entering a username or password; the existing password login continues to work alongside it. Engineering default pending Matt's confirmation — Rob named SSO the next auth priority on the 2026-07-08 call; Matt has not yet signed off UAT enablement, so the issue carriesfor-discussion. The flag is scoped to UAT — production has no frontend build incd.yml, so enabling SSO on prod is a separate, deliberate step (set the flag in the prod frontend build path, register prod OAuth redirect URIs, wire prod backend provider secrets) pending rollout sign-off. Backend providers are gated independently bybuildSocialProviders(only providers withCLIENT_ID+CLIENT_SECRETpresent render), so the flag never exposes an unconfigured provider. Mobile native SSO (system-browser OAuth +ppp://auth/sso/callbackdeep-link handling) is out of scope for this web-side enablement and is delivered separately in #10212 — seemobile.auth.sso-system-browser/mobile.auth.sso-callback-deep-link/mobile.auth.sso-web-buttons-hidden-in-webviewindocs/features/mobile.md; within the native WebView wrapper the web SSO buttons are hidden (they would dead-end indisallowed_useragent) and native SSO runs in the system browser. (#10195, #10212) † ‡ - ⚠️ SSO provider buttons rendered only for providers configured in the environment — not all three always (#5045)
- ⚠️ SSO deep-link preserved —
callbackURLset to the originally requested path, not hardcoded/(#5046) - ⚠️ OAuth error params (
?error=access_denied) on SSO callback surfaced to user with explanation (#5048) - ⏳
completeSsoProfilewrapped in a database transaction — no duplicate user profiles on concurrent requests (#5050)
Login-to-PPP-User Link Is Server-Owned (#12610)
Invariant
auth_user.ppp_user_id is the only thing that maps a Better Auth session to a PPP user, so it decides who the caller is on every request. Only trusted server code may write it. No Better Auth endpoint may accept it from a caller.
The login email is not an identity. Public POST /api/auth/sign-up/email does not verify the address, so a session's login email may belong to someone else's PPP profile. The request context (utils/entrypoint.ts) therefore sets ctx.identity.email to the stored users.email of the linked pppUserId, and leaves it unset for a login with no link (#12616) The stored users.email is user-editable and not unique either, so it is not an identity on its own: a lookup of the caller's own identity email resolves by the linked pppUserId (and is cached by id), the scope helpers refuse any resolved record that is not that id, and a profile update may not take an address another user already holds (#12616).
Acceptance Criteria
- ✅
auth.identity.ppp-user-link-server-owned— the Better Auth user fieldspppUserIdandstatusare declaredinput: false. A signed-inPOST /api/auth/update-userthat sets either one is rejected400("… is not allowed to be set"), and the session still resolves to the caller's own PPP user. An anonymousPOST /api/auth/sign-up/emailthat setspppUserIdis rejected400and creates no link. Astatussent to sign-up is ignored, and the account is createdactive(#12610). † ‡ - ✅
auth.identity.ppp-user-link-written-by-server— the email/password sign-up links the new login to its PPP user after the server has created both rows. The link is keyed on the id of the auth user the server just created. It is written only if that auth user is not already linked and its email matches the PPP user's email. If linking fails, the new auth user and PPP profile are both rolled back. SSO profile completion keeps linking the session's own auth user inside its transaction. Seed scripts use the same server helper (#12610). The email check compares against the storedusers.emailof the target PPP user, not an email the caller passes in. A lost race for the same PPP user returns409 CONFLICT(#12616). † ‡ - ✅
auth.identity.resolved-by-ppp-user-id— who the caller is comes only from the linkedpppUserId, never from the login email. A login with no linked PPP user has no PPP identity.adminProcedurereturnsFORBIDDEN, theadminUsersgate refuses it,getCurrentUserreturnsnull, and the email-keyed scope helpers (getSelfUserId/enforceUserScope) returnUNAUTHORIZED. This holds even when the login email matches an existing super admin'susers.email. A linked caller whose stored email collides with another user's (a legacy duplicate, or a race) still resolves as their own linked user and keeps their own scope;updateUserProfilerefuses with409 CONFLICTan email another user already holds (case-insensitive). SSO profile completion refuses with409 CONFLICTwhen a PPP profile already exists for the login email. It never creates a duplicate profile or adopts the existing one. Public sign-up stays open (decision pending); with identity keyed onpppUserId, an unlinked login gets no PPP access (#12616). † ‡
Enterprise SSO Binding (Org Admin Personas)
Acceptance Criteria
- ⏳
auth.enterprise-sso.org-admin-binding— Org admin personas (hospital admin, hospital exec admin, governing body admin) may bind their PPP account to their enterprise IdP (Microsoft 365 first; Okta / SAML deferred). Binding persistsenterpriseSsoProvider,enterpriseTenantId, andenterpriseSsoBoundAton the user row.enterpriseSsoBoundAt IS NOT NULLis the authoritative "is bound" signal. The binding card surfaces in My Profile for these personas only; non-admin users do not see it. The backend exposes agetEnterpriseSsoStatustRPC query returning{ isBound, provider, tenantId, boundAt }(#6671).
Open issues on label:feature:auth — no open issues. Fetched at: 2026-10-13T07:29:49Z — live list on GitHub.
Change Log
| Date | Change | PR/Issue | Reason |
|---|---|---|---|
| 2026-10-04 | External (account-less) approvers are recorded as first-class audit actors: audit_trail.user_id is nullable, with actor_type, actor_name, actor_email, external_approver_id and a check constraint. The external-approver action page asks the approver to type their full name (remembered per email in external_approvers), and the confirmation stores name, email, time, IP and browser. | #0, #12528, #12531 | Rob decision 4 Oct 2026 on #12528-#12531: external approvers become audit actors with a typed name on every approval. Migration 0257_panoramic_lorna_dane. Timesheet (#12529) and CPD-token (#12530) call sites are left to their own lanes. |
| 2026-10-04 | The external approver isolation-code flow (#7327) is wired to a decision: after redeeming a code at /external-approve the approver types their name and approves or declines (a reason of 10+ characters is required to decline); externalApproverAuth.decide records the typed name (remembered per email), email, time, IP, browser, decision and reason as an external audit actor. The live 360 reviewer link (ppp360.review) now requires the reviewer to type their name, pre-filled per email, and writes the same external-actor row. Confirmed live flows: timesheet magic link (#12529), CPD provider token (#12530) and the 360 reviewer link; the code flow had no caller that issues a WBA code, so approve/decline records the decision only and changes no WBA record. Also: EXTERNAL_APPROVER_CODE_SECRET is generated by setup-local-env.sh (.env.sample). | #0, #12531 | Rob 2026-10-04 called #7327/#7516 unwired scaffolding and decided to wire it. Open: which WBA / 360 request issues a code, and what an approve or decline changes on that record. |
| 2026-10-04 | Better Auth's public base URL now resolves BETTER_AUTH_BASE_URL, then API_BASE_URL, then the local-dev default, so admin-generated password-reset links and native SSO callbacks use the API host on NAS deployments. | #0, #12833 | NAS deploys (ADR-0006) set API_BASE_URL but never BETTER_AUTH_BASE_URL, so the admin "Generate password reset link" tool produced http://localhost:3000/api/auth/reset-password/<token> on UAT, which no one outside the server could open. No acceptance criterion changed. |
| 2026-09-29 | Added a unique index on lower(users.email) (migration 0255) — defence in depth against a concurrent-update race past the 409 CONFLICT checks on signUpInner/updateUserProfile/createUserProfile. Fails loudly on any existing duplicate rather than auto-merging accounts; does not affect application behaviour when no duplicates exist. | #12630, #12629 | Follow-up from the PR #12617 review of #12616 ("Needs Rob" item 1) — every email-keyed lookup compares case-insensitively once #12617 lands, but nothing at the schema level stopped two rows sharing a lower(email) from being created concurrently. |
| 2026-09-29 | Fixed 8 call sites (pendingAccountsService x2, hospitals.ts self-assign x3, paymentBannerService, cadenceTargetService, cpdPlanNudgeService) that hand-built their own cache-key list instead of using the centralised invalidateUserCache() helper, so none of them busted the id-keyed identity cache entry this PR's own fix commit introduced. No behaviour change to any of those features' acceptance criteria — this is an internal cache-consistency fix ensuring a linked user's cached identity/profile snapshot reflects each write immediately, as already required. | #12617, #12616 | Regressed the "reflect immediately" guarantee #7734/#5619/#5622 were filed to fix, found in PR #12617's review (1e02b4900). |
| 2026-09-29 | auth.signUp input is now an explicit .strict() allowlist of registrant fields, built from what RegistrationForm, HospitalStaffForm and InviteSignupForm send. Any other users column is rejected BAD_REQUEST: isSuperAdmin, isHospitalAdmin/isHospitalSuperAdmin, userPersona, tierLevel, accountStatus, timesheetApproverStatus, onboardingCompletedAt, pendingDowngradeAt, the enterprise SSO binding and id. The wizard''s isVerified, accountAccess and payment* keys are still accepted but never saved. isVerified now comes from the server''s GMC/AHPRA lookup, the account starts on the cpd tier, and the paid tier is written only from a Stripe PaymentIntent that succeeded and is not already bound to another account. completeSsoProfile also creates the account on the cpd floor, which supersedes the #4992 "persist accountAccess as submitted" mechanism. New ACs: auth.signup.no-mass-assignment and auth.signup.server-derived-verification-and-tier. | #12607, #12594 | Security (#12594): the signUp input accepted every users column. An unauthenticated registrant could create their own account as super admin, or with paymentStatus: completed and accountAccess: cpdppp without paying. A live-DB integration test against the tRPC procedure confirmed this. |
| 2026-09-29 | Added auth.identity.ppp-user-link-server-owned and auth.identity.ppp-user-link-written-by-server. Better Auth's pppUserId and status user fields are now input: false. The email/password sign-up and the seed scripts link a login to its PPP user through one server helper (linkAuthUserToPppUser) after both rows exist, instead of passing pppUserId through signUpEmail. | #12610 | Critical account takeover. Both fields were client-writable. A signed-in user could POST /api/auth/update-user {pppUserId: X} and their session then resolved to PPP user X, super admins included. An anonymous POST /api/auth/sign-up/email with pppUserId saved the same link. |
| 2026-09-29 | Added auth.identity.resolved-by-ppp-user-id. The request context now sets ctx.identity.email from the linked PPP user's stored email and leaves it unset for an unlinked login. adminProcedure, the adminUsers gate and getCurrentUser resolve the caller by pppUserId. SSO profile completion refuses an email that already has a PPP profile. linkAuthUserToPppUser checks the stored users.email and returns 409 on a lost race. The Invariant now states that the login email is not an identity. The caller's own identity-email lookup is pinned to (and cached by) the linked pppUserId, the scope helpers refuse a record that is not that id, and updateUserProfile refuses an email another user holds, so an edited users.email cannot make the caller resolve as another user. | #12616 | Critical anonymous privilege escalation. The caller was resolved by login email. Public sign-up does not verify email, so an anonymous sign-up with an unlinked super admin's email passed adminProcedure and loaded that admin's profile. |
| 2026-09-28 | Per-IP rate limits (tRPC limiter, external-approver code limits, Better Auth's built-in limiter) and audit / failed-login IP capture now resolve the client address from CF-Connecting-IP (set by the Cloudflare edge) with a TCP-socket-peer fallback, via one helper utils/clientIp.ts. X-Forwarded-For is no longer trusted (trust proxy is now false). No acceptance criterion changes. | #12533 | Security review of #12442 found trust proxy: true made req.ip the leftmost client-supplied X-Forwarded-For entry, so rotating that header bypassed every per-IP rate limit, including the sensitive tier on public magic-link procedures. |
| 2026-07-08 | Enabled SSO sign-in on the UAT login page via the VITE_ENABLE_SSO=true build flag (scoped to the UAT frontend build). Added AC auth.sso.enabled-on-uat-login and a @smoke BDD scenario for password-free SSO sign-in. | #10195 | Rob's stated next auth priority (2026-07-08 call) — reduce reliance on username/password. SSO was already built end-to-end (Better Auth social providers, account linking, SsoButtons) but dark-shipped because the feature flag was never set in any committed config, so the UI never rendered. This flips it on for UAT only; prod stays gated pending rollout sign-off. |
| 2026-07-08 | Resolved the "tracked separately" pointer on auth.sso.enabled-on-uat-login — mobile native SSO is now delivered in #10212 (system-browser OAuth + ppp://auth/sso/callback deep-link; web SSO buttons hidden inside the native WebView wrapper). The Identity & Profile backend gains a native-SSO Express bridge in front of Better Auth (nativeSsoBridge.ts + nativeSsoBridgeHandlers.ts): a mobile=1-only GET /api/auth/sign-in/social interceptor obtains the provider authorize URL with a trusted-origin backend callbackURL, and a GET /api/auth/sso/mobile-return handler mints the Better Auth session token (same getSession() path as getMobileToken) and 302s it back on the deep link. Requests without mobile=1 pass straight through to Better Auth, so the web OAuth flow is unchanged. | #10212, #10195 | The web-side SSO enablement (#10195) explicitly deferred mobile WebView SSO as out of scope; #10212 implements it, so the cross-reference now points at the delivering issue and the new mobile.auth.sso-* ACs in docs/features/mobile.md. Native code cannot read the ephemeral ASWebAuthenticationSession/Custom-Tabs cookie jar Better Auth sets, so the backend must carry the bearer token on the deep link — done without touching the web cookie-redirect path. |
| 2026-07-04 | Backfilled BDD + spec coverage for the in-app Change Password flow (#9833/#9857) — added the 3 missing step definitions the existing profile.feature scenarios never had (they were silently skipped by every nightly BDD UAT run), plus a new scenario that actually submits the form and re-logs in with the new password. Added the "In-App Change Password" AC section to this spec. | #10018, #9833, #9857 | #9857 shipped SecuritySection.tsx/ChangePasswordForm but its BDD scenarios never actually exercised the submit path (only rendering/visibility), and no spec entry existed for the feature at all — a gap surfaced by #9898's deep-dive and split out as Option B. |
| 2026-06-09 | Add AC auth.api.token-queries-rate-limited — getMobileToken, getLinkedAccounts and getEnterpriseSsoStatus promoted from bare protectedProcedure to rateLimitedProtectedProcedure (default tier). | #8383, #8375 | Surfaced by the #8374 iOS token-bridge security review; closes the bare-protectedProcedure inconsistency now that the SPA calls getMobileToken once per app load. Hardening, not a vulnerability fix. |
| 2026-06-03 | Resolve Q5 (per-status login messages, #4993) to Closed Questions; flip the account-status login AC to delivered. | #8166 | SGD governance sweep — transcript-grounded audit found these questions already answered; reconciled the spec to shipped reality and moved them out of Open Questions. |
| 2026-06-01 | Documented that the org-admin SSO-eligibility set (enterpriseSso.ts) and persona scope checks (checkIsHospitalAdmin.ts, now keyed off getPersonaTierLevel) under api/backend-ppp/src/services/auth/ are auth-domain code whose underlying tier_level hierarchy is governed by profile-non-doctor.md, via a cross-reference AC. | #7983, #7876 | The tier_level integer-hierarchy work (#7876) touched enterpriseSso.ts and checkIsHospitalAdmin.ts under api/backend-ppp/src/services/auth/, which auth.md owns by code-path glob (api/backend-ppp/src/services/auth/**); the tier-level model itself is spec'd in profile-non-doctor.md, so auth.md carries a cross-reference rather than duplicating the criteria. |
| 2026-05-26 | Implemented the external approver isolation-code flow (auth.external.temp-code-*): single-use hashed code (HMAC-SHA256), configurable validity window (default 7 days via EXTERNAL_APPROVER_CODE_TTL_DAYS), deep-link + /external-approve action page, short-lived signed action cookie scoped to one action (no account/password), audit log (generated/redeemed/action-taken), and IP + recipient-email rate limiting. Migration 0115_external_approver_codes. @smoke @issue-7327 scenarios in auth.feature. | #7516, #7327 | Without account-less approver auth, external timesheet/WBA approvers had to register full PPP accounts — blocking the core hospital-evaluation use case (#7327). |
| 2026-05-20 | Added Enterprise SSO Binding section for org admin personas. New AC auth.enterprise-sso.org-admin-binding covers binding a PPP account to an enterprise IdP (Microsoft 365 first), with enterpriseSsoBoundAt IS NOT NULL as the authoritative bound signal. Backend exposes getEnterpriseSsoStatus tRPC query; frontend renders an EnterpriseSsoSection card in My Profile for admin personas only. Schema adds nullable enterpriseSsoProvider, enterpriseTenantId, enterpriseSsoBoundAt columns to users (migration 0106). @smoke + @regression BDD scenarios in profile-non-doctor.feature tagged @issue-6671. | #6794, #6671 | First implementation slice of enterprise SSO binding for org admin personas — unblocks future delegated-admin and tenant-scoped sign-in flows. Provider stored as varchar (not enum) so adding Okta/SAML later requires no further migration. |
| 2026-05-20 | AHPRA validation cache — ppp_ahpra_validation_cache DB table, cache service, annual scheduler wiring, ToS posture documented. | #4842 | Redis 24h cache (ahpraScrapeClient.ts) only served as a hot-path perf cache; no durable record existed. Annual re-check processor was built but never wired to the scheduler. This PR adds the persistent DB layer and activates the annual sweep. |
| 2026-05-19 | Hardened the /signup-process route against the blank-#root failure mode: the global React.Suspense fallback now renders a visible role=status placeholder instead of an empty <div/>, and <Signup/> is wrapped in AppErrorBoundary so a render-time throw surfaces an error message instead of an empty page. @regression @issue-6577 BDD scenario added in auth.feature. | #6594, #6577 | UAT bug — /signup-process was rendering a completely blank #root because the Suspense fallback was indistinguishable from 'React never mounted'. Defensive hardening at the boundary; no AC changes. |
| 2026-05-19 | SGD transcript audit — 7 new ACs (account types, hospital-email link, sign-up failure journey, first-login redirect, external approver temp code, linked-accounts password-less prompt, 14-day link expiry + light-email security) with src: citations from 5 transcripts (2026-03-11 to 2026-05-06). | Transcript audit protocol applied across transcripts-2026-03-11, -03-18, -04-01, -04-13, -04-23, -05-06. All new ACs are ⏳ (not yet implemented) and carry inline †-citations traceable to timestamp + quote. | |
| 2026-04-23 | Triage sweep — login page (6 bugs) and SSO flow (3 bugs) had no spec coverage despite being open issues; added AC sections for both. Moved 5 HR Passport issues (#5068, #5067, #5066, #5062, #4814) to feature:hr-passport. Closed #4792 as duplicate of #4813. Added for-discussion to #4625/#4617 (support tickets). Status changed from specified → partial-drift. Open Questions table formalised with Q1–Q5. | auth triage 2026-04-23 | 27 open issues had no login/SSO spec coverage; status was wrong. |
| 2026-04-21 | Triage sweep — 27 open issues mapped to this spec | #5224, #5068, #5067, #5066, #5062, #5050, #5049, #5048, #5046, #5045, #4997, #4996, #4995, #4994, #4993, #4945, #4842, #4827, #4814, #4813, #4792, #4645, #4636, #4630, #4625, #4617, #4412 | Unblocks drift detection on the features index. |
| 2026-04-13 | Initial spec — external approver isolation code, AHPRA caching, identity model cross-ref | #4827, #4842, #4832, #4630 | Rob & Matt call 13 Apr 2026 — multiple decisions on auth posture: PCA confirmed unsuitable; external approvers should not have full accounts; AHPRA caching needs annual TTL design. |
| 2026-04-21 | Added SSO profile completion accountAccess invariant — backend must persist the value submitted by the user, never hard-code cpdppp | #4992 | Security regression: completeSsoProfile was hard-coding accountAccess: 'cpdppp' when calling createUserProfile, so every SSO user received full PPP access regardless of the plan they selected (and paid for) on the Stripe step. Invariant closes the paid-tier bypass. |
| 2026-04-21 | Added Session Expiry Handling section — global 401 interceptor redirects to /login with toast on expired session | #5044 | Before the interceptor, expired sessions silently broke the app: UserContext received null from getCurrentUser and the UI went blank with no recovery path. Interceptor restores a clear UX for the common session-expiry case. |
| 2026-04-28 | Added Password Reset — Expired-Link Recovery section. AC auth.password-reset-expired-page-has-request-new-cta — /reset-password must show an inline "request new link" CTA when the token is missing or expired, not bounce to /login. | #4625 | Matt's UAT report (Randell_06): 1-hour link TTL plus Hotmail delivery delay meant the link was already expired by the time he opened it; the page's only recovery path was a "Go to Login" button. Self-service recovery in place removes the support-ticket burden and matches consumer auth-flow norms. |
| 2026-04-21 | Added GMC licence-status enforcement invariant — isVerified = true requires an allow-listed licenceStatus from the GMC register | #5069 | Security / compliance regression: verification service accepted name-match alone, so a doctor with "Registered without a licence", "Suspended" or "Erased" could be marked verified. Added centralised allow-list (gmcLicenceStatus.ts), broadened enforceConsultantStatus to run the licence gate for every GMC-backed signup, and covered the gap with service tests + a @regression BDD scenario. |