Linked Sign-in Accounts
Feature Overview
A doctor has one master PPP account (created with email/password or a social provider at sign-up). They can optionally add one or more additional sign-in methods — their hospital Microsoft 365 account, a Google Workspace account, personal Gmail — so they can reach the same PPP profile from any of their credentials.
Design principle: No hospital IT admin involvement required. The doctor authenticates directly with the provider using their own credentials. PPP uses standard OAuth scopes (openid email profile) only — no privileged tenant permissions, no Azure AD app approval, no hospital IT coordination.
This feature is entirely about identity/sign-in. It has no relationship to "My Hospitals" (which hospital a doctor works at for CPD purposes). Those remain separate, decoupled concepts.
Open Questions
| # | Question | Ref | Proposed answer |
|---|---|---|---|
| — | No open questions. |
Original Vision
- Doctor signs up with personal email (e.g.
rob@gmail.com) - Doctor can later add their hospital M365 account (
rob.duncan@nhs.uk) as a second sign-in method - Doctor can also add a Google Workspace account or Apple ID
- All linked accounts resolve to the same PPP user record — same data, same subscription
- Doctor can remove any linked account as long as at least one remains
- No special approval flow, no IT admin contact, no hospital tenant ID mapping
What Was Built Before (Retired)
The previous "Linked Hospital Accounts" section (LinkedHospitals.tsx) attempted to:
- Trigger M365 OAuth
- Decode the returned Entra ID token to extract a tenant ID
- Look up which hospital owns that tenant in a
hospital_tenantstable - Create a
user_assigned_hospitalsrecord
This required hospitals to register their Entra tenant IDs in the PPP database — a coordination overhead that was never completed, leaving the feature permanently broken. This section and the hospitalLinking router have been removed as part of this feature (#4587).
Acceptance Criteria
Sign-in Methods Display
- ✅ "Linked Accounts" accordion on
/my-profileshows all current sign-in methods - ✅ Each method displays: provider icon, provider name (Email & Password / Google / Microsoft / Apple), account email/ID (for OAuth accounts)
- ✅ Email & Password account cannot be unlinked (it is always shown but has no Unlink button)
- ✅ OAuth accounts show an "Unlink" button, disabled when only one method remains
- ✅ The section shows a prompt to add a backup sign-in method when only one method is linked
Linking a New Account
- ✅ Doctor can click "Link Account" next to any available-but-unlinked provider (Google, Microsoft)
- ✅ Clicking initiates a proper OAuth account linking flow (not a new sign-in) so it attaches to the current session regardless of email address
- ✅ On return from OAuth, the new provider is added to the doctor's linked accounts list
- ✅ Duplicate links (same provider already linked) are handled gracefully with a clear message
- ⏳ Flow works correctly in the mobile app WebView (web browser confirmed; mobile WebView not explicitly smoke-tested)
Unlinking an Account
- ✅ Doctor can unlink any linked OAuth provider
- ✅ Unlinking the last remaining method is blocked with a clear error: "Cannot unlink — this is your only sign-in method"
- ✅ Confirmation dialog shown before unlinking
- ✅ SSO profile completion does not grant consultant status unverified (#7643).
completeSsoProfile(the social-login profile-completion path inauthService) previously hard-codeduserType=consultant. It now resolves the verified user type via the sharedresolveVerifiedUserTypehelper, so the consultant role is only granted when the AHPRA/GMC registration lookup confirms it; otherwise the SSO user is created asnon-consultant. Canonical ACs live indocs/features/medical-registration-verification.md. - ✅ SSO profile completion does not grant the paid tier from the plan choice (#12594).
completeSsoProfilecreates the profile on thecpdtier and passes any supplied PaymentIntent to Stripe verification.cpdpppis written only from a PaymentIntent that Stripe reports as succeeded. Canonical ACs live indocs/features/auth.md(SSO Profile Completion — Account Access Invariant).
Removed: Linked Hospital Accounts Section
- ✅ The "Linked Hospital Accounts" accordion (
LinkedHospitals.tsx) has been removed from/my-profile - ✅ The
hospitalLinkingtRPC router andhospitalLinkingServicehave been retired - ✅ The
hospital_tenantstable and schema remain in place (harmless, may be reused for future enterprise hospital federation features)
Architecture
How Better Auth Account Linking Works
Better Auth exposes a link social account endpoint distinct from sign-in:
GET /api/auth/link-account/social?provider=microsoft&callbackURL=...When called with an active session cookie, Better Auth:
- Initiates the OAuth flow for the requested provider
- On callback, links the returned identity to the existing session's user (not a new account)
- Inserts a new row in
auth_accountsfor the provider
This differs from /sign-in/social which creates or finds a session (email-match-only auto-linking).
Data Model
auth_users (Better Auth managed)
└── auth_accounts (one row per linked provider)
providerId: 'credential' | 'google' | 'microsoft' | 'apple'
accountId: provider's user ID (email or sub claim)
idToken: JWT from provider (stored by Better Auth)No custom tables required.
auth_users.ppp_user_id links a login to its PPP user and is server-owned. Better Auth rejects it as caller input (input: false). Only server code that has just created both rows may write it, through linkAuthUserToPppUser (#12610). See auth.identity.ppp-user-link-server-owned. The helper checks the login email against the PPP user's stored email, and a lost race returns 409 CONFLICT. SSO profile completion refuses with 409 when a PPP profile already exists for the login email. The login email never identifies the caller; only the linked pppUserId does (#12616, auth.identity.resolved-by-ppp-user-id).
tRPC Procedures (already implemented)
| Procedure | Description |
|---|---|
ppp.auth.getLinkedAccounts | Returns all auth_accounts rows for current user |
ppp.auth.unlinkAccount({ providerId }) | Deletes the auth_accounts row; blocks if last method |
ppp.auth.getAvailableProviders | Returns which OAuth providers are configured in the env |
Frontend Components
| Component | Location | Role |
|---|---|---|
LinkedAccounts.tsx | instances/ppp/src/modules/MyProfile/components/ | Displays linked accounts list, Add/Unlink actions |
MyProfile/index.tsx | instances/ppp/src/modules/MyProfile/ | Renders the "Linked Accounts" accordion |
Key Fix: handleLink Endpoint
// ❌ Before — starts a new sign-in session (wrong)
window.location.href = `${baseUrl}/sign-in/social?provider=${providerId}&callbackURL=...`;
// ✅ After — links to existing session (correct)
window.location.href = `${baseUrl}/link-account/social?provider=${providerId}&callbackURL=...`;Implementation
| File | Change |
|---|---|
instances/ppp/src/modules/MyProfile/components/LinkedAccounts.tsx | Change sign-in/social → link-account/social in handleLink; add confirm dialog before unlink |
instances/ppp/src/modules/MyProfile/index.tsx | Remove linked-hospitals accordion and LinkedHospitals import |
instances/ppp/src/modules/MyProfile/components/LinkedHospitals.tsx | Delete file |
api/backend-ppp/src/routers/procedures/hospitalLinking/index.ts | Delete file |
api/backend-ppp/src/services/hospitalLinkingService/ | Delete directory |
api/backend-ppp/src/routers/procedures/index.ts | Remove hospitalLinking export |
instances/ppp/e2e/bdd/features/auth.feature | Add @smoke scenarios for link and unlink |
Identity Model — Canonical User ID
Each PPP user has a canonical userId (UUID) that is the single source of truth across the platform. Email addresses are NOT primary keys — they are identity attachments on a join table managed by Better Auth:
auth_users (id PK, ...)
└── auth_accounts (userId FK, providerId, accountId, idToken, ...)
providerId: 'credential' | 'google' | 'microsoft' | 'apple'
accountId: provider's user ID (email or sub claim)A doctor commonly has a personal email + multiple hospital emails. Tying account = email locks them into a single email forever, breaks transitions between hospitals, and produces ghost duplicate accounts.
Rules:
- All foreign keys across PPP reference
user.id(NOTemail) - Sign-in via any linked identity resolves back to the same
userId - Email/password is one identity row; each OAuth provider (Google, Microsoft, Apple) is another row on the same
userId - Unlinking an identity removes the row but never the
user; the last identity cannot be unlinked
Tracked in #4843. Source: Rob & Matt call 13 Apr 2026 (~00:45:55 / 00:46:58).
Open GitHub Issues
Open issues on label:feature:linked-accounts — no open issues. Fetched at: 2026-10-13T07:29:49Z — live list on GitHub.
Change Log
| Date | Change | Reason |
|---|---|---|
| 2026-09-29 | SSO profile completion now creates the profile on the cpd tier. cpdppp is written only from a Stripe PaymentIntent that succeeded, not from the plan picked in the form. Cross-references the canonical ACs in auth.md. | #12607, #12594 — Security (#12594): the tier picked at sign-up was saved as submitted, so the paid tier could be claimed without paying. |
| 2026-09-29 | Data Model notes that auth_users.ppp_user_id is server-owned. Better Auth rejects it as caller input, and the email/password sign-up links it through linkAuthUserToPppUser after both rows exist. Linking a sign-in method is unchanged. | #12610 — Critical account takeover. The field was client-writable through Better Auth's update-user and sign-up endpoints, so any signed-in user could re-link their session to another PPP user. See auth.md auth.identity.ppp-user-link-server-owned. |
| 2026-09-29 | Linking a login to its PPP user (linkAuthUserToPppUser) now checks the login email against the PPP user's stored email, not an email the caller passes in. A lost race for the same PPP user returns 409 CONFLICT. SSO profile completion refuses with 409 when a PPP profile already exists for the login email. | #12616 — Hardening from the #12613 review, shipped with the #12616 identity fix. An unverified login email must never create a duplicate profile or bind to someone else's. See auth.identity.resolved-by-ppp-user-id. |
| 2026-05-19 | Feature complete — all sign-in linking/unlinking ACs implemented; spec updated from in-progress to complete; BDD smoke and regression scenarios added to auth.feature. | #6318, #4843 — Implementation was complete in code but spec still showed ⏳ items. Deep-dive audit confirmed all AC except mobile WebView smoke (tracked separately) are satisfied by LinkedAccounts.tsx + auth router. |
| 2026-04-07 | Initial spec | Redesign from M365 tenant-based hospital linking to provider-agnostic SSO account linking. Closes #4586 and #4587. No hospital IT admin involvement required. |
| 2026-04-13 | Identity model documented — canonical userId (NOT email) is the FK across all PPP tables; identities are rows on a join table | #4843. Per Rob & Matt call: doctors must be able to link multiple emails / SSO providers to one PPP profile without being tied to a single email address. |
| 2026-04-21 | SSO sign-in buttons must surface provider/network errors via a visible toast and re-enable the button — no silent hang | #5047. handleSsoSignIn previously fired-and-forgot authClient.signIn.social(), so misconfigured OAuth clients and offline networks produced a frozen UI with zero feedback. Error message must be human-readable and must not leak raw Better Auth internals. |