Refresh Repixelizer app claims through Heimdall

This commit is contained in:
Meta Vens 2026-05-20 13:43:53 +01:00
commit ee8c012c85
15 changed files with 712 additions and 7 deletions

View file

@ -14,6 +14,8 @@ import {
type OAuthMode,
type OAuthConnectionBinding,
type RedeemAuthCompletionRequest,
type RefreshSessionRequest,
type RefreshTokenPayload,
type OAuthStatePayload,
type OAuthStartRequest,
type Provider,
@ -167,6 +169,55 @@ function buildGrantFacts(grants: StoredCapabilityGrant[]): string[] {
return grants.map((grant) => grantFact(grant.capability));
}
function parseRefreshTokenPayload(payload: Record<string, unknown>): RefreshTokenPayload | null {
if (
payload.typ !== "heimdall_refresh" ||
typeof payload.iss !== "string" ||
typeof payload.aud !== "string" ||
!appSlugs.includes(payload.aud as AppSlug) ||
typeof payload.sub !== "string" ||
typeof payload.sid !== "string" ||
typeof payload.jti !== "string" ||
typeof payload.iat !== "number" ||
typeof payload.nbf !== "number" ||
typeof payload.exp !== "number" ||
typeof payload.account_id !== "string" ||
typeof payload.access_revision !== "number" ||
!payload.app ||
typeof payload.app !== "object" ||
(payload.app as Record<string, unknown>).slug !== payload.aud ||
typeof (payload.app as Record<string, unknown>).profile_version !== "string"
) {
return null;
}
return payload as unknown as RefreshTokenPayload;
}
function verifyRefreshToken(
token: string,
appSlug: AppSlug,
config: HeimdallConfig,
keys: ReturnType<typeof createRuntimeKeyMaterial>
): RefreshTokenPayload | null {
const verification = verifyJwt(token, keys.publicKey);
if (!verification.valid) {
return null;
}
const payload = parseRefreshTokenPayload(verification.payload);
if (!payload || payload.iss !== config.issuer || payload.aud !== appSlug || payload.app.slug !== appSlug) {
return null;
}
const now = nowEpochSeconds();
if (payload.nbf > now + 30 || payload.exp <= now - 30) {
return null;
}
return payload;
}
function prefersHtml(acceptHeader: string | undefined): boolean {
if (!acceptHeader) {
return false;
@ -236,6 +287,24 @@ function normalizeEntitlementPolicy(value: OAuthStartRequest["entitlementPolicy"
throw new Error("Invalid entitlement policy definition.");
}
function normalizeEntitlementPolicies(value: RefreshSessionRequest["entitlementPolicies"]): OAuthEntitlementPolicy[] {
if (!value) {
return [];
}
return value.map((entry) => {
const policy = normalizeEntitlementPolicy(entry);
if (!policy) {
throw new Error("Invalid entitlement policy definition.");
}
return policy;
});
}
function entitlementPolicyProvider(policy: OAuthEntitlementPolicy): Provider {
return policy.kind === "discord_role_access" ? "discord" : "patreon";
}
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;
@ -308,6 +377,87 @@ async function refreshLinkedIdentityCredentialIfNeeded(options: {
return options.store.upsertLinkedIdentity(upsertInput);
}
function storedIdentityToResolvedIdentity(identity: StoredLinkedIdentity) {
const resolved = {
provider: identity.provider,
providerUserId: identity.providerUserId,
profile: identity.profileJson,
};
if (identity.username !== undefined) {
Object.assign(resolved, { username: identity.username });
}
if (identity.displayName !== undefined) {
Object.assign(resolved, { displayName: identity.displayName });
}
if (identity.primaryEmail !== undefined) {
Object.assign(resolved, { primaryEmail: identity.primaryEmail });
}
return resolved;
}
async function evaluateStoredEntitlements(options: {
config: HeimdallConfig;
store: HeimdallStore;
tokenCustody: TokenCustody;
oauthRuntimes: OAuthRuntimeRegistry;
appSlug: AppSlug;
accountId: string;
entitlementPolicies: OAuthEntitlementPolicy[];
now: string;
}): Promise<string[]> {
const profile = getAppProfile(options.appSlug);
const linkedIdentities = await options.store.listStoredLinkedIdentitiesForAccount(options.accountId);
const facts: string[] = [];
for (const storedIdentity of linkedIdentities) {
if (!profile.entitlementSources.includes(storedIdentity.provider) || !storedIdentity.accessTokenEncrypted) {
continue;
}
const linkedIdentity = await refreshLinkedIdentityCredentialIfNeeded({
config: options.config,
store: options.store,
tokenCustody: options.tokenCustody,
oauthRuntimes: options.oauthRuntimes,
linkedIdentity: storedIdentity,
now: options.now,
});
if (!linkedIdentity.accessTokenEncrypted) {
continue;
}
const runtime = options.oauthRuntimes[linkedIdentity.provider];
const entitlementPolicy =
options.entitlementPolicies.find((policy) => entitlementPolicyProvider(policy) === linkedIdentity.provider) ?? null;
const tokenSet = {
accessToken: options.tokenCustody.decrypt(linkedIdentity.accessTokenEncrypted),
tokenType: "Bearer",
scope: linkedIdentity.scopes,
raw: {},
};
if (linkedIdentity.tokenExpiresAt !== undefined) {
Object.assign(tokenSet, { expiresAt: linkedIdentity.tokenExpiresAt });
}
const evaluation = await runtime.evaluateEntitlements({
config: options.config,
callback: {
appSlug: options.appSlug,
accountId: options.accountId,
connection: null,
entitlementPolicy,
},
identity: storedIdentityToResolvedIdentity(linkedIdentity),
tokenSet,
});
for (const snapshot of evaluation.snapshots) {
await options.store.upsertEntitlementSnapshot(snapshot);
}
facts.push(...evaluation.facts);
}
return [...new Set(facts)];
}
function acceptsBackendPolicy(appSlug: AppSlug, handoff: OAuthHandoff): boolean {
if (handoff.kind !== "backend_callback") {
return false;
@ -1095,6 +1245,166 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
}
);
app.post<{ Params: { appSlug: AppSlug }; Body: RefreshSessionRequest }>(
"/v1/apps/:appSlug/sessions/refresh",
{
schema: {
params: {
type: "object",
required: ["appSlug"],
additionalProperties: false,
properties: {
appSlug: { type: "string", enum: [...appSlugs] },
},
},
body: {
type: "object",
required: ["refreshToken"],
additionalProperties: false,
properties: {
refreshToken: { type: "string", minLength: 1 },
entitlementPolicy: {
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,
},
},
},
{
type: "object",
required: ["kind", "requiredTierTitle"],
additionalProperties: false,
properties: {
kind: { type: "string", const: "patreon_membership_access" },
requiredTierTitle: { type: "string", minLength: 1 },
},
},
],
},
entitlementPolicies: {
type: "array",
items: {
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,
},
},
},
{
type: "object",
required: ["kind", "requiredTierTitle"],
additionalProperties: false,
properties: {
kind: { type: "string", const: "patreon_membership_access" },
requiredTierTitle: { type: "string", minLength: 1 },
},
},
],
},
},
},
},
},
},
async (request, reply) => {
let entitlementPolicies: OAuthEntitlementPolicy[];
try {
entitlementPolicies = normalizeEntitlementPolicies(request.body.entitlementPolicies);
const legacyPolicy = normalizeEntitlementPolicy(request.body.entitlementPolicy);
if (legacyPolicy) {
entitlementPolicies.push(legacyPolicy);
}
} catch (error) {
reply.code(400);
return {
error: "invalid_entitlement_policy",
detail: error instanceof Error ? error.message : "Invalid entitlement policy definition.",
};
}
if (entitlementPolicies.length > 0 && request.params.appSlug !== "repixelizer") {
reply.code(400);
return {
error: "untrusted_entitlement_policy",
detail: "Caller-supplied entitlement policy is only accepted for Repixelizer session refresh.",
};
}
const refreshClaim = verifyRefreshToken(request.body.refreshToken, request.params.appSlug, config, keys);
if (!refreshClaim) {
reply.code(401);
return { error: "invalid_or_expired_refresh_token" };
}
const nowIso = new Date().toISOString();
const account = await store.findAccountById(refreshClaim.account_id);
const linkedIdentities = await store.listLinkedIdentitiesForAccount(refreshClaim.account_id);
const grants = await store.listActiveGrants(refreshClaim.account_id, request.params.appSlug, nowIso);
const entitlementFactList = await evaluateStoredEntitlements({
config,
store,
tokenCustody,
oauthRuntimes,
appSlug: request.params.appSlug,
accountId: refreshClaim.account_id,
entitlementPolicies,
now: nowIso,
});
const issueInput: IssueAccessClaimInput = {
appSlug: request.params.appSlug,
accountId: refreshClaim.account_id,
sessionId: refreshClaim.sid,
accessRevision: refreshClaim.access_revision,
linkedIdentities,
facts: [...entitlementFactList, ...buildGrantFacts(grants)],
};
if (account?.displayName !== undefined) {
issueInput.displayName = account.displayName;
}
const issued = await issueAccessClaim({
config,
keys,
store,
input: issueInput,
});
await store.createAuditEvent({
accountId: refreshClaim.account_id,
sessionId: refreshClaim.sid,
appSlug: request.params.appSlug,
eventType: "session_refreshed",
eventPayloadJson: {
grantedFacts: issued.claimSet.facts,
sharedCapabilities: issued.sharedCapabilities,
},
createdAt: nowIso,
});
reply.code(201);
return issued;
}
);
app.post<{
Params: { appSlug: AppSlug };
Body: { accountId: string; provider: Provider };

View file

@ -4,6 +4,7 @@ import {
type AppSlug,
type IssueClaimRequest,
type LinkedIdentityInput,
type RefreshTokenPayload,
} from "./contracts.js";
import { getAppProfile } from "./app-profiles.js";
import { type HeimdallConfig } from "./config.js";
@ -53,6 +54,10 @@ export interface IssuedAccessClaimResult {
expiresAt: string;
};
accessToken: string;
refreshToken: string;
refresh: {
expiresAt: string;
};
claimSet: AccessClaimPayload;
verification: {
issuer: string;
@ -85,6 +90,8 @@ export async function issueAccessClaim(options: {
options.config.sessionTtlSeconds
);
const expiresAtEpoch = issuedAt + ttlSeconds;
const refreshTtlSeconds = Math.max(ttlSeconds, Math.trunc(options.config.refreshTtlSeconds));
const refreshExpiresAtEpoch = issuedAt + refreshTtlSeconds;
const sessionId = options.input.sessionId ?? randomUUID();
const accessRevision = options.input.accessRevision ?? 1;
@ -114,13 +121,31 @@ export async function issueAccessClaim(options: {
}
const accessToken = signJwt(claimSet as unknown as Record<string, unknown>, options.keys);
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);
const sessionRecord: CreateSessionInput = {
id: sessionId,
accountId: options.input.accountId,
appSlug: profile.slug,
createdAt: new Date(issuedAt * 1000).toISOString(),
lastSeenAt: new Date(issuedAt * 1000).toISOString(),
expiresAt: new Date(expiresAtEpoch * 1000).toISOString(),
expiresAt: new Date(refreshExpiresAtEpoch * 1000).toISOString(),
accessRevision,
claimsJson: claimSet as unknown as Record<string, unknown>,
};
@ -135,6 +160,10 @@ export async function issueAccessClaim(options: {
expiresAt: sessionRecord.expiresAt,
},
accessToken,
refreshToken,
refresh: {
expiresAt: sessionRecord.expiresAt,
},
claimSet,
verification: {
issuer: options.config.issuer,

View file

@ -18,6 +18,7 @@ export interface HeimdallConfig {
publicBaseUrl: string;
issuer: string;
sessionTtlSeconds: number;
refreshTtlSeconds: number;
stateTtlSeconds: number;
completionTtlSeconds: number;
signingPrivateKeyPem?: string;
@ -103,6 +104,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
publicBaseUrl,
issuer,
sessionTtlSeconds: readInt(env.GC_ACCESS_SESSION_TTL_SECONDS, 3600),
refreshTtlSeconds: readInt(env.GC_ACCESS_REFRESH_TTL_SECONDS, 60 * 60 * 24 * 30),
stateTtlSeconds: readInt(env.GC_ACCESS_STATE_TTL_SECONDS, 600),
completionTtlSeconds: readInt(env.GC_ACCESS_COMPLETION_TTL_SECONDS, 300),
bootstrapSigningPrivateKeyOnMissing: readBoolean(env.GC_ACCESS_SIGNING_PRIVATE_KEY_BOOTSTRAP, false),

View file

@ -98,6 +98,12 @@ export interface RedeemAuthCompletionRequest {
completionCode: string;
}
export interface RefreshSessionRequest {
refreshToken: string;
entitlementPolicy?: OAuthEntitlementPolicy;
entitlementPolicies?: OAuthEntitlementPolicy[];
}
export interface AccessClaimPayload {
iss: string;
aud: AppSlug;
@ -119,3 +125,21 @@ export interface AccessClaimPayload {
capabilities: string[];
identities: LinkedIdentityInput[];
}
export interface RefreshTokenPayload {
iss: string;
aud: AppSlug;
sub: string;
sid: string;
jti: string;
iat: number;
nbf: number;
exp: number;
typ: "heimdall_refresh";
account_id: string;
access_revision: number;
app: {
slug: AppSlug;
profile_version: string;
};
}

View file

@ -132,6 +132,53 @@ async function exchangeDiscordAuthorizationCode(options: {
return tokenSet;
}
async function refreshDiscordAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.discord;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Discord OAuth is not fully configured.");
}
const basicAuth = Buffer.from(`${providerConfig.clientId}:${providerConfig.clientSecret}`).toString("base64");
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in: number;
scope?: string | string[];
}>(
"https://discord.com/api/v10/oauth2/token",
{
method: "POST",
headers: {
Authorization: `Basic ${basicAuth}`,
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: options.refreshToken,
}),
},
"Discord token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
expiresAt: new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString(),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
return tokenSet;
}
async function exchangePatreonAuthorizationCode(options: {
config: HeimdallConfig;
code: string;
@ -185,6 +232,56 @@ async function exchangePatreonAuthorizationCode(options: {
return tokenSet;
}
async function refreshPatreonAccessToken(options: {
config: HeimdallConfig;
refreshToken: string;
}): Promise<OAuthTokenSet> {
const providerConfig = options.config.providers.patreon;
if (!providerConfig.clientId || !providerConfig.clientSecret) {
throw new Error("Patreon OAuth is not fully configured.");
}
const tokenResponse = await fetchJson<{
access_token: string;
refresh_token?: string;
token_type: string;
expires_in?: number;
scope?: string | string[];
}>(
"https://www.patreon.com/api/oauth2/token",
{
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
body: new URLSearchParams({
grant_type: "refresh_token",
refresh_token: options.refreshToken,
client_id: providerConfig.clientId,
client_secret: providerConfig.clientSecret,
}),
},
"Patreon token refresh failed"
);
const tokenSet: OAuthTokenSet = {
accessToken: tokenResponse.access_token,
tokenType: tokenResponse.token_type,
scope: normalizeScopes(tokenResponse.scope),
raw: tokenResponse as unknown as Record<string, unknown>,
};
if (tokenResponse.refresh_token) {
tokenSet.refreshToken = tokenResponse.refresh_token;
}
if (tokenResponse.expires_in) {
tokenSet.expiresAt = new Date(Date.now() + tokenResponse.expires_in * 1000).toISOString();
}
return tokenSet;
}
async function exchangeTwitchAuthorizationCode(options: {
config: HeimdallConfig;
code: string;
@ -864,12 +961,14 @@ async function evaluatePatreonEntitlements(options: {
const discordRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangeDiscordAuthorizationCode,
refreshAccessToken: refreshDiscordAccessToken,
resolveIdentity: resolveDiscordIdentity,
evaluateEntitlements: evaluateDiscordEntitlements,
};
const patreonRuntime: OAuthProviderRuntime = {
exchangeAuthorizationCode: exchangePatreonAuthorizationCode,
refreshAccessToken: refreshPatreonAccessToken,
resolveIdentity: resolvePatreonIdentity,
evaluateEntitlements: evaluatePatreonEntitlements,
};

View file

@ -83,6 +83,10 @@ export class InMemoryStore implements HeimdallStore {
}
}
async findAccountById(accountId: string): Promise<StoredAccount | null> {
return clone(this.accounts.get(accountId) ?? null);
}
async findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredAccount | null> {
for (const linkedIdentity of this.linkedIdentities.values()) {
if (linkedIdentity.provider === provider && linkedIdentity.providerUserId === providerUserId) {
@ -113,6 +117,12 @@ export class InMemoryStore implements HeimdallStore {
return null;
}
async listStoredLinkedIdentitiesForAccount(accountId: string): Promise<StoredLinkedIdentity[]> {
return [...this.linkedIdentities.values()]
.filter((identity) => identity.accountId === accountId)
.map((identity) => clone(identity));
}
async upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity> {
const existing = [...this.linkedIdentities.values()].find(
(identity) => identity.provider === input.provider && identity.providerUserId === input.providerUserId

View file

@ -258,6 +258,20 @@ export class PostgresStore implements HeimdallStore {
);
}
async findAccountById(accountId: string): Promise<StoredAccount | null> {
const result = await this.pool.query<AccountRow>(
`
SELECT *
FROM accounts
WHERE id = $1
LIMIT 1
`,
[accountId]
);
return result.rowCount ? mapAccountRow(expectRow(result.rows[0], "findAccountById")) : null;
}
async findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredAccount | null> {
const result = await this.pool.query<AccountRow>(
`
@ -305,6 +319,20 @@ export class PostgresStore implements HeimdallStore {
return result.rowCount ? mapLinkedIdentityRow(expectRow(result.rows[0], "findStoredLinkedIdentityForAccount")) : null;
}
async listStoredLinkedIdentitiesForAccount(accountId: string): Promise<StoredLinkedIdentity[]> {
const result = await this.pool.query<LinkedIdentityRow>(
`
SELECT *
FROM linked_identities
WHERE account_id = $1
ORDER BY created_at ASC
`,
[accountId]
);
return result.rows.map(mapLinkedIdentityRow);
}
async upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity> {
const id = input.id ?? randomUUID();
const result = await this.pool.query<LinkedIdentityRow>(
@ -450,6 +478,12 @@ export class PostgresStore implements HeimdallStore {
expires_at, claims_json, access_revision
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
ON CONFLICT (id)
DO UPDATE SET
last_seen_at = EXCLUDED.last_seen_at,
expires_at = EXCLUDED.expires_at,
claims_json = EXCLUDED.claims_json,
access_revision = EXCLUDED.access_revision
RETURNING *
`,
[

View file

@ -153,9 +153,11 @@ export interface HeimdallStore {
close(): Promise<void>;
createAccount(input: CreateAccountInput): Promise<StoredAccount>;
touchAccount(accountId: string, at: string, updates?: { displayName?: string; primaryEmail?: string }): Promise<void>;
findAccountById(accountId: string): Promise<StoredAccount | null>;
findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredAccount | null>;
findStoredLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredLinkedIdentity | null>;
findStoredLinkedIdentityForAccount(accountId: string, provider: Provider): Promise<StoredLinkedIdentity | null>;
listStoredLinkedIdentitiesForAccount(accountId: string): Promise<StoredLinkedIdentity[]>;
upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity>;
listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]>;
createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant>;