fix/auth: give backend providers equal account discovery and recovery #41

Open
BlackHatMagic wants to merge 1 commit from fix/unified-provider-discovery into master

Closes #40. Supersedes the source-dependent account architecture in #39.

All configured providers participate in browser-bound directory linking and fresh-device recovery. Backend credentials/exchange stay on their host; public metadata is fetched from that host, and one-use verifier-bound provider tokens are independently verified by the directory. Metadata registration occurs on explicit admin/account actions, never settings rendering. Equivalent app configurations appear once, but each registration authenticates independently and retains its namespace. Existing local guests recover their exact users and permissions, without invitations or role changes; simultaneous local/discovery collisions fail closed and link inserts are transactional. Distinct applications are never deduplicated just by name/email. Cloudflare remains separate infrastructure authorization.

Checks: 80 tests (7 shared, 33 worker, 40 plugin), typecheck, full Worker/login/plugin build, plugin packaging and git diff --check. New SQLite-backed cross-service tests exercise arbitrary OAuth and ID-token-only OIDC, fresh-device multi-host recovery, exact guest roles, browser binding, verifier mismatch, callback/proof/claim replay, independent provider verification and collision rejection. Plugin tests cover equivalent app grouping and no source-dependent fallback.

Rollout requires vault 0007 and login 0002 migrations, both Workers, and the updated plugin. No production deployment, registrations, sessions, reset data or device files were changed. Real browser/provider/mobile and multi-window return validation remain outstanding; this PR does not claim to fix pre-existing untargeted Obsidian callbacks or consumed Reopen-browser URLs. Equivalent callbacks may require extra provider consent; a provider choice is not an unsafe identity merge.

Closes #40. Supersedes the source-dependent account architecture in #39. All configured providers participate in browser-bound directory linking and fresh-device recovery. Backend credentials/exchange stay on their host; public metadata is fetched from that host, and one-use verifier-bound provider tokens are independently verified by the directory. Metadata registration occurs on explicit admin/account actions, never settings rendering. Equivalent app configurations appear once, but each registration authenticates independently and retains its namespace. Existing local guests recover their exact users and permissions, without invitations or role changes; simultaneous local/discovery collisions fail closed and link inserts are transactional. Distinct applications are never deduplicated just by name/email. Cloudflare remains separate infrastructure authorization. Checks: 80 tests (7 shared, 33 worker, 40 plugin), typecheck, full Worker/login/plugin build, plugin packaging and git diff --check. New SQLite-backed cross-service tests exercise arbitrary OAuth and ID-token-only OIDC, fresh-device multi-host recovery, exact guest roles, browser binding, verifier mismatch, callback/proof/claim replay, independent provider verification and collision rejection. Plugin tests cover equivalent app grouping and no source-dependent fallback. Rollout requires vault 0007 and login 0002 migrations, both Workers, and the updated plugin. No production deployment, registrations, sessions, reset data or device files were changed. Real browser/provider/mobile and multi-window return validation remain outstanding; this PR does not claim to fix pre-existing untargeted Obsidian callbacks or consumed Reopen-browser URLs. Equivalent callbacks may require extra provider consent; a provider choice is not an unsafe identity merge.
Refs #40. Keep registration namespaces isolated while presenting equivalent apps once. Verify brokered provider credentials independently and recover exact local users without new invitations or role changes.
Code-Reviewer left a comment

Pi code review

5 new actionable findings

  • [P1] Untrusted registrations can redirect or disable sign-ins for an existing app — packages/worker/src/login-service.ts:199
  • [P2] A failing equivalent registration discards already discovered accounts — packages/worker/src/login-service.ts:642
  • [P2] An unavailable saved backend blocks recovery to other backends — packages/plugin/src/account-login.ts:14
  • [P2] Web provider deduplication hides existing shared-account links — packages/worker/src/login-service.ts:256
  • [P2] An unrelated provider outage blocks local identity verification — packages/worker/src/account.ts:67

Reviewed the candidate findings against the pinned head and base, focusing on provider registration and account recovery. Verification was limited to repository reads; no tests, builds, or browser flows were run.

