Joystick consent: the ask, typed refusal, receipts, and a signed-in grants page
Managed custody (callbackMint custody_only) now stops at a Heimdall page before the provider redirect. A decline or a provider access_denied is consent_refused (by viewer|provider), distinct from provider_error. A granted completion writes an append-only consent receipt with the asked and granted scopes and the digest of the wording shown. GET /v1/me/grants lists every grant and receipt of the signed-in account; revoking one strips the credential, so the app's next token request is refused, and writes a revocation receipt. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
a7cdf0fea7
commit
7ca4e2355f
13 changed files with 1112 additions and 86 deletions
384
src/app.ts
384
src/app.ts
|
|
@ -26,6 +26,7 @@ import {
|
|||
import { issueAccessClaim, type IssueAccessClaimInput } from "./claims.js";
|
||||
import { builtInAppProfiles, getAppProfile, isAllowedReturnOrigin, serializeAppProfile, admitsProviderForMode, callbackMint } from "./app-profiles.js";
|
||||
import { renderBrowserHandoffPage } from "./browser-handoff.js";
|
||||
import { consentDigest, grantViews, GRANTS_PATH, renderConsentPage, renderGrantsPage, type ConsentAsk } from "./consent.js";
|
||||
import { type HeimdallConfig, loadConfig } from "./config.js";
|
||||
import { createTokenCustody, type TokenCustody } from "./custody.js";
|
||||
import { grantFact } from "./facts.js";
|
||||
|
|
@ -37,7 +38,7 @@ import {
|
|||
type OAuthRuntimeRegistry,
|
||||
} from "./oauth.js";
|
||||
import { ManagedCredentialRefreshFailed, refreshManagedCredential } from "./managed-credential.js";
|
||||
import { buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js";
|
||||
import { authorizationScopes, buildAuthorizationUrl, providerCatalog, providerExpectedEnv } from "./providers.js";
|
||||
import { createRuntimeKeyMaterial, signJwt, verifyJwt } from "./signing.js";
|
||||
import { createStore, type HeimdallStore } from "./store/index.js";
|
||||
import {
|
||||
|
|
@ -809,6 +810,47 @@ async function resolveLinkAccount(
|
|||
return claims.account_id;
|
||||
}
|
||||
|
||||
/** The account a Heimdall access token for any app names, when the token and its session are live. */
|
||||
async function resolveAccessAccount(
|
||||
ctx: Pick<HeimdallRuntimeContext, "config" | "keys" | "store">,
|
||||
authorization: string | undefined
|
||||
): Promise<string | null> {
|
||||
const token = /^Bearer\s+(\S+)$/i.exec(authorization ?? "")?.[1];
|
||||
if (!token) return null;
|
||||
const verification = verifyJwt(token, ctx.keys.publicKey);
|
||||
if (!verification.valid) return null;
|
||||
const audience = verification.payload.aud;
|
||||
return isAppSlug(audience) ? resolveLinkAccount(ctx, audience, authorization) : null;
|
||||
}
|
||||
|
||||
const grantsPageTokenType = "heimdall_grants_page";
|
||||
const grantsPageTokenTtlSeconds = 600;
|
||||
|
||||
/** A short, purpose-bound proof of a signed-in account, so the grants page can be opened and its forms posted by a browser that holds no session. */
|
||||
function signGrantsPageToken(config: HeimdallConfig, keys: ReturnType<typeof createRuntimeKeyMaterial>, accountId: string): string {
|
||||
const iat = nowEpochSeconds();
|
||||
return signJwt({ typ: grantsPageTokenType, iss: config.issuer, account_id: accountId, iat, exp: iat + grantsPageTokenTtlSeconds }, keys);
|
||||
}
|
||||
|
||||
function grantsPageTokenAccount(config: HeimdallConfig, keys: ReturnType<typeof createRuntimeKeyMaterial>, token: unknown): string | null {
|
||||
if (typeof token !== "string") return null;
|
||||
const verification = verifyJwt(token, keys.publicKey);
|
||||
if (!verification.valid) return null;
|
||||
const { typ, iss, account_id: accountId, exp } = verification.payload;
|
||||
return typ === grantsPageTokenType && iss === config.issuer && typeof accountId === "string" && typeof exp === "number" && exp > nowEpochSeconds()
|
||||
? accountId
|
||||
: null;
|
||||
}
|
||||
|
||||
function consentAskFor(state: OAuthStatePayload): ConsentAsk {
|
||||
return {
|
||||
appSlug: state.app_slug,
|
||||
provider: state.provider,
|
||||
scopes: authorizationScopes(state.provider, state.requested_scopes ?? undefined),
|
||||
returnOrigin: new URL(state.return_to).origin,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Session refresh, extracted for the same reason as startOAuthFlow: the HTTP
|
||||
* route and the plane's `refreshAuth` (which owns Ghostlight identity) call
|
||||
|
|
@ -948,6 +990,10 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
credentials: true,
|
||||
});
|
||||
await app.register(cookie);
|
||||
// The consent and grants pages are plain HTML forms.
|
||||
app.addContentTypeParser("application/x-www-form-urlencoded", { parseAs: "string" }, (_request, body, done) => {
|
||||
done(null, Object.fromEntries(new URLSearchParams(body as string)));
|
||||
});
|
||||
|
||||
app.get("/healthz", async () => ({
|
||||
ok: true,
|
||||
|
|
@ -1126,6 +1172,106 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
return { error };
|
||||
};
|
||||
|
||||
const denyAttempt = async (state: OAuthStatePayload, denialCode: string): Promise<void> => {
|
||||
const handoff = state.handoff ?? { kind: "browser_completion" };
|
||||
if (handoff.kind !== "browser_completion" || !handoff.attemptId) return;
|
||||
await store.updateAuthAttempt(state.app_slug, handoff.attemptId, {
|
||||
status: "denied",
|
||||
at: new Date().toISOString(),
|
||||
denialCode,
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* The person said no, at Heimdall's ask (`viewer`) or at the provider
|
||||
* (`provider`, a returned access_denied). It is its own result, never a
|
||||
* provider_error: the app and the audit log can tell a refusal from a fault.
|
||||
* Nothing is stored beyond an audit row that names no one.
|
||||
*/
|
||||
const refuseConsent = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, by: "viewer" | "provider") => {
|
||||
const handoff = state.handoff ?? { kind: "browser_completion" };
|
||||
await denyAttempt(state, "consent_refused");
|
||||
await store.createAuditEvent({
|
||||
appSlug: state.app_slug,
|
||||
eventType: "consent_refused",
|
||||
eventPayloadJson: { provider: state.provider, mode: state.mode, by },
|
||||
createdAt: new Date().toISOString(),
|
||||
});
|
||||
if (handoff.kind === "backend_callback") {
|
||||
await maybeDeliverBackendHandoff(handoff, {
|
||||
source: "heimdall",
|
||||
kind: "oauth_result",
|
||||
handoffKind: "backend_callback",
|
||||
attemptId: handoff.attemptId,
|
||||
status: "error",
|
||||
provider: state.provider,
|
||||
appSlug: state.app_slug,
|
||||
mode: state.mode,
|
||||
returnTo: state.return_to,
|
||||
connection: state.connection,
|
||||
error: "consent_refused",
|
||||
by,
|
||||
});
|
||||
}
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(
|
||||
renderBrowserHandoffPage({
|
||||
handoffKind: handoff.kind,
|
||||
status: "error",
|
||||
provider: state.provider,
|
||||
appSlug: state.app_slug,
|
||||
mode: state.mode,
|
||||
returnTo: state.return_to,
|
||||
...(handoff.kind === "backend_callback" ? { attemptId: handoff.attemptId } : {}),
|
||||
error: "consent_refused",
|
||||
by,
|
||||
})
|
||||
);
|
||||
}
|
||||
reply.code(400);
|
||||
return { error: "consent_refused", by, provider: state.provider, returnTo: state.return_to };
|
||||
};
|
||||
|
||||
const providerNotConfigured = (reply: FastifyReply, state: OAuthStatePayload) => {
|
||||
reply.code(503);
|
||||
return { error: "provider_not_configured", provider: state.provider, expectedEnv: providerExpectedEnv(state.provider) };
|
||||
};
|
||||
|
||||
/** Claim the launch use, bind the browser, and send it to the provider. */
|
||||
const beginProviderRedirect = async (request: FastifyRequest, reply: FastifyReply, state: OAuthStatePayload, rawState: string) => {
|
||||
const clientId = config.providers[state.provider].clientId;
|
||||
if (!clientId) {
|
||||
return providerNotConfigured(reply, state);
|
||||
}
|
||||
const first = await store.claimOAuthStateUse({
|
||||
jti: state.jti,
|
||||
phase: "launch",
|
||||
appSlug: state.app_slug,
|
||||
usedAt: new Date().toISOString(),
|
||||
expiresAt: new Date(state.exp * 1000).toISOString(),
|
||||
});
|
||||
if (!first) {
|
||||
return refuseVerifiedState(request, reply, state, "state_already_launched");
|
||||
}
|
||||
|
||||
const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined;
|
||||
setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds());
|
||||
reply.header("Cache-Control", "no-store");
|
||||
reply.header("Referrer-Policy", "no-referrer");
|
||||
return reply.redirect(
|
||||
buildAuthorizationUrl({
|
||||
provider: state.provider,
|
||||
clientId,
|
||||
redirectUri: oauthCallbackUrl(config, state.provider),
|
||||
state: rawState,
|
||||
requestedScopes: state.requested_scopes ?? undefined,
|
||||
...(oidc ? { oidc: { nonce: oidc.nonce, codeChallenge: oidc.codeChallenge } } : {}),
|
||||
}),
|
||||
302
|
||||
);
|
||||
};
|
||||
|
||||
app.get<{
|
||||
Params: { provider: Provider };
|
||||
Querystring: { state: string };
|
||||
|
|
@ -1158,38 +1304,82 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
return { error: verified.error };
|
||||
}
|
||||
const state = verified.payload;
|
||||
const clientId = config.providers[state.provider].clientId;
|
||||
if (!clientId) {
|
||||
reply.code(503);
|
||||
return { error: "provider_not_configured", provider: state.provider, expectedEnv: providerExpectedEnv(state.provider) };
|
||||
const askProfile = getAppProfile(state.app_slug);
|
||||
if (askProfile && callbackMint(askProfile, state.provider, state.mode, state.connection) === "custody_only") {
|
||||
if (!config.providers[state.provider].clientId) {
|
||||
return providerNotConfigured(reply, state);
|
||||
}
|
||||
// Heimdall is about to hold a credential for the app: ask first. Viewing
|
||||
// the ask claims nothing; only Continue spends the launch use. The
|
||||
// binding cookie rides on the page so that the form's answer can only
|
||||
// come from the browser that was shown it.
|
||||
setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds());
|
||||
reply.header("Cache-Control", "no-store");
|
||||
reply.header("Referrer-Policy", "no-referrer");
|
||||
reply.header("X-Frame-Options", "DENY");
|
||||
reply.header(
|
||||
"Content-Security-Policy",
|
||||
`default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'self' ${new URL(providerCatalog[state.provider].authorizationEndpoint).origin}`
|
||||
);
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(renderConsentPage(consentAskFor(state), request.query.state));
|
||||
}
|
||||
return beginProviderRedirect(request, reply, state, request.query.state);
|
||||
}
|
||||
);
|
||||
|
||||
const first = await store.claimOAuthStateUse({
|
||||
jti: state.jti,
|
||||
phase: "launch",
|
||||
appSlug: state.app_slug,
|
||||
usedAt: new Date().toISOString(),
|
||||
expiresAt: new Date(state.exp * 1000).toISOString(),
|
||||
});
|
||||
if (!first) {
|
||||
app.post<{
|
||||
Params: { provider: Provider };
|
||||
Body: { state: string; decision: "continue" | "decline" };
|
||||
}>(
|
||||
"/v1/oauth/:provider/consent",
|
||||
{
|
||||
schema: {
|
||||
params: {
|
||||
type: "object",
|
||||
required: ["provider"],
|
||||
additionalProperties: false,
|
||||
properties: { provider: { type: "string", enum: [...providers] } },
|
||||
},
|
||||
body: {
|
||||
type: "object",
|
||||
required: ["state", "decision"],
|
||||
additionalProperties: false,
|
||||
properties: {
|
||||
state: { type: "string", minLength: 1 },
|
||||
decision: { type: "string", enum: ["continue", "decline"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const verified = verifyOAuthState(config, keys, request.body.state, request.params.provider);
|
||||
if (!verified.ok) {
|
||||
reply.code(400);
|
||||
return { error: verified.error };
|
||||
}
|
||||
const state = verified.payload;
|
||||
const profile = getAppProfile(state.app_slug);
|
||||
if (!profile || callbackMint(profile, state.provider, state.mode, state.connection) !== "custody_only") {
|
||||
reply.code(400);
|
||||
return { error: "consent_not_required" };
|
||||
}
|
||||
// Either answer must come from the browser the ask was shown to.
|
||||
if (!oauthBindingHolds(config, keys, request.cookies[oauthBindingCookieName(state.jti)], state)) {
|
||||
return refuseVerifiedState(request, reply, state, "state_not_bound");
|
||||
}
|
||||
if (request.body.decision === "continue") {
|
||||
return beginProviderRedirect(request, reply, state, request.body.state);
|
||||
}
|
||||
// A decline spends both uses of the state: it can neither launch nor complete afterwards.
|
||||
const usedAt = new Date().toISOString();
|
||||
const expiresAt = new Date(state.exp * 1000).toISOString();
|
||||
if (!(await store.claimOAuthStateUse({ jti: state.jti, phase: "launch", appSlug: state.app_slug, usedAt, expiresAt }))) {
|
||||
return refuseVerifiedState(request, reply, state, "state_already_launched");
|
||||
}
|
||||
|
||||
const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined;
|
||||
setOAuthBindingCookie(reply, state, signOAuthBinding(config, keys, state), state.exp - nowEpochSeconds());
|
||||
reply.header("Cache-Control", "no-store");
|
||||
reply.header("Referrer-Policy", "no-referrer");
|
||||
return reply.redirect(
|
||||
buildAuthorizationUrl({
|
||||
provider: state.provider,
|
||||
clientId,
|
||||
redirectUri: oauthCallbackUrl(config, state.provider),
|
||||
state: request.query.state,
|
||||
requestedScopes: state.requested_scopes ?? undefined,
|
||||
...(oidc ? { oidc: { nonce: oidc.nonce, codeChallenge: oidc.codeChallenge } } : {}),
|
||||
}),
|
||||
302
|
||||
);
|
||||
await store.claimOAuthStateUse({ jti: state.jti, phase: "callback", appSlug: state.app_slug, usedAt, expiresAt });
|
||||
setOAuthBindingCookie(reply, state, "", 0);
|
||||
return refuseConsent(request, reply, state, "viewer");
|
||||
}
|
||||
);
|
||||
|
||||
|
|
@ -1233,14 +1423,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
}
|
||||
const statePayload = verified.payload;
|
||||
const handoff = statePayload.handoff ?? { kind: "browser_completion" };
|
||||
const denyBrowserAttempt = async (denialCode: string): Promise<void> => {
|
||||
if (handoff.kind !== "browser_completion" || !handoff.attemptId) return;
|
||||
await store.updateAuthAttempt(statePayload.app_slug, handoff.attemptId, {
|
||||
status: "denied",
|
||||
at: new Date().toISOString(),
|
||||
denialCode,
|
||||
});
|
||||
};
|
||||
const denyBrowserAttempt = (denialCode: string): Promise<void> => denyAttempt(statePayload, denialCode);
|
||||
// The cookie is checked before the claim: a stranger without it must not be
|
||||
// able to burn the state that the browser that launched it still needs.
|
||||
// The attempt is denied, though: a launcher whose cookie lapsed can never
|
||||
|
|
@ -1262,6 +1445,9 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
return refuseVerifiedState(request, reply, statePayload, "state_already_used");
|
||||
}
|
||||
|
||||
if (request.query.error === "access_denied") {
|
||||
return refuseConsent(request, reply, statePayload, "provider");
|
||||
}
|
||||
if (request.query.error) {
|
||||
const providerError = relayedProviderText(request.query.error, 64);
|
||||
const providerErrorDescription = relayedProviderText(request.query.error_description, 256);
|
||||
|
|
@ -1519,6 +1705,24 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
|
||||
await store.upsertLinkedIdentity(buildLinkedIdentityInput(account.id));
|
||||
|
||||
// Heimdall now holds a credential the person was asked about: the
|
||||
// receipt is the record of that agreement, written with the credential.
|
||||
let consentReceiptId: string | undefined;
|
||||
if (mint === "custody_only") {
|
||||
const ask = consentAskFor(statePayload);
|
||||
const receipt = await store.createConsentReceipt({
|
||||
kind: "grant",
|
||||
accountId: account.id,
|
||||
appSlug: statePayload.app_slug,
|
||||
provider: identity.provider,
|
||||
createdAt: nowIso,
|
||||
scopesAsked: [...ask.scopes],
|
||||
scopesGranted: tokenSet.scope,
|
||||
consentPageDigest: consentDigest(ask),
|
||||
});
|
||||
consentReceiptId = receipt.id;
|
||||
}
|
||||
|
||||
const entitlementEvaluation = await runtime.evaluateEntitlements({
|
||||
config,
|
||||
callback: {
|
||||
|
|
@ -1613,6 +1817,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
entitlements: entitlementEvaluation,
|
||||
returnTo: statePayload.return_to,
|
||||
connection: statePayload.connection,
|
||||
...(consentReceiptId ? { consentReceiptId } : {}),
|
||||
...delivered,
|
||||
};
|
||||
if (handoff.kind === "backend_callback") {
|
||||
|
|
@ -1629,6 +1834,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
connection: statePayload.connection,
|
||||
account: accountSummary,
|
||||
entitlements: entitlementEvaluation,
|
||||
...(consentReceiptId ? { consentReceiptId } : {}),
|
||||
...delivered,
|
||||
});
|
||||
|
||||
|
|
@ -1658,6 +1864,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
attemptId: handoff.attemptId,
|
||||
...(consentReceiptId ? { consentReceiptId } : {}),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
|
@ -1731,6 +1938,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
mode: statePayload.mode,
|
||||
returnTo: statePayload.return_to,
|
||||
completionCode: completion.code,
|
||||
...(consentReceiptId ? { consentReceiptId } : {}),
|
||||
...(handoff.kind === "browser_completion" && handoff.attemptId
|
||||
? { attemptId: handoff.attemptId }
|
||||
: {}),
|
||||
|
|
@ -2296,5 +2504,107 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
|
|||
}
|
||||
);
|
||||
|
||||
const grantsAccount = async (request: FastifyRequest, pageToken?: unknown): Promise<string | null> =>
|
||||
(await resolveAccessAccount({ config, keys, store }, request.headers.authorization)) ??
|
||||
grantsPageTokenAccount(config, keys, pageToken);
|
||||
|
||||
const grantsReply = (reply: FastifyReply) => {
|
||||
reply.header("Cache-Control", "no-store");
|
||||
reply.header("Referrer-Policy", "no-referrer");
|
||||
reply.header("X-Frame-Options", "DENY");
|
||||
reply.header("Content-Security-Policy", "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'");
|
||||
};
|
||||
|
||||
const signInRequired = (reply: FastifyReply) => {
|
||||
reply.code(401);
|
||||
return { error: "sign_in_required", detail: "Send a Heimdall access token as a Bearer token, or open a link from POST /v1/me/grants/link." };
|
||||
};
|
||||
|
||||
// The signed-in surface for consent: every grant and receipt the account
|
||||
// holds, and the one-click way to take each back.
|
||||
app.get<{ Querystring: { t?: string } }>(
|
||||
GRANTS_PATH,
|
||||
{ schema: { querystring: { type: "object", additionalProperties: false, properties: { t: { type: "string" } } } } },
|
||||
async (request, reply) => {
|
||||
const accountId = await grantsAccount(request, request.query.t);
|
||||
if (!accountId) return signInRequired(reply);
|
||||
grantsReply(reply);
|
||||
const receipts = await store.listConsentReceipts(accountId);
|
||||
if (prefersHtml(request.headers.accept)) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
return reply.send(renderGrantsPage(grantViews(receipts), signGrantsPageToken(config, keys, accountId)));
|
||||
}
|
||||
return { grants: grantViews(receipts), receipts };
|
||||
}
|
||||
);
|
||||
|
||||
// A link a browser can open: short-lived, opens the grants page and nothing else.
|
||||
app.post(`${GRANTS_PATH}/link`, async (request, reply) => {
|
||||
const accountId = await resolveAccessAccount({ config, keys, store }, request.headers.authorization);
|
||||
if (!accountId) return signInRequired(reply);
|
||||
grantsReply(reply);
|
||||
reply.code(201);
|
||||
return {
|
||||
url: `${config.publicBaseUrl}${GRANTS_PATH}?t=${encodeURIComponent(signGrantsPageToken(config, keys, accountId))}`,
|
||||
expiresInSeconds: grantsPageTokenTtlSeconds,
|
||||
};
|
||||
});
|
||||
|
||||
app.post<{ Params: { grantId: string }; Body?: { t?: string } }>(
|
||||
`${GRANTS_PATH}/:grantId/revoke`,
|
||||
{
|
||||
schema: {
|
||||
params: { type: "object", required: ["grantId"], additionalProperties: false, properties: { grantId: { type: "string", minLength: 1 } } },
|
||||
body: { type: ["object", "null"], additionalProperties: false, properties: { t: { type: "string" } } },
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const accountId = await grantsAccount(request, request.body?.t);
|
||||
if (!accountId) return signInRequired(reply);
|
||||
grantsReply(reply);
|
||||
const receipts = await store.listConsentReceipts(accountId);
|
||||
const grant = grantViews(receipts).find((view) => view.id === request.params.grantId);
|
||||
if (!grant) {
|
||||
reply.code(404);
|
||||
return { error: "grant_not_found" };
|
||||
}
|
||||
const revoked: string[] = [];
|
||||
if (grant.status === "active") {
|
||||
// The credential is one row per account and provider, whichever app
|
||||
// asked, so taking it back ends every live grant that rests on it.
|
||||
// It is stripped first: a failure after that leaves a receipt that
|
||||
// still reads active over a credential that is gone, never the reverse.
|
||||
const identity = await store.findStoredLinkedIdentityForAccount(accountId, grant.provider);
|
||||
const at = new Date().toISOString();
|
||||
if (identity) {
|
||||
await store.updateLinkedIdentityCredential(identity.id, async () => ({ kind: "revoke", updatedAt: at }));
|
||||
}
|
||||
for (const live of grantViews(receipts).filter((view) => view.provider === grant.provider && view.status === "active")) {
|
||||
await store.createConsentReceipt({
|
||||
kind: "revocation",
|
||||
accountId,
|
||||
appSlug: live.appSlug,
|
||||
provider: live.provider,
|
||||
createdAt: at,
|
||||
revokesReceiptId: live.id,
|
||||
});
|
||||
revoked.push(live.id);
|
||||
}
|
||||
await store.createAuditEvent({
|
||||
accountId,
|
||||
eventType: "consent_revoked",
|
||||
eventPayloadJson: { provider: grant.provider, grantIds: revoked },
|
||||
createdAt: at,
|
||||
});
|
||||
}
|
||||
if (prefersHtml(request.headers.accept) || request.headers["content-type"]?.startsWith("application/x-www-form-urlencoded")) {
|
||||
reply.type("text/html; charset=utf-8");
|
||||
const views = grantViews(await store.listConsentReceipts(accountId));
|
||||
return reply.send(renderGrantsPage(views, signGrantsPageToken(config, keys, accountId), revoked.length ? "Taken back." : "Already taken back."));
|
||||
}
|
||||
return { revoked, grants: grantViews(await store.listConsentReceipts(accountId)) };
|
||||
}
|
||||
);
|
||||
|
||||
return app;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -30,6 +30,8 @@ export interface BackendHandoffSuccessPayload
|
|||
mode: OAuthMode;
|
||||
account: AccountSummary;
|
||||
entitlements: EntitlementEvaluation;
|
||||
/** The receipt of the consent a managed connection rests on. */
|
||||
consentReceiptId?: string;
|
||||
}
|
||||
|
||||
export interface BackendHandoffErrorPayload extends BackendHandoffBase {
|
||||
|
|
@ -37,6 +39,8 @@ export interface BackendHandoffErrorPayload extends BackendHandoffBase {
|
|||
mode?: OAuthMode;
|
||||
error: string;
|
||||
errorDescription?: string;
|
||||
/** Who said no, when `error` is consent_refused. */
|
||||
by?: "viewer" | "provider";
|
||||
}
|
||||
|
||||
/** A verified link that waits for the initiating account's confirm: no session, no tokens. */
|
||||
|
|
|
|||
|
|
@ -15,6 +15,8 @@ export interface BrowserHandoffSuccess extends BrowserHandoffBase {
|
|||
/** A verified link waiting for its initiator's confirm; carries no session. */
|
||||
pendingLinkId?: string;
|
||||
attemptId?: string;
|
||||
/** The receipt of the consent a managed connection rests on. */
|
||||
consentReceiptId?: string;
|
||||
}
|
||||
|
||||
export interface BrowserHandoffError extends BrowserHandoffBase {
|
||||
|
|
@ -22,6 +24,8 @@ export interface BrowserHandoffError extends BrowserHandoffBase {
|
|||
error: string;
|
||||
errorDescription?: string;
|
||||
attemptId?: string;
|
||||
/** Who said no, when `error` is consent_refused. */
|
||||
by?: "viewer" | "provider";
|
||||
}
|
||||
|
||||
export type BrowserHandoffPayload = BrowserHandoffSuccess | BrowserHandoffError;
|
||||
|
|
@ -47,6 +51,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string {
|
|||
fragment.set("heimdall_attempt_id", payload.attemptId);
|
||||
}
|
||||
|
||||
if (payload.status === "success" && payload.consentReceiptId) {
|
||||
fragment.set("heimdall_consent_receipt_id", payload.consentReceiptId);
|
||||
}
|
||||
if (payload.status === "success" && payload.completionCode) {
|
||||
fragment.set("heimdall_completion_code", payload.completionCode);
|
||||
} else if (payload.status === "success" && payload.pendingLinkId) {
|
||||
|
|
@ -54,6 +61,9 @@ function buildBrowserFallbackUrl(payload: BrowserHandoffPayload): string {
|
|||
} else {
|
||||
if (payload.status === "error") {
|
||||
fragment.set("heimdall_error", payload.error);
|
||||
if (payload.by) {
|
||||
fragment.set("heimdall_refused_by", payload.by);
|
||||
}
|
||||
if (payload.errorDescription) {
|
||||
fragment.set("heimdall_error_description", payload.errorDescription);
|
||||
}
|
||||
|
|
@ -77,14 +87,19 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string
|
|||
});
|
||||
const scriptOrigin = serializeForScript(targetOrigin);
|
||||
const scriptFallbackUrl = serializeForScript(fallbackUrl);
|
||||
const scriptTitle = serializeForScript(
|
||||
payload.status === "success" ? "Authentication Complete" : "Authentication Failed"
|
||||
);
|
||||
const refused = payload.status === "error" && payload.error === "consent_refused";
|
||||
const pageTitle = refused ? "Not Connected" : payload.status === "success" ? "Authentication Complete" : "Authentication Failed";
|
||||
const scriptTitle = serializeForScript(pageTitle);
|
||||
const scriptBody = serializeForScript(
|
||||
payload.status === "success"
|
||||
? payload.handoffKind === "backend_callback"
|
||||
? "The app backend has the auth result already. You can return to the app now."
|
||||
: "You can return to the app now."
|
||||
refused
|
||||
? "Nothing was connected and nothing was kept. You can return to the app."
|
||||
: payload.status === "success"
|
||||
? (payload.handoffKind === "backend_callback"
|
||||
? "The app backend has the auth result already. You can return to the app now."
|
||||
: "You can return to the app now.") +
|
||||
(payload.consentReceiptId
|
||||
? ` Your consent is recorded as receipt ${payload.consentReceiptId}; you can review it and take it back from your Heimdall connections page.`
|
||||
: "")
|
||||
: "The authentication flow failed. Return to the app to continue."
|
||||
);
|
||||
|
||||
|
|
@ -93,7 +108,7 @@ export function renderBrowserHandoffPage(payload: BrowserHandoffPayload): string
|
|||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${payload.status === "success" ? "Authentication Complete" : "Authentication Failed"}</title>
|
||||
<title>${pageTitle}</title>
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: light dark;
|
||||
|
|
|
|||
170
src/consent.ts
Normal file
170
src/consent.ts
Normal file
|
|
@ -0,0 +1,170 @@
|
|||
import { createHash } from "node:crypto";
|
||||
import { type AppSlug, type Provider } from "./contracts.js";
|
||||
import { getAppProfile } from "./app-profiles.js";
|
||||
import { providerCatalog } from "./providers.js";
|
||||
import { type StoredConsentReceipt } from "./store/index.js";
|
||||
|
||||
/**
|
||||
* What Heimdall tells a person before it holds a provider credential for an
|
||||
* app, and the page that lists what they agreed to. The wording is built from
|
||||
* the facts the code holds (the app, the provider, the scopes sent), never
|
||||
* from a promise the code does not keep. Any change to a line changes the
|
||||
* digest every later receipt carries, so a reader can tell which wording a
|
||||
* person saw.
|
||||
*/
|
||||
|
||||
export interface ConsentAsk {
|
||||
appSlug: AppSlug;
|
||||
provider: Provider;
|
||||
/** The scopes Heimdall will send the provider. */
|
||||
scopes: readonly string[];
|
||||
/** The origin the person returns to afterwards. */
|
||||
returnOrigin: string;
|
||||
}
|
||||
|
||||
export const GRANTS_PATH = "/v1/me/grants";
|
||||
|
||||
function appName(slug: AppSlug): string {
|
||||
return getAppProfile(slug)?.displayName ?? slug;
|
||||
}
|
||||
|
||||
/** The exact lines shown on the ask, apart from the two buttons. The digest is over these. */
|
||||
export function consentLines(ask: ConsentAsk): string[] {
|
||||
const app = appName(ask.appSlug);
|
||||
const provider = providerCatalog[ask.provider].displayName;
|
||||
return [
|
||||
`${app} asks Heimdall to hold a connection to your ${provider} account.`,
|
||||
`Heimdall will ask ${provider} for these permissions: ${ask.scopes.join(", ")}.`,
|
||||
`Heimdall keeps an encrypted refresh token and access token for this connection until you take it back or ${provider} ends it.`,
|
||||
`${app}'s server can ask Heimdall for a current access token and use it for those permissions. It never receives the refresh token.`,
|
||||
`If you say no, nothing is kept.`,
|
||||
`You can take this back at any time. Heimdall then deletes its copy of the tokens and stops handing out access tokens. The permission stays with ${provider} until you remove it in your ${provider} settings.`,
|
||||
`Afterwards you are returned to ${ask.returnOrigin}.`,
|
||||
];
|
||||
}
|
||||
|
||||
export function consentDigest(ask: ConsentAsk): string {
|
||||
return createHash("sha256").update(consentLines(ask).join("\n"), "utf8").digest("hex");
|
||||
}
|
||||
|
||||
export function escapeHtml(value: string): string {
|
||||
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """).replace(/'/g, "'");
|
||||
}
|
||||
|
||||
const pageStyle = `
|
||||
:root { color-scheme: light dark; font-family: ui-sans-serif, system-ui, sans-serif; }
|
||||
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #11161d; color: #f4f7fb; }
|
||||
main { width: min(38rem, calc(100vw - 2rem)); border-radius: 1rem; padding: 1.5rem; background: rgba(20, 27, 36, 0.96); box-shadow: 0 24px 60px rgba(0, 0, 0, 0.3); }
|
||||
h1 { margin: 0 0 0.75rem; font-size: 1.35rem; }
|
||||
p, li { line-height: 1.5; color: #d5dce6; }
|
||||
ul { padding-left: 1.2rem; }
|
||||
code { color: #d8eefe; }
|
||||
button { font: inherit; font-weight: 600; border: 0; border-radius: 999px; padding: 0.75rem 1rem; margin: 0.25rem 0.5rem 0.25rem 0; cursor: pointer; }
|
||||
button.go { color: #11161d; background: #d8eefe; }
|
||||
button.no { color: #f4f7fb; background: #2c3745; }
|
||||
section { border-top: 1px solid #2c3745; padding: 0.75rem 0; }
|
||||
small { color: #9aacbe; }`;
|
||||
|
||||
function page(title: string, body: string): string {
|
||||
return `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${escapeHtml(title)}</title>
|
||||
<style>${pageStyle}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
${body}
|
||||
</main>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
/** The ask. Two POST forms carry the signed state; the page runs no script. */
|
||||
export function renderConsentPage(ask: ConsentAsk, state: string): string {
|
||||
const lines = consentLines(ask);
|
||||
const provider = providerCatalog[ask.provider].displayName;
|
||||
const [headline, ...rest] = lines;
|
||||
const form = (decision: "continue" | "decline", label: string) =>
|
||||
`<button class="${decision === "continue" ? "go" : "no"}" type="submit" name="decision" value="${decision}">${escapeHtml(label)}</button>`;
|
||||
return page(
|
||||
`${appName(ask.appSlug)} wants to connect ${provider}`,
|
||||
` <h1>${escapeHtml(headline!)}</h1>
|
||||
<ul>
|
||||
${rest.map((line) => ` <li>${escapeHtml(line)}</li>`).join("\n")}
|
||||
</ul>
|
||||
<form method="post" action="/v1/oauth/${ask.provider}/consent">
|
||||
<input type="hidden" name="state" value="${escapeHtml(state)}">
|
||||
${form("continue", `Continue to ${provider}`)}
|
||||
${form("decline", "No, return to the app")}
|
||||
</form>`
|
||||
);
|
||||
}
|
||||
|
||||
export interface GrantView {
|
||||
id: string;
|
||||
appSlug: AppSlug;
|
||||
provider: Provider;
|
||||
scopesAsked: string[];
|
||||
scopesGranted: string[];
|
||||
grantedAt: string;
|
||||
consentPageDigest: string;
|
||||
status: "active" | "revoked";
|
||||
revokedAt?: string;
|
||||
revocationReceiptId?: string;
|
||||
}
|
||||
|
||||
/** Every grant the receipts hold, each live unless a revocation names it. */
|
||||
export function grantViews(receipts: readonly StoredConsentReceipt[]): GrantView[] {
|
||||
const revocations = new Map<string, StoredConsentReceipt & { kind: "revocation" }>();
|
||||
for (const receipt of receipts) {
|
||||
if (receipt.kind === "revocation") revocations.set(receipt.revokesReceiptId, receipt);
|
||||
}
|
||||
const views: GrantView[] = [];
|
||||
for (const receipt of receipts) {
|
||||
if (receipt.kind !== "grant") continue;
|
||||
const revocation = revocations.get(receipt.id);
|
||||
views.push({
|
||||
id: receipt.id,
|
||||
appSlug: receipt.appSlug,
|
||||
provider: receipt.provider,
|
||||
scopesAsked: receipt.scopesAsked,
|
||||
scopesGranted: receipt.scopesGranted,
|
||||
grantedAt: receipt.createdAt,
|
||||
consentPageDigest: receipt.consentPageDigest,
|
||||
status: revocation ? "revoked" : "active",
|
||||
...(revocation ? { revokedAt: revocation.createdAt, revocationReceiptId: revocation.id } : {}),
|
||||
});
|
||||
}
|
||||
return views;
|
||||
}
|
||||
|
||||
/** The signed-in page: every grant with its receipt, one button each to take it back. */
|
||||
export function renderGrantsPage(grants: readonly GrantView[], pageToken: string, notice?: string): string {
|
||||
const cards = grants.length
|
||||
? grants
|
||||
.map((grant) => {
|
||||
const provider = providerCatalog[grant.provider].displayName;
|
||||
const header = `${escapeHtml(appName(grant.appSlug))} → ${escapeHtml(provider)}`;
|
||||
const detail = `granted ${escapeHtml(grant.grantedAt)}; permissions ${escapeHtml(grant.scopesGranted.join(", ") || "none returned")}; receipt <code>${escapeHtml(grant.id)}</code>; wording <code>${escapeHtml(grant.consentPageDigest.slice(0, 12))}</code>`;
|
||||
if (grant.status === "revoked") {
|
||||
return ` <section><strong>${header}</strong> <small>taken back ${escapeHtml(grant.revokedAt ?? "")}; receipt <code>${escapeHtml(grant.revocationReceiptId ?? "")}</code></small><br><small>${detail}</small></section>`;
|
||||
}
|
||||
return ` <section><strong>${header}</strong> <small>active</small><br><small>${detail}</small>
|
||||
<form method="post" action="${GRANTS_PATH}/${escapeHtml(grant.id)}/revoke">
|
||||
<input type="hidden" name="t" value="${escapeHtml(pageToken)}">
|
||||
<button class="no" type="submit">Take this back</button>
|
||||
</form></section>`;
|
||||
})
|
||||
.join("\n")
|
||||
: ` <p>You have not connected anything through Heimdall.</p>`;
|
||||
return page(
|
||||
"Your connections",
|
||||
` <h1>Your connections</h1>
|
||||
${notice ? ` <p><strong>${escapeHtml(notice)}</strong></p>\n` : ""}${cards}
|
||||
<p><small>Taking a connection back deletes Heimdall's copy of the tokens. The app's next request for a token is refused. The permission stays with the provider until you remove it in the provider's settings.</small></p>`
|
||||
);
|
||||
}
|
||||
|
|
@ -167,6 +167,11 @@ export const providerCatalog: Record<Provider, ProviderDescriptor> = {
|
|||
},
|
||||
};
|
||||
|
||||
/** The scopes an authorization request carries: the caller's, or the provider's defaults. */
|
||||
export function authorizationScopes(provider: Provider, requested: readonly string[] | undefined): string[] {
|
||||
return requested?.length ? [...requested] : [...providerCatalog[provider].defaultScopes];
|
||||
}
|
||||
|
||||
export function buildAuthorizationUrl(options: {
|
||||
provider: Provider;
|
||||
clientId: string;
|
||||
|
|
@ -178,7 +183,7 @@ export function buildAuthorizationUrl(options: {
|
|||
}): string {
|
||||
const descriptor = providerCatalog[options.provider];
|
||||
const url = new URL(descriptor.authorizationEndpoint);
|
||||
const scopes = options.requestedScopes?.length ? options.requestedScopes : descriptor.defaultScopes;
|
||||
const scopes = authorizationScopes(options.provider, options.requestedScopes);
|
||||
|
||||
url.searchParams.set("client_id", options.clientId);
|
||||
url.searchParams.set("redirect_uri", options.redirectUri);
|
||||
|
|
|
|||
|
|
@ -5,7 +5,9 @@ import {
|
|||
type CreateAuthAttemptInput,
|
||||
type ClaimOAuthStateUseInput,
|
||||
type CreateAuthCompletionInput,
|
||||
type CreateConsentReceiptInput,
|
||||
type CreatePendingLinkInput,
|
||||
type StoredConsentReceipt,
|
||||
type StoredPendingLink,
|
||||
type CreateAuditEventInput,
|
||||
type CreateCapabilityGrantInput,
|
||||
|
|
@ -59,6 +61,7 @@ export class InMemoryStore implements HeimdallStore {
|
|||
private readonly oauthStateUses = new Map<string, string>();
|
||||
private readonly entitlementSnapshots = new Map<string, CreateEntitlementSnapshotInput>();
|
||||
private readonly auditEvents = new Map<string, CreateAuditEventInput>();
|
||||
private readonly consentReceipts: StoredConsentReceipt[] = [];
|
||||
|
||||
async ensureSchema(): Promise<void> {
|
||||
return;
|
||||
|
|
@ -482,4 +485,14 @@ export class InMemoryStore implements HeimdallStore {
|
|||
});
|
||||
this.auditEvents.set(event.id ?? randomUUID(), event);
|
||||
}
|
||||
|
||||
async createConsentReceipt(input: CreateConsentReceiptInput): Promise<StoredConsentReceipt> {
|
||||
const receipt = { id: randomUUID(), ...clone(input) } as StoredConsentReceipt;
|
||||
this.consentReceipts.push(clone(receipt));
|
||||
return clone(receipt);
|
||||
}
|
||||
|
||||
async listConsentReceipts(accountId: string): Promise<StoredConsentReceipt[]> {
|
||||
return this.consentReceipts.filter((receipt) => receipt.accountId === accountId).map(clone);
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -7,7 +7,9 @@ import {
|
|||
type CreateAuthAttemptInput,
|
||||
type ClaimOAuthStateUseInput,
|
||||
type CreateAuthCompletionInput,
|
||||
type CreateConsentReceiptInput,
|
||||
type CreatePendingLinkInput,
|
||||
type StoredConsentReceipt,
|
||||
type StoredPendingLink,
|
||||
type CreateAuditEventInput,
|
||||
type CreateCapabilityGrantInput,
|
||||
|
|
@ -248,6 +250,39 @@ function mapSessionRow(row: SessionRow): StoredSession {
|
|||
};
|
||||
}
|
||||
|
||||
interface ConsentReceiptRow {
|
||||
id: string;
|
||||
kind: "grant" | "revocation";
|
||||
account_id: string;
|
||||
app_slug: AppSlug;
|
||||
provider: Provider;
|
||||
created_at: Date | string;
|
||||
scopes_asked: string | null;
|
||||
scopes_granted: string | null;
|
||||
consent_page_digest: string | null;
|
||||
revokes_receipt_id: string | null;
|
||||
}
|
||||
|
||||
function mapConsentReceiptRow(row: ConsentReceiptRow): StoredConsentReceipt {
|
||||
const base = {
|
||||
id: row.id,
|
||||
accountId: row.account_id,
|
||||
appSlug: row.app_slug,
|
||||
provider: row.provider,
|
||||
createdAt: normalizeTimestamp(row.created_at),
|
||||
};
|
||||
if (row.kind === "revocation") {
|
||||
return { ...base, kind: "revocation", revokesReceiptId: row.revokes_receipt_id ?? "" };
|
||||
}
|
||||
return {
|
||||
...base,
|
||||
kind: "grant",
|
||||
scopesAsked: parseScopes(row.scopes_asked ?? ""),
|
||||
scopesGranted: parseScopes(row.scopes_granted ?? ""),
|
||||
consentPageDigest: row.consent_page_digest ?? "",
|
||||
};
|
||||
}
|
||||
|
||||
function mapPendingLinkRow(row: PendingLinkRow): StoredPendingLink {
|
||||
const link: StoredPendingLink = {
|
||||
id: row.id,
|
||||
|
|
@ -421,6 +456,7 @@ export const STORE_TABLE_PRIVILEGES: Readonly<Record<string, readonly ("SELECT"
|
|||
oauth_state_uses: ["INSERT"],
|
||||
capability_grants: ["SELECT", "INSERT"],
|
||||
entitlement_snapshots: ["SELECT", "INSERT", "UPDATE"],
|
||||
consent_receipts: ["SELECT", "INSERT"],
|
||||
audit_events: ["INSERT"],
|
||||
};
|
||||
|
||||
|
|
@ -1196,6 +1232,41 @@ export class PostgresStore implements HeimdallStore {
|
|||
);
|
||||
}
|
||||
|
||||
async createConsentReceipt(input: CreateConsentReceiptInput): Promise<StoredConsentReceipt> {
|
||||
const grant = input.kind === "grant" ? input : null;
|
||||
const result = await this.pool.query<ConsentReceiptRow>(
|
||||
`
|
||||
INSERT INTO consent_receipts (
|
||||
id, kind, account_id, app_slug, provider, created_at,
|
||||
scopes_asked, scopes_granted, consent_page_digest, revokes_receipt_id
|
||||
)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)
|
||||
RETURNING *
|
||||
`,
|
||||
[
|
||||
randomUUID(),
|
||||
input.kind,
|
||||
input.accountId,
|
||||
input.appSlug,
|
||||
input.provider,
|
||||
input.createdAt,
|
||||
grant ? grant.scopesAsked.join(" ") : null,
|
||||
grant ? grant.scopesGranted.join(" ") : null,
|
||||
grant ? grant.consentPageDigest : null,
|
||||
input.kind === "revocation" ? input.revokesReceiptId : null,
|
||||
]
|
||||
);
|
||||
return mapConsentReceiptRow(expectRow(result.rows[0], "createConsentReceipt"));
|
||||
}
|
||||
|
||||
async listConsentReceipts(accountId: string): Promise<StoredConsentReceipt[]> {
|
||||
const result = await this.pool.query<ConsentReceiptRow>(
|
||||
`SELECT * FROM consent_receipts WHERE account_id = $1 ORDER BY created_at, id`,
|
||||
[accountId]
|
||||
);
|
||||
return result.rows.map(mapConsentReceiptRow);
|
||||
}
|
||||
|
||||
async createAuditEvent(input: CreateAuditEventInput): Promise<void> {
|
||||
await this.pool.query(
|
||||
`
|
||||
|
|
|
|||
|
|
@ -180,6 +180,24 @@ CREATE TABLE IF NOT EXISTS entitlement_snapshots (
|
|||
UNIQUE(account_id, provider, scope)
|
||||
);
|
||||
|
||||
-- Consent receipts are append-only (the store role has INSERT and SELECT
|
||||
-- only): a revocation is a row that names the grant it takes back.
|
||||
CREATE TABLE IF NOT EXISTS consent_receipts (
|
||||
id TEXT PRIMARY KEY,
|
||||
kind TEXT NOT NULL,
|
||||
account_id TEXT NOT NULL REFERENCES accounts(id) ON DELETE CASCADE,
|
||||
app_slug TEXT NOT NULL,
|
||||
provider TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
scopes_asked TEXT,
|
||||
scopes_granted TEXT,
|
||||
consent_page_digest TEXT,
|
||||
revokes_receipt_id TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS consent_receipts_account_idx
|
||||
ON consent_receipts(account_id, created_at);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS audit_events (
|
||||
id TEXT PRIMARY KEY,
|
||||
account_id TEXT,
|
||||
|
|
|
|||
|
|
@ -252,6 +252,31 @@ export interface StoredPrivateCommandReceipt {
|
|||
|
||||
export type CreatePrivateCommandReceiptInput = StoredPrivateCommandReceipt;
|
||||
|
||||
/**
|
||||
* What a person agreed to, or took back. Append-only: a grant row is never
|
||||
* edited, and a revocation is a second row naming it, so a grant is live
|
||||
* exactly when no revocation names it. `scopesAsked` is what Heimdall sent the
|
||||
* provider, `scopesGranted` what the provider returned, `consentPageDigest`
|
||||
* the hash of the wording the person was shown.
|
||||
*/
|
||||
export type StoredConsentReceipt = {
|
||||
id: string;
|
||||
accountId: string;
|
||||
appSlug: AppSlug;
|
||||
provider: Provider;
|
||||
createdAt: string;
|
||||
} & (
|
||||
| { kind: "grant"; scopesAsked: string[]; scopesGranted: string[]; consentPageDigest: string }
|
||||
| { kind: "revocation"; revokesReceiptId: string }
|
||||
);
|
||||
|
||||
/** The store mints `id`; a caller cannot choose it. */
|
||||
export type CreateConsentReceiptInput = StoredConsentReceipt extends infer R
|
||||
? R extends StoredConsentReceipt
|
||||
? Omit<R, "id">
|
||||
: never
|
||||
: never;
|
||||
|
||||
export interface HeimdallStore {
|
||||
ensureSchema(): Promise<void>;
|
||||
close(): Promise<void>;
|
||||
|
|
@ -325,4 +350,7 @@ export interface HeimdallStore {
|
|||
*/
|
||||
claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean>;
|
||||
createAuditEvent(input: CreateAuditEventInput): Promise<void>;
|
||||
createConsentReceipt(input: CreateConsentReceiptInput): Promise<StoredConsentReceipt>;
|
||||
/** Every receipt the account holds, oldest first. */
|
||||
listConsentReceipts(accountId: string): Promise<StoredConsentReceipt[]>;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue