From 4d827c7bd4de14d0c08efffbe8ed2f93b9a26186 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 20:45:03 +0100 Subject: [PATCH 1/6] Heimdall: an app's invite grant lets a first Google sign-in mint an account, carried only in the signed state Bifrost's profile may grant; its authenticated sign_in start may carry firstLoginGrant invite. The callback mints only when no account holds the identity; otherwise identity_not_linked stands. Co-Authored-By: Claude Opus 5.5 --- src/app-profiles.ts | 9 +++++++++ src/app.ts | 43 +++++++++++++++++++++++++++++++++++++++++-- src/contracts.ts | 8 ++++++++ 3 files changed, 58 insertions(+), 2 deletions(-) diff --git a/src/app-profiles.ts b/src/app-profiles.ts index a77f76a..b388ce2 100644 --- a/src/app-profiles.ts +++ b/src/app-profiles.ts @@ -56,6 +56,14 @@ export interface AppProfile { * state. Absent for apps whose browser starts are public by design. */ startRequiresAppCaller?: boolean; + /** + * The app decides who is invited. Its authenticated sign_in start may carry + * `firstLoginGrant: "invite"`, which lets a provider that otherwise requires a + * link (Google) mint the account for an identity no account holds. The grant + * never attaches an identity to an existing account. Absent for every app that + * may not grant. + */ + mayGrantFirstLogin?: true; /** * The app may assert, with its secret and a member's live bearer, that the * member just passed a factor the app itself checked (POST @@ -170,6 +178,7 @@ const bifrostProfile: AppProfile = { managedConnectionProviders: [], allowedReturnOrigins: ["https://bifrost.gamecult.org"], startRequiresAppCaller: true, + mayGrantFirstLogin: true, stepUpAssertion: { methods: ["bifrost-passkey", "bifrost-email-code"] }, // A passkey proves the account; an email code proves an inbox, which is one login's worth at most. identityMoves: { accountProofMethods: ["bifrost-passkey"] }, diff --git a/src/app.ts b/src/app.ts index b3c7755..3ef3212 100644 --- a/src/app.ts +++ b/src/app.ts @@ -103,6 +103,7 @@ function buildOAuthStateToken(options: { entitlementPolicy: OAuthEntitlementPolicy | undefined; requestedScopes: string[] | undefined; stepUp: boolean | undefined; + firstLoginGrant: "invite" | undefined; keys: ReturnType; }): { token: string; jti: string; expiresAt: string } { const issuedAt = nowEpochSeconds(); @@ -126,6 +127,7 @@ function buildOAuthStateToken(options: { entitlement_policy: options.entitlementPolicy ?? null, requested_scopes: options.requestedScopes ?? null, step_up: options.stepUp ? true : null, + first_login_grant: options.firstLoginGrant ?? null, }; const token = signJwt(payload as unknown as Record, options.keys); @@ -190,7 +192,8 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay !entitlementPolicyIsValid || !(payload.initiator_account_id === undefined || payload.initiator_account_id === null || typeof payload.initiator_account_id === "string") || !requestedScopesAreValid || - !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) + !(payload.step_up === undefined || payload.step_up === null || payload.step_up === true) || + !(payload.first_login_grant === undefined || payload.first_login_grant === null || (payload.first_login_grant === "invite" && payload.mode === "sign_in")) ) { return null; } @@ -211,6 +214,9 @@ function parseOAuthStatePayload(payload: Record): OAuthStatePay if (!normalizedPayload.step_up) { normalizedPayload.step_up = null; } + if (!normalizedPayload.first_login_grant) { + normalizedPayload.first_login_grant = null; + } return normalizedPayload; } @@ -827,6 +833,23 @@ export async function startOAuthFlow( return { statusCode: 401, body: { error: "app_auth_required" } }; } + // A grant is the app's word that it invited this person: only the authenticated app caller of a profile that may grant, and only on sign_in. + // After the app-secret gate, so a caller without the secret learns nothing about what a grant needs. + if (input.firstLoginGrant !== undefined) { + const grantAllowed = + input.firstLoginGrant === "invite" && + input.mode === "sign_in" && + isAppCaller(caller) && + caller.appSlug === profile.slug && + profile.mayGrantFirstLogin === true; + if (!grantAllowed) { + return { + statusCode: 400, + body: { error: "first_login_grant_refused", detail: "firstLoginGrant needs the app's own sign_in start, from an app that may grant." }, + }; + } + } + // After the app-secret gate, so a caller without the secret learns nothing about what a target must look like. if (input.connection !== undefined && !isUsableConnectionTarget(input.connection.targetId)) { return { @@ -865,6 +888,7 @@ export async function startOAuthFlow( entitlementPolicy, requestedScopes: input.requestedScopes, stepUp: input.stepUp, + firstLoginGrant: input.firstLoginGrant, keys, }); return { @@ -1509,6 +1533,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise { @@ -2142,6 +2172,15 @@ export async function buildApp(options: BuildAppOptions = {}): Promise Date: Sun, 29 Nov 2026 20:45:04 +0100 Subject: [PATCH 2/6] Tests: invite grant mints, is refused without the app caller, other apps, link mode, tampered state Co-Authored-By: Claude Opus 5.5 --- tests/google-link.test.ts | 138 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 138 insertions(+) diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index 4a1fc6d..fc26db4 100644 --- a/tests/google-link.test.ts +++ b/tests/google-link.test.ts @@ -535,3 +535,141 @@ describe("Google as a Heimdall OIDC provider", () => { expect(accountCount(store)).toBe(1); }); }); + +describe("an invite grant lets Bifrost's sign-in start mint the first Google account", () => { + const RETURN = "https://bifrost.gamecult.org/auth/heimdall/complete"; + + function startGrant(app: FastifyInstance, extra: Record = {}, headers: Record = BIFROST_APP) { + return app.inject({ + method: "POST", + url: "/v1/oauth/google/start", + headers, + payload: { appSlug: "bifrost", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite", ...extra }, + }); + } + + async function googleCallback(app: FastifyInstance, start: { json(): never }, claims?: Record) { + const flow = await launchWithRedirect(app, start.json()); + fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) }); + return { flow, done: await callbackGoogle(app, flow) }; + } + + const auditEvents = (store: InMemoryStore) => + [...(store as unknown as { auditEvents: Map }).auditEvents.values()]; + + it("google_first_login_without_grant_refused: no grant, identity_not_linked, nothing minted", async () => { + const { app, store } = await build(); + const start = await startGoogle(app, undefined, "sign_in"); + const { done } = await googleCallback(app, start); + expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]); + expect(accountCount(store)).toBe(0); + }); + + it("google_first_login_with_bifrost_grant_mints: one account, the identity linked to it, audited", async () => { + const { app, store } = await build(); + const start = await startGrant(app); + expect(start.statusCode).toBe(201); + const { done } = await googleCallback(app, start); + expect(done.statusCode).toBe(201); + expect(accountCount(store)).toBe(1); + expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(done.json().account.id); + const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant"); + expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "bifrost" }]); + }); + + it("a granted state is single-use: replaying the callback mints nothing more", async () => { + const { app, store } = await build(); + const start = await startGrant(app); + const { flow } = await googleCallback(app, start); + const again = await callbackGoogle(app, flow); + expect(again.statusCode).toBeGreaterThanOrEqual(400); + expect(accountCount(store)).toBe(1); + }); + + it("grant_from_other_app_refused: an app whose profile may not grant gets first_login_grant_refused", async () => { + const { app, store } = await build(); + const res = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + headers: { "x-heimdall-app-secret": "repixelizer-secret" }, + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, + }); + expect([res.statusCode, res.json().error]).toEqual([400, "first_login_grant_refused"]); + // Another app's secret on Bifrost's start is no Bifrost caller. + const other = await startGrant(app, {}, { "x-heimdall-app-secret": "repixelizer-secret" }); + expect(other.statusCode).toBe(401); + expect(accountCount(store)).toBe(0); + }); + + it("grant_without_app_caller_refused: a public start with firstLoginGrant is refused", async () => { + const { app, store } = await build(); + for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }]) { + const res = await startGrant(app, {}, headers); + expect(res.statusCode, JSON.stringify(headers)).toBeGreaterThanOrEqual(400); + expect(res.json().authorizationUrl).toBeUndefined(); + } + // An app that does not require a caller is still refused by the grant gate itself. + const open = await app.inject({ + method: "POST", + url: "/v1/oauth/discord/start", + payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, + }); + expect([open.statusCode, open.json().error]).toEqual([400, "first_login_grant_refused"]); + expect(accountCount(store)).toBe(0); + }); + + it("refuses a grant on link mode and a grant value other than invite", async () => { + const { app } = await build(); + const { accessToken } = await signInWithDiscord(app); + const link = await app.inject({ + method: "POST", + url: "/v1/oauth/google/start", + headers: { ...BIFROST_APP, authorization: `Bearer ${accessToken}` }, + payload: { appSlug: "bifrost", mode: "link", returnTo: RETURN, firstLoginGrant: "invite" }, + }); + expect([link.statusCode, link.json().error]).toEqual([400, "first_login_grant_refused"]); + expect((await startGrant(app, { firstLoginGrant: "admin" })).statusCode).toBe(400); + }); + + it("grant_ignored_for_existing_account: a Google identity already held signs in to its account, no second account", async () => { + const { app, store } = await build(); + const { accessToken, accountId } = await signInWithDiscord(app); + await linkGoogle(app, accessToken); + const start = await startGrant(app); + const { done } = await googleCallback(app, start); + expect(done.statusCode).toBe(201); + expect(done.json().account.id).toBe(accountId); + expect(accountCount(store)).toBe(1); + expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false); + }); + + it("a grant never attaches an identity to an existing account: a new sub mints its own account and an held sub is never moved", async () => { + const store = new InMemoryStore(); + const first = await build(store, "discord-1"); + const a = await signInWithDiscord(first.app, "discord-1"); + await linkGoogle(first.app, a.accessToken); + const second = await build(store, "discord-2"); + const b = await signInWithDiscord(second.app, "discord-2"); + const start = await startGrant(second.app); + const { done } = await googleCallback(second.app, start, { sub: "g-sub-new" }); + expect(done.statusCode).toBe(201); + expect(done.json().account.id).not.toBe(a.accountId); + expect(done.json().account.id).not.toBe(b.accountId); + expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(a.accountId); + expect((await store.findStoredLinkedIdentity("google", "g-sub-new"))?.accountId).toBe(done.json().account.id); + }); + + it("grant_tampered_state_refused: a first_login_grant added to a signed state fails verification", async () => { + const { app, store } = await build(); + const plain = await startGoogle(app, undefined, "sign_in"); + const [head, body, sig] = stateOf(plain.json()).split("."); + const payload = JSON.parse(Buffer.from(body!, "base64url").toString()); + const forged = [head, Buffer.from(JSON.stringify({ ...payload, first_login_grant: "invite" })).toString("base64url"), sig].join("."); + const launched = await app.inject({ method: "GET", url: `/v1/oauth/google/launch?state=${encodeURIComponent(forged)}` }); + expect(launched.statusCode).toBe(400); + expect(launched.headers.location).toBeUndefined(); + const cb = await app.inject({ method: "GET", url: `/v1/oauth/google/callback?code=g-code&state=${encodeURIComponent(forged)}` }); + expect(cb.statusCode).toBeGreaterThanOrEqual(400); + expect(accountCount(store)).toBe(0); + }); +}); -- 2.47.3 From 8d350be506b4b75e8449e5c1f894a2d5419069bb Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 20:45:04 +0100 Subject: [PATCH 3/6] Service contract: Google section gains the invite grant Co-Authored-By: Claude Opus 5.5 --- docs/service-contract.md | 28 +++++++++++++++++++++------- 1 file changed, 21 insertions(+), 7 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index 6b77caa..f14602d 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -236,10 +236,11 @@ Launch note: implemented yet - Repixelizer launch can configure Discord and Patreon on its provider buttons -### Google (OpenID Connect, link-only) +### Google (OpenID Connect, link-only; mints only under an invite grant) -`google` is an identity provider that never mints an account. It is a second -door into a person who already has one. +`google` is an identity provider that does not mint an account by itself. It is +a second door into a person who already has one, and a first door only for a +person an app has invited (see the invite grant below). - Callback redirect URI (register exactly this in the Google Cloud OAuth client): `{GC_ACCESS_BASE_URL}/v1/oauth/google/callback`, which is @@ -256,10 +257,23 @@ door into a person who already has one. - `mode: "link"` needs `Authorization: Bearer ` for the same app; the identity attaches to that token's account and to no other. `mode: "sign_in"` signs in an account the `sub` is already linked to. -- A `sub` no account holds, arriving with `sign_in`, is refused and mints - nothing. A `sub` linked to another account is refused and never moved. - Both audit as `oauth_callback_failed` with error class `LinkRefusal` - and the code `identity_not_linked` or `link_initiator_mismatch`. +- A `sub` no account holds, arriving with `sign_in` and no invite grant, is + refused and mints nothing. A `sub` linked to another account is refused and + never moved. Both audit as `oauth_callback_failed` with error class + `LinkRefusal` and the code `identity_not_linked` or `link_initiator_mismatch`. +- Invite grant. An app whose profile sets `mayGrantFirstLogin` (only `bifrost`) + may start `mode: "sign_in"` with `firstLoginGrant: "invite"`, saying it has + invited this person. The start must carry that app's own secret; any other + caller, any other app, any other mode, or any other value is + `400 first_login_grant_refused` (a Bifrost start without the secret is still + `401 app_auth_required`). The grant rides only in the signed state + (`first_login_grant`), so nothing a browser sends can set it, and the state + stays single-use. At the callback a `sub` no account holds, under a grant, + mints one account with that identity linked, and audits + `account_minted_by_grant` with `{ provider, appSlug }`. A `sub` an account + already holds signs in to that account exactly as without a grant; the grant + never attaches an identity to an existing account and never moves one. + `mode: "link"` takes no grant and is unchanged. - Link is two-phase. The callback verifies the identity and records a pending link (TTL `completionTtlSeconds`), answering `status: "link_pending"` with a `pendingLinkId` and no session; it writes no linked identity. The app calls -- 2.47.3 From c8c26dc6585bb62fb4a4e35f5ab6aa88b55be8c6 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 20:47:46 +0100 Subject: [PATCH 4/6] Grant gate: keep the caller check on one line, as the caller-identity source test requires Co-Authored-By: Claude Opus 5.5 --- src/app.ts | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/app.ts b/src/app.ts index 3ef3212..003636e 100644 --- a/src/app.ts +++ b/src/app.ts @@ -839,9 +839,8 @@ export async function startOAuthFlow( const grantAllowed = input.firstLoginGrant === "invite" && input.mode === "sign_in" && - isAppCaller(caller) && - caller.appSlug === profile.slug && - profile.mayGrantFirstLogin === true; + profile.mayGrantFirstLogin === true && + isAppCaller(caller) && caller.appSlug === profile.slug; if (!grantAllowed) { return { statusCode: 400, -- 2.47.3 From b7e86eeef64aca9f632401256a3e6e32a3fd0d13 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 20:50:05 +0100 Subject: [PATCH 5/6] Grant start reuses the app-caller gate instead of a second caller read; public grant start is 401 app_auth_required Co-Authored-By: Claude Opus 5.5 --- docs/service-contract.md | 8 ++++---- src/app.ts | 13 ++++--------- tests/google-link.test.ts | 4 ++-- 3 files changed, 10 insertions(+), 15 deletions(-) diff --git a/docs/service-contract.md b/docs/service-contract.md index f14602d..2412fbb 100644 --- a/docs/service-contract.md +++ b/docs/service-contract.md @@ -263,10 +263,10 @@ person an app has invited (see the invite grant below). `LinkRefusal` and the code `identity_not_linked` or `link_initiator_mismatch`. - Invite grant. An app whose profile sets `mayGrantFirstLogin` (only `bifrost`) may start `mode: "sign_in"` with `firstLoginGrant: "invite"`, saying it has - invited this person. The start must carry that app's own secret; any other - caller, any other app, any other mode, or any other value is - `400 first_login_grant_refused` (a Bifrost start without the secret is still - `401 app_auth_required`). The grant rides only in the signed state + invited this person. The start must carry that app's own secret: any other + caller, including a public start, is `401 app_auth_required`. An app whose + profile may not grant, any other mode, or any other value is + `400 first_login_grant_refused`. The grant rides only in the signed state (`first_login_grant`), so nothing a browser sends can set it, and the state stays single-use. At the callback a `sub` no account holds, under a grant, mints one account with that identity linked, and audits diff --git a/src/app.ts b/src/app.ts index 003636e..5e327cf 100644 --- a/src/app.ts +++ b/src/app.ts @@ -829,19 +829,14 @@ export async function startOAuthFlow( if (options?.trustedBrowserAttemptId && handoff.kind === "browser_completion") { handoff = { kind: "browser_completion", attemptId: options.trustedBrowserAttemptId }; } - if ((entitlementPolicy || profile.startRequiresAppCaller || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { + if ((entitlementPolicy || profile.startRequiresAppCaller || input.firstLoginGrant !== undefined || (input.mode === "connect" && input.connection !== undefined)) && (!isAppCaller(caller) || caller.appSlug !== profile.slug)) { return { statusCode: 401, body: { error: "app_auth_required" } }; } - // A grant is the app's word that it invited this person: only the authenticated app caller of a profile that may grant, and only on sign_in. - // After the app-secret gate, so a caller without the secret learns nothing about what a grant needs. + // A grant is the app's word that it invited this person: the app-caller gate above has already admitted only the profile's own app, + // and a caller without the secret learns nothing about what a grant needs. Here: only a profile that may grant, only on sign_in. if (input.firstLoginGrant !== undefined) { - const grantAllowed = - input.firstLoginGrant === "invite" && - input.mode === "sign_in" && - profile.mayGrantFirstLogin === true && - isAppCaller(caller) && caller.appSlug === profile.slug; - if (!grantAllowed) { + if (!(input.firstLoginGrant === "invite" && input.mode === "sign_in" && profile.mayGrantFirstLogin === true)) { return { statusCode: 400, body: { error: "first_login_grant_refused", detail: "firstLoginGrant needs the app's own sign_in start, from an app that may grant." }, diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index fc26db4..1e917c3 100644 --- a/tests/google-link.test.ts +++ b/tests/google-link.test.ts @@ -608,13 +608,13 @@ describe("an invite grant lets Bifrost's sign-in start mint the first Google acc expect(res.statusCode, JSON.stringify(headers)).toBeGreaterThanOrEqual(400); expect(res.json().authorizationUrl).toBeUndefined(); } - // An app that does not require a caller is still refused by the grant gate itself. + // An app that does not require a caller is still refused: a grant is a start only the app itself may make. const open = await app.inject({ method: "POST", url: "/v1/oauth/discord/start", payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/", firstLoginGrant: "invite" }, }); - expect([open.statusCode, open.json().error]).toEqual([400, "first_login_grant_refused"]); + expect([open.statusCode, open.json().error]).toEqual([401, "app_auth_required"]); expect(accountCount(store)).toBe(0); }); -- 2.47.3 From 4612ae391a4d17cc507cbdf33b59e2864995976b Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Sun, 29 Nov 2026 20:51:55 +0100 Subject: [PATCH 6/6] Test config: repixelizer holds a secret so the other-app grant case is a real app caller Co-Authored-By: Claude Opus 5.5 --- tests/google-link.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/google-link.test.ts b/tests/google-link.test.ts index 1e917c3..630d4a1 100644 --- a/tests/google-link.test.ts +++ b/tests/google-link.test.ts @@ -25,7 +25,7 @@ function config(): HeimdallConfig { storage: { backend: "memory", applySchemaOnStartup: true }, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"), bootstrapSigningPrivateKeyOnMissing: true, - appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret" }, + appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret" }, providers: { ...base.providers, google: { clientId: CLIENT_ID, clientSecret: "google-secret" }, -- 2.47.3