Change walkthrough
Area Files Changes
Other code (12) packages/shared/src/identity-provider.ts, packages/shared/src/account.ts, packages/worker/src/login-service.ts, packages/worker/src/auth.ts (+8 more) Define public provider metadata and application-equivalence keys. Extend login configuration and account results with provider metadata and user IDs. Register backend providers and traverse equivalent registrations during discovery. Expose provider metadata and issue verifier-bound broker results.
Tests (1) packages/worker/src/federated-login.test.ts Add cross-service federation and recovery tests.
Documentation (2) README.md, docs/DEPLOY.md Document unified provider discovery and credential-hosting boundaries. Document federation deployment and migration requirements.

Review effort: 4/5.

Static observations (not validation results)
Observation Detail
⚠️ Diff size 25 files, +1202/-163. Large diff; review coverage may be incomplete.
Binary changes No binary changes reported by this diff.
Credential patterns No matches after excluding known examples/placeholders. Added-line heuristics only; not a security audit.

Reviewed e738a8d71e09b798b7bc14ab69944d9ad6e38566 with proxy/glm-5.3-flash + proxy/deepseek-v4.1-flash + proxy/gpt-6.1-sol → proxy/gpt-6.1-terra. Automated advisory review; no project commands or tests were executed.

<!-- forgejo-pi-review:983c6ad22ae21b55eaa3963df96cf4f15a2a12c8d119a77f8918f0a501b43bb0 --> ## Pi code review **5 new actionable findings** - **[P1] Untrusted registrations can redirect or disable sign-ins for an existing app** — `packages/worker/src/login-service.ts:199` - **[P2] A failing equivalent registration discards already discovered accounts** — `packages/worker/src/login-service.ts:642` - **[P2] An unavailable saved backend blocks recovery to other backends** — `packages/plugin/src/account-login.ts:14` - **[P2] Web provider deduplication hides existing shared-account links** — `packages/worker/src/login-service.ts:256` - **[P2] An unrelated provider outage blocks local identity verification** — `packages/worker/src/account.ts:67` Reviewed the candidate findings against the pinned head and base, focusing on provider registration and account recovery. Verification was limited to repository reads; no tests, builds, or browser flows were run. <details> <summary>Change walkthrough</summary> | Area | Files | Changes | | --- | --- | --- | | Other code (12) | `packages/shared/src/identity-provider.ts`, `packages/shared/src/account.ts`, `packages/worker/src/login-service.ts`, `packages/worker/src/auth.ts` (+8 more) | Define public provider metadata and application-equivalence keys. Extend login configuration and account results with provider metadata and user IDs. Register backend providers and traverse equivalent registrations during discovery. Expose provider metadata and issue verifier-bound broker results. | | Tests (1) | `packages/worker/src/federated-login.test.ts` | Add cross-service federation and recovery tests. | | Documentation (2) | `README.md`, `docs/DEPLOY.md` | Document unified provider discovery and credential-hosting boundaries. Document federation deployment and migration requirements. | Review effort: **4/5**. </details> <details> <summary>Static observations (not validation results)</summary> | Observation | Detail | | --- | --- | | ⚠️ Diff size | 25 files, +1202/-163. Large diff; review coverage may be incomplete. | | Binary changes | No binary changes reported by this diff. | | Credential patterns | No matches after excluding known examples/placeholders. Added-line heuristics only; not a security audit. | </details> --- Reviewed `e738a8d71e09b798b7bc14ab69944d9ad6e38566` with `proxy/glm-5.3-flash + proxy/deepseek-v4.1-flash + proxy/gpt-6.1-sol → proxy/gpt-6.1-terra`. Automated advisory review; no project commands or tests were executed.
@ -20,3 +14,1 @@
);
} catch (error) {
errors.push(error instanceof Error ? error.message : String(error));
if (backend && api) await registerBackendProviders(backend);
Collaborator

[P2] An unavailable saved backend blocks recovery to other backends

Quality — Provider selection requires a successful metadata refresh for the saved backend before loading directory choices, even for a signed-out user trying to recover a different account.

Trigger: A signed-out device retains backend A's URL, A returns an error from its metadata endpoint, and the user tries to sign in to a linked account on healthy backend B.

Impact: Backend A's outage prevents directory recovery to otherwise available backend B.

Evidence: main.ts retains backendUrl on disconnect, rebuilds an ApiClient for it without a session, and passes both to selectAccountProvider. The awaited registration precedes loginConfig and throws on a failed metadata fetch; the base implementation caught backend-provider loading errors and still offered shared providers.

**[P2] An unavailable saved backend blocks recovery to other backends** Quality — Provider selection requires a successful metadata refresh for the saved backend before loading directory choices, even for a signed-out user trying to recover a different account. **Trigger:** A signed-out device retains backend A's URL, A returns an error from its metadata endpoint, and the user tries to sign in to a linked account on healthy backend B. **Impact:** Backend A's outage prevents directory recovery to otherwise available backend B. **Evidence:** main.ts retains backendUrl on disconnect, rebuilds an ApiClient for it without a session, and passes both to selectAccountProvider. The awaited registration precedes loginConfig and throws on a failed metadata fetch; the base implementation caught backend-provider loading errors and still offered shared providers.
@ -46,0 +64,4 @@
): Promise<void> {
if (!proof.localProvider && !proof.localSubject && !proof.localApp) return;
if (proof.localApp && proof.localProvider && proof.localSubject) {
const provider = (await identityProviders(env)).find((app) => app.id === proof.localProvider);
Collaborator

[P2] An unrelated provider outage blocks local identity verification

Quality — Verifying a local proof enumerates every enabled provider and fetches discovery metadata for each one. A failure in an unrelated OIDC provider therefore prevents verification of the healthy provider being used.

Trigger: A backend has multiple enabled providers, one OIDC issuer's discovery endpoint fails, and a user links or recovers through a different provider with local claims.

Impact: Linking and local-account recovery on that backend fail even though the selected provider is healthy.

Evidence: verifyLocalProof calls identityProviders(env) before finding the claimed provider. identityProviders uses Promise.all over all enabled providers, and endpointsFor throws when any OIDC discovery request fails. Both linkDiscoveryIdentity and resolveDiscoveryUser invoke this check.

**[P2] An unrelated provider outage blocks local identity verification** Quality — Verifying a local proof enumerates every enabled provider and fetches discovery metadata for each one. A failure in an unrelated OIDC provider therefore prevents verification of the healthy provider being used. **Trigger:** A backend has multiple enabled providers, one OIDC issuer's discovery endpoint fails, and a user links or recovers through a different provider with local claims. **Impact:** Linking and local-account recovery on that backend fail even though the selected provider is healthy. **Evidence:** verifyLocalProof calls identityProviders(env) before finding the claimed provider. identityProviders uses Promise.all over all enabled providers, and endpointsFor throws when any OIDC discovery request fails. Both linkDiscoveryIdentity and resolveDiscoveryUser invoke this check.
@ -99,0 +196,4 @@
.map((row) => row.id)
: [];
const remaining = input.linkTicket ? [] : equivalent;
if (remaining.length > 15)
Collaborator

[P1] Untrusted registrations can redirect or disable sign-ins for an existing app

Security — A public backend can copy an existing app's metadata and join its equivalence group without proving control of the OAuth application. Users selecting that app can then be sent to the attacker's broker, or the attacker can disable discovery for the app by registering enough copies.

Trigger: An attacker serves copied public app metadata from an HTTPS backend and calls the unauthenticated registration endpoint. A single copy is included in normal equivalent-registration flows; 16 distinct provider IDs exceed the start limit.

Impact: Users can be routed from the trusted sign-in flow to an attacker-controlled phishing page. With 16 copies, all directory sign-ins for the affected app fail before authentication, including fresh-device recovery.

Evidence: POST /v1/providers/register accepts up to 32 IDs after fetching metadata from the supplied host, without verifying control of the copied OAuth app. /v1/config publishes the registrations; /v1/start groups them solely by identityProviderKey and rejects more than 15 remaining registrations. Otherwise the callback chain redirects the browser to each remote backend's /auth/broker/start.

**[P1] Untrusted registrations can redirect or disable sign-ins for an existing app** Security — A public backend can copy an existing app's metadata and join its equivalence group without proving control of the OAuth application. Users selecting that app can then be sent to the attacker's broker, or the attacker can disable discovery for the app by registering enough copies. **Trigger:** An attacker serves copied public app metadata from an HTTPS backend and calls the unauthenticated registration endpoint. A single copy is included in normal equivalent-registration flows; 16 distinct provider IDs exceed the start limit. **Impact:** Users can be routed from the trusted sign-in flow to an attacker-controlled phishing page. With 16 copies, all directory sign-ins for the affected app fail before authentication, including fresh-device recovery. **Evidence:** POST /v1/providers/register accepts up to 32 IDs after fetching metadata from the supplied host, without verifying control of the copied OAuth app. /v1/config publishes the registrations; /v1/start groups them solely by identityProviderKey and rejects more than 15 remaining registrations. Otherwise the callback chain redirects the browser to each remote backend's /auth/broker/start.
@ -134,0 +253,4 @@
const links = available
.filter((provider) => {
const key = identityProviderKey(provider.app);
if (seen.has(key)) return false;
Collaborator

[P2] Web provider deduplication hides existing shared-account links

Compliance — The web picker prefers a backend registration over an equivalent shared registration, but the web flow authenticates only the selected namespace. An existing shared-only link therefore cannot be recovered through that choice.

Trigger: A backend has an app equivalent to a shared-service app, and a user previously linked only the shared identity. The user follows the backend's shared sign-in link and selects the deduplicated provider.

Impact: A previously working browser sign-in fails until the user relinks or uses another recovery path.

Evidence: /web lists backend registrations first and removes subsequent choices with the same identityProviderKey. /web/start does not initialize equivalent traversal, and the callback uses the backend-specific identity hash and local proof, neither of which matches the user's historical shared-only binding. The base web picker offered the shared registration directly.

**[P2] Web provider deduplication hides existing shared-account links** Compliance — The web picker prefers a backend registration over an equivalent shared registration, but the web flow authenticates only the selected namespace. An existing shared-only link therefore cannot be recovered through that choice. **Trigger:** A backend has an app equivalent to a shared-service app, and a user previously linked only the shared identity. The user follows the backend's shared sign-in link and selects the deduplicated provider. **Impact:** A previously working browser sign-in fails until the user relinks or uses another recovery path. **Evidence:** /web lists backend registrations first and removes subsequent choices with the same identityProviderKey. /web/start does not initialize equivalent traversal, and the callback uses the backend-specific identity hash and local proof, neither of which matches the user's historical shared-only binding. The base web picker offered the shared registration directly.
@ -364,0 +639,4 @@
// One provider choice may contain several equivalent registrations. Verify
// them separately in the same browser; never equate subjects across hosts.
const remaining = JSON.parse(flow.remaining_providers || "[]") as string[];
if (result.status === "ready" && remaining.length) {
Collaborator

[P2] A failing equivalent registration discards already discovered accounts

Quality — Discovery requires every equivalent registration to complete before returning any accounts. A later failed hop aborts the flow even when an earlier hop already found a usable account.

Trigger: Two legitimate equivalent registrations exist and one backend is unavailable, has invalid credentials, or its additional consent is declined.

Impact: Users cannot recover accounts on healthy backends through discovery until the failing registration works or is removed; an unreachable browser redirect can instead leave the flow pending until timeout.

Evidence: The callback stores prior candidates in accounts_ct and redirects to the next registration whenever remaining_providers is nonempty. Broker failures and declined authorization reach the outer catch, which stores an error; /v1/claim then consumes the flow and returns the error rather than accounts_ct. Registrations are removed only when their backend re-registers without them.

**[P2] A failing equivalent registration discards already discovered accounts** Quality — Discovery requires every equivalent registration to complete before returning any accounts. A later failed hop aborts the flow even when an earlier hop already found a usable account. **Trigger:** Two legitimate equivalent registrations exist and one backend is unavailable, has invalid credentials, or its additional consent is declined. **Impact:** Users cannot recover accounts on healthy backends through discovery until the failing registration works or is removed; an unreachable browser redirect can instead leave the flow pending until timeout. **Evidence:** The callback stores prior candidates in accounts_ct and redirects to the next registration whenever remaining_providers is nonempty. Broker failures and declined authorization reach the outer catch, which stores an error; /v1/claim then consumes the flow and returns the error rather than accounts_ct. Registrations are removed only when their backend re-registers without them.
This pull request can be merged automatically.
You are not authorized to merge this pull request.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin fix/unified-provider-discovery:fix/unified-provider-discovery
git switch fix/unified-provider-discovery

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch master
git merge --no-ff fix/unified-provider-discovery
git switch fix/unified-provider-discovery
git rebase master
git switch master
git merge --ff-only fix/unified-provider-discovery
git switch fix/unified-provider-discovery
git rebase master
git switch master
git merge --no-ff fix/unified-provider-discovery
git switch master
git merge --squash fix/unified-provider-discovery
git switch master
git merge --ff-only fix/unified-provider-discovery
git switch master
git merge fix/unified-provider-discovery
git push origin master
Sign in to join this conversation.
No reviewers
No labels
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
BlackHatMagic/Behold.quest!41
No description provided.