Heimdall/src/app.ts

1185 lines
39 KiB
TypeScript
Raw Normal View History

2026-04-29 15:00:55 +01:00
import { randomUUID, timingSafeEqual } from "node:crypto";
2026-04-26 12:25:11 +01:00
import cors from "@fastify/cors";
import Fastify, { type FastifyInstance } from "fastify";
2026-04-26 17:00:57 +01:00
import { deliverBackendHandoff, type BackendHandoffPayload } from "./backend-handoff.js";
2026-04-26 12:25:11 +01:00
import {
appSlugs,
connectionKinds,
2026-04-26 17:00:57 +01:00
oauthHandoffKinds,
2026-04-26 12:25:11 +01:00
oauthModes,
providers,
type AppSlug,
2026-04-26 17:00:57 +01:00
type OAuthHandoff,
2026-04-29 13:22:01 +01:00
type OAuthEntitlementPolicy,
2026-04-26 12:50:07 +01:00
type OAuthMode,
2026-04-26 12:25:11 +01:00
type OAuthConnectionBinding,
type RedeemAuthCompletionRequest,
2026-04-26 12:50:07 +01:00
type OAuthStatePayload,
2026-04-26 12:25:11 +01:00
type OAuthStartRequest,
type Provider,
} from "./contracts.js";
2026-04-26 12:50:07 +01:00
import { mapIssueClaimRequest, issueAccessClaim, type IssueAccessClaimInput } from "./claims.js";
2026-04-26 12:25:11 +01:00
import { getAppProfile, serializeAppProfile, supportsProvider } from "./app-profiles.js";
import { renderBrowserHandoffPage } from "./browser-handoff.js";
2026-04-26 12:25:11 +01:00
import { type HeimdallConfig, loadConfig } from "./config.js";
import { createTokenCustody, type TokenCustody } from "./custody.js";
import { grantFact } from "./facts.js";
2026-04-26 12:50:07 +01:00
import { createOAuthRuntimeRegistry, type OAuthRuntimeRegistry } from "./oauth.js";
2026-04-26 12:25:11 +01:00
import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js";
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js";
2026-04-26 12:50:07 +01:00
import { createStore, type HeimdallStore } from "./store/index.js";
import {
type CreateAccountInput,
type StoredCapabilityGrant,
type StoredLinkedIdentity,
type UpsertLinkedIdentityInput,
} from "./store/types.js";
const MANAGED_CREDENTIAL_REFRESH_SKEW_MS = 5 * 60 * 1000;
2026-04-26 12:25:11 +01:00
interface BuildAppOptions {
config?: HeimdallConfig;
2026-04-26 12:50:07 +01:00
store?: HeimdallStore;
oauthRuntimes?: Partial<OAuthRuntimeRegistry>;
tokenCustody?: TokenCustody;
2026-04-26 12:25:11 +01:00
}
function buildDiscovery(config: HeimdallConfig) {
return {
issuer: config.issuer,
jwksUri: `${config.publicBaseUrl}/.well-known/jwks.json`,
configurationUri: `${config.publicBaseUrl}/.well-known/heimdall-configuration`,
oauthStartEndpoint: `${config.publicBaseUrl}/v1/oauth/{provider}/start`,
oauthCallbackEndpoint: `${config.publicBaseUrl}/v1/oauth/{provider}/callback`,
claimIssueEndpoint: `${config.publicBaseUrl}/v1/apps/{appSlug}/claims/issue`,
supportedProviders: providers.map((provider) => ({
key: provider,
displayName: providerCatalog[provider].displayName,
roles: providerCatalog[provider].roles,
})),
apps: appSlugs.map((appSlug) => serializeAppProfile(getAppProfile(appSlug))),
};
}
2026-04-26 12:50:07 +01:00
function nowEpochSeconds(): number {
return Math.floor(Date.now() / 1000);
}
2026-04-26 12:25:11 +01:00
function buildOAuthStateToken(options: {
config: HeimdallConfig;
provider: Provider;
appSlug: AppSlug;
2026-04-26 12:50:07 +01:00
mode: OAuthMode;
2026-04-26 12:25:11 +01:00
returnTo: string;
connection: OAuthConnectionBinding | undefined;
2026-04-26 17:00:57 +01:00
handoff: OAuthHandoff;
2026-04-29 13:22:01 +01:00
entitlementPolicy: OAuthEntitlementPolicy | undefined;
2026-04-26 12:25:11 +01:00
keys: ReturnType<typeof createRuntimeKeyMaterial>;
}): { token: string; expiresAt: string } {
const issuedAt = nowEpochSeconds();
const expiresAtEpoch = issuedAt + options.config.stateTtlSeconds;
2026-04-26 12:50:07 +01:00
const payload: OAuthStatePayload = {
iss: options.config.issuer,
sub: options.appSlug,
aud: options.provider,
jti: randomUUID(),
iat: issuedAt,
nbf: issuedAt,
exp: expiresAtEpoch,
typ: "heimdall_oauth_state",
provider: options.provider,
app_slug: options.appSlug,
mode: options.mode,
return_to: options.returnTo,
connection: options.connection ?? null,
2026-04-26 17:00:57 +01:00
handoff: options.handoff,
2026-04-29 13:22:01 +01:00
entitlement_policy: options.entitlementPolicy ?? null,
2026-04-26 12:50:07 +01:00
};
const token = signJwt(payload as unknown as Record<string, unknown>, options.keys);
2026-04-26 12:25:11 +01:00
return {
token,
expiresAt: new Date(expiresAtEpoch * 1000).toISOString(),
};
}
2026-04-26 12:50:07 +01:00
function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePayload | null {
2026-04-26 17:00:57 +01:00
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")));
2026-04-29 13:22:01 +01:00
const entitlementPolicy = payload.entitlement_policy;
const entitlementPolicyIsValid =
entitlementPolicy === null ||
entitlementPolicy === undefined ||
2026-04-29 14:36:03 +01:00
((typeof entitlementPolicy === "object" &&
2026-04-29 13:22:01 +01:00
entitlementPolicy !== null &&
(entitlementPolicy as Record<string, unknown>).kind === "discord_role_access" &&
typeof (entitlementPolicy as Record<string, unknown>).guildId === "string" &&
Array.isArray((entitlementPolicy as Record<string, unknown>).allowedRoleIds) &&
((entitlementPolicy as Record<string, unknown>).allowedRoleIds as unknown[]).every(
(roleId) => typeof roleId === "string"
2026-04-29 14:36:03 +01:00
)) ||
(typeof entitlementPolicy === "object" &&
entitlementPolicy !== null &&
(entitlementPolicy as Record<string, unknown>).kind === "patreon_membership_access" &&
typeof (entitlementPolicy as Record<string, unknown>).requiredTierTitle === "string"));
2026-04-26 12:50:07 +01:00
if (
payload.typ !== "heimdall_oauth_state" ||
typeof payload.provider !== "string" ||
!providers.includes(payload.provider as Provider) ||
typeof payload.app_slug !== "string" ||
!appSlugs.includes(payload.app_slug as AppSlug) ||
typeof payload.mode !== "string" ||
!oauthModes.includes(payload.mode as OAuthMode) ||
typeof payload.return_to !== "string" ||
typeof payload.iss !== "string" ||
typeof payload.sub !== "string" ||
typeof payload.aud !== "string" ||
typeof payload.jti !== "string" ||
typeof payload.iat !== "number" ||
typeof payload.nbf !== "number" ||
2026-04-26 17:00:57 +01:00
typeof payload.exp !== "number" ||
2026-04-29 13:22:01 +01:00
!handoffIsValid ||
!entitlementPolicyIsValid
2026-04-26 12:50:07 +01:00
) {
return null;
}
2026-04-26 17:00:57 +01:00
const normalizedPayload = payload as unknown as OAuthStatePayload;
if (!normalizedPayload.handoff) {
normalizedPayload.handoff = { kind: "browser_completion" };
}
2026-04-29 13:22:01 +01:00
if (!normalizedPayload.entitlement_policy) {
normalizedPayload.entitlement_policy = null;
}
2026-04-26 17:00:57 +01:00
return normalizedPayload;
2026-04-26 12:50:07 +01:00
}
function buildGrantFacts(grants: StoredCapabilityGrant[]): string[] {
return grants.map((grant) => grantFact(grant.capability));
2026-04-26 12:50:07 +01:00
}
function prefersHtml(acceptHeader: string | undefined): boolean {
if (!acceptHeader) {
return false;
}
return acceptHeader.includes("text/html") || acceptHeader.includes("application/xhtml+xml");
}
2026-04-26 17:00:57 +01:00
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.");
}
2026-04-29 13:22:01 +01:00
function normalizeEntitlementPolicy(value: OAuthStartRequest["entitlementPolicy"]): OAuthEntitlementPolicy | undefined {
if (!value) {
return undefined;
}
if (
value.kind === "discord_role_access" &&
typeof value.guildId === "string" &&
value.guildId.trim() &&
Array.isArray(value.allowedRoleIds)
) {
const allowedRoleIds = value.allowedRoleIds.map((roleId) => roleId.trim()).filter(Boolean);
if (allowedRoleIds.length) {
return {
kind: "discord_role_access",
guildId: value.guildId.trim(),
allowedRoleIds,
};
}
}
2026-04-29 14:36:03 +01:00
if (
value.kind === "patreon_membership_access" &&
typeof value.requiredTierTitle === "string" &&
value.requiredTierTitle.trim()
) {
return {
kind: "patreon_membership_access",
requiredTierTitle: value.requiredTierTitle.trim(),
};
}
2026-04-29 13:22:01 +01:00
throw new Error("Invalid entitlement policy definition.");
}
2026-04-29 15:00:55 +01:00
function getSharedSecret(request: { headers: Record<string, string | string[] | undefined> }): string | undefined {
const header = request.headers["x-heimdall-app-secret"];
return Array.isArray(header) ? header[0] : header;
}
function secretMatches(expected: string | undefined, provided: string | undefined): boolean {
if (!expected || !provided) {
return false;
}
const expectedBuffer = Buffer.from(expected);
const providedBuffer = Buffer.from(provided);
return expectedBuffer.length === providedBuffer.length && timingSafeEqual(expectedBuffer, providedBuffer);
}
async function refreshLinkedIdentityCredentialIfNeeded(options: {
config: HeimdallConfig;
store: HeimdallStore;
tokenCustody: TokenCustody;
oauthRuntimes: OAuthRuntimeRegistry;
linkedIdentity: StoredLinkedIdentity;
now: string;
}): Promise<StoredLinkedIdentity> {
const expiresAt = options.linkedIdentity.tokenExpiresAt ? Date.parse(options.linkedIdentity.tokenExpiresAt) : undefined;
if (
!expiresAt ||
expiresAt - Date.now() > MANAGED_CREDENTIAL_REFRESH_SKEW_MS ||
!options.linkedIdentity.refreshTokenEncrypted
) {
return options.linkedIdentity;
}
const runtime = options.oauthRuntimes[options.linkedIdentity.provider];
if (!runtime.refreshAccessToken) {
return options.linkedIdentity;
}
const refreshToken = options.tokenCustody.decrypt(options.linkedIdentity.refreshTokenEncrypted);
const refreshed = await runtime.refreshAccessToken({
config: options.config,
refreshToken,
});
const upsertInput: UpsertLinkedIdentityInput = {
id: options.linkedIdentity.id,
accountId: options.linkedIdentity.accountId,
provider: options.linkedIdentity.provider,
providerUserId: options.linkedIdentity.providerUserId,
accessTokenEncrypted: options.tokenCustody.encrypt(refreshed.accessToken),
refreshTokenEncrypted: options.tokenCustody.encrypt(refreshed.refreshToken ?? refreshToken),
scopes: refreshed.scope.length ? refreshed.scope : options.linkedIdentity.scopes,
profileJson: options.linkedIdentity.profileJson,
createdAt: options.linkedIdentity.createdAt,
updatedAt: options.now,
};
const tokenExpiresAt = refreshed.expiresAt ?? options.linkedIdentity.tokenExpiresAt;
if (tokenExpiresAt !== undefined) {
upsertInput.tokenExpiresAt = tokenExpiresAt;
}
if (options.linkedIdentity.username !== undefined) {
upsertInput.username = options.linkedIdentity.username;
}
if (options.linkedIdentity.displayName !== undefined) {
upsertInput.displayName = options.linkedIdentity.displayName;
}
if (options.linkedIdentity.primaryEmail !== undefined) {
upsertInput.primaryEmail = options.linkedIdentity.primaryEmail;
}
return options.store.upsertLinkedIdentity(upsertInput);
}
2026-04-29 13:22:01 +01:00
function acceptsBackendPolicy(appSlug: AppSlug, handoff: OAuthHandoff): boolean {
if (handoff.kind !== "backend_callback") {
return false;
}
if (appSlug === "repixelizer") {
return handoff.callbackUrl === "https://repixelizer.gamecult.org/api/auth/heimdall/callback";
}
return false;
}
2026-04-26 17:00:57 +01:00
async function maybeDeliverBackendHandoff(handoff: OAuthHandoff, payload: BackendHandoffPayload): Promise<void> {
if (handoff.kind !== "backend_callback") {
return;
}
await deliverBackendHandoff(handoff.callbackUrl, payload);
}
2026-04-26 12:25:11 +01:00
export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
const config = options.config ?? loadConfig();
2026-04-26 12:50:07 +01:00
const store = options.store ?? (await createStore(config));
2026-04-26 12:25:11 +01:00
const keys = createRuntimeKeyMaterial(config);
const tokenCustody = options.tokenCustody ?? createTokenCustody(config);
2026-04-26 12:50:07 +01:00
const oauthRuntimes: OAuthRuntimeRegistry = {
...createOAuthRuntimeRegistry(),
...(options.oauthRuntimes ?? {}),
};
2026-04-26 12:25:11 +01:00
const app = Fastify({ logger: false });
app.decorate("heimdallContext", { config, keys, store, oauthRuntimes, tokenCustody });
2026-04-26 12:50:07 +01:00
app.addHook("onClose", async () => {
await store.close();
});
2026-04-26 12:25:11 +01:00
await app.register(cors, {
origin: true,
credentials: true,
});
app.get("/healthz", async () => ({
ok: true,
service: config.serviceName,
issuer: config.issuer,
2026-04-26 12:50:07 +01:00
storageBackend: config.storage.backend,
signingKeySource: keys.source,
tokenCustodySource: tokenCustody.source,
2026-04-26 12:25:11 +01:00
now: new Date().toISOString(),
}));
app.get("/.well-known/jwks.json", async () => ({
keys: [keys.publicJwk],
}));
app.get("/.well-known/heimdall-configuration", async () => buildDiscovery(config));
app.get("/v1/apps", async () => ({
apps: appSlugs.map((appSlug) => serializeAppProfile(getAppProfile(appSlug))),
}));
app.get<{ Params: { appSlug: AppSlug } }>(
"/v1/apps/:appSlug",
{
schema: {
params: {
type: "object",
required: ["appSlug"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
},
},
},
},
async (request) => serializeAppProfile(getAppProfile(request.params.appSlug))
);
app.post<{ Params: { provider: Provider }; Body: OAuthStartRequest }>(
"/v1/oauth/:provider/start",
{
schema: {
params: {
type: "object",
required: ["provider"],
additionalProperties: false,
properties: {
provider: { type: "string", enum: [...providers] },
},
},
body: {
type: "object",
required: ["appSlug", "mode", "returnTo"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
mode: { type: "string", enum: [...oauthModes] },
returnTo: { type: "string", format: "uri" },
requestedScopes: {
type: "array",
items: { type: "string" },
uniqueItems: true,
},
connection: {
type: "object",
required: ["kind", "targetId"],
additionalProperties: false,
properties: {
kind: { type: "string", enum: [...connectionKinds] },
targetId: { type: "string", minLength: 1 },
summary: { type: "string" },
},
},
2026-04-26 17:00:57 +01:00
handoff: {
type: "object",
required: ["kind"],
additionalProperties: false,
properties: {
kind: { type: "string", enum: [...oauthHandoffKinds] },
attemptId: { type: "string", minLength: 1 },
callbackUrl: { type: "string", format: "uri" },
},
},
2026-04-29 13:22:01 +01:00
entitlementPolicy: {
2026-04-29 14:36:03 +01:00
anyOf: [
{
type: "object",
required: ["kind", "guildId", "allowedRoleIds"],
additionalProperties: false,
properties: {
kind: { type: "string", const: "discord_role_access" },
guildId: { type: "string", minLength: 1 },
allowedRoleIds: {
type: "array",
minItems: 1,
items: { type: "string", minLength: 1 },
uniqueItems: true,
},
},
2026-04-29 13:22:01 +01:00
},
2026-04-29 14:36:03 +01:00
{
type: "object",
required: ["kind", "requiredTierTitle"],
additionalProperties: false,
properties: {
kind: { type: "string", const: "patreon_membership_access" },
requiredTierTitle: { type: "string", minLength: 1 },
},
},
],
2026-04-29 13:22:01 +01:00
},
2026-04-26 12:25:11 +01:00
},
},
},
},
async (request, reply) => {
const { provider } = request.params;
const profile = getAppProfile(request.body.appSlug);
if (!supportsProvider(profile, provider)) {
reply.code(400);
return {
error: "provider_not_supported_for_app",
provider,
appSlug: profile.slug,
};
}
2026-04-26 17:00:57 +01:00
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.",
};
}
2026-04-29 13:22:01 +01:00
let entitlementPolicy: OAuthEntitlementPolicy | undefined;
try {
entitlementPolicy = normalizeEntitlementPolicy(request.body.entitlementPolicy);
} catch (error) {
reply.code(400);
return {
error: "invalid_entitlement_policy",
detail: error instanceof Error ? error.message : "Invalid entitlement policy definition.",
};
}
if (entitlementPolicy && !acceptsBackendPolicy(profile.slug, handoff)) {
reply.code(400);
return {
error: "untrusted_entitlement_policy",
detail: "Caller-supplied entitlement policy is only accepted for trusted backend callback handoffs.",
};
}
2026-04-26 17:00:57 +01:00
2026-04-26 12:25:11 +01:00
const providerConfig = config.providers[provider];
if (!providerConfig.clientId) {
reply.code(503);
return {
error: "provider_not_configured",
provider,
expectedEnv: providerExpectedEnv(provider),
};
}
const callbackUrl = `${config.publicBaseUrl}/v1/oauth/${provider}/callback`;
const state = buildOAuthStateToken({
config,
provider,
appSlug: profile.slug,
mode: request.body.mode,
returnTo: request.body.returnTo,
connection: request.body.connection,
2026-04-26 17:00:57 +01:00
handoff,
2026-04-29 13:22:01 +01:00
entitlementPolicy,
2026-04-26 12:25:11 +01:00
keys,
});
reply.code(201);
return {
provider,
appSlug: profile.slug,
mode: request.body.mode,
callbackUrl,
authorizationUrl: buildAuthorizationUrl({
provider,
clientId: providerConfig.clientId,
redirectUri: callbackUrl,
state: state.token,
requestedScopes: request.body.requestedScopes,
}),
2026-04-26 17:00:57 +01:00
handoff,
2026-04-26 12:25:11 +01:00
stateToken: state.token,
stateExpiresAt: state.expiresAt,
};
}
);
app.get<{
Params: { provider: Provider };
Querystring: { code?: string; state?: string; error?: string; error_description?: string };
}>(
"/v1/oauth/:provider/callback",
{
schema: {
params: {
type: "object",
required: ["provider"],
additionalProperties: false,
properties: {
provider: { type: "string", enum: [...providers] },
},
},
querystring: {
type: "object",
additionalProperties: false,
properties: {
code: { type: "string" },
state: { type: "string" },
error: { type: "string" },
error_description: { type: "string" },
},
},
},
},
async (request, reply) => {
if (!request.query.state) {
reply.code(400);
return { error: "missing_state" };
}
const verification = verifyJwt(request.query.state, keys.publicKey);
if (!verification.valid) {
reply.code(400);
return { error: "invalid_state", detail: verification.error };
}
2026-04-26 12:50:07 +01:00
const statePayload = parseOAuthStatePayload(verification.payload);
if (!statePayload || statePayload.provider !== request.params.provider) {
2026-04-26 12:25:11 +01:00
reply.code(400);
return { error: "state_provider_mismatch" };
}
2026-04-26 17:00:57 +01:00
const handoff = statePayload.handoff ?? { kind: "browser_completion" };
2026-04-26 12:25:11 +01:00
if (request.query.error) {
2026-04-26 17:00:57 +01:00
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,
2026-04-29 15:00:55 +01:00
connection: statePayload.connection,
2026-04-26 17:00:57 +01:00
error: "provider_error",
errorDescription: request.query.error_description ?? request.query.error,
});
}
2026-04-26 12:50:07 +01:00
if (prefersHtml(request.headers.accept)) {
reply.type("text/html; charset=utf-8");
return reply.send(
renderBrowserHandoffPage({
2026-04-26 17:00:57 +01:00
handoffKind: handoff.kind,
status: "error",
provider: request.params.provider,
appSlug: statePayload.app_slug,
mode: statePayload.mode,
returnTo: statePayload.return_to,
2026-04-26 17:00:57 +01:00
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
error: "provider_error",
errorDescription: request.query.error_description ?? request.query.error,
})
);
2026-04-26 12:50:07 +01:00
}
2026-04-26 12:25:11 +01:00
reply.code(400);
return {
error: "provider_error",
provider: request.params.provider,
providerError: request.query.error,
providerErrorDescription: request.query.error_description,
returnTo: statePayload.return_to,
2026-04-26 12:25:11 +01:00
};
}
if (!request.query.code) {
2026-04-26 17:00:57 +01:00
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,
2026-04-29 15:00:55 +01:00
connection: statePayload.connection,
2026-04-26 17:00:57 +01:00
error: "missing_code",
});
}
2026-04-26 12:50:07 +01:00
if (prefersHtml(request.headers.accept)) {
reply.type("text/html; charset=utf-8");
return reply.send(
renderBrowserHandoffPage({
2026-04-26 17:00:57 +01:00
handoffKind: handoff.kind,
status: "error",
provider: request.params.provider,
appSlug: statePayload.app_slug,
mode: statePayload.mode,
returnTo: statePayload.return_to,
2026-04-26 17:00:57 +01:00
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
error: "missing_code",
})
);
2026-04-26 12:50:07 +01:00
}
2026-04-26 12:25:11 +01:00
reply.code(400);
return { error: "missing_code", returnTo: statePayload.return_to };
2026-04-26 12:25:11 +01:00
}
2026-04-26 12:50:07 +01:00
const callbackUrl = `${config.publicBaseUrl}/v1/oauth/${request.params.provider}/callback`;
const runtime = oauthRuntimes[request.params.provider];
try {
const tokenSet = await runtime.exchangeAuthorizationCode({
config,
code: request.query.code,
redirectUri: callbackUrl,
});
const identity = await runtime.resolveIdentity({
2026-04-29 15:00:55 +01:00
config,
2026-04-26 12:50:07 +01:00
accessToken: tokenSet.accessToken,
});
const nowIso = new Date().toISOString();
let account = await store.findAccountByLinkedIdentity(identity.provider, identity.providerUserId);
if (!account) {
const createAccountInput: CreateAccountInput = {
createdAt: nowIso,
lastSeenAt: nowIso,
};
const displayName = identity.displayName ?? identity.username;
if (displayName !== undefined) {
createAccountInput.displayName = displayName;
}
if (identity.primaryEmail !== undefined) {
createAccountInput.primaryEmail = identity.primaryEmail;
}
account = await store.createAccount(createAccountInput);
} else {
const accountUpdates: { displayName?: string; primaryEmail?: string } = {};
const displayName = identity.displayName ?? identity.username;
if (displayName !== undefined) {
accountUpdates.displayName = displayName;
}
if (identity.primaryEmail !== undefined) {
accountUpdates.primaryEmail = identity.primaryEmail;
}
await store.touchAccount(account.id, nowIso, accountUpdates);
}
const linkedIdentityInput: UpsertLinkedIdentityInput = {
accountId: account.id,
provider: identity.provider,
providerUserId: identity.providerUserId,
scopes: tokenSet.scope,
profileJson: identity.profile,
createdAt: nowIso,
updatedAt: nowIso,
};
if (identity.username !== undefined) {
linkedIdentityInput.username = identity.username;
}
if (identity.displayName !== undefined) {
linkedIdentityInput.displayName = identity.displayName;
}
if (identity.primaryEmail !== undefined) {
linkedIdentityInput.primaryEmail = identity.primaryEmail;
}
linkedIdentityInput.accessTokenEncrypted = tokenCustody.encrypt(tokenSet.accessToken);
2026-04-26 12:50:07 +01:00
if (tokenSet.refreshToken !== undefined) {
linkedIdentityInput.refreshTokenEncrypted = tokenCustody.encrypt(tokenSet.refreshToken);
2026-04-26 12:50:07 +01:00
}
if (tokenSet.expiresAt !== undefined) {
linkedIdentityInput.tokenExpiresAt = tokenSet.expiresAt;
}
await store.upsertLinkedIdentity(linkedIdentityInput);
const entitlementEvaluation = await runtime.evaluateEntitlements({
config,
callback: {
appSlug: statePayload.app_slug,
accountId: account.id,
connection: statePayload.connection,
2026-04-29 13:22:01 +01:00
entitlementPolicy: statePayload.entitlement_policy,
2026-04-26 12:50:07 +01:00
},
identity,
tokenSet,
});
for (const snapshot of entitlementEvaluation.snapshots) {
await store.upsertEntitlementSnapshot(snapshot);
}
const grants = await store.listActiveGrants(account.id, statePayload.app_slug, nowIso);
const issueInput: IssueAccessClaimInput = {
appSlug: statePayload.app_slug,
accountId: account.id,
linkedIdentities: await store.listLinkedIdentitiesForAccount(account.id),
facts: [...entitlementEvaluation.facts, ...buildGrantFacts(grants)],
};
if (account.displayName !== undefined) {
issueInput.displayName = account.displayName;
}
const issued = await issueAccessClaim({
config,
keys,
store,
input: issueInput,
});
await store.createAuditEvent({
accountId: account.id,
sessionId: issued.session.sessionId,
appSlug: statePayload.app_slug,
eventType: "oauth_callback_succeeded",
eventPayloadJson: {
provider: request.params.provider,
mode: statePayload.mode,
returnTo: statePayload.return_to,
grantedFacts: issued.claimSet.facts,
sharedCapabilities: issued.sharedCapabilities,
},
createdAt: nowIso,
});
const accountSummary: {
id: string;
displayName?: string;
primaryEmail?: string;
} = {
id: account.id,
};
if (account.displayName !== undefined) {
accountSummary.displayName = account.displayName;
}
if (account.primaryEmail !== undefined) {
accountSummary.primaryEmail = account.primaryEmail;
}
const completionPayload = {
status: "success",
provider: request.params.provider,
mode: statePayload.mode,
appSlug: statePayload.app_slug,
account: accountSummary,
entitlements: entitlementEvaluation,
returnTo: statePayload.return_to,
2026-04-29 15:00:55 +01:00
connection: statePayload.connection,
...issued,
};
2026-04-26 17:00:57 +01:00
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,
2026-04-29 15:00:55 +01:00
connection: statePayload.connection,
2026-04-26 17:00:57 +01:00
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,
2026-04-29 15:00:55 +01:00
connection: statePayload.connection,
2026-04-26 17:00:57 +01:00
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,
provider: request.params.provider,
mode: statePayload.mode,
accountId: account.id,
sessionId: issued.session.sessionId,
returnTo: statePayload.return_to,
createdAt: nowIso,
expiresAt: completionExpiresAt,
payloadJson: completionPayload as unknown as Record<string, unknown>,
});
await store.createAuditEvent({
accountId: account.id,
sessionId: issued.session.sessionId,
appSlug: statePayload.app_slug,
eventType: "auth_completion_created",
eventPayloadJson: {
provider: request.params.provider,
mode: statePayload.mode,
completionCode: completion.code,
expiresAt: completion.expiresAt,
},
createdAt: nowIso,
2026-04-26 12:50:07 +01:00
});
if (prefersHtml(request.headers.accept)) {
reply.type("text/html; charset=utf-8");
return reply.send(
renderBrowserHandoffPage({
2026-04-26 17:00:57 +01:00
handoffKind: "browser_completion",
status: "success",
provider: request.params.provider,
appSlug: statePayload.app_slug,
mode: statePayload.mode,
returnTo: statePayload.return_to,
completionCode: completion.code,
})
);
2026-04-26 12:50:07 +01:00
}
reply.code(201);
return {
completion: {
code: completion.code,
expiresAt: completion.expiresAt,
redeemEndpoint: `${config.publicBaseUrl}/v1/apps/${statePayload.app_slug}/auth-completions/redeem`,
2026-04-26 12:50:07 +01:00
},
...completionPayload,
2026-04-26 12:50:07 +01:00
};
} catch (error) {
const message = error instanceof Error ? error.message : "OAuth callback failed.";
const nowIso = new Date().toISOString();
await store.createAuditEvent({
appSlug: statePayload.app_slug,
eventType: "oauth_callback_failed",
eventPayloadJson: {
provider: request.params.provider,
mode: statePayload.mode,
error: message,
},
createdAt: nowIso,
});
2026-04-26 17:00:57 +01:00
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,
mode: statePayload.mode,
returnTo: statePayload.return_to,
2026-04-29 15:00:55 +01:00
connection: statePayload.connection,
2026-04-26 17:00:57 +01:00
error: "oauth_callback_failed",
errorDescription: message,
});
} catch {}
}
2026-04-26 12:50:07 +01:00
if (prefersHtml(request.headers.accept)) {
reply.type("text/html; charset=utf-8");
return reply.send(
renderBrowserHandoffPage({
2026-04-26 17:00:57 +01:00
handoffKind: handoff.kind,
status: "error",
provider: request.params.provider,
appSlug: statePayload.app_slug,
mode: statePayload.mode,
returnTo: statePayload.return_to,
2026-04-26 17:00:57 +01:00
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
error: "oauth_callback_failed",
errorDescription: message,
})
);
2026-04-26 12:50:07 +01:00
}
reply.code(502);
return {
error: "oauth_callback_failed",
detail: message,
provider: request.params.provider,
appSlug: statePayload.app_slug,
returnTo: statePayload.return_to,
2026-04-26 12:50:07 +01:00
};
}
2026-04-26 12:25:11 +01:00
}
);
app.post<{ Params: { appSlug: AppSlug }; Body: RedeemAuthCompletionRequest }>(
"/v1/apps/:appSlug/auth-completions/redeem",
{
schema: {
params: {
type: "object",
required: ["appSlug"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
},
},
body: {
type: "object",
required: ["completionCode"],
additionalProperties: false,
properties: {
completionCode: { type: "string", minLength: 1 },
},
},
},
},
async (request, reply) => {
const nowIso = new Date().toISOString();
const completion = await store.consumeAuthCompletion(request.params.appSlug, request.body.completionCode, nowIso);
if (!completion) {
reply.code(410);
return { error: "invalid_or_expired_completion_code" };
}
await store.createAuditEvent({
accountId: completion.accountId,
sessionId: completion.sessionId,
appSlug: completion.appSlug,
eventType: "auth_completion_redeemed",
eventPayloadJson: {
provider: completion.provider,
mode: completion.mode,
completionCode: completion.code,
},
createdAt: nowIso,
});
reply.code(201);
return completion.payloadJson;
}
);
2026-04-26 12:50:07 +01:00
app.post<{ Params: { appSlug: AppSlug }; Body: import("./contracts.js").IssueClaimRequest }>(
2026-04-26 12:25:11 +01:00
"/v1/apps/:appSlug/claims/issue",
{
schema: {
params: {
type: "object",
required: ["appSlug"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
},
},
body: {
type: "object",
required: ["accountId"],
additionalProperties: false,
properties: {
accountId: { type: "string", minLength: 1 },
sessionId: { type: "string", minLength: 1 },
displayName: { type: "string", minLength: 1 },
facts: {
type: "array",
items: { type: "string" },
uniqueItems: true,
},
accessRevision: { type: "integer", minimum: 1 },
ttlSeconds: { type: "integer", minimum: 60, maximum: 86400 },
linkedIdentities: {
type: "array",
items: {
type: "object",
required: ["provider", "providerUserId"],
additionalProperties: false,
properties: {
provider: { type: "string", enum: [...providers] },
providerUserId: { type: "string", minLength: 1 },
username: { type: "string" },
displayName: { type: "string" },
},
},
},
},
},
},
},
async (request, reply) => {
2026-04-26 12:50:07 +01:00
const issued = await issueAccessClaim({
config,
keys,
store,
input: mapIssueClaimRequest(request.params.appSlug, request.body),
2026-04-26 12:25:11 +01:00
});
reply.code(201);
2026-04-26 12:50:07 +01:00
return issued;
2026-04-26 12:25:11 +01:00
}
);
2026-04-29 15:00:55 +01:00
app.post<{
Params: { appSlug: AppSlug };
Body: { accountId: string; provider: Provider };
}>(
"/v1/apps/:appSlug/managed-credentials/resolve",
{
schema: {
params: {
type: "object",
required: ["appSlug"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
},
},
body: {
type: "object",
required: ["accountId", "provider"],
additionalProperties: false,
properties: {
accountId: { type: "string", minLength: 1 },
provider: { type: "string", enum: [...providers] },
},
},
},
},
async (request, reply) => {
const profile = getAppProfile(request.params.appSlug);
const providedSecret = getSharedSecret(request);
if (!secretMatches(config.appSharedSecrets[profile.slug], providedSecret)) {
reply.code(401);
return { error: "app_auth_required" };
}
if (!profile.managedConnectionProviders.includes(request.body.provider)) {
reply.code(400);
return {
error: "provider_not_managed_for_app",
provider: request.body.provider,
appSlug: profile.slug,
};
}
const storedLinkedIdentity = await store.findStoredLinkedIdentityForAccount(request.body.accountId, request.body.provider);
if (!storedLinkedIdentity?.accessTokenEncrypted) {
reply.code(404);
return { error: "managed_credential_not_found" };
}
const now = new Date().toISOString();
const linkedIdentity = await refreshLinkedIdentityCredentialIfNeeded({
config,
store,
tokenCustody,
oauthRuntimes,
linkedIdentity: storedLinkedIdentity,
now,
});
if (!linkedIdentity.accessTokenEncrypted) {
2026-04-29 15:00:55 +01:00
reply.code(404);
return { error: "managed_credential_not_found" };
}
const response: {
accountId: string;
provider: Provider;
providerUserId: string;
accessToken: string;
tokenExpiresAt?: string;
scopes: string[];
} = {
accountId: linkedIdentity.accountId,
provider: linkedIdentity.provider,
providerUserId: linkedIdentity.providerUserId,
accessToken: tokenCustody.decrypt(linkedIdentity.accessTokenEncrypted),
scopes: linkedIdentity.scopes,
};
if (linkedIdentity.tokenExpiresAt) {
response.tokenExpiresAt = linkedIdentity.tokenExpiresAt;
}
return response;
}
);
2026-04-26 12:25:11 +01:00
return app;
}