Skip to content

Auth — Verification & External Approvers ​

Feature Overview ​

Three connected concerns that share a single specification because their decisions interact:

  1. External approver authentication — how off-platform consultants (timesheet approvers, 360 reviewers) authenticate to act on a single item without holding a full PPP account
  2. AHPRA verification pipeline — how Australian medical registration is confirmed, cached, and re-validated
  3. 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 an audit_trail row with actor_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_DAYS env 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 an audit_trail row with actor_type = 'external' carrying name, email, time, IP and browser, and audit_trail.user_id is 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 off getPersonaTierLevel rather than enum literals) under api/backend-ppp/src/services/auth/** are auth-domain code, but the underlying tier_level integer hierarchy (re-parentable org tiers, shipped in #7876) is governed by profile-non-doctor.md. The acceptance criteria for the tier-level model and the org-admin persona tiers are maintained there — see profile-non-doctor.md. (#7876)
Linked Accounts — Password-less Prompt ​

Acceptance Criteria ​

  • ⏳ auth.account.linked-password-less-prompt — The Linked Accounts section of the profile MUST include an explanatory prompt informing the user that linking accounts lets them sign in without remembering a password. †
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 returns TOO_MANY_REQUESTS before any DB read. †
  • ✅ auth.login.inputs-16px-no-ios-zoom — The login / auth inputs (the EmailField and PasswordField atoms) MUST render at ≥16px so iOS / WKWebView never focus-zooms the first screen a user taps out of frame. The shared INPUT_STYLES.authLogin design 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 general INPUT_STYLES.outlined token keeps its 14px sizing so non-auth outlined inputs are unaffected. Mirrors the mobile-side AC mobile.auth.no-ios-zoom in mobile.md and complements the app-wide mobile.forms.no-focus-zoom (#8338). †

Open Questions ​

#QuestionRefProposed answer
Closed Questions (5) — click to expand
#QuestionRefProposed answer
Q1External approver code lifetime — 7 days, 14 days, or single-session?#4827Answered (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.
Q2External approver delivery channel — email only, or also SMS?#4827Answered (transcript 2026-05-06): Email only (magic link). No SMS.
Q3Code expiry behaviour — re-request flow or contact admin?#4827Answered (transcript 2026-05-06 ~00:08:38): Regeneration — user can regenerate an expired link. Super admin can also view and resend.
Q4Remember Me session lifetime — what should the extended duration be?#4994Answered (Rob, 2026-05-21): 30 days.
Q5Account status on login — show specific reason (suspended/pending) or generic "contact support"?#4993Resolved 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.

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_cache table created — ppp_ahpra_validation_cache in 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 annual processRegistrationReCheckNotifications job provides the sweep (#4842)
  • ✅ Background job wired: processRegistrationReCheckNotifications added to scheduler-lambda.ts (#4842); updates DB cache on each annual run
  • ⏳ AHPRA "Verified" badge on profile only renders when the cache says valid AND expiresAt is 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.md and docs/features/cpd.md to 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 licenceStatus as 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 flip isVerified to 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"
  • ✅ validateConsultantStatus returns hasAcceptableLicence: boolean and the raw licenceStatus string for audit/UI copy
  • ✅ enforceConsultantStatus (authService) runs the licence gate for ALL GMC-backed signups — not only consultant claims — and sets isVerified = false whenever hasAcceptableLicence === 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-5069 scenario proves a revoked-licence response never lands as isVerified = 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 — enforceAhpraConsultantStatus downgrades an unconfirmed userType=consultant claim to non-consultant (specialist status comes from validateAhpraNumber.suggestedUserType). A shared resolveVerifiedUserType resolver enforces the same rule on the SSO completion path (completeSsoProfile), which previously hard-coded consultant. Indeterminate / failed lookups fail safe to non-consultant. See docs/features/medical-registration-verification.md for the canonical source-of-truth / no-self-claim ACs.

What NOT To Do ​

  • ❌ Check licenceStatus inline at each call site — always route through isAcceptableGmcLicenceStatus so 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 and UserContext fell through with user = null. Users saw a blank / broken UI with no explanation and no way to recover.
  • A single cache-level onError on 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 UNAUTHORIZED errors (either tRPC code === 'UNAUTHORIZED' or HTTP 401)
  • ✅ On detection, the interceptor navigates to /login?reason=session-expired and preserves the originating path via a redirect= query param
  • ✅ A notistack toast 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 ​

  • ⏳ auth.account.types-four-tiers — The platform supports exactly four account types: CPD-only; CPD + PPP; CPD + PPP + Hospital; Hospital-only. The accountAccess field (and downstream entitlement gates) must distinguish all four without collapsing any pair. †
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) collects accountAccess via the shared PaymentForm exactly 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 ​

  • ⏳ completeSsoProfileInputSchema includes accountAccess as a required string constrained to the known values (cpd, cpdppp)
  • ⏳ completeSsoProfile never grants cpdppp from the submitted accountAccess alone. It creates the profile on the cpd floor and hands any supplied PaymentIntent to Stripe verification, whatever paymentStatus the client claims (#12594; supersedes the #4992 "pass the submitted value straight into createUserProfile" mechanism)
  • ⏳ An SSO user who selects "CPD only" at profile completion has accountAccess = 'cpd' on the resulting mb_user row (NOT 'cpdppp')
  • ⏳ An SSO user who selects "CPD + PPP" and whose Stripe PaymentIntent succeeded has accountAccess = 'cpdppp', written from the PaymentIntent's metadata.accountType
  • ⏳ A service test asserts that a client-selected cpdppp alone reaches createUserProfile as cpd
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 other users column is rejected BAD_REQUEST and 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 and id. † ‡
  • ✅ auth.signup.server-derived-verification-and-tier — the wizard still sends isVerified, accountAccess and payment* values. They are accepted for compatibility but never saved. isVerified comes only from the server's own GMC or AHPRA register lookup. The account starts on the cpd tier with no payment recorded. The paid tier and paymentStatus = 'completed' are written only from a Stripe PaymentIntent that Stripe reports as succeeded and that is not already bound to another account (#12594). † ‡
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 a credential-provider row from getLinkedAccounts) expanding the Security accordion sees a Change Password form with current password, new password, and confirm password fields (ChangePasswordForm.tsx, rendered by SecuritySection.tsx). † ‡
  • ✅ auth.change-password.success-feedback — Submitting valid current + new password calls authClient.changePassword with revokeOtherSessions: true and 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 no credential-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 any sendResetPassword error 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 sendResetPassword hook 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 (sendEmail in api/backend-ppp/src/utils/mailer-helper.ts) emits a structured event: 'ACS_SEND_FAILURE' log marker. An Azure Monitor Scheduled Query Rule (api/infra-azure/src/index.ts) fires on any ACS_SEND_FAILURE occurrence 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's AZURE_COMMUNICATION_CONNECTION_STRING and 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. †
Sign-Up Failure Journey ​

Acceptance Criteria ​

  • ⏳ auth.signup.failure-offers-login — When sign-up fails because an account already exists for the supplied email, the page MUST present a prominent "Log in instead" CTA that routes the user to the login screen. The user must never reach a dead end with no recovery path. †
First-Login Redirect ​

Acceptance Criteria ​

  • ⏳ auth.onboarding.first-login-redirect-profile — Upon completing the CPD-plan suggestion step during onboarding, a user logging in for the first time MUST be redirected to the Profile completion screen so they can fill in the required details before accessing the dashboard. †
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-session polled 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-session on 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 the VITE_ENABLE_SSO=true build flag set on the ci-gate UAT frontend build (the only build feeding the ppp-frontend-uat-build artifact). 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 carries for-discussion. The flag is scoped to UAT — production has no frontend build in cd.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 by buildSocialProviders (only providers with CLIENT_ID+CLIENT_SECRET present render), so the flag never exposes an unconfigured provider. Mobile native SSO (system-browser OAuth + ppp://auth/sso/callback deep-link handling) is out of scope for this web-side enablement and is delivered separately in #10212 — see mobile.auth.sso-system-browser / mobile.auth.sso-callback-deep-link / mobile.auth.sso-web-buttons-hidden-in-webview in docs/features/mobile.md; within the native WebView wrapper the web SSO buttons are hidden (they would dead-end in disallowed_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 — callbackURL set to the originally requested path, not hardcoded / (#5046)
  • ⚠️ OAuth error params (?error=access_denied) on SSO callback surfaced to user with explanation (#5048)
  • ⏳ completeSsoProfile wrapped in a database transaction — no duplicate user profiles on concurrent requests (#5050)
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 persists enterpriseSsoProvider, enterpriseTenantId, and enterpriseSsoBoundAt on the user row. enterpriseSsoBoundAt IS NOT NULL is 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 a getEnterpriseSsoStatus tRPC 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 ​
DateChangePR/IssueReason
2026-10-04External (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, #12531Rob 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-04The 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, #12531Rob 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-04Better 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, #12833NAS 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-29Added 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, #12629Follow-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-29Fixed 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, #12616Regressed the "reflect immediately" guarantee #7734/#5619/#5622 were filed to fix, found in PR #12617's review (1e02b4900).
2026-09-29auth.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, #12594Security (#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-29Added 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.#12610Critical 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-29Added 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.#12616Critical 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-28Per-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.#12533Security 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-08Enabled 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.#10195Rob'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-08Resolved 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, #10195The 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-04Backfilled 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-09Add AC auth.api.token-queries-rate-limited — getMobileToken, getLinkedAccounts and getEnterpriseSsoStatus promoted from bare protectedProcedure to rateLimitedProtectedProcedure (default tier).#8383, #8375Surfaced 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-03Resolve Q5 (per-status login messages, #4993) to Closed Questions; flip the account-status login AC to delivered.#8166SGD 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-01Documented 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, #7876The 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-26Implemented 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, #7327Without account-less approver auth, external timesheet/WBA approvers had to register full PPP accounts — blocking the core hospital-evaluation use case (#7327).
2026-05-20Added 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, #6671First 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-20AHPRA validation cache — ppp_ahpra_validation_cache DB table, cache service, annual scheduler wiring, ToS posture documented.#4842Redis 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-19Hardened 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, #6577UAT 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-19SGD 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-23Triage 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-2327 open issues had no login/SSO spec coverage; status was wrong.
2026-04-21Triage 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, #4412Unblocks drift detection on the features index.
2026-04-13Initial spec — external approver isolation code, AHPRA caching, identity model cross-ref#4827, #4842, #4832, #4630Rob & 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-21Added SSO profile completion accountAccess invariant — backend must persist the value submitted by the user, never hard-code cpdppp#4992Security 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-21Added Session Expiry Handling section — global 401 interceptor redirects to /login with toast on expired session#5044Before 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-28Added 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.#4625Matt'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-21Added GMC licence-status enforcement invariant — isVerified = true requires an allow-listed licenceStatus from the GMC register#5069Security / 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.

Internal documentation — org members only