Prefer direct backend auth handoff
This commit is contained in:
parent
6795439ac7
commit
f8eec3558f
13 changed files with 515 additions and 47 deletions
|
|
@ -28,8 +28,11 @@ Landed right now:
|
|||
- account, linked-identity, session, grant, entitlement snapshot, and audit
|
||||
persistence
|
||||
- a real Discord OAuth callback path for the first Repixelizer access flow
|
||||
- direct backend callback handoff for same-host or Yggdrasil-reachable app
|
||||
backends
|
||||
- AES-256-GCM sealing for managed provider tokens at rest
|
||||
- a one-time browser completion exchange for opener `postMessage` handoff
|
||||
- a one-time browser completion exchange kept as fallback for opener
|
||||
`postMessage` handoff
|
||||
- app profile surfaces for Repixelizer and StreamPixels
|
||||
- signed claim issuance for app-local verification experiments
|
||||
- a local verifier helper in `src/verifier.ts` so app backends can validate
|
||||
|
|
|
|||
|
|
@ -99,17 +99,22 @@ Preferred browser handoff:
|
|||
|
||||
1. Repixelizer opens Heimdall auth in a script-opened new tab/window
|
||||
2. Heimdall completes provider auth and upstream entitlement checks
|
||||
3. Heimdall callback posts a one-time completion code back to the opener
|
||||
4. the callback context tries to close itself
|
||||
5. Repixelizer backend redeems the completion code with Heimdall
|
||||
6. Repixelizer establishes local trusted auth state from the redeemed result
|
||||
3. Heimdall delivers the auth result directly to a Repixelizer backend callback
|
||||
endpoint keyed by a local auth attempt id
|
||||
4. Repixelizer backend establishes local trusted auth state from that direct
|
||||
delivery
|
||||
5. the callback context only needs to signal status, try to close itself, and
|
||||
offer a dead-simple return path
|
||||
6. the main Repixelizer page learns completion from its own backend by polling,
|
||||
SSE, or websocket
|
||||
|
||||
Important rule:
|
||||
|
||||
- Repixelizer should not rely on a raw access token arriving in the callback
|
||||
URL
|
||||
- the browser may see a one-time completion code in fallback paths, but the
|
||||
final trusted auth material should come from backend redemption
|
||||
- the browser should not be the primary carrier of the final auth result
|
||||
- the one-time completion-code redeem flow remains acceptable as a fallback,
|
||||
not the preferred same-host path
|
||||
|
||||
Repixelizer should still do locally:
|
||||
|
||||
|
|
|
|||
|
|
@ -349,19 +349,33 @@ The generic flow should be the same across hosted experiments:
|
|||
|
||||
The browser should never be the custodian of provider tokens.
|
||||
|
||||
Preferred browser handoff for hosted apps:
|
||||
Preferred same-host or Yggdrasil-reachable handoff for hosted apps:
|
||||
|
||||
1. the app keeps its main page open
|
||||
2. auth starts in a script-opened new browser context
|
||||
3. Heimdall callback completes the provider flow server-side
|
||||
4. Heimdall returns a short-lived one-time completion artifact
|
||||
5. the callback page `postMessage`s that artifact back to the opener and tries
|
||||
to close itself
|
||||
6. the host app backend redeems the artifact with Heimdall and establishes the
|
||||
app's local trusted auth state
|
||||
4. Heimdall delivers the auth result directly to the host app backend over an
|
||||
internal backend channel
|
||||
5. the host app backend establishes the app's local trusted auth state
|
||||
6. the callback page only needs to signal completion status, try to close
|
||||
itself, and offer a dead-simple return path
|
||||
|
||||
This avoids spraying long-lived app auth into callback URLs while still giving
|
||||
the user the familiar "log in over there, keep working over here" flow.
|
||||
Recommended browser role in that flow:
|
||||
|
||||
- the main app page tracks its own auth attempt locally
|
||||
- the main app page learns completion from its own backend by polling, SSE, or
|
||||
websocket
|
||||
- the browser should not be the primary carrier of the final auth result
|
||||
|
||||
Fallback flow for looser integrations:
|
||||
|
||||
- Heimdall can still mint a short-lived one-time completion artifact
|
||||
- the callback page can `postMessage` that artifact to the opener
|
||||
- the host app backend can redeem it with Heimdall
|
||||
- keep this as the portable escape hatch, not the preferred same-host path
|
||||
|
||||
This keeps the real auth handoff on the server side while still giving the
|
||||
user the familiar "log in over there, keep working over here" flow.
|
||||
|
||||
## App integration contract
|
||||
|
||||
|
|
|
|||
|
|
@ -27,8 +27,10 @@ What exists right now is:
|
|||
- persisted accounts, linked identities, sessions, grants, entitlement
|
||||
snapshots, and audit records
|
||||
- a real Discord provider callback slice for Repixelizer access
|
||||
- a direct backend callback handoff for same-host app integrations
|
||||
- a one-time browser completion handoff so auth callback pages can post back to
|
||||
the opener instead of leaking final app auth in URL fragments
|
||||
the opener instead of leaking final app auth in URL fragments, now retained
|
||||
as fallback rather than the preferred same-host path
|
||||
- file-backed signing-key loading/bootstrap for stable service identity
|
||||
- AES-256-GCM token sealing for managed provider credentials at rest
|
||||
- a local verifier helper that app backends can use against Heimdall JWKS
|
||||
|
|
@ -124,7 +126,7 @@ Next in this phase:
|
|||
### Phase 3: Repixelizer binding
|
||||
|
||||
- integrate Heimdall into the hosted demo
|
||||
- consume the one-time completion flow from the Repixelizer frontend/backend
|
||||
- consume the direct backend callback flow from the Repixelizer frontend/backend
|
||||
- gate `POST /api/jobs`
|
||||
- gate per-job read/cancel/event routes by local session ownership
|
||||
- consume the landed verifier seam so Repixelizer can trust Heimdall JWTs locally
|
||||
|
|
|
|||
|
|
@ -126,6 +126,11 @@ Request body:
|
|||
"appSlug": "repixelizer",
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://repixelizer.gamecult.org/app/",
|
||||
"handoff": {
|
||||
"kind": "backend_callback",
|
||||
"attemptId": "auth-attempt-123",
|
||||
"callbackUrl": "https://repixelizer.gamecult.org/api/auth/heimdall/callback"
|
||||
},
|
||||
"connection": {
|
||||
"kind": "creator",
|
||||
"targetId": "creator:alpha",
|
||||
|
|
@ -168,17 +173,41 @@ Current status:
|
|||
- for Discord, exchanges the authorization code, resolves the provider
|
||||
identity, persists the local account/link/session/audit records, evaluates
|
||||
Repixelizer entitlement facts, and issues a signed Heimdall access claim
|
||||
- for browser-style callers, renders a Heimdall-hosted completion page that
|
||||
posts a one-time completion code back to the opener and tries to close
|
||||
itself
|
||||
- if opener handoff fails, the completion page still offers a fallback return
|
||||
link carrying only the one-time completion code, not the access token
|
||||
- for non-browser callers, returns JSON with the issued claim/session data plus
|
||||
completion metadata
|
||||
- when `handoff.kind=backend_callback`, delivers the auth result directly to
|
||||
the app backend and renders a tiny browser status page that can close itself
|
||||
- when `handoff.kind=browser_completion` or handoff is omitted, keeps the older
|
||||
one-time completion-code flow as a fallback path
|
||||
- if opener handoff is used and fails, the completion page still offers a
|
||||
fallback return link carrying only the one-time completion code, not the
|
||||
access token
|
||||
- other configured providers still return "not implemented" at the runtime
|
||||
adapter layer until their callback paths are added
|
||||
|
||||
Success response for non-browser callers now includes:
|
||||
Success response for backend-callback handoff now includes:
|
||||
|
||||
```json
|
||||
{
|
||||
"delivery": {
|
||||
"kind": "backend_callback",
|
||||
"attemptId": "auth-attempt-123",
|
||||
"callbackUrl": "https://repixelizer.gamecult.org/api/auth/heimdall/callback",
|
||||
"status": "delivered"
|
||||
},
|
||||
"account": {
|
||||
"id": "acct_repixelizer_001",
|
||||
"displayName": "Meta"
|
||||
},
|
||||
"session": {
|
||||
"accountId": "acct_repixelizer_001",
|
||||
"sessionId": "uuid",
|
||||
"appSlug": "repixelizer",
|
||||
"accessRevision": 1,
|
||||
"expiresAt": "2026-04-26T13:00:00.000Z"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Success response for browser-completion fallback still includes:
|
||||
|
||||
```json
|
||||
{
|
||||
|
|
@ -190,6 +219,69 @@ Success response for non-browser callers now includes:
|
|||
}
|
||||
```
|
||||
|
||||
### Backend callback delivery payload
|
||||
|
||||
Purpose:
|
||||
|
||||
- push the final auth result directly into the app backend without asking the
|
||||
browser to courier it
|
||||
|
||||
Current payload shape on success:
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "heimdall",
|
||||
"kind": "oauth_result",
|
||||
"handoffKind": "backend_callback",
|
||||
"attemptId": "auth-attempt-123",
|
||||
"status": "success",
|
||||
"provider": "discord",
|
||||
"appSlug": "repixelizer",
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://repixelizer.gamecult.org/app/",
|
||||
"account": {
|
||||
"id": "acct_repixelizer_001",
|
||||
"displayName": "Meta"
|
||||
},
|
||||
"session": {},
|
||||
"accessToken": "<signed-jwt>",
|
||||
"claimSet": {},
|
||||
"verification": {},
|
||||
"sharedCapabilities": ["app_access", "queue_submit"],
|
||||
"hybridCapabilities": [],
|
||||
"entitlements": {
|
||||
"facts": ["entitlement.app_access"],
|
||||
"snapshots": []
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Current payload shape on failure:
|
||||
|
||||
```json
|
||||
{
|
||||
"source": "heimdall",
|
||||
"kind": "oauth_result",
|
||||
"handoffKind": "backend_callback",
|
||||
"attemptId": "auth-attempt-123",
|
||||
"status": "error",
|
||||
"provider": "discord",
|
||||
"appSlug": "repixelizer",
|
||||
"mode": "sign_in",
|
||||
"returnTo": "https://repixelizer.gamecult.org/app/",
|
||||
"error": "oauth_callback_failed",
|
||||
"errorDescription": "..."
|
||||
}
|
||||
```
|
||||
|
||||
Important behavior:
|
||||
|
||||
- app backends should treat this as the preferred same-host or
|
||||
Yggdrasil-reachable integration path
|
||||
- app backends should still verify the included Heimdall `accessToken` locally
|
||||
- the browser only needs to learn attempt completion, not carry the final auth
|
||||
result
|
||||
|
||||
### `POST /v1/apps/{appSlug}/auth-completions/redeem`
|
||||
|
||||
Purpose:
|
||||
|
|
@ -197,6 +289,11 @@ Purpose:
|
|||
- redeem a short-lived one-time browser completion code
|
||||
- return the trusted Heimdall auth result to the app backend
|
||||
|
||||
Current role:
|
||||
|
||||
- fallback path for looser integrations, manual testing, or opener-based flows
|
||||
- not the preferred same-host consumer path anymore
|
||||
|
||||
Request body:
|
||||
|
||||
```json
|
||||
|
|
@ -367,6 +464,6 @@ The following are not landed yet:
|
|||
Consume the hardened slice in the first real app binding:
|
||||
|
||||
- the first Repixelizer consumer binding that trusts Heimdall claims locally
|
||||
- the first Repixelizer backend redeem path for completion codes
|
||||
- the first Repixelizer backend callback endpoint and attempt-status bridge
|
||||
- any missing app-local session bridge or verifier middleware sugar that makes
|
||||
that integration less feral
|
||||
|
|
|
|||
|
|
@ -50,6 +50,9 @@ Do not trust this file for the exact live HEAD. Always check git.
|
|||
claim issuance for the Repixelizer slice
|
||||
- browser-style auth handoff now uses a one-time completion code posted back to
|
||||
the opener, with backend redemption instead of fragment-token handoff
|
||||
- same-host or Yggdrasil-reachable app integrations can now ask Heimdall to
|
||||
deliver the auth result directly to an app backend callback endpoint, leaving
|
||||
the browser with only status/attempt signaling
|
||||
- signing keys can now load from a persisted file path and bootstrap that file
|
||||
on first boot when explicitly enabled
|
||||
- managed provider tokens are now sealed at rest with AES-256-GCM instead of
|
||||
|
|
@ -80,8 +83,8 @@ If the user asks to continue, the current next move is to harden and consume
|
|||
the landed slice:
|
||||
|
||||
- the first Repixelizer consumer integration that opens auth in a new browser
|
||||
context, redeems Heimdall completion codes server-side, and trusts Heimdall
|
||||
claims locally
|
||||
context, receives direct backend callback delivery from Heimdall, and trusts
|
||||
Heimdall claims locally
|
||||
- any small app-facing middleware sugar needed once that integration starts
|
||||
colliding with real routes
|
||||
|
||||
|
|
|
|||
206
src/app.ts
206
src/app.ts
|
|
@ -1,12 +1,15 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import cors from "@fastify/cors";
|
||||
import Fastify, { type FastifyInstance } from "fastify";
|
||||
import { deliverBackendHandoff, type BackendHandoffPayload } from "./backend-handoff.js";
|
||||
import {
|
||||
appSlugs,
|
||||
connectionKinds,
|
||||
oauthHandoffKinds,
|
||||
oauthModes,
|
||||
providers,
|
||||
type AppSlug,
|
||||
type OAuthHandoff,
|
||||
type OAuthMode,
|
||||
type OAuthConnectionBinding,
|
||||
type RedeemAuthCompletionRequest,
|
||||
|
|
@ -61,6 +64,7 @@ function buildOAuthStateToken(options: {
|
|||
mode: OAuthMode;
|
||||
returnTo: string;
|
||||
connection: OAuthConnectionBinding | undefined;
|
||||
handoff: OAuthHandoff;
|
||||
keys: ReturnType<typeof createRuntimeKeyMaterial>;
|
||||
}): { token: string; expiresAt: string } {
|
||||
const issuedAt = nowEpochSeconds();
|
||||
|
|
@ -79,6 +83,7 @@ function buildOAuthStateToken(options: {
|
|||
mode: options.mode,
|
||||
return_to: options.returnTo,
|
||||
connection: options.connection ?? null,
|
||||
handoff: options.handoff,
|
||||
};
|
||||
const token = signJwt(payload as unknown as Record<string, unknown>, options.keys);
|
||||
|
||||
|
|
@ -89,6 +94,16 @@ function buildOAuthStateToken(options: {
|
|||
}
|
||||
|
||||
function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePayload | null {
|
||||
const handoff = payload.handoff;
|
||||
const handoffIsValid =
|
||||
handoff === null ||
|
||||
handoff === undefined ||
|
||||
(typeof handoff === "object" &&
|
||||
handoff !== null &&
|
||||
((handoff as Record<string, unknown>).kind === "browser_completion" ||
|
||||
((handoff as Record<string, unknown>).kind === "backend_callback" &&
|
||||
typeof (handoff as Record<string, unknown>).attemptId === "string" &&
|
||||
typeof (handoff as Record<string, unknown>).callbackUrl === "string")));
|
||||
if (
|
||||
payload.typ !== "heimdall_oauth_state" ||
|
||||
typeof payload.provider !== "string" ||
|
||||
|
|
@ -104,12 +119,18 @@ function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePay
|
|||
typeof payload.jti !== "string" ||
|
||||
typeof payload.iat !== "number" ||
|
||||
typeof payload.nbf !== "number" ||
|
||||
typeof payload.exp !== "number"
|
||||
typeof payload.exp !== "number" ||
|
||||
!handoffIsValid
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return payload as unknown as OAuthStatePayload;
|
||||
const normalizedPayload = payload as unknown as OAuthStatePayload;
|
||||
if (!normalizedPayload.handoff) {
|
||||
normalizedPayload.handoff = { kind: "browser_completion" };
|
||||
}
|
||||
|
||||
return normalizedPayload;
|
||||
}
|
||||
|
||||
function buildGrantFacts(grants: StoredCapabilityGrant[]): string[] {
|
||||
|
|
@ -124,6 +145,40 @@ function prefersHtml(acceptHeader: string | undefined): boolean {
|
|||
return acceptHeader.includes("text/html") || acceptHeader.includes("application/xhtml+xml");
|
||||
}
|
||||
|
||||
function normalizeOAuthHandoff(value: OAuthStartRequest["handoff"]): OAuthHandoff {
|
||||
if (!value) {
|
||||
return { kind: "browser_completion" };
|
||||
}
|
||||
|
||||
if (value.kind === "browser_completion") {
|
||||
return value;
|
||||
}
|
||||
|
||||
if (
|
||||
value.kind === "backend_callback" &&
|
||||
typeof value.attemptId === "string" &&
|
||||
value.attemptId.trim() &&
|
||||
typeof value.callbackUrl === "string" &&
|
||||
value.callbackUrl.trim()
|
||||
) {
|
||||
return {
|
||||
kind: "backend_callback",
|
||||
attemptId: value.attemptId.trim(),
|
||||
callbackUrl: value.callbackUrl.trim(),
|
||||
};
|
||||
}
|
||||
|
||||
throw new Error("Invalid OAuth handoff definition.");
|
||||
}
|
||||
|
||||
async function maybeDeliverBackendHandoff(handoff: OAuthHandoff, payload: BackendHandoffPayload): Promise<void> {
|
||||
if (handoff.kind !== "backend_callback") {
|
||||
return;
|
||||
}
|
||||
|
||||
await deliverBackendHandoff(handoff.callbackUrl, payload);
|
||||
}
|
||||
|
||||
export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = options.config ?? loadConfig();
|
||||
const store = options.store ?? (await createStore(config));
|
||||
|
|
@ -216,6 +271,16 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
summary: { type: "string" },
|
||||
},
|
||||
},
|
||||
handoff: {
|
||||
type: "object",
|
||||
required: ["kind"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
kind: { type: "string", enum: [...oauthHandoffKinds] },
|
||||
attemptId: { type: "string", minLength: 1 },
|
||||
callbackUrl: { type: "string", format: "uri" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
|
|
@ -233,6 +298,17 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
};
|
||||
}
|
||||
|
||||
let handoff: OAuthHandoff;
|
||||
try {
|
||||
handoff = normalizeOAuthHandoff(request.body.handoff);
|
||||
} catch (error) {
|
||||
reply.code(400);
|
||||
return {
|
||||
error: "invalid_handoff",
|
||||
detail: error instanceof Error ? error.message : "Invalid OAuth handoff definition.",
|
||||
};
|
||||
}
|
||||
|
||||
const providerConfig = config.providers[provider];
|
||||
if (!providerConfig.clientId) {
|
||||
reply.code(503);
|
||||
|
|
@ -251,6 +327,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
mode: request.body.mode,
|
||||
returnTo: request.body.returnTo,
|
||||
connection: request.body.connection,
|
||||
handoff,
|
||||
keys,
|
||||
});
|
||||
|
||||
|
|
@ -267,6 +344,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
state: state.token,
|
||||
requestedScopes: request.body.requestedScopes,
|
||||
}),
|
||||
handoff,
|
||||
stateToken: state.token,
|
||||
stateExpiresAt: state.expiresAt,
|
||||
};
|
||||
|
|
@ -317,17 +395,36 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
reply.code(400);
|
||||
return { error: "state_provider_mismatch" };
|
||||
}
|
||||
const handoff = statePayload.handoff ?? { kind: "browser_completion" };
|
||||
|
||||
if (request.query.error) {
|
||||
if (handoff.kind === "backend_callback") {
|
||||
await maybeDeliverBackendHandoff(handoff, {
|
||||
source: "heimdall",
|
||||
kind: "oauth_result",
|
||||
handoffKind: "backend_callback",
|
||||
attemptId: handoff.attemptId,
|
||||
status: "error",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
error: "provider_error",
|
||||
errorDescription: request.query.error_description ?? request.query.error,
|
||||
});
|
||||
}
|
||||
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
handoffKind: handoff.kind,
|
||||
status: "error",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
|
||||
error: "provider_error",
|
||||
errorDescription: request.query.error_description ?? request.query.error,
|
||||
})
|
||||
|
|
@ -345,15 +442,32 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
}
|
||||
|
||||
if (!request.query.code) {
|
||||
if (handoff.kind === "backend_callback") {
|
||||
await maybeDeliverBackendHandoff(handoff, {
|
||||
source: "heimdall",
|
||||
kind: "oauth_result",
|
||||
handoffKind: "backend_callback",
|
||||
attemptId: handoff.attemptId,
|
||||
status: "error",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
error: "missing_code",
|
||||
});
|
||||
}
|
||||
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
handoffKind: handoff.kind,
|
||||
status: "error",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
|
||||
error: "missing_code",
|
||||
})
|
||||
);
|
||||
|
|
@ -501,6 +615,65 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
returnTo: statePayload.return_to,
|
||||
...issued,
|
||||
};
|
||||
if (handoff.kind === "backend_callback") {
|
||||
await maybeDeliverBackendHandoff(handoff, {
|
||||
source: "heimdall",
|
||||
kind: "oauth_result",
|
||||
handoffKind: "backend_callback",
|
||||
attemptId: handoff.attemptId,
|
||||
status: "success",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
account: accountSummary,
|
||||
entitlements: entitlementEvaluation,
|
||||
...issued,
|
||||
});
|
||||
|
||||
await store.createAuditEvent({
|
||||
accountId: account.id,
|
||||
sessionId: issued.session.sessionId,
|
||||
appSlug: statePayload.app_slug,
|
||||
eventType: "backend_handoff_delivered",
|
||||
eventPayloadJson: {
|
||||
provider: request.params.provider,
|
||||
mode: statePayload.mode,
|
||||
attemptId: handoff.attemptId,
|
||||
callbackUrl: handoff.callbackUrl,
|
||||
},
|
||||
createdAt: nowIso,
|
||||
});
|
||||
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
handoffKind: "backend_callback",
|
||||
status: "success",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
attemptId: handoff.attemptId,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
reply.code(201);
|
||||
return {
|
||||
delivery: {
|
||||
kind: "backend_callback",
|
||||
attemptId: handoff.attemptId,
|
||||
callbackUrl: handoff.callbackUrl,
|
||||
status: "delivered",
|
||||
},
|
||||
account: accountSummary,
|
||||
session: issued.session,
|
||||
verification: issued.verification,
|
||||
};
|
||||
}
|
||||
|
||||
const completionExpiresAt = new Date(Date.now() + config.completionTtlSeconds * 1000).toISOString();
|
||||
const completion = await store.createAuthCompletion({
|
||||
appSlug: statePayload.app_slug,
|
||||
|
|
@ -532,6 +705,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
handoffKind: "browser_completion",
|
||||
status: "success",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
|
|
@ -565,10 +739,13 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
createdAt: nowIso,
|
||||
});
|
||||
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
if (handoff.kind === "backend_callback") {
|
||||
try {
|
||||
await maybeDeliverBackendHandoff(handoff, {
|
||||
source: "heimdall",
|
||||
kind: "oauth_result",
|
||||
handoffKind: "backend_callback",
|
||||
attemptId: handoff.attemptId,
|
||||
status: "error",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
|
|
@ -576,6 +753,23 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
returnTo: statePayload.return_to,
|
||||
error: "oauth_callback_failed",
|
||||
errorDescription: message,
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
handoffKind: handoff.kind,
|
||||
status: "error",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
|
||||
error: "oauth_callback_failed",
|
||||
errorDescription: message,
|
||||
})
|
||||
);
|
||||
}
|
||||
|
|
|
|||
52
src/backend-handoff.ts
Normal file
52
src/backend-handoff.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import { type IssuedAccessClaimResult } from "./claims.js";
|
||||
import { type AppSlug, type OAuthMode, type Provider } from "./contracts.js";
|
||||
import { type EntitlementEvaluation } from "./oauth.js";
|
||||
|
||||
interface AccountSummary {
|
||||
id: string;
|
||||
displayName?: string;
|
||||
primaryEmail?: string;
|
||||
}
|
||||
|
||||
interface BackendHandoffBase {
|
||||
source: "heimdall";
|
||||
kind: "oauth_result";
|
||||
handoffKind: "backend_callback";
|
||||
attemptId: string;
|
||||
provider: Provider;
|
||||
appSlug: AppSlug;
|
||||
returnTo: string;
|
||||
}
|
||||
|
||||
export interface BackendHandoffSuccessPayload extends BackendHandoffBase, IssuedAccessClaimResult {
|
||||
status: "success";
|
||||
mode: OAuthMode;
|
||||
account: AccountSummary;
|
||||
entitlements: EntitlementEvaluation;
|
||||
}
|
||||
|
||||
export interface BackendHandoffErrorPayload extends BackendHandoffBase {
|
||||
status: "error";
|
||||
mode?: OAuthMode;
|
||||
error: string;
|
||||
errorDescription?: string;
|
||||
}
|
||||
|
||||
export type BackendHandoffPayload = BackendHandoffSuccessPayload | BackendHandoffErrorPayload;
|
||||
|
||||
export async function deliverBackendHandoff(callbackUrl: string, payload: BackendHandoffPayload): Promise<void> {
|
||||
const response = await fetch(callbackUrl, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const body = await response.text();
|
||||
throw new Error(
|
||||
`Backend handoff delivery failed (status ${response.status}): ${body || "empty response"}`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,23 +1,25 @@
|
|||
import { type AppSlug, type OAuthMode, type Provider } from "./contracts.js";
|
||||
import { type AppSlug, type OAuthHandoffKind, type OAuthMode, type Provider } from "./contracts.js";
|
||||
|
||||
interface BrowserHandoffBase {
|
||||
handoffKind: OAuthHandoffKind;
|
||||
provider: Provider;
|
||||
appSlug: AppSlug;
|
||||
mode?: OAuthMode;
|
||||
returnTo: string;
|
||||
}
|
||||
|
||||
export interface BrowserHandoffSuccess extends BrowserHandoffBase {
|
||||
status: "success";
|
||||
appSlug: AppSlug;
|
||||
mode: OAuthMode;
|
||||
completionCode: string;
|
||||
completionCode?: string;
|
||||
attemptId?: string;
|
||||
}
|
||||
|
||||
export interface BrowserHandoffError extends BrowserHandoffBase {
|
||||
status: "error";
|
||||
appSlug: AppSlug;
|
||||
mode?: OAuthMode;
|
||||
error: string;
|
||||
errorDescription?: string;
|
||||
attemptId?: string;
|
||||
}
|
||||
|
||||
export type BrowserHandoffPayload = BrowserHandoffSuccess | BrowserHandoffError;
|
||||
|
|
@ -31,22 +33,26 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string {
|
|||
const fragment = new URLSearchParams({
|
||||
heimdall_status: payload.status,
|
||||
heimdall_provider: payload.provider,
|
||||
heimdall_handoff_kind: payload.handoffKind,
|
||||
});
|
||||
|
||||
if ("appSlug" in payload) {
|
||||
fragment.set("heimdall_app_slug", payload.appSlug);
|
||||
}
|
||||
fragment.set("heimdall_app_slug", payload.appSlug);
|
||||
|
||||
if ("mode" in payload && payload.mode) {
|
||||
fragment.set("heimdall_mode", payload.mode);
|
||||
}
|
||||
|
||||
if (payload.status === "success") {
|
||||
if (payload.attemptId) {
|
||||
fragment.set("heimdall_attempt_id", payload.attemptId);
|
||||
}
|
||||
|
||||
if (payload.status === "success" && payload.completionCode) {
|
||||
fragment.set("heimdall_completion_code", payload.completionCode);
|
||||
} else {
|
||||
fragment.set("heimdall_error", payload.error);
|
||||
if (payload.errorDescription) {
|
||||
fragment.set("heimdall_error_description", payload.errorDescription);
|
||||
if (payload.status === "error") {
|
||||
fragment.set("heimdall_error", payload.error);
|
||||
if (payload.errorDescription) {
|
||||
fragment.set("heimdall_error_description", payload.errorDescription);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
@ -69,7 +75,9 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string
|
|||
);
|
||||
const scriptBody = serializeForScript(
|
||||
payload.status === "success"
|
||||
? "You can return to the app now."
|
||||
? payload.handoffKind === "backend_callback"
|
||||
? "The app backend has the auth result already. You can return to the app now."
|
||||
: "You can return to the app now."
|
||||
: "The authentication flow failed. Return to the app to continue."
|
||||
);
|
||||
|
||||
|
|
|
|||
|
|
@ -14,17 +14,34 @@ export const connectionKinds = ["account", "creator", "workspace", "project", "c
|
|||
|
||||
export type ConnectionKind = (typeof connectionKinds)[number];
|
||||
|
||||
export const oauthHandoffKinds = ["browser_completion", "backend_callback"] as const;
|
||||
|
||||
export type OAuthHandoffKind = (typeof oauthHandoffKinds)[number];
|
||||
|
||||
export interface OAuthConnectionBinding {
|
||||
kind: ConnectionKind;
|
||||
targetId: string;
|
||||
summary?: string;
|
||||
}
|
||||
|
||||
export interface OAuthBrowserCompletionHandoff {
|
||||
kind: "browser_completion";
|
||||
}
|
||||
|
||||
export interface OAuthBackendCallbackHandoff {
|
||||
kind: "backend_callback";
|
||||
attemptId: string;
|
||||
callbackUrl: string;
|
||||
}
|
||||
|
||||
export type OAuthHandoff = OAuthBrowserCompletionHandoff | OAuthBackendCallbackHandoff;
|
||||
|
||||
export interface OAuthStartRequest {
|
||||
appSlug: AppSlug;
|
||||
mode: OAuthMode;
|
||||
returnTo: string;
|
||||
connection?: OAuthConnectionBinding;
|
||||
handoff?: OAuthHandoff;
|
||||
requestedScopes?: string[];
|
||||
}
|
||||
|
||||
|
|
@ -42,6 +59,7 @@ export interface OAuthStatePayload {
|
|||
mode: OAuthMode;
|
||||
return_to: string;
|
||||
connection: OAuthConnectionBinding | null;
|
||||
handoff: OAuthHandoff | null;
|
||||
}
|
||||
|
||||
export interface LinkedIdentityInput {
|
||||
|
|
|
|||
|
|
@ -8,3 +8,4 @@
|
|||
{"ts": "2026-04-26T13:58:45+00:00", "type": "design", "status": "accepted", "note": "Heimdall claim facts should prefer provider-agnostic, app-facing entitlement names such as entitlement.app_access. Provider-specific evidence like Discord role matches stays in linked identities and entitlement snapshots unless a consumer truly needs that upstream detail in the claim surface."}
|
||||
{"ts": "2026-04-26T14:22:37+00:00", "type": "implementation", "status": "accepted", "note": "Browser-style Heimdall auth handoff now uses a short-lived one-time completion code: the callback page posts the result to the opener, tries to close itself, and the app backend redeems the code with Heimdall instead of receiving the final access token in a callback URL fragment."}
|
||||
{"ts": "2026-04-26T15:22:58+00:00", "type": "implementation", "status": "accepted", "note": "Heimdall now supports file-backed signing-key loading/bootstrap, AES-256-GCM token sealing for managed provider credentials at rest, and a local JWT verifier seam in src/verifier.ts; the next move shifts from custody hardening to the first real Repixelizer consumer integration."}
|
||||
{"ts": "2026-04-26T16:00:35+00:00", "type": "design", "status": "accepted", "note": "Heimdall now supports direct backend callback delivery as the preferred same-host or Yggdrasil-reachable app handoff path; the browser completion-code redeem flow remains as fallback, not the primary consumer contract."}
|
||||
|
|
|
|||
|
|
@ -79,6 +79,7 @@ landed_baseline:
|
|||
- Durable auth persistence landed for accounts, linked identities, sessions, grants, entitlement snapshots, and audit events.
|
||||
- The first real provider slice landed for Discord callback exchange, identity resolution, entitlement evaluation, and session/claim issuance for Repixelizer.
|
||||
- Signing-key persistence/bootstrap, managed token encryption at rest, and a local verifier seam landed for the first real consumer integration pass.
|
||||
- Direct backend callback handoff landed as the preferred same-host app-consumer path, with browser completion-code exchange retained as fallback.
|
||||
|
||||
rejected_paths:
|
||||
- name: per_app_auth_copy_paste
|
||||
|
|
@ -89,5 +90,5 @@ rejected_paths:
|
|||
reason: reusing auth mechanics does not justify centralizing app-domain audience or product data
|
||||
|
||||
current_status:
|
||||
summary: Heimdall now has a hardened first provider slice: TypeScript/Fastify runtime, Ed25519 JWT signing with file-backed key support, JWKS/discovery exposure, signed OAuth start-state handling, durable auth/control-plane persistence, a real Discord callback path, AES-256-GCM token sealing for managed provider credentials at rest, a local JWT verifier seam for app backends, and a one-time completion-code exchange that lets browser auth contexts post back to the opener without leaking final app auth in URL fragments. The key boundary still holds: Heimdall owns auth/control-plane authority and credential custody; app-domain bindings and runtime behavior remain app-owned.
|
||||
next_action: Consume the hardened slice in the first real Repixelizer integration: open auth in a new browser context, redeem Heimdall completion codes server-side, trust Heimdall claims locally through the verifier seam, and add any tiny app-local session bridge needed without dragging app-domain data into Heimdall.
|
||||
summary: Heimdall now has a hardened first provider slice plus a direct app-backend handoff path: TypeScript/Fastify runtime, Ed25519 JWT signing with file-backed key support, JWKS/discovery exposure, signed OAuth start-state handling, durable auth/control-plane persistence, a real Discord callback path, AES-256-GCM token sealing for managed provider credentials at rest, a local JWT verifier seam for app backends, direct backend callback delivery for same-host consumers, and the older one-time completion-code exchange retained as fallback. The key boundary still holds: Heimdall owns auth/control-plane authority and credential custody; app-domain bindings and runtime behavior remain app-owned.
|
||||
next_action: Consume the hardened slice in the first real Repixelizer integration: open auth in a new browser context, let Heimdall deliver the result directly to a Repixelizer backend callback endpoint keyed by a local auth attempt, trust Heimdall claims locally through the verifier seam, and add any tiny app-local session bridge or attempt-status surface needed without dragging app-domain data into Heimdall.
|
||||
|
|
|
|||
|
|
@ -86,6 +86,7 @@ function createMockDiscordRuntime(): OAuthProviderRuntime {
|
|||
}
|
||||
|
||||
const apps: Awaited<ReturnType<typeof buildApp>>[] = [];
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
function getPublicKey(app: FastifyInstance) {
|
||||
return (
|
||||
|
|
@ -130,6 +131,7 @@ async function startDiscordSignIn(app: FastifyInstance): Promise<string> {
|
|||
}
|
||||
|
||||
afterEach(async () => {
|
||||
globalThis.fetch = originalFetch;
|
||||
while (apps.length) {
|
||||
await apps.pop()?.close();
|
||||
}
|
||||
|
|
@ -332,6 +334,74 @@ describe("Heimdall service", () => {
|
|||
expect(response.body).not.toContain("heimdall_access_token");
|
||||
});
|
||||
|
||||
it("delivers auth results directly to app backends when backend callback handoff is requested", async () => {
|
||||
const deliveries: Array<Record<string, unknown>> = [];
|
||||
globalThis.fetch = async (input, init) => {
|
||||
if (String(input) !== "https://repixelizer.gamecult.org/api/auth/heimdall/callback") {
|
||||
throw new Error(`Unexpected fetch target in backend handoff test: ${String(input)}`);
|
||||
}
|
||||
|
||||
deliveries.push(JSON.parse(String(init?.body)) as Record<string, unknown>);
|
||||
return new Response(null, { status: 204 });
|
||||
};
|
||||
|
||||
const app = await buildApp({
|
||||
config: createTestConfig(),
|
||||
oauthRuntimes: {
|
||||
discord: createMockDiscordRuntime(),
|
||||
},
|
||||
});
|
||||
apps.push(app);
|
||||
|
||||
const startResponse = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/discord/start",
|
||||
payload: {
|
||||
appSlug: "repixelizer",
|
||||
mode: "sign_in",
|
||||
returnTo: "https://repixelizer.gamecult.org/app/",
|
||||
handoff: {
|
||||
kind: "backend_callback",
|
||||
attemptId: "attempt-123",
|
||||
callbackUrl: "https://repixelizer.gamecult.org/api/auth/heimdall/callback",
|
||||
},
|
||||
},
|
||||
});
|
||||
expect(startResponse.statusCode).toBe(201);
|
||||
const stateToken = startResponse.json().stateToken as string;
|
||||
|
||||
const response = await app.inject({
|
||||
method: "GET",
|
||||
url: `/v1/oauth/discord/callback?code=test-code&state=${encodeURIComponent(stateToken)}`,
|
||||
headers: {
|
||||
accept: "text/html",
|
||||
},
|
||||
});
|
||||
|
||||
expect(response.statusCode).toBe(200);
|
||||
expect(response.body).toContain("heimdall_attempt_id");
|
||||
expect(response.body).not.toContain("heimdall_completion_code");
|
||||
expect(deliveries).toHaveLength(1);
|
||||
const delivery = deliveries[0];
|
||||
expect(delivery).toBeDefined();
|
||||
expect(delivery).toEqual(
|
||||
expect.objectContaining({
|
||||
source: "heimdall",
|
||||
kind: "oauth_result",
|
||||
handoffKind: "backend_callback",
|
||||
attemptId: "attempt-123",
|
||||
status: "success",
|
||||
provider: "discord",
|
||||
appSlug: "repixelizer",
|
||||
})
|
||||
);
|
||||
|
||||
const deliveryAccessToken = delivery?.accessToken;
|
||||
expect(typeof deliveryAccessToken).toBe("string");
|
||||
const verified = verifyJwt(String(deliveryAccessToken), getPublicKey(app));
|
||||
expect(verified.valid).toBe(true);
|
||||
});
|
||||
|
||||
it("issues direct claims from provider-agnostic entitlement facts", async () => {
|
||||
const app = await buildApp({ config: createTestConfig() });
|
||||
apps.push(app);
|
||||
|
|
|
|||
Loading…
Reference in a new issue