Merge ghostlight/google-sign-in: ghostlight signs in with Google or Discord; the Dungeon's invite is the only admission gate (firstLoginGrant invite, start requires the app caller, app_access from identity.authenticated); requiredEntitlementPolicyKind deleted (Weksa cut-heimdall-ghostlight-google r1, report h1, Soul s1: no blockers; under operator ruling ghostlight-verse:ruling:weksa-owns-dungeon-google-sign-in)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 23:35:33 +01:00
commit 58d183231c
13 changed files with 499 additions and 75 deletions

View file

@ -11,14 +11,23 @@ selection, and every world mutation.
- `app_slug`: `ghostlight`
- public URL: `https://yggdrasil.gamecult.org/ghostlight/`
- identity provider: Discord
- access rule: Ghostlight supplies its configured KLTST Discord-role policy on
the app-authenticated private boundary; Heimdall evaluates the policy and
grants `app_access` only when it succeeds
- identity providers: Discord and Google
- access rule: Heimdall authenticates; `app_access` is `identity.authenticated`.
Who may play is the Dungeon's account catalog and its one-time invites, not a
Discord role. No Discord role policy is required of begin or refresh, and one
a caller still sends is evaluated by nobody for this app
- starts: every start is app-authenticated (`startRequiresAppCaller`); a public
start without the app secret is `401 app_auth_required`
- first Google sign-in: Google is linked-identity only, so a `sub` no account
holds is refused (`identity_not_linked`) unless the begin carried
`firstLoginGrant: "invite"`, which the Dungeon sends only for an invite its
catalog holds live. The grant mints a Heimdall account for a new `sub`; it
never attaches to or moves an existing account
## Capabilities
- `app_access`: shared capability granting entry to the demo
- `app_access`: shared capability; every authenticated identity has it, and
admission is the Dungeon's catalog
- `campaign_play`: hybrid capability; Ghostlight must also prove that the
authenticated account owns the selected campaign
@ -27,6 +36,6 @@ plugin stores only an opaque attempt handle. Ghostlight redeems that handle over
the encrypted loopback command plane, verifies the resulting `aud=ghostlight`
claim against Heimdall JWKS, and establishes app-local campaign authority.
Short-lived local access continues without a Heimdall round trip. Scheduled
refresh re-evaluates the Ghostlight-owned KLTST role policy; explicit logout
refresh re-evaluates nothing app-specific; explicit logout
revokes both Ghostlight's local session and the matching Heimdall refresh
custody record.

View file

