Refuse an unbound or replayed state with a page back to the app, and keep use records through the skew

Browsers (Accept: text/html) refused for state_not_bound, state_already_launched
or state_already_used get the handoff page linking to return_to, re-checked
against the app's allowed origins; other callers keep the JSON code. A callback
with no binding denies the attempt its signed state names (pending only).
The memory store prunes a use record at exp + 30 s, as the state itself is
accepted that long; the schema comment says the same.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Heimdall 2026-11-05 17:16:38 +00:00
commit f1ddc2fffc
5 changed files with 182 additions and 25 deletions

View file

@ -1,7 +1,7 @@
import { createHmac, randomUUID } from "node:crypto";
import cookie from "@fastify/cookie";
import cors from "@fastify/cors";
import Fastify, { type FastifyError, type FastifyInstance, type FastifyReply } from "fastify";
import Fastify, { type FastifyError, type FastifyInstance, type FastifyReply, type FastifyRequest } from "fastify";
import { type AppCaller, isAppCaller, resolveAppCaller } from "./app-caller.js";
import { deliverBackendHandoff, type BackendHandoffPayload } from "./backend-handoff.js";
import {
@ -1094,6 +1094,38 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
}
);
/**
* A refusal of a verified state. A browser (Accept: text/html) gets the
* handoff page linking back to the state's return_to, so the person is not
* left on a bare JSON body; the origin is re-checked against the app's
* allowlist here rather than trusting the signed value. Anything else gets
* the fixed JSON code.
*/
const refuseVerifiedState = (
request: FastifyRequest,
reply: FastifyReply,
state: OAuthStatePayload,
error: "state_not_bound" | "state_already_launched" | "state_already_used"
) => {
reply.code(400);
const profile = getAppProfile(state.app_slug);
if (prefersHtml(request.headers.accept) && profile && isAllowedReturnOrigin(profile, state.return_to)) {
reply.type("text/html; charset=utf-8");
return reply.send(
renderBrowserHandoffPage({
handoffKind: (state.handoff ?? { kind: "browser_completion" }).kind,
status: "error",
provider: state.provider,
appSlug: state.app_slug,
mode: state.mode,
returnTo: state.return_to,
error,
})
);
}
return { error };
};
app.get<{
Params: { provider: Provider };
Querystring: { state: string };
@ -1140,8 +1172,7 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
expiresAt: new Date(state.exp * 1000).toISOString(),
});
if (!first) {
reply.code(400);
return { error: "state_already_launched" };
return refuseVerifiedState(request, reply, state, "state_already_launched");
}
const oidc = providerCatalog[state.provider].oidc ? deriveOidcSecrets(state.jti, keys.privateKey) : undefined;
@ -1201,11 +1232,23 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
return { error: verified.error };
}
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,
});
};
// 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
// complete this state, and its page polls an attempt that would otherwise
// sit pending until it expires.
if (!oauthBindingHolds(config, keys, request.cookies[oauthBindingCookieName(statePayload.jti)], statePayload)) {
reply.code(400);
return { error: "state_not_bound" };
await denyBrowserAttempt("state_not_bound");
return refuseVerifiedState(request, reply, statePayload, "state_not_bound");
}
setOAuthBindingCookie(reply, statePayload, "", 0);
const firstCallback = await store.claimOAuthStateUse({
@ -1216,18 +1259,8 @@ export async function buildApp(options: BuildAppOptions = {}): Promise<FastifyIn
expiresAt: new Date(statePayload.exp * 1000).toISOString(),
});
if (!firstCallback) {
reply.code(400);
return { error: "state_already_used" };
return refuseVerifiedState(request, reply, statePayload, "state_already_used");
}
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,
});
};
if (request.query.error) {
const providerError = relayedProviderText(request.query.error, 64);

View file

@ -24,6 +24,9 @@ import {
type UpsertLinkedIdentityInput,
} from "./types.js";
/** The skew a signed OAuth state is still accepted for past its exp (verifyOAuthState). */
const OAUTH_STATE_SKEW_MS = 30_000;
function clone<T>(value: T): T {
return JSON.parse(JSON.stringify(value)) as T;
}
@ -452,8 +455,10 @@ export class InMemoryStore implements HeimdallStore {
}
async claimOAuthStateUse(input: ClaimOAuthStateUseInput): Promise<boolean> {
// A state is still accepted until its exp + 30 s skew, so a use record must outlive that.
const usedAtMs = Date.parse(input.usedAt);
for (const [key, expiresAt] of this.oauthStateUses) {
if (expiresAt <= input.usedAt) {
if (Date.parse(expiresAt) + OAUTH_STATE_SKEW_MS <= usedAtMs) {
this.oauthStateUses.delete(key);
}
}

View file

@ -138,9 +138,9 @@ CREATE UNIQUE INDEX IF NOT EXISTS auth_completions_attempt_unconsumed_unique_idx
-- One use per (state jti, phase): a signed OAuth state launches once and
-- completes once. The first INSERT for a pair wins; ON CONFLICT DO NOTHING
-- reports every later claim as no row. The store deletes nothing, so rows stay
-- like consumed auth_completions; after expires_at a state is refused before
-- any claim, so a row is never consulted again.
-- reports every later claim as no row. The Postgres store deletes nothing, so rows
-- stay like consumed auth_completions; a state is accepted until expires_at + 30 s
-- of skew, so a row may be pruned only after that and is never consulted again.
CREATE TABLE IF NOT EXISTS oauth_state_uses (
jti TEXT NOT NULL,
phase TEXT NOT NULL,