2026-04-26 12:50:07 +01:00
import { randomUUID } from "node:crypto" ;
import {
type AccessClaimPayload ,
type AppSlug ,
type LinkedIdentityInput ,
2026-05-20 13:43:53 +01:00
type RefreshTokenPayload ,
2026-04-26 12:50:07 +01:00
} from "./contracts.js" ;
R21.3: delete the unreachable registered-app resolution path
The runtime app-registration writer (POST /v1/apps) was deleted in an
earlier pass because it minted a client_secret nobody verified. This
pass kept resolveAppProfile's registered-app fallback and
listAppProfiles on the theory that AppSlug is an open string and
dynamic registration was a live extension point. Soul falsified that:
every HTTP route enumerates the four built-in slugs in its own JSON
schema (app.ts's `enum: [...appSlugs]` at every appSlug param/body
field), so a registered row could never be resolved from a request.
With the writer already gone, this was unreachable code behind a dead
writer -- delete it rather than keep authenticating a door nobody can
open.
Deleted: src/app-registry.ts entirely (resolveAppProfile,
listAppProfiles, isBuiltInApp, registeredAppToProfile,
returnOriginsFromRedirectUris); StoredRegisteredApp and the
findRegisteredApp/listRegisteredApps HeimdallStore methods
(store/types.ts); their InMemoryStore and PostgresStore
implementations, including seedRegisteredApp and mapRegisteredApp; the
registered_apps table (store/schema.ts now drops it on any store built
before this schema); tests/app-registry.test.ts.
Every call site (app.ts x5, claims.ts, private-command-plane.ts) now
calls the existing built-in-only getAppProfile (app-profiles.ts)
directly -- sync, no store needed. If dynamic app registration is
wanted later it returns as a designed, authenticated feature, not by
resurrecting this vestige.
Net -305 lines against the prior commit.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 14:51:23 +02:00
import { evaluateSharedCapabilities , getAppProfile , type AppProfile } from "./app-profiles.js" ;
2026-04-26 12:50:07 +01:00
import { type HeimdallConfig } from "./config.js" ;
2026-04-26 14:58:58 +01:00
import { identityFacts } from "./facts.js" ;
2026-04-26 12:50:07 +01:00
import { signJwt , type RuntimeKeyMaterial } from "./signing.js" ;
import { type CreateSessionInput , type HeimdallStore } from "./store/types.js" ;
2026-11-13 18:59:21 +00:00
/** How long a step-up sign-in's proof stays good for an action that demands it (identity unlink). */
export const STEP_UP_PROOF_TTL_SECONDS = 600 ;
2026-11-14 00:54:52 +00:00
/** How long a plain sign-in's proof stays good for an action that accepts a weak proof (an identity move). */
export const AUTH_PROOF_TTL_SECONDS = 300 ;
2026-04-26 12:50:07 +01:00
function nowEpochSeconds ( ) : number {
return Math . floor ( Date . now ( ) / 1000 ) ;
}
function clampTtlSeconds ( value : number , fallback : number ) : number {
if ( ! Number . isFinite ( value ) ) {
return fallback ;
}
return Math . max ( 60 , Math . min ( 86 _400 , Math . trunc ( value ) ) ) ;
}
function normalizeFacts ( accountId : string , linkedIdentities : LinkedIdentityInput [ ] , facts : string [ ] ) : string [ ] {
const normalized = new Set ( facts ) ;
if ( accountId . trim ( ) || linkedIdentities . length ) {
2026-04-26 14:58:58 +01:00
normalized . add ( identityFacts . authenticated ) ;
2026-04-26 12:50:07 +01:00
}
return [ . . . normalized ] . sort ( ) ;
}
export interface IssueAccessClaimInput {
appSlug : AppSlug ;
accountId : string ;
displayName? : string ;
linkedIdentities : LinkedIdentityInput [ ] ;
facts : string [ ] ;
2026-10-19 13:23:53 +02:00
/ * *
* The claim names the account and its identities and carries no facts and
* no capabilities ( a managed - credential connect for a provider that is not
* an identity provider ) . The facts are not even ` identity.authenticated ` .
* /
withoutCapabilities? : boolean ;
2026-04-26 12:50:07 +01:00
sessionId? : string ;
accessRevision? : number ;
ttlSeconds? : number ;
2026-11-13 18:59:21 +00:00
/** Epoch seconds of a step-up sign-in completing; only that callback sets it, a refresh never does. */
stepUpAt? : number ;
2026-11-13 19:59:26 +00:00
/** Required with stepUpAt (`provider:<name>`); the claim never carries one without the other. */
stepUpMethod? : string ;
2026-11-14 00:54:52 +00:00
/** Epoch seconds of the sign-in that minted this token, with authIdentityId (both or neither). Only a sign_in callback sets them; a refresh, link or connect never does. */
authAt? : number ;
/** The linked_identities.id the sign-in came through. */
authIdentityId? : string ;
2026-04-26 12:50:07 +01:00
}
export interface IssuedAccessClaimResult {
session : {
accountId : string ;
sessionId : string ;
appSlug : AppSlug ;
accessRevision : number ;
expiresAt : string ;
} ;
accessToken : string ;
2026-05-20 13:43:53 +01:00
refreshToken : string ;
refresh : {
expiresAt : string ;
} ;
2026-04-26 12:50:07 +01:00
claimSet : AccessClaimPayload ;
verification : {
issuer : string ;
jwksUri : string ;
alg : string ;
kid : string ;
} ;
sharedCapabilities : string [ ] ;
Register apps at runtime instead of at build time
App slugs were a compile-time union of four names. That was fine while every app
was ours and it blocks what Heimdall is for: an app it has never heard of,
running on someone else's machine, registering against a self-hosted instance
without forking and rebuilding the auth authority. A creator self-hosting
Erycina alongside Heimdall would otherwise maintain a patched auth server
forever.
AppSlug is now a string, which it always was on the wire; the union was a
narrowing the type system could enforce only because the set was closed.
Membership moved from appSlugs.includes to the registry, and where no store is
reachable — the offline token verifier is the case that matters — it is a shape
check, isAppSlug, rather than a false claim to know what exists. A host app
verifying its own tokens should compare aud against its own slug, which it knows
and Heimdall's built-in list does not.
Registration is data end to end. Storage carries the profile and a hash of the
client secret rather than the secret. Built-in profiles resolve first and their
slugs are refused at registration, in both places, so a registration cannot
shadow a shipped app and inherit its audience.
POST /v1/apps answers in the RFC 7591 shape so an ordinary OAuth client library
can read it, returning client_secret exactly once. It is gated on an operator
secret and closed entirely until one is configured: an open registration
endpoint on an OAuth provider lets anyone create a client that starts Discord
and Patreon flows under the instance's identity, which is a phishing surface
wearing the operator's name. A fresh instance is not accidentally open.
Redirect URIs are validated rather than stored as given. They are where an
authorization code is delivered, so a permissive one is a token-theft primitive:
absolute, no fragment, https unless loopback.
Six call sites assumed an app profile always exists. They now answer 404 for an
app nobody registered, and claim issuance refuses outright rather than signing a
token whose audience no verifier can resolve.
108 tests pass, 34 of them new. Zero type errors.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 00:11:41 +02:00
hybridCapabilities : AppProfile [ "capabilities" ] ;
2026-04-26 12:50:07 +01:00
}
export async function issueAccessClaim ( options : {
config : HeimdallConfig ;
keys : RuntimeKeyMaterial ;
store : HeimdallStore ;
input : IssueAccessClaimInput ;
} ) : Promise < IssuedAccessClaimResult > {
R21.3: delete the unreachable registered-app resolution path
The runtime app-registration writer (POST /v1/apps) was deleted in an
earlier pass because it minted a client_secret nobody verified. This
pass kept resolveAppProfile's registered-app fallback and
listAppProfiles on the theory that AppSlug is an open string and
dynamic registration was a live extension point. Soul falsified that:
every HTTP route enumerates the four built-in slugs in its own JSON
schema (app.ts's `enum: [...appSlugs]` at every appSlug param/body
field), so a registered row could never be resolved from a request.
With the writer already gone, this was unreachable code behind a dead
writer -- delete it rather than keep authenticating a door nobody can
open.
Deleted: src/app-registry.ts entirely (resolveAppProfile,
listAppProfiles, isBuiltInApp, registeredAppToProfile,
returnOriginsFromRedirectUris); StoredRegisteredApp and the
findRegisteredApp/listRegisteredApps HeimdallStore methods
(store/types.ts); their InMemoryStore and PostgresStore
implementations, including seedRegisteredApp and mapRegisteredApp; the
registered_apps table (store/schema.ts now drops it on any store built
before this schema); tests/app-registry.test.ts.
Every call site (app.ts x5, claims.ts, private-command-plane.ts) now
calls the existing built-in-only getAppProfile (app-profiles.ts)
directly -- sync, no store needed. If dynamic app registration is
wanted later it returns as a designed, authenticated feature, not by
resurrecting this vestige.
Net -305 lines against the prior commit.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 14:51:23 +02:00
const profile = getAppProfile ( options . input . appSlug ) ;
Register apps at runtime instead of at build time
App slugs were a compile-time union of four names. That was fine while every app
was ours and it blocks what Heimdall is for: an app it has never heard of,
running on someone else's machine, registering against a self-hosted instance
without forking and rebuilding the auth authority. A creator self-hosting
Erycina alongside Heimdall would otherwise maintain a patched auth server
forever.
AppSlug is now a string, which it always was on the wire; the union was a
narrowing the type system could enforce only because the set was closed.
Membership moved from appSlugs.includes to the registry, and where no store is
reachable — the offline token verifier is the case that matters — it is a shape
check, isAppSlug, rather than a false claim to know what exists. A host app
verifying its own tokens should compare aud against its own slug, which it knows
and Heimdall's built-in list does not.
Registration is data end to end. Storage carries the profile and a hash of the
client secret rather than the secret. Built-in profiles resolve first and their
slugs are refused at registration, in both places, so a registration cannot
shadow a shipped app and inherit its audience.
POST /v1/apps answers in the RFC 7591 shape so an ordinary OAuth client library
can read it, returning client_secret exactly once. It is gated on an operator
secret and closed entirely until one is configured: an open registration
endpoint on an OAuth provider lets anyone create a client that starts Discord
and Patreon flows under the instance's identity, which is a phishing surface
wearing the operator's name. A fresh instance is not accidentally open.
Redirect URIs are validated rather than stored as given. They are where an
authorization code is delivered, so a permissive one is a token-theft primitive:
absolute, no fragment, https unless loopback.
Six call sites assumed an app profile always exists. They now answer 404 for an
app nobody registered, and claim issuance refuses outright rather than signing a
token whose audience no verifier can resolve.
108 tests pass, 34 of them new. Zero type errors.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 00:11:41 +02:00
if ( ! profile ) {
// An unregistered audience must not receive a signed claim: the token
// would name an app no verifier can resolve a profile for.
throw new Error ( ` Cannot issue an access claim for unknown app ' ${ options . input . appSlug } '. ` ) ;
}
2026-10-19 13:23:53 +02:00
const withoutCapabilities = options . input . withoutCapabilities === true ;
const facts = withoutCapabilities
? [ ]
: normalizeFacts ( options . input . accountId , options . input . linkedIdentities , options . input . facts ) ;
2026-10-19 13:34:41 +02:00
// Every shared capability needs a non-empty anyOf (capability-rules), so an
// empty fact set yields no capabilities: facts are the one owner of that.
const sharedCapabilities = evaluateSharedCapabilities ( profile , {
accountId : options.input.accountId ,
facts : new Set ( facts ) ,
identities : options.input.linkedIdentities ,
} ) ;
2026-04-26 12:50:07 +01:00
const issuedAt = nowEpochSeconds ( ) ;
const ttlSeconds = clampTtlSeconds (
options . input . ttlSeconds ? ? options . config . sessionTtlSeconds ,
options . config . sessionTtlSeconds
) ;
const expiresAtEpoch = issuedAt + ttlSeconds ;
2026-05-20 13:43:53 +01:00
const refreshTtlSeconds = Math . max ( ttlSeconds , Math . trunc ( options . config . refreshTtlSeconds ) ) ;
const refreshExpiresAtEpoch = issuedAt + refreshTtlSeconds ;
2026-04-26 12:50:07 +01:00
const sessionId = options . input . sessionId ? ? randomUUID ( ) ;
const accessRevision = options . input . accessRevision ? ? 1 ;
const claimSet : AccessClaimPayload = {
iss : options.config.issuer ,
aud : profile.slug ,
sub : options.input.accountId ,
sid : sessionId ,
jti : randomUUID ( ) ,
iat : issuedAt ,
nbf : issuedAt ,
exp : expiresAtEpoch ,
typ : "heimdall_access" ,
account_id : options.input.accountId ,
access_revision : accessRevision ,
app : {
slug : profile.slug ,
profile_version : profile.profileVersion ,
} ,
facts ,
capabilities : sharedCapabilities ,
identities : options.input.linkedIdentities ,
} ;
2026-11-13 18:59:21 +00:00
if ( options . input . stepUpAt !== undefined ) {
claimSet . step_up_at = options . input . stepUpAt ;
2026-11-13 19:59:26 +00:00
if ( options . input . stepUpMethod !== undefined ) {
claimSet . step_up_method = options . input . stepUpMethod ;
}
2026-11-13 18:59:21 +00:00
}
2026-11-14 00:54:52 +00:00
if ( options . input . authAt !== undefined && options . input . authIdentityId !== undefined ) {
claimSet . auth_at = options . input . authAt ;
claimSet . auth_identity_id = options . input . authIdentityId ;
}
2026-04-26 12:50:07 +01:00
if ( options . input . displayName ) {
claimSet . display_name = options . input . displayName ;
}
const accessToken = signJwt ( claimSet as unknown as Record < string , unknown > , options . keys ) ;
2026-05-20 13:43:53 +01:00
const refreshClaimSet : RefreshTokenPayload = {
iss : options.config.issuer ,
aud : profile.slug ,
sub : options.input.accountId ,
sid : sessionId ,
jti : randomUUID ( ) ,
iat : issuedAt ,
nbf : issuedAt ,
exp : refreshExpiresAtEpoch ,
typ : "heimdall_refresh" ,
account_id : options.input.accountId ,
access_revision : accessRevision ,
app : {
slug : profile.slug ,
profile_version : profile.profileVersion ,
} ,
} ;
const refreshToken = signJwt ( refreshClaimSet as unknown as Record < string , unknown > , options . keys ) ;
2026-04-26 12:50:07 +01:00
const sessionRecord : CreateSessionInput = {
id : sessionId ,
accountId : options.input.accountId ,
appSlug : profile.slug ,
createdAt : new Date ( issuedAt * 1000 ) . toISOString ( ) ,
lastSeenAt : new Date ( issuedAt * 1000 ) . toISOString ( ) ,
2026-05-20 13:43:53 +01:00
expiresAt : new Date ( refreshExpiresAtEpoch * 1000 ) . toISOString ( ) ,
2026-04-26 12:50:07 +01:00
accessRevision ,
claimsJson : claimSet as unknown as Record < string , unknown > ,
} ;
await options . store . createSession ( sessionRecord ) ;
return {
session : {
accountId : options.input.accountId ,
sessionId ,
appSlug : profile.slug ,
accessRevision ,
expiresAt : sessionRecord.expiresAt ,
} ,
accessToken ,
2026-05-20 13:43:53 +01:00
refreshToken ,
refresh : {
expiresAt : sessionRecord.expiresAt ,
} ,
2026-04-26 12:50:07 +01:00
claimSet ,
verification : {
issuer : options.config.issuer ,
jwksUri : ` ${ options . config . publicBaseUrl } /.well-known/jwks.json ` ,
alg : options.keys.alg ,
kid : options.keys.kid ,
} ,
sharedCapabilities ,
2026-10-19 13:23:53 +02:00
hybridCapabilities : withoutCapabilities
? [ ]
: profile . capabilities . filter ( ( capability ) = > capability . mode === "hybrid" ) ,
2026-04-26 12:50:07 +01:00
} ;
}
2026-11-13 19:59:26 +00:00
/ * *
* A new access token for the session the bearer already holds , carrying proof
* the calling app asserted . Everything the bearer claimed is copied and
* nothing is recomputed , so the route can add proof and no capability ; ` exp `
* stays the bearer ' s , so it cannot extend a lifetime ; no refresh token is
* minted and no session row is written , so it cannot extend the session .
* /
export function signAssertedStepUpClaim ( options : {
keys : RuntimeKeyMaterial ;
bearerClaims : Record < string , unknown > ;
method : string ;
} ) : { accessToken : string ; claimSet : Record < string , unknown > ; stepUpAt : number } {
const stepUpAt = nowEpochSeconds ( ) ;
const claimSet = {
. . . options . bearerClaims ,
jti : randomUUID ( ) ,
iat : stepUpAt ,
nbf : stepUpAt ,
step_up_at : stepUpAt ,
step_up_method : options.method ,
} ;
return { accessToken : signJwt ( claimSet , options . keys ) , claimSet , stepUpAt } ;
}
2026-11-14 00:54:52 +00:00
/ * *
* How fresh a bearer ' s proof of the member is , from its claims alone :
* ` strong ` when a step - up ( Heimdall 's or the app' s asserted one ) happened in
* the last STEP_UP_PROOF_TTL_SECONDS , else ` weak ` when the sign - in did in the
* last AUTH_PROOF_TTL_SECONDS , else null . The one freshness rule : identity
* unlink and identity moves both read it .
* /
export function proofTier ( claims : Record < string , unknown > , nowS : number ) : "strong" | "weak" | null {
const within = ( at : unknown , window : number ) = > typeof at === "number" && at <= nowS && nowS - at <= window ;
if ( within ( claims . step_up_at , STEP_UP_PROOF_TTL_SECONDS ) ) return "strong" ;
if ( within ( claims . auth_at , AUTH_PROOF_TTL_SECONDS ) ) return "weak" ;
return null ;
}
/ * *
* What a fresh proof covers of its account : ` account ` ( every login ) only for a
* strong proof whose step_up_method the app ' s profile lists as an account
* proof ; otherwise the one login the sign - in came through ( its id ) ; otherwise
* nothing . A proof through login X never speaks for the account ' s other logins .
* /
export function proofCovers (
claims : Record < string , unknown > ,
accountProofMethods : readonly string [ ] ,
nowS : number
) : "account" | string | null {
if (
proofTier ( claims , nowS ) === "strong" &&
typeof claims . step_up_method === "string" &&
accountProofMethods . includes ( claims . step_up_method )
) {
return "account" ;
}
return typeof claims . auth_identity_id === "string" ? claims.auth_identity_id : null ;
}