@ -187,10 +187,10 @@ Failure modes:
the caller did not authenticate as that app via `x-heimdall-app-secret`
(`resolveAppCaller`, `src/app-caller.ts`) -- this applies regardless of
`handoff.kind` or app slug; a caller with no policy to attach needs no secret,
unless the app's profile sets `startRequiresAppCaller` (Bifrost only): then
unless the app's profile sets `startRequiresAppCaller` (Bifrost and Ghostlight): then
every start for that app, with or without a policy, needs that app's secret.
Bifrost binds browser completion to a nonce that rides readable in the signed
state's `return_to`, so only Bifrost may mint a Bifrost state; apps whose
Bifrost and Ghostlight bind browser completion to a nonce that rides readable
in the signed state's `return_to`, so only the app may mint its own state; apps whose
browser starts are public by design leave the flag unset
- `401 app_auth_required` also when `mode` is `connect` and the body carries a
`connection` (a creator or account target): a connection target is app-backend
@ -261,7 +261,7 @@ person an app has invited (see the invite grant below).
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`)
- Invite grant. An app whose profile sets `mayGrantFirstLogin` (`bifrost` and `ghostlight`)
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, including a public start, is `401 app_auth_required`. An app whose
@ -287,7 +287,7 @@ person an app has invited (see the invite grant below).
what Discord or Patreon grant.
- Configure with `GC_ACCESS_PROVIDER_GOOGLE_CLIENT_ID` and
`GC_ACCESS_PROVIDER_GOOGLE_CLIENT_SECRET_FILE`. Admitted to the `bifrost`
app profile only.
and `ghostlight` app profiles only.
### `GET /v1/oauth/{provider}/callback`
@ -1005,6 +1005,14 @@ same result only for the exact same authenticated request; content changes are
denied. Completion consumption remains single-use in Heimdall's canonical
store.
`heimdall.auth.begin` takes `provider`, `mode`, `returnTo`, an optional
`entitlementPolicy` (accepted for any app, required of none) and an optional
`firstLoginGrant`. Absent or null is no grant; exactly `"invite"` is passed to
the same start gate as the public route (the app's own caller, `sign_in` only,
an app whose profile may grant); any other value is refused before an attempt
is created. Ghostlight sends `"invite"` only for a browser whose invite the
Dungeon's catalog holds live; Heimdall holds no invite records.
Refresh claims are admitted only while their exact persisted session,
app/account custody, access revision, and refresh expiry still match. Logout
uses the refresh claim as custody proof and atomically advances the persisted

View file

@ -0,0 +1,241 @@
{
"kind": "cut_spec",
"value": {
"campaign": "ghostlight-verse",
"cut": "heimdall-ghostlight-google",
"revision": 1,
"title": "Heimdall: ghostlight admits Google, honours the Dungeon's invite grant, and stops gating on the Discord role",
"repo": "GameCult/Heimdall",
"branch": "ghostlight/google-sign-in",
"base": "2bcb2ca4e7fb640e07deae42302b0919a62e5bc4",
"depends_on": [],
"first": [
"Work in the existing worktree F:\\Projects\\Heimdall-wt-ghostlight-google on branch ghostlight/google-sign-in (from origin/main 2bcb2ca). Read AGENTS.md; follow its state/evidence conventions for the closing evidence line.",
"Read docs/service-contract.md 'Invite grant' (about line 264) and src/app.ts startOAuthFlow gates (about lines 832-846): the grant mechanism already exists for bifrost. This cut extends it to ghostlight and threads it through the private command plane; it adds no invite records to Heimdall.",
"Delete first: AppProfile.requiredEntitlementPolicyKind (app-profiles.ts:41-47, set only by ghostlight at :203) and requireEntitlementPolicyIfProfileDemandsIt (private-command-plane.ts:385-407) with its two call sites (:236 refresh, :272 begin). A caller-sent policy stays accepted and optional as for every other app.",
"Heimdall ruling heimdall-body:ruling:bifrost-google-invitation-link-only forbids attaching Google to an existing account by an invitation path. This cut does not: the grant only mints a new account for a sub no account holds and never attaches (contract text at :264-274). Do not widen that.",
"Open the Heimdall PR on Forgejo only when Self says so; the brief for this mapping pass forbids it, Hands' own brief decides."
],
"deletes": [
{
"path": "src/app-profiles.ts",
"lines": 8,
"note": "requiredEntitlementPolicyKind field and its doc comment; ghostlight's requiredEntitlementPolicyKind line"
},
{
"path": "src/private-command-plane.ts",
"lines": 22,
"note": "requireEntitlementPolicyIfProfileDemandsIt and its two awaits"
},
{
"path": "tests",
"lines": 30,
"note": "tests that pin 'ghostlight authentication/refresh requires its caller-owned discord_role_access policy' are deleted or inverted (a ghostlight begin without policy now starts)"
}
],
"keeps_moves": [
"The grant gates in startOAuthFlow (app caller of this slug, sign_in only, mayGrantFirstLogin) and the callback mint under first_login_grant are unchanged.",
"Bifrost's profile, its grant and its Google link flow are unchanged.",
"The private-plane attempt handle (trustedBrowserAttemptId, never body-supplied) is the ghostlight browser binding and is unchanged.",
"Discord stays a ghostlight identity provider; a Discord policy a caller still sends is evaluated by nobody for ghostlight (entitlementSources empty) and is harmless."
],
"adds": [
"ghostlight profile: identityProviders ['discord','google']; entitlementSources []; startRequiresAppCaller: true; mayGrantFirstLogin: true; profileVersion '2026-12-02'.",
"ghostlight app_access: anyOf [identityFacts.authenticated] (as streampixels viewer_access at :147), summary 'Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog'. campaign_play summary/localRequirement: 'Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership'.",
"beginAuth reads payload.firstLoginGrant: absent/null -> none; exactly 'invite' -> passed to startOAuthFlow input.firstLoginGrant; any other value -> throw 'Auth begin payload is incomplete.' (same refusal shape as a bad provider). startOAuthFlow's existing gate then decides."
],
"file_changes": [
{
"location": {
"path": "src/app-profiles.ts",
"line": 195,
"end_line": 218,
"symbol": "ghostlightProfile"
},
"change": "As in adds: providers, entitlementSources [], startRequiresAppCaller, mayGrantFirstLogin, app_access on identity.authenticated, summaries, profileVersion. Import identityFacts is already present."
},
{
"location": {
"path": "src/private-command-plane.ts",
"line": 260,
"end_line": null,
"symbol": "beginAuth"
},
"change": "Thread firstLoginGrant into the startOAuthFlow input; drop the policy-demand await."
},
{
"location": {
"path": "src/private-command-plane.ts",
"line": 221,
"end_line": null,
"symbol": "refreshAuth"
},
"change": "Drop the policy-demand await; policy remains optional and passed through when present."
},
{
"location": {
"path": "schemas/heimdall.auth_begin_command.v1.schema.json",
"line": 1,
"end_line": null
},
"change": "provider enum gains google; entitlementPolicy leaves required; add firstLoginGrant {enum:['invite']}."
},
{
"location": {
"path": "schemas/heimdall.auth_refresh_command.v1.schema.json",
"line": 1,
"end_line": null
},
"change": "entitlementPolicy optional if it is required there."
},
{
"location": {
"path": "docs/service-contract.md",
"line": 190,
"end_line": null
},
"change": "startRequiresAppCaller: 'Bifrost and Ghostlight'; mayGrantFirstLogin (about :264): 'bifrost and ghostlight'; Google (about :289): admitted to bifrost and ghostlight; private-plane begin accepts firstLoginGrant 'invite'."
},
{
"location": {
"path": "docs/app-profiles/ghostlight.md",
"line": 1,
"end_line": null
},
"change": "Providers Discord and Google; access rule: Heimdall authenticates, app_access is identity.authenticated, admission is the Dungeon's catalog and one-time invites (ruling dungeon-owns-accounts); a first Google sign-in mints a Heimdall account only under the Dungeon's grant; no Discord role policy; refresh re-evaluates nothing app-specific."
}
],
"reads": [
{
"location": {
"path": "src/app.ts",
"line": 832,
"end_line": null,
"symbol": "startOAuthFlow"
},
"why": "the app-caller and grant gates the private plane now reaches with a grant"
},
{
"location": {
"path": "src/app.ts",
"line": 2034,
"end_line": null
},
"why": "callback: requires_link + first_login_grant mints and audits account_minted_by_grant"
},
{
"location": {
"path": "tests/google-link.test.ts",
"line": 1,
"end_line": null
},
"why": "the bifrost grant tests to mirror for ghostlight over the private plane"
},
{
"location": {
"path": "tests/caller-identity-soul.test.ts",
"line": 23,
"end_line": null
},
"why": "private-plane ghostlight fixtures (ghostlightSecret, runtime ids)"
}
],
"authority_map": {
"owner": "The Dungeon's account catalog (catalog.cc) owns admission: an identity plays if an account holds it, or if it redeems a live one-time Dungeon invite, consumed in the write that creates the account. Heimdall owns authentication only: it proves which external identity signed in and names the Heimdall account (claim sub) that identity belongs to.",
"inputs": [
"Dungeon: the invite the browser presents at begin, its catalog, the Heimdall-verified claim at complete",
"Heimdall: the app-authenticated begin (ghostlight secret over the private plane), the provider's OIDC/OAuth answer, the signed state"
],
"outputs": [
"Dungeon -> Heimdall: firstLoginGrant 'invite' on a begin whose browser presented an invite the catalog holds live",
"Heimdall -> Dungeon: a claim aud=ghostlight with app_access for every authenticated identity",
"Dungeon: an account row, the spent invite, an app session"
],
"derived_state": [
"Heimdall's first_login_grant is no longer an invite: it is derived from the Dungeon's live invite at begin and is notification-only (it lets Heimdall mint an auth account for a Google sub no account holds)",
"ghostlight app_access is no longer an admission gate: it is derived from identity.authenticated; the Dungeon's app_access checks become claim-shape checks that cannot refuse an authenticated sign-in",
"the invite bound to an attempt in AuthGuard is a copy of what the browser presented at begin, memory-only, living no longer than the begin cookie"
],
"forbidden_writers": [
"Heimdall's Discord role policy (requiredEntitlementPolicyKind, entitlementSources discord) no longer decides who enters the Dungeon",
"Heimdall holds no invite records for ghostlight and never decides who is invited",
"the complete body no longer carries an invite; only the begin-bound invite reaches catalog.sign_in",
"no public (secretless) ghostlight OAuth start: startRequiresAppCaller"
],
"shared_paths": [
"Google, Discord and any later provider begin through one auth_begin -> HeimdallClient::begin -> heimdall.auth.begin path; the grant decision is the same catalog read for every provider",
"every sign-in, first or returning, any provider, ends in one catalog.sign_in"
],
"deletion_line": "Delete before adding: Heimdall's requiredEntitlementPolicyKind field and requireEntitlementPolicyIfProfileDemandsIt; the Dungeon's DiscordGate, its two env names and the policy on begin and refresh; the complete body's invite field."
},
"verification": {
"builds": [
"pnpm typecheck && pnpm test in the worktree (vendor/CultLib built as AGENTS.md says); report the pre-existing odin-publication failure separately if it still appears"
],
"tests": [
{
"name": "ghostlight google first sign-in under grant",
"pins": "private-plane begin {provider google, firstLoginGrant invite} -> 201 state with first_login_grant; callback with an unheld sub mints one account and audits account_minted_by_grant {provider google, appSlug ghostlight}; the completion's claim carries app_access"
},
{
"name": "ghostlight google first sign-in without grant",
"pins": "same begin without firstLoginGrant -> callback refuses identity_not_linked and mints nothing"
},
{
"name": "returning google identity",
"pins": "a sub an account already holds signs in with or without the grant to that same account; the grant attaches nothing"
},
{
"name": "discord without policy",
"pins": "private-plane ghostlight discord begin with no entitlementPolicy starts (no throw); refresh without policy refreshes; claim carries app_access"
},
{
"name": "public ghostlight start refused",
"pins": "POST /v1/oauth/google/start and /v1/oauth/discord/start for appSlug ghostlight without x-heimdall-app-secret -> 401 app_auth_required"
},
{
"name": "bad grant value",
"pins": "private-plane begin with firstLoginGrant 'yes' is refused before any attempt row or state is minted"
},
{
"name": "other apps unchanged",
"pins": "repixelizer/streampixels public starts unchanged; firstLoginGrant from repixelizer still 400 first_login_grant_refused"
}
],
"negative": [
{
"pattern": "requiredEntitlementPolicyKind|requireEntitlementPolicyIfProfileDemandsIt",
"scope": "src, tests, docs: zero hits"
},
{
"pattern": "discord_role_access",
"scope": "src/app-profiles.ts: zero hits (the policy kind itself stays in contracts and the Discord evaluator)"
},
{
"pattern": "invite",
"scope": "src/store/**: no new table, column or row for ghostlight invites"
}
],
"operator": [
"Deploy is cut ops-google-sign-in's runbook section, after this merges to Heimdall main; not part of this cut."
]
},
"estimate": {
"lines_added": 140,
"lines_removed": 70,
"dependencies_added": [],
"dependencies_removed": [],
"formats_added": [],
"formats_removed": [],
"targets_added": [],
"targets_removed": []
},
"rulings": [
"ghostlight-verse:ruling:weksa-owns-dungeon-google-sign-in",
"ghostlight-verse:ruling:dungeon-owns-accounts"
],
"questions": [
"ghostlight-verse:question:heimdall-ghostlight-google-twitch-sign-in"
]
}
}

View file

@ -2,11 +2,12 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "heimdall.auth_begin_command.v1",
"type": "object",
"required": ["provider", "mode", "returnTo", "entitlementPolicy"],
"required": ["provider", "mode", "returnTo"],
"properties": {
"provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick"] },
"provider": { "enum": ["discord", "patreon", "github", "twitch", "youtube", "spotify", "joystick", "google"] },
"mode": { "enum": ["sign_in", "link", "connect"] },
"returnTo": { "type": "string", "format": "uri" },
"firstLoginGrant": { "enum": ["invite"] },
"entitlementPolicy": {
"oneOf": [
{

View file

@ -2,7 +2,7 @@
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "heimdall.auth_refresh_command.v1",
"type": "object",
"required": ["schema", "refreshToken", "entitlementPolicy"],
"required": ["schema", "refreshToken"],
"properties": {
"schema": { "const": "heimdall.auth_refresh_command.v1" },
"refreshToken": { "type": "string", "minLength": 1 },

View file

@ -3,7 +3,7 @@ import {
type CapabilityDefinition,
type CapabilityMode,
} from "./capability-rules.js";
import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js";
import { type AppSlug, type LinkedIdentityInput, type OAuthConnectionBinding, type OAuthMode, type Provider } from "./contracts.js";
import { entitlementFacts, grantFacts, identityFacts } from "./facts.js";
export type { CapabilityDefinition, CapabilityMode };
@ -38,13 +38,6 @@ export interface AppProfile {
* primitive, not a convenience. Compared by URL origin, not prefix.
*/
allowedReturnOrigins: readonly string[];
/**
* Some apps require the caller to supply an entitlement policy of a
* specific kind on every begin/refresh (ghostlight's caller-owned Discord
* role gate). Data instead of a per-slug branch in the private command
* plane; absent for apps with no such requirement.
*/
requiredEntitlementPolicyKind?: OAuthEntitlementPolicy["kind"];
/**
* The app binds browser completion to its own pending attempt, and the
* binding is the secrecy of the attempt nonce, which rides readable in the
@ -195,24 +188,25 @@ const bifrostProfile: AppProfile = {
const ghostlightProfile: AppProfile = {
slug: "ghostlight",
displayName: "Ghostlight Dungeon",
profileVersion: "2026-08-22",
identityProviders: ["discord"],
entitlementSources: ["discord"],
profileVersion: "2026-12-02",
identityProviders: ["discord", "google"],
entitlementSources: [],
managedConnectionProviders: [],
allowedReturnOrigins: ["https://yggdrasil.gamecult.org"],
requiredEntitlementPolicyKind: "discord_role_access",
startRequiresAppCaller: true,
mayGrantFirstLogin: true,
capabilities: [
{
key: "app_access",
mode: "shared",
summary: "May enter Ghostlight Dungeon after Heimdall verifies the app-supplied GameCult Discord role policy.",
anyOf: gameCultMembership,
summary: "Heimdall authenticated this identity for Ghostlight; who may play is the Dungeon's account catalog.",
anyOf: [identityFacts.authenticated],
},
{
key: "campaign_play",
mode: "hybrid",
summary: "May play campaigns owned by the authenticated Ghostlight account.",
localRequirement: "Ghostlight must combine app_access with local campaign ownership.",
summary: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.",
localRequirement: "Ghostlight combines a Heimdall sign-in with its own account catalog and campaign ownership.",
},
],
};

View file

@ -9,7 +9,6 @@ import {
import { type FastifyInstance } from "fastify";
import { errorIdentity, getHeimdallRuntimeContext, refreshAppSession, startOAuthFlow, verifyRefreshToken } from "./app.js";
import { callerFromOpenedEnvelope } from "./app-caller.js";
import { getAppProfile } from "./app-profiles.js";
import { executeHeimdallAccessPlugin, HEIMDALL_ACCESS_PLUGIN_ID, type EvePluginAbiRequest } from "./access-plugin.js";
import { isAppSlug, oauthModes, providers, type AppSlug, type OAuthEntitlementPolicy, type OAuthMode, type Provider } from "./contracts.js";
import { type HeimdallConfig } from "./config.js";
@ -233,7 +232,6 @@ async function refreshAuth(
// handler function the HTTP route uses rather than forging the HTTP header
// back at itself.
const context = getHeimdallRuntimeContext(app);
await requireEntitlementPolicyIfProfileDemandsIt(appSlug, entitlementPolicy, "refresh");
const result = await refreshAppSession(context, appSlug, callerFromOpenedEnvelope(appSlug), {
refreshToken,
...(entitlementPolicy ? { entitlementPolicy } : {}),
@ -268,8 +266,10 @@ async function beginAuth(
const returnTo = String(payload.returnTo ?? "");
if (!providers.includes(provider) || !oauthModes.includes(mode) || !returnTo) throw new Error("Auth begin payload is incomplete.");
const entitlementPolicy = parseEntitlementPolicy(payload.entitlementPolicy);
// The app's word that it invited this person (the Dungeon holds the invite). Only the literal "invite" is a grant; startOAuthFlow's gate decides whether this app and mode may carry one.
const grant = payload.firstLoginGrant;
if (grant !== undefined && grant !== null && grant !== "invite") throw new Error("Auth begin payload is incomplete.");
const store = getHeimdallRuntimeContext(app).store;
await requireEntitlementPolicyIfProfileDemandsIt(appSlug, entitlementPolicy, "authentication");
const now = new Date();
const attempt = await store.createAuthAttempt({
handle: randomUUID(),
@ -292,6 +292,7 @@ async function beginAuth(
returnTo,
handoff: { kind: "browser_completion" },
...(entitlementPolicy ? { entitlementPolicy } : {}),
...(grant === "invite" ? { firstLoginGrant: "invite" as const } : {}),
},
{ trustedBrowserAttemptId: attempt.handle }
);
@ -387,25 +388,6 @@ function parseEntitlementPolicy(value: unknown): OAuthEntitlementPolicy | undefi
return undefined;
}
/**
* Ghostlight requires its caller-owned Discord role policy on every begin and
* refresh; that used to be a literal `appSlug === "ghostlight"` branch here.
* The requirement is now data on the app's profile
* (AppProfile.requiredEntitlementPolicyKind), so a future app with the same
* need declares it in its profile instead of adding another branch.
*/
async function requireEntitlementPolicyIfProfileDemandsIt(
appSlug: AppSlug,
entitlementPolicy: OAuthEntitlementPolicy | undefined,
action: "authentication" | "refresh",
): Promise<void> {
const profile = getAppProfile(appSlug);
const requiredKind = profile?.requiredEntitlementPolicyKind;
if (requiredKind && entitlementPolicy?.kind !== requiredKind) {
throw new Error(`${appSlug} ${action} requires its caller-owned ${requiredKind} policy.`);
}
}
function response(
request: CultNetOperationRequestMessage,
status: string,

View file

@ -41,3 +41,4 @@
{"ts": "2026-11-13T19:10:00+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-13: GET /v1/me/identities lists an account's identities (no credentials, profile or email); POST /v1/me/identities/:id/unlink deletes one with a step-up proof (access claim step_up_at, 600 s, never carried by refresh), refuses the last identity (409), writes revocation receipts when the provider's last identity goes. upsertLinkedIdentity no longer moves an identity between accounts (IdentityHeldElsewhereError; links/confirm 409 identity_linked_elsewhere, callback link_initiator_mismatch). The store role needs DELETE on linked_identities (startup refuses without it): owner-role GRANT at deploy."}
{"ts": "2026-11-13T20:01:42+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-13: POST /v1/apps/{app}/step-up (profile grant stepUpAssertion, bifrost only; methods bifrost-passkey, bifrost-email-code). App secret plus the member's live bearer for that app; mints a same-session access token with step_up_at now and new claim step_up_method (exp kept, no refresh, no session write); nonce single-use via oauth_state_uses phase step_up_assert (no schema change), retained to the session expiry as of the claim (a refresh may slide the session past it); in-process rate limits 10 per 600 s per account, 120 per 60 s per app; audit step_up_asserted and step_up_assertion_refused with a nonce digest (429s and not-permitted refusals audited once per window; not-permitted has a 5 per 60 s per-app budget); nonce is base64url 16-128. Provider step-up sign-ins now carry step_up_method provider:<name>; identity_unlinked records stepUpMethod. Heimdall cannot verify the factor: it trusts the calling app. Not deployed; no env, secret or migration. For heimdall-body:follow_up:chat-s7419-7419.", "branch": "heimdall/app-asserted-step-up"}
{"ts": "2026-11-14T01:10:00+00:00", "type": "design", "status": "accepted", "note": "Changelog 2026-11-14: POST /v1/apps/{app}/identity-moves (profile grant identityMoves, bifrost only; accountProofMethods bifrost-passkey) and the identity_moves table, the only writer of linked_identities.account_id (moveIdentities, one transaction, accounts locked in id order, shared decideMove on both stores). Access claims gain auth_at and auth_identity_id (sign_in callback only). proofTier is the one freshness rule (unlink reads it; strong 600 s step_up_at, weak 300 s auth_at); proofCovers: only an asserted account-proof method covers a whole account, otherwise the login in auth_identity_id (ruling move-proof-strict-passkey). Moves strip credentials, revoke the source's sessions, expire its pending links and unredeemed completions, write revocation receipts under the source, audit identity_moved; moveId is idempotent (replay answers the stored receipt without proof liveness); a move is reversible once. Not deployed: the owner must apply the identity_moves DDL and GRANT SELECT, INSERT ON identity_moves to the store role before the new build starts (startup refuses SCHEMA_MISSING / SCHEMA_PRIVILEGES otherwise).", "branch": "heimdall/identity-moves"}
{"ts": "2026-12-02T22:23:49+00:00", "type": "design", "status": "accepted", "note": "ghostlight/google-sign-in: ghostlight admits Google, requires the app secret on every start (login-CSRF), accepts firstLoginGrant 'invite' on private-plane begin, app_access = identity.authenticated, no Discord role policy (requiredEntitlementPolicyKind and its guard deleted). Admission is the Dungeon's catalog. Not deployed. Local pnpm test: only pre-existing entrypoint-secrets failure on Windows; StrykerJS not configured, two hand mutants killed."}

View file

@ -318,10 +318,10 @@ describe("Heimdall service", () => {
}
});
it("flags only Bifrost's profile", () => {
it("flags only Bifrost's and Ghostlight's profiles", () => {
expect(
Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug)
).toEqual(["bifrost"]);
Object.values(builtInAppProfiles).filter((profile) => profile.startRequiresAppCaller).map((profile) => profile.slug).sort()
).toEqual(["bifrost", "ghostlight"]);
});
});

View file

@ -197,6 +197,8 @@ async function seedAccountAndSession(store: HeimdallStore, appSlug: AppSlug) {
describe("R21.1: the attempt handle is unreachable from the public start route", () => {
const legitReturn = "https://yggdrasil.gamecult.org/ghostlight/";
// Ghostlight's starts are the app's own (startRequiresAppCaller); what the body may not do is name an attempt handle, even for the app.
const ghostlightApp = { "x-heimdall-app-secret": ghostlightSecret };
it("a well-formed browser_completion attemptId is dropped before the state token is signed", async () => {
const { app, store } = await harness();
@ -213,7 +215,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
mode: "sign_in",
returnTo: legitReturn,
handoff: { kind: "browser_completion", attemptId: attempt.handle },
});
}, ghostlightApp);
expect(response.statusCode, response.body).toBe(201);
expect(response.json().handoff).toEqual({ kind: "browser_completion" });
const state = jwtPayload(stateOf(response.json()));
@ -236,7 +238,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
["empty string", { kind: "browser_completion", attemptId: "" }],
])("a %s attemptId never reaches the state token", async (_label, handoff) => {
const { app } = await harness();
const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff });
const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, handoff }, ghostlightApp);
expect(response.body).not.toContain(planted);
if (response.statusCode === 201) {
expect(response.json().handoff).toEqual({ kind: "browser_completion" });
@ -249,7 +251,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
it("a top-level attemptId / trustedBrowserAttemptId / options field on the body is stripped, never bound", async () => {
const { app } = await harness();
for (const extra of [{ attemptId: planted }, { trustedBrowserAttemptId: planted }, { options: { trustedBrowserAttemptId: planted } }]) {
const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra });
const response = await start(app, { appSlug: "ghostlight", mode: "sign_in", returnTo: legitReturn, ...extra }, ghostlightApp);
expect(response.statusCode, response.body).toBe(201);
expect(response.body).not.toContain(planted);
expect(jwtPayload(stateOf(response.json())).handoff).toEqual({ kind: "browser_completion" });
@ -300,17 +302,16 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
const handle = String(receipt.handle);
const victimState = new URL((receipt.navigation as { url: string }).url).searchParams.get("state") ?? "";
// Attacker names the victim's handle on the public start route, then
// completes as themselves before the victim does.
// Attacker names the victim's handle on the public start route: Ghostlight's
// start is refused outright without the app's secret, so no state exists to complete.
const attackerStart = await start(app, {
appSlug: "ghostlight",
mode: "sign_in",
returnTo: legitReturn,
handoff: { kind: "browser_completion", attemptId: handle },
});
expect(attackerStart.statusCode).toBe(201);
const attackerCallback = await completeAs(app, stateOf(attackerStart.json()), "attacker");
expect(attackerCallback.statusCode, attackerCallback.body).toBe(201);
expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]);
expect(attackerStart.json().authorizationUrl).toBeUndefined();
expect((await store.findAuthAttempt("ghostlight", handle))?.status).toBe("pending");
// Victim completes; the handle's single unconsumed slot is still free.
@ -339,7 +340,7 @@ describe("R21.1: the attempt handle is unreachable from the public start route",
mode: "sign_in",
returnTo: legitReturn,
handoff: { kind: "backend_callback", attemptId: attempt.handle, callbackUrl: "http://127.0.0.1:1/never" },
});
}, ghostlightApp);
expect(response.statusCode, response.body).toBe(201);
// Delivery to port 1 fails; whatever the callback returns, the attempt
// must be untouched and no completion may be bound to it.

View file

@ -261,14 +261,14 @@ describe("attempt-handle binding: the public start route may attach a completion
expiresAt: new Date(Date.now() + 600_000).toISOString(),
});
// Ghostlight's start is the app's own: without its secret there is no state to complete with.
const attackerStart = await start(app, {
appSlug: "ghostlight",
mode: "sign_in",
returnTo: "https://yggdrasil.gamecult.org/ghostlight/",
handoff: { kind: "browser_completion", attemptId: attempt.handle },
});
expect(attackerStart.statusCode).toBe(201);
await completeAs(app, stateOf(attackerStart.json()), "attacker");
expect([attackerStart.statusCode, attackerStart.json().error]).toEqual([401, "app_auth_required"]);
const after = await store.findAuthAttempt("ghostlight", attempt.handle);
expect(after?.status).toBe("pending");

View file

@ -1,18 +1,25 @@
import { createHash, createSign, generateKeyPairSync } from "node:crypto";
import { afterEach, describe, expect, it, vi } from "vitest";
import { type FastifyInstance } from "fastify";
import { decode, encode } from "@msgpack/msgpack";
import { invokeCultNetOperation } from "cultnet-ts";
import { buildApp } from "../src/app.js";
import { loadConfig, type HeimdallConfig } from "../src/config.js";
import { resetGoogleJwksCache } from "../src/google-oidc.js";
import { type OAuthProviderRuntime } from "../src/oauth.js";
import { startHeimdallPrivateCommandPlane } from "../src/private-command-plane.js";
import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope } from "../src/private-command-security.js";
import { decodeJwt } from "../src/signing.js";
import { IdentityHeldElsewhereError, InMemoryStore } from "../src/store/index.js";
import { launchFlow, launchWithRedirect, stateOf, type LaunchedFlow } from "./oauth-flow.js";
const CLIENT_ID = "google-client";
const GHOSTLIGHT_SECRET = "ghostlight-private-command-secret";
const REDIRECT = "https://heimdall.gamecult.org/v1/oauth/google/callback";
const rsa = generateKeyPairSync("rsa", { modulusLength: 2048 });
const originalFetch = globalThis.fetch;
const apps: FastifyInstance[] = [];
const planes: Array<{ close(): Promise<unknown> }> = [];
function config(): HeimdallConfig {
const base = loadConfig({
@ -25,7 +32,10 @@ function config(): HeimdallConfig {
storage: { backend: "memory", applySchemaOnStartup: true },
tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
bootstrapSigningPrivateKeyOnMissing: true,
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret" },
privateCommandHost: "127.0.0.1",
privateCommandPort: 0,
appSharedSecrets: { ...base.appSharedSecrets, bifrost: "bifrost-secret", repixelizer: "repixelizer-secret", ghostlight: GHOSTLIGHT_SECRET },
appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] },
providers: {
...base.providers,
google: { clientId: CLIENT_ID, clientSecret: "google-secret" },
@ -185,6 +195,7 @@ async function linkGoogle(app: FastifyInstance, token: string, claims?: Record<s
afterEach(async () => {
globalThis.fetch = originalFetch;
resetGoogleJwksCache();
while (planes.length) await planes.pop()?.close();
while (apps.length) await apps.pop()?.close();
});
@ -673,3 +684,179 @@ describe("an invite grant lets Bifrost's sign-in start mint the first Google acc
expect(accountCount(store)).toBe(0);
});
});
describe("ghostlight admits Google over the private command plane, and the Dungeon's invite is the only grant", () => {
const RETURN = "https://yggdrasil.gamecult.org/ghostlight/";
let seq = 0;
async function buildGhostlight() {
const store = new InMemoryStore();
const cfg = config();
const app = await buildApp({ config: cfg, store, oauthRuntimes: { discord: discordRuntime("discord-1", "Person") } });
apps.push(app);
const plane = await startHeimdallPrivateCommandPlane(app, cfg);
planes.push(plane);
return { app, store, plane };
}
/** One sealed command to the plane as Ghostlight's own runtime; the opened receipt, or the transport status when refused. */
async function command(plane: { endpoint: string }, operation: string, contentSchema: string, payload: Record<string, unknown>) {
const id = `gl-${++seq}`;
const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: id, secret: GHOSTLIGHT_SECRET, payload });
const response = await invokeCultNetOperation(
plane.endpoint,
{
schemaVersion: "cultnet.operation_request.v0" as const,
messageId: id,
serviceId: "heimdall.private.commands",
operation,
payloadSchema: "heimdall.private_command_envelope.v1",
payloadEncoding: "messagepack-base64" as const,
payload: Buffer.from(encode(envelope)).toString("base64"),
sourceRuntimeId: "yggdrasil-ghostlight",
},
{ runtimeId: "yggdrasil-ghostlight" }
);
if (response.status !== "accepted") return { status: response.status, receipt: undefined };
const wire = decode(Buffer.from(response.payload, "base64")) as HeimdallPrivateEnvelope;
return { status: response.status, receipt: openPrivateEnvelope(wire, GHOSTLIGHT_SECRET) as Record<string, unknown> };
}
const begin = (plane: { endpoint: string }, payload: Record<string, unknown>) =>
command(plane, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", { mode: "sign_in", returnTo: RETURN, ...payload });
const complete = (plane: { endpoint: string }, handle: unknown) =>
command(plane, "heimdall.auth.complete", "heimdall.auth_complete_command.v1", { handle });
/** Begin google as Ghostlight, walk the browser to Google and back, and return the callback answer plus the attempt handle. */
async function googleSignIn(app: FastifyInstance, plane: { endpoint: string }, payload: Record<string, unknown>, claims?: Record<string, unknown>) {
const started = await begin(plane, { provider: "google", ...payload });
expect(started.status).toBe("accepted");
const receipt = started.receipt as { handle: string; navigation: { url: string } };
const flow = await launchWithRedirect(app, { authorizationUrl: receipt.navigation.url });
fakeGoogle({ nonceFrom: () => flow.url.searchParams.get("nonce") ?? undefined, ...(claims ? { claims } : {}) });
return { handle: receipt.handle, done: await callbackGoogle(app, flow) };
}
const auditEvents = (store: InMemoryStore) =>
[...(store as unknown as { auditEvents: Map<string, { eventType: string; eventPayloadJson?: unknown }> }).auditEvents.values()];
const attemptCount = (store: InMemoryStore) => (store as unknown as { authAttempts: Map<string, unknown> }).authAttempts.size;
const capabilitiesOf = (receipt: Record<string, unknown> | undefined) =>
decodeJwt(String(receipt?.accessToken)).payload.capabilities as string[];
it("a first Google sign-in under the Dungeon's invite grant mints one account, audits it, and the claim carries app_access", async () => {
const { app, store, plane } = await buildGhostlight();
const { handle, done } = await googleSignIn(app, plane, { firstLoginGrant: "invite" });
expect(done.statusCode, done.body).toBe(201);
expect(accountCount(store)).toBe(1);
const minted = auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant");
expect(minted.map((e) => e.eventPayloadJson)).toEqual([{ provider: "google", appSlug: "ghostlight" }]);
const completion = (await complete(plane, handle)).receipt;
expect(completion).toMatchObject({ status: "authenticated", handle });
expect(capabilitiesOf(completion)).toContain("app_access");
});
it("a first Google sign-in with no live grant is refused identity_not_linked and mints nothing", async () => {
const { app, store, plane } = await buildGhostlight();
for (const extra of [{}, { firstLoginGrant: null }]) {
const { handle, done } = await googleSignIn(app, plane, extra);
expect([done.statusCode, done.json().error]).toEqual([403, "identity_not_linked"]);
expect(auditEvents(store).some((e) => e.eventType === "account_minted_by_grant")).toBe(false);
expect((await complete(plane, handle)).receipt?.status).toBe("denied");
}
expect(accountCount(store)).toBe(0);
});
it("a returning Google identity signs in to its own account with or without the grant, and the grant attaches nothing", async () => {
const { app, store, plane } = await buildGhostlight();
const first = await googleSignIn(app, plane, { firstLoginGrant: "invite" });
const accountId = first.done.json().account.id;
for (const extra of [{}, { firstLoginGrant: "invite" }]) {
const again = await googleSignIn(app, plane, extra);
expect(again.done.statusCode, again.done.body).toBe(201);
expect(again.done.json().account.id).toBe(accountId);
}
// A different Google subject under the grant is its own new account; the held one is never moved.
const other = await googleSignIn(app, plane, { firstLoginGrant: "invite" }, { sub: "g-sub-2" });
expect(other.done.json().account.id).not.toBe(accountId);
expect((await store.findStoredLinkedIdentity("google", "g-sub-1"))?.accountId).toBe(accountId);
expect(accountCount(store)).toBe(2);
expect(auditEvents(store).filter((e) => e.eventType === "account_minted_by_grant")).toHaveLength(2);
});
it("discord begins and refreshes with no entitlement policy, and the claim carries app_access", async () => {
const { app, plane } = await buildGhostlight();
const started = await begin(plane, { provider: "discord" });
expect(started.status).toBe("accepted");
const receipt = started.receipt as { handle: string; navigation: { url: string } };
const flow = await launchFlow(app, { authorizationUrl: receipt.navigation.url });
const callback = await app.inject({
method: "GET",
url: `/v1/oauth/discord/callback?code=c&state=${encodeURIComponent(flow.state)}`,
headers: { cookie: flow.cookie },
});
expect(callback.statusCode, callback.body).toBe(201);
const completion = (await complete(plane, receipt.handle)).receipt;
expect(completion?.status).toBe("authenticated");
expect(capabilitiesOf(completion)).toContain("app_access");
const refreshed = await command(plane, "heimdall.auth.refresh", "heimdall.auth_refresh_command.v1", { refreshToken: completion?.refreshToken });
expect(refreshed.receipt).toMatchObject({ schema: "heimdall.auth_refresh_receipt.v1", status: "authenticated" });
expect(capabilitiesOf(refreshed.receipt)).toContain("app_access");
});
it("a public ghostlight start, with no secret or the wrong one, is refused app_auth_required for every provider", async () => {
const { app, store } = await buildGhostlight();
for (const provider of ["google", "discord"]) {
for (const headers of [{}, { "x-heimdall-app-secret": "wrong" }, { "x-heimdall-app-secret": "bifrost-secret" }]) {
const res = await app.inject({
method: "POST",
url: `/v1/oauth/${provider}/start`,
headers,
payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN },
});
expect([res.statusCode, res.json().error], `${provider} ${JSON.stringify(headers)}`).toEqual([401, "app_auth_required"]);
expect(res.json().authorizationUrl).toBeUndefined();
}
}
// The same start with a grant is no easier without the app's secret.
const granted = await app.inject({
method: "POST",
url: "/v1/oauth/google/start",
payload: { appSlug: "ghostlight", mode: "sign_in", returnTo: RETURN, firstLoginGrant: "invite" },
});
expect([granted.statusCode, granted.json().error]).toEqual([401, "app_auth_required"]);
expect(accountCount(store)).toBe(0);
expect(attemptCount(store)).toBe(0);
});
it("a begin whose firstLoginGrant is anything but 'invite' is refused before any attempt or state is minted", async () => {
const { plane, store } = await buildGhostlight();
for (const bad of ["yes", "admin", true, 1, {}]) {
const res = await begin(plane, { provider: "google", firstLoginGrant: bad });
expect(res.status, JSON.stringify(bad)).not.toBe("accepted");
}
expect(attemptCount(store)).toBe(0);
});
it("a grant on link mode is refused by startOAuthFlow's gate, not smuggled past it", async () => {
const { plane } = await buildGhostlight();
const res = await begin(plane, { provider: "google", mode: "link", firstLoginGrant: "invite" });
expect(res.status).not.toBe("accepted");
});
it("other apps are unchanged: repixelizer's public start still opens and its grant is still first_login_grant_refused", async () => {
const { app } = await buildGhostlight();
const open = await app.inject({
method: "POST",
url: "/v1/oauth/discord/start",
payload: { appSlug: "repixelizer", mode: "sign_in", returnTo: "https://repixelizer.gamecult.org/app/" },
});
expect(open.statusCode).toBe(201);
const granted = 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([granted.statusCode, granted.json().error]).toEqual([400, "first_login_grant_refused"]);
});
});

View file

@ -14,7 +14,7 @@ import { openPrivateEnvelope, sealPrivateEnvelope, type HeimdallPrivateEnvelope
import { InMemoryStore } from "../src/store/index.js";
import { launchState } from "./oauth-flow.js";
const secret = "ghostlight-private-command-secret";
const secret = "bifrost-private-command-secret";
const resources: Array<{ close(): Promise<unknown> }> = [];
afterEach(async () => {
vi.unstubAllGlobals();
@ -29,24 +29,24 @@ function config(): HeimdallConfig {
idunnRudpHealth: undefined, idunnHealthContract: "heimdall.cultnet-rudp-provider-health", providerHealthIdentityPath: "/tmp/.hd/p.cc",
sessionTtlSeconds: 3600, refreshTtlSeconds: 3600, stateTtlSeconds: 600, completionTtlSeconds: 300,
bootstrapSigningPrivateKeyOnMissing: false, tokenEncryptionKeyBase64: Buffer.alloc(32, 7).toString("base64"),
appSharedSecrets: { ghostlight: secret }, appRuntimeIds: { ghostlight: ["yggdrasil-ghostlight"] }, appBackendCallbacks: {},
appSharedSecrets: { bifrost: secret }, appRuntimeIds: { bifrost: ["bifrost-runtime"] }, appBackendCallbacks: {},
storage: { backend: "memory", applySchemaOnStartup: true },
providers: { discord: { clientId: "discord-client", clientSecret: "discord-secret" }, patreon: {}, github: {}, twitch: {}, youtube: {}, spotify: {}, joystick: {}, google: {} },
} as HeimdallConfig;
}
async function command(endpoint: unknown, operation: string, contentSchema: string, key: string, payload: Record<string, unknown>) {
const envelope = sealPrivateEnvelope({ appSlug: "ghostlight", operation, contentSchema, idempotencyKey: key, secret, payload });
const envelope = sealPrivateEnvelope({ appSlug: "bifrost", operation, contentSchema, idempotencyKey: key, secret, payload });
return invokeCultNetOperation(endpoint as never, {
schemaVersion: "cultnet.operation_request.v0", messageId: `m-${key}`, serviceId: "heimdall.private.commands", operation,
payloadSchema: "heimdall.private_command_envelope.v1", payloadEncoding: "messagepack-base64",
payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "yggdrasil-ghostlight",
} as never, { runtimeId: "yggdrasil-ghostlight" });
payload: Buffer.from(encode(envelope)).toString("base64"), sourceRuntimeId: "bifrost-runtime",
} as never, { runtimeId: "bifrost-runtime" });
}
const open = (reply: { payload: string }) =>
openPrivateEnvelope(decode(Buffer.from(reply.payload, "base64")) as HeimdallPrivateEnvelope, secret);
/** A signed-in Ghostlight session, then a refresh whose provider answer is `refreshAnswer`. */
/** A signed-in Bifrost session, then a refresh whose provider answer is `refreshAnswer`. */
async function refreshAgainst(refreshAnswer: () => Response) {
let refreshing = false;
vi.stubGlobal("fetch", async (url: string | URL, init?: RequestInit) => {
@ -72,7 +72,7 @@ async function refreshAgainst(refreshAnswer: () => Response) {
resources.push(plane);
const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] };
const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1",
{ provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy }));
{ provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy }));
const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!;
const { cookie } = await launchState(app, state);
const callback = await app.inject({
@ -133,7 +133,7 @@ it("keeps the completion code out of the audit trail when the plane redeems by a
resources.push(plane);
const policy = { kind: "discord_role_access", guildId: "g", allowedRoleIds: ["r"] };
const begin = open(await command(plane.endpoint, "heimdall.auth.begin", "heimdall.auth_begin_command.v1", "k1",
{ provider: "discord", mode: "sign_in", returnTo: "https://yggdrasil.gamecult.org/ghostlight/", entitlementPolicy: policy }));
{ provider: "discord", mode: "sign_in", returnTo: "https://bifrost.gamecult.org/auth/heimdall/complete", entitlementPolicy: policy }));
const state = new URL(String((begin.navigation as { url: string }).url)).searchParams.get("state")!;
const { cookie } = await launchState(app, state);
const callback = await app.inject({