Land first stateful Discord auth slice
This commit is contained in:
parent
702ac33f34
commit
cb0041343a
21 changed files with 2479 additions and 188 deletions
409
src/app.ts
409
src/app.ts
|
|
@ -6,40 +6,26 @@ import {
|
|||
connectionKinds,
|
||||
oauthModes,
|
||||
providers,
|
||||
type AccessClaimPayload,
|
||||
type AppSlug,
|
||||
type IssueClaimRequest,
|
||||
type OAuthMode,
|
||||
type OAuthConnectionBinding,
|
||||
type OAuthStatePayload,
|
||||
type OAuthStartRequest,
|
||||
type Provider,
|
||||
} from "./contracts.js";
|
||||
import { mapIssueClaimRequest, issueAccessClaim, type IssueAccessClaimInput } from "./claims.js";
|
||||
import { getAppProfile, serializeAppProfile, supportsProvider } from "./app-profiles.js";
|
||||
import { type HeimdallConfig, loadConfig } from "./config.js";
|
||||
import { createOAuthRuntimeRegistry, type OAuthRuntimeRegistry } from "./oauth.js";
|
||||
import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js";
|
||||
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js";
|
||||
import { createStore, type HeimdallStore } from "./store/index.js";
|
||||
import { type CreateAccountInput, type StoredCapabilityGrant, type UpsertLinkedIdentityInput } from "./store/types.js";
|
||||
|
||||
interface BuildAppOptions {
|
||||
config?: HeimdallConfig;
|
||||
}
|
||||
|
||||
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(request: IssueClaimRequest): string[] {
|
||||
const facts = new Set(request.facts ?? []);
|
||||
if (request.accountId.trim() || request.linkedIdentities?.length) {
|
||||
facts.add("identity.authenticated");
|
||||
}
|
||||
return [...facts].sort();
|
||||
store?: HeimdallStore;
|
||||
oauthRuntimes?: Partial<OAuthRuntimeRegistry>;
|
||||
}
|
||||
|
||||
function buildDiscovery(config: HeimdallConfig) {
|
||||
|
|
@ -59,36 +45,37 @@ function buildDiscovery(config: HeimdallConfig) {
|
|||
};
|
||||
}
|
||||
|
||||
function nowEpochSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000);
|
||||
}
|
||||
|
||||
function buildOAuthStateToken(options: {
|
||||
config: HeimdallConfig;
|
||||
provider: Provider;
|
||||
appSlug: AppSlug;
|
||||
mode: OAuthStartRequest["mode"];
|
||||
mode: OAuthMode;
|
||||
returnTo: string;
|
||||
connection: OAuthConnectionBinding | undefined;
|
||||
keys: ReturnType<typeof createRuntimeKeyMaterial>;
|
||||
}): { token: string; expiresAt: string } {
|
||||
const issuedAt = nowEpochSeconds();
|
||||
const expiresAtEpoch = issuedAt + options.config.stateTtlSeconds;
|
||||
|
||||
const token = signJwt(
|
||||
{
|
||||
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,
|
||||
},
|
||||
options.keys
|
||||
);
|
||||
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,
|
||||
};
|
||||
const token = signJwt(payload as unknown as Record<string, unknown>, options.keys);
|
||||
|
||||
return {
|
||||
token,
|
||||
|
|
@ -96,11 +83,69 @@ function buildOAuthStateToken(options: {
|
|||
};
|
||||
}
|
||||
|
||||
function parseOAuthStatePayload(payload: Record<string, unknown>): OAuthStatePayload | null {
|
||||
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" ||
|
||||
typeof payload.exp !== "number"
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return payload as unknown as OAuthStatePayload;
|
||||
}
|
||||
|
||||
function buildGrantFacts(grants: StoredCapabilityGrant[]): string[] {
|
||||
return grants.map((grant) => `grant.${grant.capability}`);
|
||||
}
|
||||
|
||||
function prefersHtml(acceptHeader: string | undefined): boolean {
|
||||
if (!acceptHeader) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return acceptHeader.includes("text/html") || acceptHeader.includes("application/xhtml+xml");
|
||||
}
|
||||
|
||||
function buildRedirectUrl(returnTo: string, params: Record<string, string | undefined>): string {
|
||||
const url = new URL(returnTo);
|
||||
const fragment = new URLSearchParams();
|
||||
|
||||
for (const [key, value] of Object.entries(params)) {
|
||||
if (value) {
|
||||
fragment.set(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
url.hash = fragment.toString();
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyInstance> {
|
||||
const config = options.config ?? loadConfig();
|
||||
const store = options.store ?? (await createStore(config));
|
||||
const keys = createRuntimeKeyMaterial(config);
|
||||
const oauthRuntimes: OAuthRuntimeRegistry = {
|
||||
...createOAuthRuntimeRegistry(),
|
||||
...(options.oauthRuntimes ?? {}),
|
||||
};
|
||||
const app = Fastify({ logger: false });
|
||||
app.decorate("heimdallContext", { config, keys });
|
||||
app.decorate("heimdallContext", { config, keys, store, oauthRuntimes });
|
||||
app.addHook("onClose", async () => {
|
||||
await store.close();
|
||||
});
|
||||
|
||||
await app.register(cors, {
|
||||
origin: true,
|
||||
|
|
@ -111,6 +156,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
ok: true,
|
||||
service: config.serviceName,
|
||||
issuer: config.issuer,
|
||||
storageBackend: config.storage.backend,
|
||||
now: new Date().toISOString(),
|
||||
}));
|
||||
|
||||
|
|
@ -272,41 +318,227 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
return { error: "invalid_state", detail: verification.error };
|
||||
}
|
||||
|
||||
const statePayload = verification.payload;
|
||||
if (statePayload.typ !== "heimdall_oauth_state" || statePayload.provider !== request.params.provider) {
|
||||
const statePayload = parseOAuthStatePayload(verification.payload);
|
||||
if (!statePayload || statePayload.provider !== request.params.provider) {
|
||||
reply.code(400);
|
||||
return { error: "state_provider_mismatch" };
|
||||
}
|
||||
|
||||
if (request.query.error) {
|
||||
const redirectUrl = buildRedirectUrl(statePayload.return_to, {
|
||||
heimdall_status: "error",
|
||||
heimdall_provider: request.params.provider,
|
||||
heimdall_error: "provider_error",
|
||||
heimdall_error_description: request.query.error_description ?? request.query.error,
|
||||
});
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
return reply.redirect(redirectUrl);
|
||||
}
|
||||
|
||||
reply.code(400);
|
||||
return {
|
||||
error: "provider_error",
|
||||
provider: request.params.provider,
|
||||
providerError: request.query.error,
|
||||
providerErrorDescription: request.query.error_description,
|
||||
redirectUrl,
|
||||
};
|
||||
}
|
||||
|
||||
if (!request.query.code) {
|
||||
const redirectUrl = buildRedirectUrl(statePayload.return_to, {
|
||||
heimdall_status: "error",
|
||||
heimdall_provider: request.params.provider,
|
||||
heimdall_error: "missing_code",
|
||||
});
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
return reply.redirect(redirectUrl);
|
||||
}
|
||||
|
||||
reply.code(400);
|
||||
return { error: "missing_code" };
|
||||
return { error: "missing_code", redirectUrl };
|
||||
}
|
||||
|
||||
reply.code(501);
|
||||
return {
|
||||
error: "token_exchange_not_implemented",
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
connection: statePayload.connection,
|
||||
codeReceived: true,
|
||||
};
|
||||
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({
|
||||
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 = tokenSet.accessToken;
|
||||
if (tokenSet.refreshToken !== undefined) {
|
||||
linkedIdentityInput.refreshTokenEncrypted = tokenSet.refreshToken;
|
||||
}
|
||||
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,
|
||||
},
|
||||
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 redirectUrl = buildRedirectUrl(statePayload.return_to, {
|
||||
heimdall_status: "success",
|
||||
heimdall_provider: request.params.provider,
|
||||
heimdall_app_slug: statePayload.app_slug,
|
||||
heimdall_account_id: account.id,
|
||||
heimdall_session_id: issued.session.sessionId,
|
||||
heimdall_access_token: issued.accessToken,
|
||||
});
|
||||
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
return reply.redirect(redirectUrl);
|
||||
}
|
||||
|
||||
reply.code(201);
|
||||
return {
|
||||
provider: request.params.provider,
|
||||
mode: statePayload.mode,
|
||||
account,
|
||||
linkedIdentity: identity,
|
||||
token: {
|
||||
tokenType: tokenSet.tokenType,
|
||||
scope: tokenSet.scope,
|
||||
expiresAt: tokenSet.expiresAt,
|
||||
},
|
||||
entitlements: entitlementEvaluation,
|
||||
redirectUrl,
|
||||
returnTo: statePayload.return_to,
|
||||
...issued,
|
||||
};
|
||||
} 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,
|
||||
});
|
||||
|
||||
const redirectUrl = buildRedirectUrl(statePayload.return_to, {
|
||||
heimdall_status: "error",
|
||||
heimdall_provider: request.params.provider,
|
||||
heimdall_error: "oauth_callback_failed",
|
||||
heimdall_error_description: message,
|
||||
});
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
return reply.redirect(redirectUrl);
|
||||
}
|
||||
|
||||
reply.code(502);
|
||||
return {
|
||||
error: "oauth_callback_failed",
|
||||
detail: message,
|
||||
provider: request.params.provider,
|
||||
appSlug: statePayload.app_slug,
|
||||
redirectUrl,
|
||||
};
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
app.post<{ Params: { appSlug: AppSlug }; Body: IssueClaimRequest }>(
|
||||
app.post<{ Params: { appSlug: AppSlug }; Body: import("./contracts.js").IssueClaimRequest }>(
|
||||
"/v1/apps/:appSlug/claims/issue",
|
||||
{
|
||||
schema: {
|
||||
|
|
@ -352,65 +584,14 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const profile = getAppProfile(request.params.appSlug);
|
||||
const facts = normalizeFacts(request.body);
|
||||
const factSet = new Set(facts);
|
||||
const linkedIdentities = request.body.linkedIdentities ?? [];
|
||||
const sharedCapabilities = profile.evaluateSharedCapabilities({
|
||||
accountId: request.body.accountId,
|
||||
facts: factSet,
|
||||
identities: linkedIdentities,
|
||||
const issued = await issueAccessClaim({
|
||||
config,
|
||||
keys,
|
||||
store,
|
||||
input: mapIssueClaimRequest(request.params.appSlug, request.body),
|
||||
});
|
||||
|
||||
const issuedAt = nowEpochSeconds();
|
||||
const ttlSeconds = clampTtlSeconds(request.body.ttlSeconds ?? config.sessionTtlSeconds, config.sessionTtlSeconds);
|
||||
const expiresAtEpoch = issuedAt + ttlSeconds;
|
||||
const sessionId = request.body.sessionId ?? randomUUID();
|
||||
const accessClaim: AccessClaimPayload = {
|
||||
iss: config.issuer,
|
||||
aud: profile.slug,
|
||||
sub: request.body.accountId,
|
||||
sid: sessionId,
|
||||
jti: randomUUID(),
|
||||
iat: issuedAt,
|
||||
nbf: issuedAt,
|
||||
exp: expiresAtEpoch,
|
||||
typ: "heimdall_access",
|
||||
account_id: request.body.accountId,
|
||||
access_revision: request.body.accessRevision ?? 1,
|
||||
app: {
|
||||
slug: profile.slug,
|
||||
profile_version: profile.profileVersion,
|
||||
},
|
||||
facts,
|
||||
capabilities: sharedCapabilities,
|
||||
identities: linkedIdentities,
|
||||
};
|
||||
|
||||
if (request.body.displayName) {
|
||||
accessClaim.display_name = request.body.displayName;
|
||||
}
|
||||
|
||||
reply.code(201);
|
||||
return {
|
||||
session: {
|
||||
accountId: request.body.accountId,
|
||||
sessionId,
|
||||
appSlug: profile.slug,
|
||||
accessRevision: accessClaim.access_revision,
|
||||
expiresAt: new Date(expiresAtEpoch * 1000).toISOString(),
|
||||
},
|
||||
accessToken: signJwt(accessClaim as unknown as Record<string, unknown>, keys),
|
||||
claimSet: accessClaim,
|
||||
verification: {
|
||||
issuer: config.issuer,
|
||||
jwksUri: `${config.publicBaseUrl}/.well-known/jwks.json`,
|
||||
alg: keys.alg,
|
||||
kid: keys.kid,
|
||||
},
|
||||
sharedCapabilities,
|
||||
hybridCapabilities: profile.capabilities.filter((capability) => capability.mode === "hybrid"),
|
||||
};
|
||||
return issued;
|
||||
}
|
||||
);
|
||||
|
||||
|
|
|
|||
174
src/claims.ts
Normal file
174
src/claims.ts
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import {
|
||||
type AccessClaimPayload,
|
||||
type AppSlug,
|
||||
type IssueClaimRequest,
|
||||
type LinkedIdentityInput,
|
||||
} from "./contracts.js";
|
||||
import { getAppProfile } from "./app-profiles.js";
|
||||
import { type HeimdallConfig } from "./config.js";
|
||||
import { signJwt, type RuntimeKeyMaterial } from "./signing.js";
|
||||
import { type CreateSessionInput, type HeimdallStore } from "./store/types.js";
|
||||
|
||||
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) {
|
||||
normalized.add("identity.authenticated");
|
||||
}
|
||||
|
||||
return [...normalized].sort();
|
||||
}
|
||||
|
||||
export interface IssueAccessClaimInput {
|
||||
appSlug: AppSlug;
|
||||
accountId: string;
|
||||
displayName?: string;
|
||||
linkedIdentities: LinkedIdentityInput[];
|
||||
facts: string[];
|
||||
sessionId?: string;
|
||||
accessRevision?: number;
|
||||
ttlSeconds?: number;
|
||||
}
|
||||
|
||||
export interface IssuedAccessClaimResult {
|
||||
session: {
|
||||
accountId: string;
|
||||
sessionId: string;
|
||||
appSlug: AppSlug;
|
||||
accessRevision: number;
|
||||
expiresAt: string;
|
||||
};
|
||||
accessToken: string;
|
||||
claimSet: AccessClaimPayload;
|
||||
verification: {
|
||||
issuer: string;
|
||||
jwksUri: string;
|
||||
alg: string;
|
||||
kid: string;
|
||||
};
|
||||
sharedCapabilities: string[];
|
||||
hybridCapabilities: ReturnType<typeof getAppProfile>["capabilities"];
|
||||
}
|
||||
|
||||
export async function issueAccessClaim(options: {
|
||||
config: HeimdallConfig;
|
||||
keys: RuntimeKeyMaterial;
|
||||
store: HeimdallStore;
|
||||
input: IssueAccessClaimInput;
|
||||
}): Promise<IssuedAccessClaimResult> {
|
||||
const profile = getAppProfile(options.input.appSlug);
|
||||
const facts = normalizeFacts(options.input.accountId, options.input.linkedIdentities, options.input.facts);
|
||||
const factSet = new Set(facts);
|
||||
const sharedCapabilities = profile.evaluateSharedCapabilities({
|
||||
accountId: options.input.accountId,
|
||||
facts: factSet,
|
||||
identities: options.input.linkedIdentities,
|
||||
});
|
||||
|
||||
const issuedAt = nowEpochSeconds();
|
||||
const ttlSeconds = clampTtlSeconds(
|
||||
options.input.ttlSeconds ?? options.config.sessionTtlSeconds,
|
||||
options.config.sessionTtlSeconds
|
||||
);
|
||||
const expiresAtEpoch = issuedAt + ttlSeconds;
|
||||
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,
|
||||
};
|
||||
|
||||
if (options.input.displayName) {
|
||||
claimSet.display_name = options.input.displayName;
|
||||
}
|
||||
|
||||
const accessToken = signJwt(claimSet 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(),
|
||||
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,
|
||||
claimSet,
|
||||
verification: {
|
||||
issuer: options.config.issuer,
|
||||
jwksUri: `${options.config.publicBaseUrl}/.well-known/jwks.json`,
|
||||
alg: options.keys.alg,
|
||||
kid: options.keys.kid,
|
||||
},
|
||||
sharedCapabilities,
|
||||
hybridCapabilities: profile.capabilities.filter((capability) => capability.mode === "hybrid"),
|
||||
};
|
||||
}
|
||||
|
||||
export function mapIssueClaimRequest(appSlug: AppSlug, request: IssueClaimRequest): IssueAccessClaimInput {
|
||||
const input: IssueAccessClaimInput = {
|
||||
appSlug,
|
||||
accountId: request.accountId,
|
||||
linkedIdentities: request.linkedIdentities ?? [],
|
||||
facts: request.facts ?? [],
|
||||
};
|
||||
|
||||
if (request.displayName !== undefined) {
|
||||
input.displayName = request.displayName;
|
||||
}
|
||||
|
||||
if (request.sessionId !== undefined) {
|
||||
input.sessionId = request.sessionId;
|
||||
}
|
||||
|
||||
if (request.accessRevision !== undefined) {
|
||||
input.accessRevision = request.accessRevision;
|
||||
}
|
||||
|
||||
if (request.ttlSeconds !== undefined) {
|
||||
input.ttlSeconds = request.ttlSeconds;
|
||||
}
|
||||
|
||||
return input;
|
||||
}
|
||||
|
|
@ -5,6 +5,17 @@ export interface ProviderClientConfig {
|
|||
clientSecret?: string;
|
||||
}
|
||||
|
||||
export interface StorageConfig {
|
||||
backend: "memory" | "postgres";
|
||||
databaseUrl?: string;
|
||||
applySchemaOnStartup: boolean;
|
||||
}
|
||||
|
||||
export interface RepixelizerBindingConfig {
|
||||
discordGuildId?: string;
|
||||
discordAllowedRoleIds: string[];
|
||||
}
|
||||
|
||||
export interface HeimdallConfig {
|
||||
serviceName: string;
|
||||
host: string;
|
||||
|
|
@ -15,6 +26,10 @@ export interface HeimdallConfig {
|
|||
stateTtlSeconds: number;
|
||||
signingPrivateKeyPem?: string;
|
||||
signingKeyId?: string;
|
||||
storage: StorageConfig;
|
||||
apps: {
|
||||
repixelizer: RepixelizerBindingConfig;
|
||||
};
|
||||
providers: Record<Provider, ProviderClientConfig>;
|
||||
}
|
||||
|
||||
|
|
@ -31,6 +46,34 @@ function readInt(envValue: string | undefined, fallback: number): number {
|
|||
return Number.isFinite(parsed) ? parsed : fallback;
|
||||
}
|
||||
|
||||
function readBoolean(envValue: string | undefined, fallback: boolean): boolean {
|
||||
if (!envValue) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const normalized = envValue.trim().toLowerCase();
|
||||
if (["1", "true", "yes", "on"].includes(normalized)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (["0", "false", "no", "off"].includes(normalized)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function readCsv(envValue: string | undefined): string[] {
|
||||
if (!envValue) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return envValue
|
||||
.split(",")
|
||||
.map((value) => value.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
|
||||
function readProviderConfig(env: NodeJS.ProcessEnv, provider: Provider): ProviderClientConfig {
|
||||
const prefix = `GC_ACCESS_PROVIDER_${provider.toUpperCase()}`;
|
||||
const config: ProviderClientConfig = {};
|
||||
|
|
@ -53,6 +96,8 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
|
|||
const port = readInt(env.PORT, 4100);
|
||||
const publicBaseUrl = trimTrailingSlash(env.GC_ACCESS_BASE_URL ?? `http://${host}:${port}`);
|
||||
const issuer = trimTrailingSlash(env.GC_ACCESS_ISSUER ?? publicBaseUrl);
|
||||
const storageBackend =
|
||||
env.GC_ACCESS_STORAGE_BACKEND === "postgres" || env.GC_ACCESS_DATABASE_URL ? "postgres" : "memory";
|
||||
const providersConfig = Object.fromEntries(
|
||||
providers.map((provider) => [provider, readProviderConfig(env, provider)])
|
||||
) as Record<Provider, ProviderClientConfig>;
|
||||
|
|
@ -65,6 +110,15 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
|
|||
issuer,
|
||||
sessionTtlSeconds: readInt(env.GC_ACCESS_SESSION_TTL_SECONDS, 3600),
|
||||
stateTtlSeconds: readInt(env.GC_ACCESS_STATE_TTL_SECONDS, 600),
|
||||
storage: {
|
||||
backend: storageBackend,
|
||||
applySchemaOnStartup: readBoolean(env.GC_ACCESS_APPLY_SCHEMA_ON_STARTUP, true),
|
||||
},
|
||||
apps: {
|
||||
repixelizer: {
|
||||
discordAllowedRoleIds: readCsv(env.GC_ACCESS_APP_REPIXELIZER_DISCORD_ALLOWED_ROLE_IDS),
|
||||
},
|
||||
},
|
||||
providers: providersConfig,
|
||||
};
|
||||
|
||||
|
|
@ -77,5 +131,13 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): HeimdallConfig
|
|||
config.signingKeyId = env.GC_ACCESS_SIGNING_KEY_ID;
|
||||
}
|
||||
|
||||
if (env.GC_ACCESS_DATABASE_URL) {
|
||||
config.storage.databaseUrl = env.GC_ACCESS_DATABASE_URL;
|
||||
}
|
||||
|
||||
if (env.GC_ACCESS_APP_REPIXELIZER_DISCORD_GUILD_ID) {
|
||||
config.apps.repixelizer.discordGuildId = env.GC_ACCESS_APP_REPIXELIZER_DISCORD_GUILD_ID;
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -28,6 +28,22 @@ export interface OAuthStartRequest {
|
|||
requestedScopes?: string[];
|
||||
}
|
||||
|
||||
export interface OAuthStatePayload {
|
||||
iss: string;
|
||||
sub: AppSlug;
|
||||
aud: Provider;
|
||||
jti: string;
|
||||
iat: number;
|
||||
nbf: number;
|
||||
exp: number;
|
||||
typ: "heimdall_oauth_state";
|
||||
provider: Provider;
|
||||
app_slug: AppSlug;
|
||||
mode: OAuthMode;
|
||||
return_to: string;
|
||||
connection: OAuthConnectionBinding | null;
|
||||
}
|
||||
|
||||
export interface LinkedIdentityInput {
|
||||
provider: Provider;
|
||||
providerUserId: string;
|
||||
|
|
|
|||
276
src/oauth.ts
Normal file
276
src/oauth.ts
Normal file
|
|
@ -0,0 +1,276 @@
|
|||
import { Buffer } from "node:buffer";
|
||||
import { type AppSlug, type OAuthConnectionBinding, type Provider } from "./contracts.js";
|
||||
import { type HeimdallConfig } from "./config.js";
|
||||
import { type CreateEntitlementSnapshotInput } from "./store/types.js";
|
||||
|
||||
export interface OAuthTokenSet {
|
||||
accessToken: string;
|
||||
refreshToken?: string;
|
||||
tokenType: string;
|
||||
scope: string[];
|
||||
expiresAt?: string;
|
||||
raw: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface ResolvedIdentity {
|
||||
provider: Provider;
|
||||
providerUserId: string;
|
||||
username?: string;
|
||||
displayName?: string;
|
||||
primaryEmail?: string;
|
||||
avatarUrl?: string;
|
||||
profile: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface EntitlementEvaluation {
|
||||
facts: string[];
|
||||
snapshots: CreateEntitlementSnapshotInput[];
|
||||
}
|
||||
|
||||
export interface OAuthCallbackContext {
|
||||
appSlug: AppSlug;
|
||||
accountId: string;
|
||||
connection: OAuthConnectionBinding | null;
|
||||
}
|
||||
|
||||
export interface OAuthProviderRuntime {
|
||||
exchangeAuthorizationCode(options: {
|
||||
config: HeimdallConfig;
|
||||
code: string;
|
||||
redirectUri: string;
|
||||
}): Promise<OAuthTokenSet>;
|
||||
resolveIdentity(options: { accessToken: string }): Promise<ResolvedIdentity>;
|
||||
evaluateEntitlements(options: {
|
||||
config: HeimdallConfig;
|
||||
callback: OAuthCallbackContext;
|
||||
identity: ResolvedIdentity;
|
||||
tokenSet: OAuthTokenSet;
|
||||
}): Promise<EntitlementEvaluation>;
|
||||
}
|
||||
|
||||
function buildErrorMessage(status: number, body: string, fallback: string): string {
|
||||
return `${fallback} (status ${status}): ${body || "empty response"}`;
|
||||
}
|
||||
|
||||
async function fetchJson<T>(input: string | URL, init: RequestInit, fallbackError: string): Promise<T> {
|
||||
const response = await fetch(input, init);
|
||||
const text = await response.text();
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(buildErrorMessage(response.status, text, fallbackError));
|
||||
}
|
||||
|
||||
return (text ? JSON.parse(text) : {}) as T;
|
||||
}
|
||||
|
||||
async function exchangeDiscordAuthorizationCode(options: {
|
||||
config: HeimdallConfig;
|
||||
code: string;
|
||||
redirectUri: string;
|
||||
}): Promise<OAuthTokenSet> {
|
||||
const providerConfig = options.config.providers.discord;
|
||||
if (!providerConfig.clientId || !providerConfig.clientSecret) {
|
||||
throw new Error("Discord OAuth is not fully configured.");
|
||||
}
|
||||
|
||||
const body = new URLSearchParams({
|
||||
grant_type: "authorization_code",
|
||||
code: options.code,
|
||||
redirect_uri: options.redirectUri,
|
||||
});
|
||||
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;
|
||||
}>(
|
||||
"https://discord.com/api/v10/oauth2/token",
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
Authorization: `Basic ${basicAuth}`,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
},
|
||||
body,
|
||||
},
|
||||
"Discord token exchange failed"
|
||||
);
|
||||
|
||||
const tokenSet: OAuthTokenSet = {
|
||||
accessToken: tokenResponse.access_token,
|
||||
tokenType: tokenResponse.token_type,
|
||||
scope: tokenResponse.scope.split(/\s+/).filter(Boolean),
|
||||
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 resolveDiscordIdentity(options: { accessToken: string }): Promise<ResolvedIdentity> {
|
||||
const user = await fetchJson<{
|
||||
id: string;
|
||||
username?: string;
|
||||
global_name?: string;
|
||||
email?: string;
|
||||
avatar?: string | null;
|
||||
}>(
|
||||
"https://discord.com/api/v10/users/@me",
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${options.accessToken}`,
|
||||
},
|
||||
},
|
||||
"Discord identity lookup failed"
|
||||
);
|
||||
|
||||
const identity: ResolvedIdentity = {
|
||||
provider: "discord",
|
||||
providerUserId: user.id,
|
||||
profile: user as unknown as Record<string, unknown>,
|
||||
};
|
||||
|
||||
if (user.username) {
|
||||
identity.username = user.username;
|
||||
}
|
||||
|
||||
const displayName = user.global_name ?? user.username;
|
||||
if (displayName) {
|
||||
identity.displayName = displayName;
|
||||
}
|
||||
|
||||
if (user.email) {
|
||||
identity.primaryEmail = user.email;
|
||||
}
|
||||
|
||||
if (user.avatar) {
|
||||
identity.avatarUrl = `https://cdn.discordapp.com/avatars/${user.id}/${user.avatar}.png`;
|
||||
}
|
||||
|
||||
return identity;
|
||||
}
|
||||
|
||||
async function evaluateDiscordEntitlements(options: {
|
||||
config: HeimdallConfig;
|
||||
callback: OAuthCallbackContext;
|
||||
tokenSet: OAuthTokenSet;
|
||||
}): Promise<EntitlementEvaluation> {
|
||||
if (options.callback.appSlug !== "repixelizer") {
|
||||
return { facts: [], snapshots: [] };
|
||||
}
|
||||
|
||||
const guildId = options.config.apps.repixelizer.discordGuildId;
|
||||
const allowedRoleIds = options.config.apps.repixelizer.discordAllowedRoleIds;
|
||||
|
||||
if (!guildId) {
|
||||
return { facts: [], snapshots: [] };
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`https://discord.com/api/v10/users/@me/guilds/${guildId}/member`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${options.tokenSet.accessToken}`,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
if (response.status === 404) {
|
||||
return {
|
||||
facts: [],
|
||||
snapshots: [
|
||||
{
|
||||
accountId: options.callback.accountId,
|
||||
provider: "discord",
|
||||
scope: `repixelizer:discord_member:${guildId}`,
|
||||
evaluatedAt: new Date().toISOString(),
|
||||
isAllowed: false,
|
||||
reasonCode: "not_in_guild",
|
||||
reasonDetail: "Current user is not a member of the configured GameCult guild.",
|
||||
rawSummaryJson: { guildId },
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
throw new Error(buildErrorMessage(response.status, text, "Discord guild member lookup failed"));
|
||||
}
|
||||
|
||||
const member = (text ? JSON.parse(text) : {}) as {
|
||||
nick?: string;
|
||||
roles?: string[];
|
||||
joined_at?: string;
|
||||
};
|
||||
const roles = member.roles ?? [];
|
||||
const matchedRoles = allowedRoleIds.filter((roleId) => roles.includes(roleId));
|
||||
const facts = ["discord.in_guild"];
|
||||
|
||||
if (matchedRoles.length > 0) {
|
||||
facts.push("discord.allowed_role");
|
||||
}
|
||||
|
||||
return {
|
||||
facts,
|
||||
snapshots: [
|
||||
{
|
||||
accountId: options.callback.accountId,
|
||||
provider: "discord",
|
||||
scope: `repixelizer:discord_role_access:${guildId}`,
|
||||
evaluatedAt: new Date().toISOString(),
|
||||
isAllowed: matchedRoles.length > 0,
|
||||
reasonCode: matchedRoles.length > 0 ? "matched_role" : "missing_role",
|
||||
reasonDetail:
|
||||
matchedRoles.length > 0
|
||||
? `Matched Discord roles: ${matchedRoles.join(", ")}`
|
||||
: allowedRoleIds.length
|
||||
? "User is in the guild but lacks the configured Repixelizer access role."
|
||||
: "No Repixelizer Discord role ids are configured.",
|
||||
rawSummaryJson: {
|
||||
guildId,
|
||||
roles,
|
||||
matchedRoles,
|
||||
nick: member.nick,
|
||||
joinedAt: member.joined_at,
|
||||
},
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
const discordRuntime: OAuthProviderRuntime = {
|
||||
exchangeAuthorizationCode: exchangeDiscordAuthorizationCode,
|
||||
resolveIdentity: resolveDiscordIdentity,
|
||||
evaluateEntitlements: evaluateDiscordEntitlements,
|
||||
};
|
||||
|
||||
const notImplementedRuntime: OAuthProviderRuntime = {
|
||||
async exchangeAuthorizationCode() {
|
||||
throw new Error("Provider callback exchange is not implemented yet.");
|
||||
},
|
||||
async resolveIdentity() {
|
||||
throw new Error("Provider identity resolution is not implemented yet.");
|
||||
},
|
||||
async evaluateEntitlements() {
|
||||
return { facts: [], snapshots: [] };
|
||||
},
|
||||
};
|
||||
|
||||
export type OAuthRuntimeRegistry = Record<Provider, OAuthProviderRuntime>;
|
||||
|
||||
export function createOAuthRuntimeRegistry(): OAuthRuntimeRegistry {
|
||||
return {
|
||||
discord: discordRuntime,
|
||||
patreon: notImplementedRuntime,
|
||||
github: notImplementedRuntime,
|
||||
twitch: notImplementedRuntime,
|
||||
youtube: notImplementedRuntime,
|
||||
};
|
||||
}
|
||||
|
|
@ -18,7 +18,7 @@ export const providerCatalog: Record<Provider, ProviderDescriptor> = {
|
|||
key: "discord",
|
||||
displayName: "Discord",
|
||||
authorizationEndpoint: "https://discord.com/oauth2/authorize",
|
||||
defaultScopes: ["identify", "guilds"],
|
||||
defaultScopes: ["identify", "email", "guilds.members.read"],
|
||||
roles: ["identity", "entitlement"],
|
||||
clientIdEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_ID",
|
||||
clientSecretEnv: "GC_ACCESS_PROVIDER_DISCORD_CLIENT_SECRET",
|
||||
|
|
|
|||
210
src/store/in-memory.ts
Normal file
210
src/store/in-memory.ts
Normal file
|
|
@ -0,0 +1,210 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contracts.js";
|
||||
import {
|
||||
type CreateAccountInput,
|
||||
type CreateAuditEventInput,
|
||||
type CreateCapabilityGrantInput,
|
||||
type CreateEntitlementSnapshotInput,
|
||||
type CreateSessionInput,
|
||||
type HeimdallStore,
|
||||
type StoredAccount,
|
||||
type StoredCapabilityGrant,
|
||||
type StoredLinkedIdentity,
|
||||
type StoredSession,
|
||||
type UpsertLinkedIdentityInput,
|
||||
} from "./types.js";
|
||||
|
||||
function clone<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
function isGrantActive(grant: StoredCapabilityGrant, appSlug: AppSlug, at: string): boolean {
|
||||
if (grant.status !== "active") {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (grant.expiresAt && grant.expiresAt <= at) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return grant.scopeType === "global" || grant.scopeId === appSlug;
|
||||
}
|
||||
|
||||
export class InMemoryStore implements HeimdallStore {
|
||||
private readonly accounts = new Map<string, StoredAccount>();
|
||||
private readonly linkedIdentities = new Map<string, StoredLinkedIdentity>();
|
||||
private readonly grants = new Map<string, StoredCapabilityGrant>();
|
||||
private readonly sessions = new Map<string, StoredSession>();
|
||||
private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>();
|
||||
private readonly auditEvents = new Map<string, CreateAuditEventInput>();
|
||||
|
||||
async ensureSchema(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
async createAccount(input: CreateAccountInput): Promise<StoredAccount> {
|
||||
const account: StoredAccount = {
|
||||
id: input.id ?? randomUUID(),
|
||||
createdAt: input.createdAt,
|
||||
lastSeenAt: input.lastSeenAt,
|
||||
};
|
||||
|
||||
if (input.displayName !== undefined) {
|
||||
account.displayName = input.displayName;
|
||||
}
|
||||
|
||||
if (input.primaryEmail !== undefined) {
|
||||
account.primaryEmail = input.primaryEmail;
|
||||
}
|
||||
|
||||
this.accounts.set(account.id, clone(account));
|
||||
return clone(account);
|
||||
}
|
||||
|
||||
async touchAccount(accountId: string, at: string, updates?: { displayName?: string; primaryEmail?: string }): Promise<void> {
|
||||
const account = this.accounts.get(accountId);
|
||||
if (!account) {
|
||||
throw new Error(`Account '${accountId}' was not found.`);
|
||||
}
|
||||
|
||||
account.lastSeenAt = at;
|
||||
if (updates?.displayName) {
|
||||
account.displayName = updates.displayName;
|
||||
}
|
||||
if (updates?.primaryEmail) {
|
||||
account.primaryEmail = updates.primaryEmail;
|
||||
}
|
||||
}
|
||||
|
||||
async findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredAccount | null> {
|
||||
for (const linkedIdentity of this.linkedIdentities.values()) {
|
||||
if (linkedIdentity.provider === provider && linkedIdentity.providerUserId === providerUserId) {
|
||||
return clone(this.accounts.get(linkedIdentity.accountId) ?? null);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
async upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity> {
|
||||
const existing = [...this.linkedIdentities.values()].find(
|
||||
(identity) => identity.provider === input.provider && identity.providerUserId === input.providerUserId
|
||||
);
|
||||
const id = existing?.id ?? input.id ?? randomUUID();
|
||||
const linkedIdentity: StoredLinkedIdentity = {
|
||||
id,
|
||||
accountId: input.accountId,
|
||||
provider: input.provider,
|
||||
providerUserId: input.providerUserId,
|
||||
scopes: [...input.scopes],
|
||||
profileJson: clone(input.profileJson),
|
||||
createdAt: existing?.createdAt ?? input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
};
|
||||
|
||||
if (input.username !== undefined) {
|
||||
linkedIdentity.username = input.username;
|
||||
}
|
||||
|
||||
if (input.displayName !== undefined) {
|
||||
linkedIdentity.displayName = input.displayName;
|
||||
}
|
||||
|
||||
if (input.primaryEmail !== undefined) {
|
||||
linkedIdentity.primaryEmail = input.primaryEmail;
|
||||
}
|
||||
|
||||
if (input.accessTokenEncrypted !== undefined) {
|
||||
linkedIdentity.accessTokenEncrypted = input.accessTokenEncrypted;
|
||||
}
|
||||
|
||||
if (input.refreshTokenEncrypted !== undefined) {
|
||||
linkedIdentity.refreshTokenEncrypted = input.refreshTokenEncrypted;
|
||||
}
|
||||
|
||||
if (input.tokenExpiresAt !== undefined) {
|
||||
linkedIdentity.tokenExpiresAt = input.tokenExpiresAt;
|
||||
}
|
||||
|
||||
this.linkedIdentities.set(id, clone(linkedIdentity));
|
||||
return clone(linkedIdentity);
|
||||
}
|
||||
|
||||
async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> {
|
||||
return [...this.linkedIdentities.values()]
|
||||
.filter((identity) => identity.accountId === accountId)
|
||||
.map((identity) => {
|
||||
const linkedIdentity: LinkedIdentityInput = {
|
||||
provider: identity.provider,
|
||||
providerUserId: identity.providerUserId,
|
||||
};
|
||||
|
||||
if (identity.username !== undefined) {
|
||||
linkedIdentity.username = identity.username;
|
||||
}
|
||||
|
||||
if (identity.displayName !== undefined) {
|
||||
linkedIdentity.displayName = identity.displayName;
|
||||
}
|
||||
|
||||
return linkedIdentity;
|
||||
});
|
||||
}
|
||||
|
||||
async createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant> {
|
||||
const grant: StoredCapabilityGrant = {
|
||||
id: input.id ?? randomUUID(),
|
||||
accountId: input.accountId,
|
||||
scopeType: input.scopeType,
|
||||
capability: input.capability,
|
||||
source: input.source,
|
||||
status: input.status,
|
||||
createdAt: input.createdAt,
|
||||
updatedAt: input.updatedAt,
|
||||
};
|
||||
|
||||
if (input.scopeId !== undefined) {
|
||||
grant.scopeId = input.scopeId;
|
||||
}
|
||||
|
||||
if (input.expiresAt !== undefined) {
|
||||
grant.expiresAt = input.expiresAt;
|
||||
}
|
||||
|
||||
if (input.note !== undefined) {
|
||||
grant.note = input.note;
|
||||
}
|
||||
|
||||
this.grants.set(grant.id, clone(grant));
|
||||
return clone(grant);
|
||||
}
|
||||
|
||||
async listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]> {
|
||||
return [...this.grants.values()]
|
||||
.filter((grant) => grant.accountId === accountId && isGrantActive(grant, appSlug, at))
|
||||
.map((grant) => clone(grant));
|
||||
}
|
||||
|
||||
async createSession(input: CreateSessionInput): Promise<StoredSession> {
|
||||
const session: StoredSession = clone(input);
|
||||
this.sessions.set(session.id, session);
|
||||
return clone(session);
|
||||
}
|
||||
|
||||
async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> {
|
||||
const key = `${input.accountId}:${input.provider}:${input.scope}`;
|
||||
this.entitlementSnapshots.set(key, clone(input));
|
||||
}
|
||||
|
||||
async createAuditEvent(input: CreateAuditEventInput): Promise<void> {
|
||||
const event: CreateAuditEventInput = clone({
|
||||
...input,
|
||||
id: input.id ?? randomUUID(),
|
||||
});
|
||||
this.auditEvents.set(event.id ?? randomUUID(), event);
|
||||
}
|
||||
}
|
||||
21
src/store/index.ts
Normal file
21
src/store/index.ts
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import { type HeimdallConfig } from "../config.js";
|
||||
import { InMemoryStore } from "./in-memory.js";
|
||||
import { createPostgresStore } from "./postgres.js";
|
||||
import { type HeimdallStore } from "./types.js";
|
||||
|
||||
export * from "./types.js";
|
||||
export { InMemoryStore } from "./in-memory.js";
|
||||
export { PostgresStore, createPostgresStore } from "./postgres.js";
|
||||
|
||||
export async function createStore(config: HeimdallConfig): Promise<HeimdallStore> {
|
||||
const store =
|
||||
config.storage.backend === "postgres"
|
||||
? createPostgresStore(config.storage.databaseUrl ?? "postgres://127.0.0.1/heimdall")
|
||||
: new InMemoryStore();
|
||||
|
||||
if (config.storage.applySchemaOnStartup) {
|
||||
await store.ensureSchema();
|
||||
}
|
||||
|
||||
return store;
|
||||
}
|
||||
455
src/store/postgres.ts
Normal file
455
src/store/postgres.ts
Normal file
|
|
@ -0,0 +1,455 @@
|
|||
import { randomUUID } from "node:crypto";
|
||||
import { Pool, type PoolClient, type QueryResultRow } from "pg";
|
||||
import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contracts.js";
|
||||
import { CREATE_SCHEMA_SQL } from "./schema.js";
|
||||
import {
|
||||
type CreateAccountInput,
|
||||
type CreateAuditEventInput,
|
||||
type CreateCapabilityGrantInput,
|
||||
type CreateEntitlementSnapshotInput,
|
||||
type CreateSessionInput,
|
||||
type HeimdallStore,
|
||||
type StoredAccount,
|
||||
type StoredCapabilityGrant,
|
||||
type StoredLinkedIdentity,
|
||||
type StoredSession,
|
||||
type UpsertLinkedIdentityInput,
|
||||
} from "./types.js";
|
||||
|
||||
interface AccountRow extends QueryResultRow {
|
||||
id: string;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
display_name: string | null;
|
||||
primary_email: string | null;
|
||||
}
|
||||
|
||||
interface LinkedIdentityRow extends QueryResultRow {
|
||||
id: string;
|
||||
account_id: string;
|
||||
provider: Provider;
|
||||
provider_user_id: string;
|
||||
username: string | null;
|
||||
display_name: string | null;
|
||||
primary_email: string | null;
|
||||
access_token_encrypted: string | null;
|
||||
refresh_token_encrypted: string | null;
|
||||
token_expires_at: string | null;
|
||||
scopes: string;
|
||||
profile_json: Record<string, unknown>;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface GrantRow extends QueryResultRow {
|
||||
id: string;
|
||||
account_id: string;
|
||||
scope_type: "global" | "app";
|
||||
scope_id: AppSlug | null;
|
||||
capability: string;
|
||||
source: string;
|
||||
status: "active" | "revoked";
|
||||
expires_at: string | null;
|
||||
note: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
interface SessionRow extends QueryResultRow {
|
||||
id: string;
|
||||
account_id: string;
|
||||
app_slug: AppSlug;
|
||||
created_at: string;
|
||||
last_seen_at: string;
|
||||
expires_at: string;
|
||||
access_revision: number;
|
||||
claims_json: Record<string, unknown>;
|
||||
}
|
||||
|
||||
function expectRow<T>(row: T | undefined, label: string): T {
|
||||
if (!row) {
|
||||
throw new Error(`${label} query returned no rows.`);
|
||||
}
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
function nullable<T>(value: T | undefined): T | null {
|
||||
return value ?? null;
|
||||
}
|
||||
|
||||
function parseScopes(value: string): string[] {
|
||||
return value.split(" ").map((item) => item.trim()).filter(Boolean);
|
||||
}
|
||||
|
||||
function mapAccountRow(row: AccountRow): StoredAccount {
|
||||
const account: StoredAccount = {
|
||||
id: row.id,
|
||||
createdAt: row.created_at,
|
||||
lastSeenAt: row.last_seen_at,
|
||||
};
|
||||
|
||||
if (row.display_name) {
|
||||
account.displayName = row.display_name;
|
||||
}
|
||||
|
||||
if (row.primary_email) {
|
||||
account.primaryEmail = row.primary_email;
|
||||
}
|
||||
|
||||
return account;
|
||||
}
|
||||
|
||||
function mapLinkedIdentityRow(row: LinkedIdentityRow): StoredLinkedIdentity {
|
||||
const identity: StoredLinkedIdentity = {
|
||||
id: row.id,
|
||||
accountId: row.account_id,
|
||||
provider: row.provider,
|
||||
providerUserId: row.provider_user_id,
|
||||
scopes: parseScopes(row.scopes),
|
||||
profileJson: row.profile_json,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
|
||||
if (row.username) {
|
||||
identity.username = row.username;
|
||||
}
|
||||
|
||||
if (row.display_name) {
|
||||
identity.displayName = row.display_name;
|
||||
}
|
||||
|
||||
if (row.primary_email) {
|
||||
identity.primaryEmail = row.primary_email;
|
||||
}
|
||||
|
||||
if (row.access_token_encrypted) {
|
||||
identity.accessTokenEncrypted = row.access_token_encrypted;
|
||||
}
|
||||
|
||||
if (row.refresh_token_encrypted) {
|
||||
identity.refreshTokenEncrypted = row.refresh_token_encrypted;
|
||||
}
|
||||
|
||||
if (row.token_expires_at) {
|
||||
identity.tokenExpiresAt = row.token_expires_at;
|
||||
}
|
||||
|
||||
return identity;
|
||||
}
|
||||
|
||||
function mapGrantRow(row: GrantRow): StoredCapabilityGrant {
|
||||
const grant: StoredCapabilityGrant = {
|
||||
id: row.id,
|
||||
accountId: row.account_id,
|
||||
scopeType: row.scope_type,
|
||||
capability: row.capability,
|
||||
source: row.source,
|
||||
status: row.status,
|
||||
createdAt: row.created_at,
|
||||
updatedAt: row.updated_at,
|
||||
};
|
||||
|
||||
if (row.scope_id) {
|
||||
grant.scopeId = row.scope_id;
|
||||
}
|
||||
|
||||
if (row.expires_at) {
|
||||
grant.expiresAt = row.expires_at;
|
||||
}
|
||||
|
||||
if (row.note) {
|
||||
grant.note = row.note;
|
||||
}
|
||||
|
||||
return grant;
|
||||
}
|
||||
|
||||
function mapSessionRow(row: SessionRow): StoredSession {
|
||||
return {
|
||||
id: row.id,
|
||||
accountId: row.account_id,
|
||||
appSlug: row.app_slug,
|
||||
createdAt: row.created_at,
|
||||
lastSeenAt: row.last_seen_at,
|
||||
expiresAt: row.expires_at,
|
||||
accessRevision: row.access_revision,
|
||||
claimsJson: row.claims_json,
|
||||
};
|
||||
}
|
||||
|
||||
export class PostgresStore implements HeimdallStore {
|
||||
constructor(private readonly pool: Pick<Pool, "query" | "end">) {}
|
||||
|
||||
async ensureSchema(): Promise<void> {
|
||||
await this.pool.query(CREATE_SCHEMA_SQL);
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await this.pool.end();
|
||||
}
|
||||
|
||||
async createAccount(input: CreateAccountInput): Promise<StoredAccount> {
|
||||
const id = input.id ?? randomUUID();
|
||||
const result = await this.pool.query<AccountRow>(
|
||||
`
|
||||
INSERT INTO accounts (id, created_at, last_seen_at, display_name, primary_email)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
RETURNING *
|
||||
`,
|
||||
[id, input.createdAt, input.lastSeenAt, nullable(input.displayName), nullable(input.primaryEmail)]
|
||||
);
|
||||
|
||||
return mapAccountRow(expectRow(result.rows[0], "createAccount"));
|
||||
}
|
||||
|
||||
async touchAccount(accountId: string, at: string, updates?: { displayName?: string; primaryEmail?: string }): Promise<void> {
|
||||
await this.pool.query(
|
||||
`
|
||||
UPDATE accounts
|
||||
SET last_seen_at = $2,
|
||||
display_name = COALESCE($3, display_name),
|
||||
primary_email = COALESCE($4, primary_email)
|
||||
WHERE id = $1
|
||||
`,
|
||||
[accountId, at, nullable(updates?.displayName), nullable(updates?.primaryEmail)]
|
||||
);
|
||||
}
|
||||
|
||||
async findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredAccount | null> {
|
||||
const result = await this.pool.query<AccountRow>(
|
||||
`
|
||||
SELECT accounts.*
|
||||
FROM accounts
|
||||
INNER JOIN linked_identities ON linked_identities.account_id = accounts.id
|
||||
WHERE linked_identities.provider = $1
|
||||
AND linked_identities.provider_user_id = $2
|
||||
LIMIT 1
|
||||
`,
|
||||
[provider, providerUserId]
|
||||
);
|
||||
|
||||
return result.rowCount ? mapAccountRow(expectRow(result.rows[0], "findAccountByLinkedIdentity")) : null;
|
||||
}
|
||||
|
||||
async upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity> {
|
||||
const id = input.id ?? randomUUID();
|
||||
const result = await this.pool.query<LinkedIdentityRow>(
|
||||
`
|
||||
INSERT INTO linked_identities (
|
||||
id,
|
||||
account_id,
|
||||
provider,
|
||||
provider_user_id,
|
||||
username,
|
||||
display_name,
|
||||
primary_email,
|
||||
access_token_encrypted,
|
||||
refresh_token_encrypted,
|
||||
token_expires_at,
|
||||
scopes,
|
||||
profile_json,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7,
|
||||
$8, $9, $10, $11, $12, $13, $14
|
||||
)
|
||||
ON CONFLICT (provider, provider_user_id)
|
||||
DO UPDATE SET
|
||||
account_id = EXCLUDED.account_id,
|
||||
username = EXCLUDED.username,
|
||||
display_name = EXCLUDED.display_name,
|
||||
primary_email = EXCLUDED.primary_email,
|
||||
access_token_encrypted = EXCLUDED.access_token_encrypted,
|
||||
refresh_token_encrypted = EXCLUDED.refresh_token_encrypted,
|
||||
token_expires_at = EXCLUDED.token_expires_at,
|
||||
scopes = EXCLUDED.scopes,
|
||||
profile_json = EXCLUDED.profile_json,
|
||||
updated_at = EXCLUDED.updated_at
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
id,
|
||||
input.accountId,
|
||||
input.provider,
|
||||
input.providerUserId,
|
||||
nullable(input.username),
|
||||
nullable(input.displayName),
|
||||
nullable(input.primaryEmail),
|
||||
nullable(input.accessTokenEncrypted),
|
||||
nullable(input.refreshTokenEncrypted),
|
||||
nullable(input.tokenExpiresAt),
|
||||
input.scopes.join(" "),
|
||||
JSON.stringify(input.profileJson),
|
||||
input.createdAt,
|
||||
input.updatedAt,
|
||||
]
|
||||
);
|
||||
|
||||
return mapLinkedIdentityRow(expectRow(result.rows[0], "upsertLinkedIdentity"));
|
||||
}
|
||||
|
||||
async listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]> {
|
||||
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((row) => {
|
||||
const linkedIdentity: LinkedIdentityInput = {
|
||||
provider: row.provider,
|
||||
providerUserId: row.provider_user_id,
|
||||
};
|
||||
|
||||
if (row.username) {
|
||||
linkedIdentity.username = row.username;
|
||||
}
|
||||
|
||||
if (row.display_name) {
|
||||
linkedIdentity.displayName = row.display_name;
|
||||
}
|
||||
|
||||
return linkedIdentity;
|
||||
});
|
||||
}
|
||||
|
||||
async createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant> {
|
||||
const id = input.id ?? randomUUID();
|
||||
const result = await this.pool.query<GrantRow>(
|
||||
`
|
||||
INSERT INTO capability_grants (
|
||||
id, account_id, scope_type, scope_id, capability,
|
||||
source, status, expires_at, note, created_at, updated_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
id,
|
||||
input.accountId,
|
||||
input.scopeType,
|
||||
nullable(input.scopeId),
|
||||
input.capability,
|
||||
input.source,
|
||||
input.status,
|
||||
nullable(input.expiresAt),
|
||||
nullable(input.note),
|
||||
input.createdAt,
|
||||
input.updatedAt,
|
||||
]
|
||||
);
|
||||
|
||||
return mapGrantRow(expectRow(result.rows[0], "createCapabilityGrant"));
|
||||
}
|
||||
|
||||
async listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]> {
|
||||
const result = await this.pool.query<GrantRow>(
|
||||
`
|
||||
SELECT *
|
||||
FROM capability_grants
|
||||
WHERE account_id = $1
|
||||
AND status = 'active'
|
||||
AND (expires_at IS NULL OR expires_at > $3)
|
||||
AND (
|
||||
scope_type = 'global'
|
||||
OR (scope_type = 'app' AND scope_id = $2)
|
||||
)
|
||||
ORDER BY created_at ASC
|
||||
`,
|
||||
[accountId, appSlug, at]
|
||||
);
|
||||
|
||||
return result.rows.map(mapGrantRow);
|
||||
}
|
||||
|
||||
async createSession(input: CreateSessionInput): Promise<StoredSession> {
|
||||
const result = await this.pool.query<SessionRow>(
|
||||
`
|
||||
INSERT INTO sessions (
|
||||
id, account_id, app_slug, created_at, last_seen_at,
|
||||
expires_at, claims_json, access_revision
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
input.id,
|
||||
input.accountId,
|
||||
input.appSlug,
|
||||
input.createdAt,
|
||||
input.lastSeenAt,
|
||||
input.expiresAt,
|
||||
JSON.stringify(input.claimsJson),
|
||||
input.accessRevision,
|
||||
]
|
||||
);
|
||||
|
||||
return mapSessionRow(expectRow(result.rows[0], "createSession"));
|
||||
}
|
||||
|
||||
async upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void> {
|
||||
await this.pool.query(
|
||||
`
|
||||
INSERT INTO entitlement_snapshots (
|
||||
id, account_id, provider, scope, evaluated_at,
|
||||
is_allowed, reason_code, reason_detail, raw_summary_json
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (account_id, provider, scope)
|
||||
DO UPDATE SET
|
||||
evaluated_at = EXCLUDED.evaluated_at,
|
||||
is_allowed = EXCLUDED.is_allowed,
|
||||
reason_code = EXCLUDED.reason_code,
|
||||
reason_detail = EXCLUDED.reason_detail,
|
||||
raw_summary_json = EXCLUDED.raw_summary_json
|
||||
`,
|
||||
[
|
||||
randomUUID(),
|
||||
input.accountId,
|
||||
input.provider,
|
||||
input.scope,
|
||||
input.evaluatedAt,
|
||||
input.isAllowed,
|
||||
input.reasonCode,
|
||||
nullable(input.reasonDetail),
|
||||
JSON.stringify(input.rawSummaryJson),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
async createAuditEvent(input: CreateAuditEventInput): Promise<void> {
|
||||
await this.pool.query(
|
||||
`
|
||||
INSERT INTO audit_events (
|
||||
id, account_id, session_id, app_slug, event_type,
|
||||
event_payload_json, created_at
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7)
|
||||
`,
|
||||
[
|
||||
input.id ?? randomUUID(),
|
||||
nullable(input.accountId),
|
||||
nullable(input.sessionId),
|
||||
nullable(input.appSlug),
|
||||
input.eventType,
|
||||
JSON.stringify(input.eventPayloadJson),
|
||||
input.createdAt,
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function createPostgresStore(databaseUrl: string): HeimdallStore {
|
||||
const pool = new Pool({
|
||||
connectionString: databaseUrl,
|
||||
});
|
||||
return new PostgresStore(pool);
|
||||
}
|
||||
87
src/store/schema.ts
Normal file
87
src/store/schema.ts
Normal file
|
|
@ -0,0 +1,87 @@
|
|||
export const CREATE_SCHEMA_SQL = `
|
||||
CREATE TABLE IF NOT EXISTS accounts (
|
||||
id TEXT PRIMARY KEY,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
last_seen_at TIMESTAMPTZ NOT NULL,
|
||||
display_name TEXT,
|
||||
primary_email TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS linked_identities (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
provider TEXT NOT NULL,
|
||||
provider_user_id TEXT NOT NULL,
|
||||
username TEXT,
|
||||
display_name TEXT,
|
||||
primary_email TEXT,
|
||||
access_token_encrypted TEXT,
|
||||
refresh_token_encrypted TEXT,
|
||||
token_expires_at TIMESTAMPTZ,
|
||||
scopes TEXT NOT NULL DEFAULT '',
|
||||
profile_json JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL,
|
||||
UNIQUE(provider, provider_user_id)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS linked_identities_account_id_idx
|
||||
ON linked_identities(account_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
app_slug TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
last_seen_at TIMESTAMPTZ NOT NULL,
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
claims_json JSONB NOT NULL,
|
||||
access_revision INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS sessions_account_id_idx
|
||||
ON sessions(account_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS capability_grants (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
scope_type TEXT NOT NULL,
|
||||
scope_id TEXT,
|
||||
capability TEXT NOT NULL,
|
||||
source TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
expires_at TIMESTAMPTZ,
|
||||
note TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS capability_grants_lookup_idx
|
||||
ON capability_grants(account_id, scope_type, scope_id, status);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS entitlement_snapshots (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
provider TEXT NOT NULL,
|
||||
scope TEXT NOT NULL,
|
||||
evaluated_at TIMESTAMPTZ NOT NULL,
|
||||
is_allowed BOOLEAN NOT NULL,
|
||||
reason_code TEXT NOT NULL,
|
||||
reason_detail TEXT,
|
||||
raw_summary_json JSONB NOT NULL,
|
||||
UNIQUE(account_id, provider, scope)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT,
|
||||
session_id TEXT,
|
||||
app_slug TEXT,
|
||||
event_type TEXT NOT NULL,
|
||||
event_payload_json JSONB NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS audit_events_lookup_idx
|
||||
ON audit_events(account_id, session_id, app_slug, created_at);
|
||||
`;
|
||||
137
src/store/types.ts
Normal file
137
src/store/types.ts
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
import { type AppSlug, type LinkedIdentityInput, type Provider } from "../contracts.js";
|
||||
|
||||
export interface StoredAccount {
|
||||
id: string;
|
||||
createdAt: string;
|
||||
lastSeenAt: string;
|
||||
displayName?: string;
|
||||
primaryEmail?: string;
|
||||
}
|
||||
|
||||
export interface CreateAccountInput {
|
||||
id?: string;
|
||||
createdAt: string;
|
||||
lastSeenAt: string;
|
||||
displayName?: string;
|
||||
primaryEmail?: string;
|
||||
}
|
||||
|
||||
export interface StoredLinkedIdentity {
|
||||
id: string;
|
||||
accountId: string;
|
||||
provider: Provider;
|
||||
providerUserId: string;
|
||||
username?: string;
|
||||
displayName?: string;
|
||||
primaryEmail?: string;
|
||||
accessTokenEncrypted?: string;
|
||||
refreshTokenEncrypted?: string;
|
||||
tokenExpiresAt?: string;
|
||||
scopes: string[];
|
||||
profileJson: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface UpsertLinkedIdentityInput {
|
||||
id?: string;
|
||||
accountId: string;
|
||||
provider: Provider;
|
||||
providerUserId: string;
|
||||
username?: string;
|
||||
displayName?: string;
|
||||
primaryEmail?: string;
|
||||
accessTokenEncrypted?: string;
|
||||
refreshTokenEncrypted?: string;
|
||||
tokenExpiresAt?: string;
|
||||
scopes: string[];
|
||||
profileJson: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface StoredSession {
|
||||
id: string;
|
||||
accountId: string;
|
||||
appSlug: AppSlug;
|
||||
createdAt: string;
|
||||
lastSeenAt: string;
|
||||
expiresAt: string;
|
||||
accessRevision: number;
|
||||
claimsJson: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CreateSessionInput {
|
||||
id: string;
|
||||
accountId: string;
|
||||
appSlug: AppSlug;
|
||||
createdAt: string;
|
||||
lastSeenAt: string;
|
||||
expiresAt: string;
|
||||
accessRevision: number;
|
||||
claimsJson: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface StoredCapabilityGrant {
|
||||
id: string;
|
||||
accountId: string;
|
||||
scopeType: "global" | "app";
|
||||
scopeId?: AppSlug;
|
||||
capability: string;
|
||||
source: string;
|
||||
status: "active" | "revoked";
|
||||
expiresAt?: string;
|
||||
note?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CreateCapabilityGrantInput {
|
||||
id?: string;
|
||||
accountId: string;
|
||||
scopeType: "global" | "app";
|
||||
scopeId?: AppSlug;
|
||||
capability: string;
|
||||
source: string;
|
||||
status: "active" | "revoked";
|
||||
expiresAt?: string;
|
||||
note?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
}
|
||||
|
||||
export interface CreateEntitlementSnapshotInput {
|
||||
accountId: string;
|
||||
provider: Provider;
|
||||
scope: string;
|
||||
evaluatedAt: string;
|
||||
isAllowed: boolean;
|
||||
reasonCode: string;
|
||||
reasonDetail?: string;
|
||||
rawSummaryJson: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface CreateAuditEventInput {
|
||||
id?: string;
|
||||
accountId?: string;
|
||||
sessionId?: string;
|
||||
appSlug?: AppSlug;
|
||||
eventType: string;
|
||||
eventPayloadJson: Record<string, unknown>;
|
||||
createdAt: string;
|
||||
}
|
||||
|
||||
export interface HeimdallStore {
|
||||
ensureSchema(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
createAccount(input: CreateAccountInput): Promise<StoredAccount>;
|
||||
touchAccount(accountId: string, at: string, updates?: { displayName?: string; primaryEmail?: string }): Promise<void>;
|
||||
findAccountByLinkedIdentity(provider: Provider, providerUserId: string): Promise<StoredAccount | null>;
|
||||
upsertLinkedIdentity(input: UpsertLinkedIdentityInput): Promise<StoredLinkedIdentity>;
|
||||
listLinkedIdentitiesForAccount(accountId: string): Promise<LinkedIdentityInput[]>;
|
||||
createCapabilityGrant(input: CreateCapabilityGrantInput): Promise<StoredCapabilityGrant>;
|
||||
listActiveGrants(accountId: string, appSlug: AppSlug, at: string): Promise<StoredCapabilityGrant[]>;
|
||||
createSession(input: CreateSessionInput): Promise<StoredSession>;
|
||||
upsertEntitlementSnapshot(input: CreateEntitlementSnapshotInput): Promise<void>;
|
||||
createAuditEvent(input: CreateAuditEventInput): Promise<void>;
|
||||
}
|
||||
Loading…
Reference in a new issue