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[]>;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,62 +1,441 @@
|
|||
import { afterEach, describe, expect, it } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { type FastifyInstance } from "fastify";
|
||||
import { buildApp } from "../src/app.js";
|
||||
import { createTestConfig } from "./oauth-flow.js";
|
||||
import { consentDigest, consentLines, type ConsentAsk } from "../src/consent.js";
|
||||
import { type OAuthProviderRuntime } from "../src/oauth.js";
|
||||
import { providerCatalog } from "../src/providers.js";
|
||||
import { InMemoryStore } from "../src/store/index.js";
|
||||
import { createTestConfig, setCookieOf, stateOf } from "./oauth-flow.js";
|
||||
|
||||
// SKETCH for docs/joystick-consent-flow.md. Skipped: every test here names a
|
||||
// behaviour the consent cut must build. Remove `.skip` as each one lands.
|
||||
// The consent cut for managed custody (docs/joystick-consent-flow.md): the ask,
|
||||
// the typed refusal, the receipt, and the signed-in page that lists and revokes.
|
||||
|
||||
const apps: FastifyInstance[] = [];
|
||||
afterEach(async () => {
|
||||
vi.restoreAllMocks();
|
||||
while (apps.length) await apps.pop()?.close();
|
||||
});
|
||||
|
||||
async function creatorConnectStart(app: FastifyInstance) {
|
||||
const defaultScopes = providerCatalog.joystick.defaultScopes;
|
||||
const secret = { "x-heimdall-app-secret": "streampixels-secret" };
|
||||
const form = { "content-type": "application/x-www-form-urlencoded" };
|
||||
|
||||
/** A Joystick that returns whatever `code-<user>` names, granting only `granted`. */
|
||||
function joystick(granted: string[] = ["identity:read", "stream:read"]): OAuthProviderRuntime {
|
||||
return {
|
||||
async exchangeAuthorizationCode({ code }) {
|
||||
return { accessToken: `joy-access-${code}`, refreshToken: `joy-refresh-${code}`, tokenType: "Bearer", scope: granted, expiresAt: "2099-01-01T00:00:00.000Z", raw: {} };
|
||||
},
|
||||
async resolveIdentity({ accessToken }) {
|
||||
const id = accessToken.replace("joy-access-code-", "");
|
||||
return { provider: "joystick", providerUserId: `joy-${id}`, username: id, profile: { id } };
|
||||
},
|
||||
async evaluateEntitlements() {
|
||||
return { facts: [], snapshots: [] };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function newApp(options: { granted?: string[]; callbacks?: string[] } = {}) {
|
||||
const store = new InMemoryStore();
|
||||
const config = createTestConfig();
|
||||
if (options.callbacks) config.appBackendCallbacks = { streampixels: options.callbacks };
|
||||
const app = await buildApp({ config, store, oauthRuntimes: { joystick: joystick(options.granted) } });
|
||||
apps.push(app);
|
||||
return { app, store };
|
||||
}
|
||||
|
||||
async function startConnect(app: FastifyInstance, handoff: Record<string, unknown> = { kind: "browser_completion" }) {
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/joystick/start",
|
||||
headers: { "x-heimdall-app-secret": "streampixels-secret" },
|
||||
headers: secret,
|
||||
payload: {
|
||||
appSlug: "streampixels",
|
||||
mode: "connect",
|
||||
connection: { kind: "creator", targetId: "creator-1" },
|
||||
returnTo: "https://streampixels.gamecult.org/settings",
|
||||
handoff: { kind: "browser_completion" },
|
||||
handoff,
|
||||
},
|
||||
});
|
||||
expect(response.statusCode).toBe(201);
|
||||
const url = new URL(response.json().authorizationUrl as string);
|
||||
return `${url.pathname}${url.search}`;
|
||||
return stateOf(response.json());
|
||||
}
|
||||
|
||||
describe.skip("Joystick consent flow (draft)", () => {
|
||||
it("launch shows a Heimdall ask naming app, provider and scopes, and does not redirect", async () => {
|
||||
const app = await buildApp({ config: createTestConfig() });
|
||||
apps.push(app);
|
||||
const launch = await app.inject({ method: "GET", url: await creatorConnectStart(app), headers: { accept: "text/html" } });
|
||||
expect(launch.statusCode).toBe(200);
|
||||
expect(launch.headers.location).toBeUndefined();
|
||||
for (const needle of ["StreamPixels", "Joystick", "identity:read", "subscribers:read", "refresh token"]) {
|
||||
expect(launch.body).toContain(needle);
|
||||
const launchUrl = (state: string) => `/v1/oauth/joystick/launch?state=${encodeURIComponent(state)}`;
|
||||
const cookieOf = (response: { headers: Record<string, unknown> }) =>
|
||||
setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-"))!.split(";")[0]!;
|
||||
|
||||
/** The browser is shown the ask. */
|
||||
async function seeAsk(app: FastifyInstance, state: string) {
|
||||
const response = await app.inject({ method: "GET", url: launchUrl(state), headers: { accept: "text/html" } });
|
||||
expect(response.statusCode).toBe(200);
|
||||
return { page: response, cookie: cookieOf(response) };
|
||||
}
|
||||
|
||||
function answer(app: FastifyInstance, state: string, decision: "continue" | "decline", cookie?: string, accept = "text/html") {
|
||||
return app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/joystick/consent",
|
||||
headers: { ...form, accept, ...(cookie ? { cookie } : {}) },
|
||||
payload: new URLSearchParams({ state, decision }).toString(),
|
||||
});
|
||||
}
|
||||
|
||||
function callback(app: FastifyInstance, state: string, cookie: string, query: string, accept = "application/json") {
|
||||
return app.inject({
|
||||
method: "GET",
|
||||
url: `/v1/oauth/joystick/callback?state=${encodeURIComponent(state)}&${query}`,
|
||||
headers: { cookie, accept },
|
||||
});
|
||||
}
|
||||
|
||||
/** Ask, accept, and complete as Joystick user `user`; returns the callback's JSON. */
|
||||
async function grantAs(app: FastifyInstance, user: string) {
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
const go = await answer(app, state, "continue", cookie);
|
||||
expect(go.statusCode).toBe(302);
|
||||
const done = await callback(app, state, cookie, `code=code-${user}`);
|
||||
expect(done.statusCode).toBe(201);
|
||||
return done.json() as { accessToken: string; consentReceiptId: string; account: { id: string }; session: { accountId: string } };
|
||||
}
|
||||
|
||||
const bearer = (token: string) => ({ authorization: `Bearer ${token}` });
|
||||
const grantsOf = async (app: FastifyInstance, token: string) =>
|
||||
(await app.inject({ method: "GET", url: "/v1/me/grants", headers: bearer(token) })).json() as { grants: Array<Record<string, any>>; receipts: Array<Record<string, any>> };
|
||||
const resolveCredential = (app: FastifyInstance, accountId: string) =>
|
||||
app.inject({ method: "POST", url: "/v1/apps/streampixels/managed-credentials/resolve", headers: secret, payload: { accountId, provider: "joystick" } });
|
||||
|
||||
describe("the ask", () => {
|
||||
it("launch shows a Heimdall page naming app, provider, scopes and custody, and does not redirect", async () => {
|
||||
const { app } = await newApp();
|
||||
const { page } = await seeAsk(app, await startConnect(app));
|
||||
expect(page.headers.location).toBeUndefined();
|
||||
for (const needle of ["StreamPixels", "Joystick", ...defaultScopes, "refresh token", "streampixels.gamecult.org", "Continue to Joystick", "No, return to the app"]) {
|
||||
expect(page.body).toContain(needle);
|
||||
}
|
||||
expect(page.body).not.toContain("<script");
|
||||
expect(page.headers["content-security-policy"]).toContain("form-action 'self' https://joystick.tv");
|
||||
});
|
||||
|
||||
it("a viewer who declines yields consent_refused by viewer, stores no credential, and consumes the state", async () => {
|
||||
// POST the decline form from the launch page with the binding cookie;
|
||||
// expect result {error: "consent_refused", by: "viewer"}, an audit event
|
||||
// "consent_refused", no managed credential row, and a second launch refused.
|
||||
expect.fail("not built");
|
||||
it("viewing the ask claims nothing: the launch is still spendable once after any number of views", async () => {
|
||||
const { app } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
await seeAsk(app, state);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302);
|
||||
const again = await answer(app, state, "continue", cookie, "application/json");
|
||||
expect(again.statusCode).toBe(400);
|
||||
expect(again.json()).toEqual({ error: "state_already_launched" });
|
||||
});
|
||||
|
||||
it("a provider access_denied is consent_refused by provider, distinct from provider_error", async () => {
|
||||
expect.fail("not built");
|
||||
it("Continue sends exactly the scopes the page listed", async () => {
|
||||
const { app } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
const go = await answer(app, state, "continue", cookie);
|
||||
expect(go.statusCode).toBe(302);
|
||||
const target = new URL(go.headers.location as string);
|
||||
expect(target.origin).toBe("https://joystick.tv");
|
||||
expect(target.searchParams.get("scope")).toBe(defaultScopes.join(" "));
|
||||
});
|
||||
|
||||
it("a granted completion writes one receipt with asked and granted scopes and the page digest", async () => {
|
||||
expect.fail("not built");
|
||||
it("a flow with no custody (sign-in through an identity provider) gets no ask and redirects as before", async () => {
|
||||
const { app } = await newApp();
|
||||
const start = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/twitch/start",
|
||||
headers: secret,
|
||||
payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/", handoff: { kind: "browser_completion" } },
|
||||
});
|
||||
expect(start.statusCode).toBe(201);
|
||||
const launch = await app.inject({ method: "GET", url: `/v1/oauth/twitch/launch?state=${encodeURIComponent(stateOf(start.json()))}`, headers: { accept: "text/html" } });
|
||||
expect(launch.statusCode).toBe(302);
|
||||
});
|
||||
|
||||
it("the receipt page is readable only by the browser or account that consented, and revoke stamps revokedAt without editing the grant row", async () => {
|
||||
expect.fail("not built");
|
||||
it("an answer without the cookie the ask set is refused and spends nothing", async () => {
|
||||
const { app } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
for (const decision of ["continue", "decline"] as const) {
|
||||
const stranger = await answer(app, state, decision, undefined, "application/json");
|
||||
expect(stranger.statusCode, decision).toBe(400);
|
||||
expect(stranger.json(), decision).toEqual({ error: "state_not_bound" });
|
||||
}
|
||||
expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302);
|
||||
});
|
||||
|
||||
it("the consent route refuses a flow that has no ask", async () => {
|
||||
const { app } = await newApp();
|
||||
const start = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/twitch/start",
|
||||
headers: secret,
|
||||
payload: { appSlug: "streampixels", mode: "sign_in", returnTo: "https://streampixels.gamecult.org/", handoff: { kind: "browser_completion" } },
|
||||
});
|
||||
const state = stateOf(start.json());
|
||||
const response = await app.inject({
|
||||
method: "POST",
|
||||
url: "/v1/oauth/twitch/consent",
|
||||
headers: form,
|
||||
payload: new URLSearchParams({ state, decision: "continue" }).toString(),
|
||||
});
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toEqual({ error: "consent_not_required" });
|
||||
});
|
||||
});
|
||||
|
||||
describe("the wording digest", () => {
|
||||
const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: ["identity:read"], returnOrigin: "https://streampixels.gamecult.org" };
|
||||
it("is the sha-256 of the lines shown, and moves with the app, provider, scopes and origin", () => {
|
||||
expect(consentDigest(ask)).toBe(createHash("sha256").update(consentLines(ask).join("\n"), "utf8").digest("hex"));
|
||||
const variants: ConsentAsk[] = [
|
||||
{ ...ask, appSlug: "bifrost" },
|
||||
{ ...ask, provider: "twitch" },
|
||||
{ ...ask, scopes: ["identity:read", "chat:read"] },
|
||||
{ ...ask, returnOrigin: "https://elsewhere.example" },
|
||||
];
|
||||
for (const variant of variants) expect(consentDigest(variant)).not.toBe(consentDigest(ask));
|
||||
});
|
||||
});
|
||||
|
||||
describe("refusal", () => {
|
||||
it("declining yields consent_refused by the viewer, stores nothing, and spends the state", async () => {
|
||||
const { app, store } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
const no = await answer(app, state, "decline", cookie, "application/json");
|
||||
expect(no.statusCode).toBe(400);
|
||||
expect(no.json()).toMatchObject({ error: "consent_refused", by: "viewer", provider: "joystick" });
|
||||
|
||||
// Nothing launches or completes afterwards, and nothing was kept.
|
||||
expect((await answer(app, state, "continue", cookie, "application/json")).json()).toEqual({ error: "state_already_launched" });
|
||||
expect((await callback(app, state, cookie, "code=code-a")).json()).toEqual({ error: "state_already_used" });
|
||||
expect(await store.findStoredLinkedIdentity("joystick", "joy-a")).toBeNull();
|
||||
const events = [...(store as unknown as { auditEvents: Map<string, { eventType: string; eventPayloadJson: unknown }> }).auditEvents.values()];
|
||||
expect(events.filter((event) => event.eventType === "consent_refused").map((event) => event.eventPayloadJson)).toEqual([
|
||||
{ provider: "joystick", mode: "connect", by: "viewer" },
|
||||
]);
|
||||
});
|
||||
|
||||
it("the browser sees a 'Not Connected' page, not an authentication failure", async () => {
|
||||
const { app } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
const no = await answer(app, state, "decline", cookie);
|
||||
expect(no.statusCode).toBe(200);
|
||||
expect(no.body).toContain("Not Connected");
|
||||
expect(no.body).toContain("consent_refused");
|
||||
expect(no.body).not.toContain("Authentication Failed");
|
||||
});
|
||||
|
||||
it("an access_denied from the provider is consent_refused by the provider, distinct from provider_error", async () => {
|
||||
const { app, store } = await newApp();
|
||||
const denied = await newFlow(app);
|
||||
const response = await callback(app, denied.state, denied.cookie, "error=access_denied");
|
||||
expect(response.statusCode).toBe(400);
|
||||
expect(response.json()).toMatchObject({ error: "consent_refused", by: "provider" });
|
||||
|
||||
const faulty = await newFlow(app);
|
||||
expect((await callback(app, faulty.state, faulty.cookie, "error=server_error")).json().error).toBe("provider_error");
|
||||
const events = [...(store as unknown as { auditEvents: Map<string, { eventType: string }> }).auditEvents.values()];
|
||||
expect(events.filter((event) => event.eventType === "consent_refused")).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("a backend_callback app is told, with who refused", async () => {
|
||||
const callbackUrl = "https://streampixels.gamecult.org/api/heimdall/callback";
|
||||
const { app } = await newApp({ callbacks: [callbackUrl] });
|
||||
const delivered: Array<Record<string, unknown>> = [];
|
||||
vi.spyOn(globalThis, "fetch").mockImplementation(async (_url, init) => {
|
||||
delivered.push(JSON.parse(String(init?.body)));
|
||||
return new Response("ok", { status: 200 });
|
||||
});
|
||||
const handoff = { kind: "backend_callback", callbackUrl, attemptId: "attempt-1" };
|
||||
|
||||
const byViewer = await startConnect(app, handoff);
|
||||
const { cookie } = await seeAsk(app, byViewer);
|
||||
await answer(app, byViewer, "decline", cookie);
|
||||
const byProvider = await startConnect(app, handoff);
|
||||
const second = await seeAsk(app, byProvider);
|
||||
await answer(app, byProvider, "continue", second.cookie);
|
||||
await callback(app, byProvider, second.cookie, "error=access_denied");
|
||||
|
||||
expect(delivered.map((payload) => [payload.status, payload.error, payload.by])).toEqual([
|
||||
["error", "consent_refused", "viewer"],
|
||||
["error", "consent_refused", "provider"],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
async function newFlow(app: FastifyInstance) {
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
expect((await answer(app, state, "continue", cookie)).statusCode).toBe(302);
|
||||
return { state, cookie };
|
||||
}
|
||||
|
||||
describe("the receipt", () => {
|
||||
it("a granted completion writes one receipt with asked and granted scopes and the digest of the wording shown", async () => {
|
||||
const { app, store } = await newApp({ granted: ["identity:read", "stream:read"] });
|
||||
const done = await grantAs(app, "a");
|
||||
const receipts = await store.listConsentReceipts(done.account.id);
|
||||
expect(receipts).toHaveLength(1);
|
||||
const ask: ConsentAsk = { appSlug: "streampixels", provider: "joystick", scopes: defaultScopes, returnOrigin: "https://streampixels.gamecult.org" };
|
||||
expect(receipts[0]).toMatchObject({
|
||||
id: done.consentReceiptId,
|
||||
kind: "grant",
|
||||
accountId: done.account.id,
|
||||
appSlug: "streampixels",
|
||||
provider: "joystick",
|
||||
scopesAsked: defaultScopes,
|
||||
scopesGranted: ["identity:read", "stream:read"],
|
||||
consentPageDigest: consentDigest(ask),
|
||||
});
|
||||
});
|
||||
|
||||
it("a refusal leaves no receipt", async () => {
|
||||
const { app, store } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
await answer(app, state, "decline", cookie);
|
||||
expect(await store.listConsentReceipts("anyone")).toEqual([]);
|
||||
expect((await store.findStoredLinkedIdentity("joystick", "joy-a"))).toBeNull();
|
||||
});
|
||||
|
||||
it("the success page names the receipt", async () => {
|
||||
const { app } = await newApp();
|
||||
const state = await startConnect(app);
|
||||
const { cookie } = await seeAsk(app, state);
|
||||
await answer(app, state, "continue", cookie);
|
||||
const page = await callback(app, state, cookie, "code=code-a", "text/html");
|
||||
expect(page.statusCode).toBe(200);
|
||||
expect(page.body).toMatch(/receipt [0-9a-f-]{36}/);
|
||||
});
|
||||
});
|
||||
|
||||
describe("my grants", () => {
|
||||
it("is closed to anyone without a live Heimdall access token", async () => {
|
||||
const { app } = await newApp();
|
||||
for (const headers of [{}, bearer("not-a-token")]) {
|
||||
const response = await app.inject({ method: "GET", url: "/v1/me/grants", headers });
|
||||
expect(response.statusCode).toBe(401);
|
||||
expect(response.json().error).toBe("sign_in_required");
|
||||
}
|
||||
const link = await app.inject({ method: "POST", url: "/v1/me/grants/link" });
|
||||
expect(link.statusCode).toBe(401);
|
||||
const revoke = await app.inject({ method: "POST", url: "/v1/me/grants/x/revoke" });
|
||||
expect(revoke.statusCode).toBe(401);
|
||||
});
|
||||
|
||||
it("lists the signed-in account's grants and receipts, and no one else's", async () => {
|
||||
const { app } = await newApp();
|
||||
const a = await grantAs(app, "a");
|
||||
const b = await grantAs(app, "b");
|
||||
const mine = await grantsOf(app, a.accessToken);
|
||||
expect(mine.grants).toHaveLength(1);
|
||||
expect(mine.grants[0]).toMatchObject({ id: a.consentReceiptId, status: "active", provider: "joystick", appSlug: "streampixels", scopesGranted: ["identity:read", "stream:read"] });
|
||||
expect(JSON.stringify(mine)).not.toContain(b.consentReceiptId);
|
||||
expect(mine.receipts.map((receipt) => receipt.accountId)).toEqual([a.account.id]);
|
||||
});
|
||||
|
||||
it("revoke takes effect on the next token use, edits no row, and receipts the revocation", async () => {
|
||||
const { app, store } = await newApp();
|
||||
const a = await grantAs(app, "a");
|
||||
expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200);
|
||||
const before = await store.listConsentReceipts(a.account.id);
|
||||
|
||||
const revoke = await app.inject({ method: "POST", url: `/v1/me/grants/${a.consentReceiptId}/revoke`, headers: bearer(a.accessToken) });
|
||||
expect(revoke.statusCode).toBe(200);
|
||||
expect(revoke.json().revoked).toEqual([a.consentReceiptId]);
|
||||
|
||||
const next = await resolveCredential(app, a.account.id);
|
||||
expect(next.statusCode).toBe(410);
|
||||
expect(next.json().error).toBe("managed_credential_revoked");
|
||||
|
||||
const after = await store.listConsentReceipts(a.account.id);
|
||||
expect(after).toHaveLength(2);
|
||||
expect(after[0]).toEqual(before[0]);
|
||||
expect(after[1]).toMatchObject({ kind: "revocation", revokesReceiptId: a.consentReceiptId, accountId: a.account.id });
|
||||
const view = (await grantsOf(app, a.accessToken)).grants[0]!;
|
||||
expect(view).toMatchObject({ status: "revoked", revocationReceiptId: after[1]!.id });
|
||||
expect(view.revokedAt).toBe(after[1]!.createdAt);
|
||||
});
|
||||
|
||||
it("revoke is the owner's alone: another account's grant id is not found and its credential is untouched", async () => {
|
||||
const { app } = await newApp();
|
||||
const a = await grantAs(app, "a");
|
||||
const b = await grantAs(app, "b");
|
||||
const attempt = await app.inject({ method: "POST", url: `/v1/me/grants/${a.consentReceiptId}/revoke`, headers: bearer(b.accessToken) });
|
||||
expect(attempt.statusCode).toBe(404);
|
||||
expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200);
|
||||
expect((await resolveCredential(app, b.account.id)).statusCode).toBe(200);
|
||||
});
|
||||
|
||||
it("revoking twice changes nothing the second time", async () => {
|
||||
const { app, store } = await newApp();
|
||||
const a = await grantAs(app, "a");
|
||||
const url = `/v1/me/grants/${a.consentReceiptId}/revoke`;
|
||||
await app.inject({ method: "POST", url, headers: bearer(a.accessToken) });
|
||||
const second = await app.inject({ method: "POST", url, headers: bearer(a.accessToken) });
|
||||
expect(second.statusCode).toBe(200);
|
||||
expect(second.json().revoked).toEqual([]);
|
||||
expect(await store.listConsentReceipts(a.account.id)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("a fresh connection after a revoke is a new grant, live again, and the old one stays revoked", async () => {
|
||||
const { app } = await newApp();
|
||||
const first = await grantAs(app, "a");
|
||||
await app.inject({ method: "POST", url: `/v1/me/grants/${first.consentReceiptId}/revoke`, headers: bearer(first.accessToken) });
|
||||
const second = await grantAs(app, "a");
|
||||
expect(second.consentReceiptId).not.toBe(first.consentReceiptId);
|
||||
expect((await resolveCredential(app, second.account.id)).statusCode).toBe(200);
|
||||
const grants = (await grantsOf(app, second.accessToken)).grants;
|
||||
expect(grants.map((grant) => [grant.id, grant.status])).toEqual([
|
||||
[first.consentReceiptId, "revoked"],
|
||||
[second.consentReceiptId, "active"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("a browser with no session opens the page from a minted link and revokes with one form post", async () => {
|
||||
const { app } = await newApp();
|
||||
const a = await grantAs(app, "a");
|
||||
const link = await app.inject({ method: "POST", url: "/v1/me/grants/link", headers: bearer(a.accessToken) });
|
||||
expect(link.statusCode).toBe(201);
|
||||
const url = new URL(link.json().url as string);
|
||||
const page = await app.inject({ method: "GET", url: `${url.pathname}${url.search}`, headers: { accept: "text/html" } });
|
||||
expect(page.statusCode).toBe(200);
|
||||
expect(page.body).toContain(a.consentReceiptId);
|
||||
expect(page.body).toContain("Take this back");
|
||||
expect(page.body).not.toContain("<script");
|
||||
|
||||
const token = url.searchParams.get("t")!;
|
||||
const post = await app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/me/grants/${a.consentReceiptId}/revoke`,
|
||||
headers: { ...form, accept: "text/html" },
|
||||
payload: new URLSearchParams({ t: token }).toString(),
|
||||
});
|
||||
expect(post.statusCode).toBe(200);
|
||||
expect(post.body).toContain("Taken back.");
|
||||
expect((await resolveCredential(app, a.account.id)).statusCode).toBe(410);
|
||||
});
|
||||
|
||||
it("a page link proves only what it was minted for: an access token, a foreign token or none opens nothing", async () => {
|
||||
const { app } = await newApp();
|
||||
const a = await grantAs(app, "a");
|
||||
for (const t of [a.accessToken, "garbage", ""]) {
|
||||
const response = await app.inject({ method: "GET", url: `/v1/me/grants?t=${encodeURIComponent(t)}` });
|
||||
expect(response.statusCode, t).toBe(401);
|
||||
const revoke = await app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/me/grants/${a.consentReceiptId}/revoke`,
|
||||
headers: form,
|
||||
payload: new URLSearchParams({ t }).toString(),
|
||||
});
|
||||
expect(revoke.statusCode, t).toBe(401);
|
||||
}
|
||||
expect((await resolveCredential(app, a.account.id)).statusCode).toBe(200);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -117,7 +117,18 @@ export function setCookieOf(response: { headers: Record<string, unknown> }): str
|
|||
|
||||
async function followLaunch(app: FastifyInstance, state: string): Promise<LaunchedFlow & { providerUrl: URL }> {
|
||||
const provider = decodeJwt(state).payload.provider as string;
|
||||
const response = await app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` });
|
||||
let response = await app.inject({ method: "GET", url: `/v1/oauth/${provider}/launch?state=${encodeURIComponent(state)}` });
|
||||
if (response.statusCode === 200) {
|
||||
// Heimdall's ask (managed custody): the person says Continue, with the cookie the ask set.
|
||||
const asked = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-"));
|
||||
expect(asked, "the ask sets the binding cookie").toBeDefined();
|
||||
response = await app.inject({
|
||||
method: "POST",
|
||||
url: `/v1/oauth/${provider}/consent`,
|
||||
headers: { "content-type": "application/x-www-form-urlencoded", cookie: (asked as string).split(";")[0] as string },
|
||||
payload: new URLSearchParams({ state, decision: "continue" }).toString(),
|
||||
});
|
||||
}
|
||||
expect(response.statusCode, "launch").toBe(302);
|
||||
const set = setCookieOf(response).find((value) => value.startsWith("__Host-heimdall-oauth-"));
|
||||
expect(set, "launch sets the binding cookie").toBeDefined();
|
||||
|
|
@ -143,8 +154,5 @@ export async function launchWithRedirect(app: FastifyInstance, start: StartBody)
|
|||
|
||||
/** The provider URL a browser is redirected to once it has followed authorizationUrl through the launch hop. */
|
||||
export async function providerRedirect(app: FastifyInstance, start: StartBody): Promise<URL> {
|
||||
const url = new URL(start.authorizationUrl);
|
||||
const response = await app.inject({ method: "GET", url: `${url.pathname}${url.search}` });
|
||||
expect(response.statusCode, "launch").toBe(302);
|
||||
return new URL(response.headers.location as string);
|
||||
return (await followLaunch(app, stateOf(start))).providerUrl;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -299,14 +299,15 @@ describe("OAuth state binding", () => {
|
|||
expect(await claim("a", 1_000_000 + 30_000)).toBe(true);
|
||||
});
|
||||
|
||||
it("a provider error from the launching browser still denies the attempt, once", async () => {
|
||||
it("a provider refusal from the launching browser still denies the attempt, once", async () => {
|
||||
const app = await newApp();
|
||||
const start = await bifrostStart(app);
|
||||
const victim = await launchFlow(app, start);
|
||||
|
||||
const denied = await callback(app, victim.state, victim.cookie, "error=access_denied");
|
||||
expect(denied.statusCode).toBe(400);
|
||||
expect(denied.json().error).toBe("provider_error");
|
||||
expect(denied.json().error).toBe("consent_refused");
|
||||
expect(denied.json().by).toBe("provider");
|
||||
const replay = await callback(app, victim.state, victim.cookie, "error=access_denied");
|
||||
expect(replay.json()).toEqual({ error: "state_already_used" });
|
||||
});
|
||||
|
|
|
|||
|
|
@ -270,9 +270,10 @@ describe("PostgresStore.checkSchema", () => {
|
|||
"oauth_state_uses",
|
||||
"capability_grants",
|
||||
"entitlement_snapshots",
|
||||
"consent_receipts",
|
||||
"audit_events",
|
||||
]);
|
||||
expect(REQUIRED_COLUMNS).toHaveLength(101);
|
||||
expect(REQUIRED_COLUMNS).toHaveLength(111);
|
||||
expect(REQUIRED_COLUMNS).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ table: "auth_completions", column: "code", type: "TEXT", nullable: false },
|
||||
|
|
@ -283,7 +284,7 @@ describe("PostgresStore.checkSchema", () => {
|
|||
{ table: "auth_completions", column: "attempt_id", type: "TEXT", nullable: true },
|
||||
])
|
||||
);
|
||||
expect(REQUIRED_KEYS).toHaveLength(14);
|
||||
expect(REQUIRED_KEYS).toHaveLength(15);
|
||||
expect(REQUIRED_KEYS).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ table: "linked_identities", columns: "provider,provider_user_id", predicate: "" },
|
||||
|
|
@ -418,6 +419,9 @@ async function exerciseStore(store: PostgresStore): Promise<Set<string>> {
|
|||
expect(await s.claimOAuthStateUse(stateUse)).toBe(true);
|
||||
expect(await s.claimOAuthStateUse(stateUse)).toBe(false);
|
||||
expect(await s.claimOAuthStateUse({ ...stateUse, phase: "callback" })).toBe(true);
|
||||
const grant = await s.createConsentReceipt({ kind: "grant", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: now, scopesAsked: ["a", "b"], scopesGranted: ["a"], consentPageDigest: "d" });
|
||||
await s.createConsentReceipt({ kind: "revocation", accountId: account.id, appSlug: "streampixels", provider: "joystick", createdAt: later, revokesReceiptId: grant.id });
|
||||
expect((await s.listConsentReceipts(account.id)).map((r) => r.kind)).toEqual(["grant", "revocation"]);
|
||||
await s.createAuditEvent({ eventType: "probe", eventPayloadJson: {}, createdAt: now });
|
||||
return called;
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue