// THE KERNEL EXECUTOR (docs/concepts/the-model.md, rule 5): the one way a pack reaches a vendor. // Built by the kernel from a validated root URL and the sealed credential; a pack builds its own // client over it and never holds a credential. The root URL is HOSTILE INPUT (a tenant sets it): // the validator enforces absolute https, refuses loopback/link-local/private/metadata targets and // userinfo, refuses ALL IP-literal origins (v4 and v6), and caps length. What it CANNOT do, stated // so nobody assumes more: pin DNS (fetch owns resolution). A shell may allow http to LOOPBACK only // (a twin standing in for the vendor on this machine — the journeys run that way). import type { CredentialPayload } from './credential.ts'; import type { RemoteExecute } from './remote-execute.ts'; import type { HostRule } from './packRegistry.ts'; import { RateBudget } from './rateBudget.ts'; import { signSigV4 } from './sigv4.ts'; import clockForm from '../world-clock.cjs'; /** * HOW A VENDOR AUTHENTICATES — a fact about the vendor, declared by the pack (`TwinPack.auth`) and * applied here (docs/concepts/the-model.md#the-rules, rule 5: the executor "applies the credential by strategy"). * * The executor dispatches on the STRATEGY NAME and never on vendor identity, and imports no pack: * architecture invariant A2's own instruction is that vendor-specific knowledge lives in the * descriptor rather than a kernel switch table. Absent means header replacement (`credential.headers`). */ export type TwinAuthStrategy = /** A vendor of lanes whose lanes authenticate apart (Cloudflare's API by bearer, its R2 by SigV4): a lane named takes * its own strategy, every other call the sealed headers; the request names its lane (`RemoteExecuteRequest.lane`). */ | { in: 'lanes'; lanes: Record } | { in: 'choice'; choices: Array<{ credential: string; strategy: TwinAuthStrategy }> } | { in: 'signature'; algorithm: 'oauth1-hmac-sha1' } /** the key rides in the query string (`?key=…`, `?appid=…`) — no header will do */ | { in: 'query'; name: string } /** the key rides in the path (Telegram's `/bot/METHOD_NAME`): `pattern`'s first group is its place */ | { in: 'path'; pattern: string } /** AWS Signature Version 4 — a signature computed per request over the whole canonical request. * `scope` answers which region and service THIS request is for, because a pack may route several * services over one executor (aws routes six); it is pure and is handed no secret. */ | { in: 'signature'; algorithm: 'aws-sigv4'; scope: { region: string; service: string } | ((req: { method: string; path: string; host: string; headers: Record; body?: string | Uint8Array }) => { region: string; service: string }) } /** a signature computed PER REQUEST over bytes only the pack can canonicalize */ | { in: 'signature'; algorithm: 'hmac-sha256'; encoding: 'hex' | 'base64'; header: string; /** The exact bytes to sign, from the request as the kernel will send it. Pure: it is handed no * secret, which is what keeps the secret out of pack code while the pack still decides what * the vendor signs. * * `null` means THIS REQUEST IS NOT SIGNED — a real thing vendors do (Veriff exempts * `POST /sessions`, the call that has no session to sign for yet). It is the pack stating the * vendor's own rule, not a failure: an unsigned request the vendor expects to be unsigned is * correct, and the alternative would be signing bytes the vendor will reject. */ canonical: (req: { method: string; path: string; body?: string }) => string | null; } /** A TOKEN EXCHANGE: the sealed secret is traded for a short-lived token the calls then carry (Bluesky's * createSession from an app password, an OAuth refresh-token grant). The kernel sends `request` itself — * its body fields are literals or `{ credential: '' }` read from the sealed credential — keeps * the token it answers to itself, and puts it on every later call; a `retryOn` answer (401 by default) * exchanges once more and retries the call once. The pack never holds the secret or the token: what it * needs to know about the session it asks the vendor for with an ordinary authenticated call. */ | { in: 'exchange'; request: { method: 'POST'; path: string; format: 'json' | 'form'; body: Record; /** HTTP Basic client authentication on the token request (an OAuth confidential client), from sealed fields */ basicAuth?: { user: { credential: string }; password: { credential: string } }; }; /** the token's field in the JSON answer (a dotted path) */ token: string; /** the header it rides in (default `authorization`) and its scheme (default `Bearer`; '' for none) */ header?: string; scheme?: string; retryOn?: number[]; /** the vendor's code for an expired token in the answer's `error` field (Bluesky's `ExpiredToken`): with it, * a retryOn status exchanges again only when the answer names that code, so a bad request never spends * the shared token or the vendor's session allowance */ retryCode?: string; /** A vendor that ROTATES the secret each exchange spends (X issues a new refresh token with every refresh grant, * and the old one no longer works): the answer's field holding the new one (a dotted path) and the sealed field * it replaces. The kernel keeps the new value for its next exchange and hands the updated credential to the * root's custody to seal (`onRotate`), so the root outlives the first refresh token. */ rotate?: { answer: string; credential: string }; /** The answer's field giving the token's lifetime in seconds (a dotted path; OAuth's `expires_in`): a token held past * it is exchanged again before the next call. For a vendor that answers an expired token with no `retryOn` status * (TikTok's API for Business answers HTTP 200 with a code), and so a long-lived process never sends a dead token. */ expiresIn?: string; }; async function oauth1SignedHeader(credential: CredentialPayload, method: string, target: URL, headers: Headers, body?: string | Uint8Array): Promise { const field = (name: string): string => { const value = credential[name]; if (typeof value !== 'string' || !value) throw new Error(`remote execute: oauth1-hmac-sha1 needs sealed ${name}`); return value; }; const consumerKey = field('consumerKey'), consumerSecret = field('consumerSecret'); const token = field('token'), tokenSecret = field('tokenSecret'); const encode = (value: string): string => encodeURIComponent(value).replace(/[!\x27()*]/g, c => `%${c.charCodeAt(0).toString(16).toUpperCase()}`); const protocol: Array<[string, string]> = [ ['oauth_consumer_key', consumerKey], ['oauth_token', token], ['oauth_signature_method', 'HMAC-SHA1'], ['oauth_timestamp', String(Math.floor(clockForm.machineNow() / 1000))], ['oauth_nonce', crypto.randomUUID()], ['oauth_version', '1.0'], ]; const form = typeof body === 'string' && /^application\/x-www-form-urlencoded/i.test(headers.get('content-type') ?? '') ? [...new URLSearchParams(body)] : []; const pairs = [...protocol, ...target.searchParams, ...form].filter(([name]) => name !== 'oauth_signature').map(([name, value]) => [encode(name), encode(value)]); pairs.sort(([a, av], [b, bv]) => a < b ? -1 : a > b ? 1 : av < bv ? -1 : av > bv ? 1 : 0); const base = `${method.toUpperCase()}&${encode(`${target.protocol}//${target.host.toLowerCase()}${target.pathname}`)}&${encode(pairs.map(([name, value]) => `${name}=${value}`).join('&'))}`; const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(`${encode(consumerSecret)}&${encode(tokenSecret)}`), { name: 'HMAC', hash: 'SHA-1' }, false, ['sign']); const bytes = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(base))); const signature = btoa(Array.from(bytes, byte => String.fromCharCode(byte)).join('')); return `OAuth ${[...protocol, ['oauth_signature', signature]].map(([name, value]) => `${encode(name)}="${encode(value)}"`).join(', ')}`; } const MAX_ORIGIN_LENGTH = 2048; function isLoopbackHost(hostname: string): boolean { return hostname === '127.0.0.1' || hostname === 'localhost' || hostname === '[::1]' || hostname === '::1'; } /** Throws with the precise refusal; returns the parsed URL when the origin is usable. */ export function validateRemoteOrigin(origin: string, opts: { allowInsecureLoopback?: boolean } = {}): URL { if (origin.length > MAX_ORIGIN_LENGTH) throw new Error(`remote origin exceeds ${MAX_ORIGIN_LENGTH} characters`); let url: URL; try { url = new URL(origin); } catch { throw new Error('remote origin must be an absolute URL'); } if (url.username !== '' || url.password !== '') throw new Error('remote origin must not carry userinfo'); const loopback = isLoopbackHost(url.hostname); if (url.protocol !== 'https:') { if (!(url.protocol === 'http:' && loopback && opts.allowInsecureLoopback === true)) { throw new Error('remote origin must be https (http is allowed only to loopback, and only where the shell permits it)'); } } if (!loopback || opts.allowInsecureLoopback !== true) { if (loopback) throw new Error('remote origin must not target loopback on this deployment'); // Trailing dots defeat suffix/equality checks ('localhost.' resolves as localhost); // strip before every hostname comparison. const host = url.hostname.replace(/^\[|\]$/g, '').replace(/\.+$/, ''); // NO IP-LITERAL ORIGINS, v4 or v6: the WHATWG parser normalizes exotic // v4 spellings to dotted form, but v6 carries mapped-v4 ([::ffff:7f00:1]), NAT64 // and [::] forms no regex allowlist survives — and no real vendor publishes an IP // origin. Hostnames only; loopback literals ride the explicit allowance above. if (/^\d+\.\d+\.\d+\.\d+$/.test(host) || url.hostname.startsWith('[') || host.includes(':')) { throw new Error('remote origin must be a hostname, never an IP literal'); } if (host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.internal')) { throw new Error('remote origin must not target a local-only hostname'); } } return url; } /** Build the kernel's RemoteExecute (R14 scheduled pull) from the link's validated * origin + the sealed credential — a pack never holds a credential, a scheduler never * learns a vendor shape. */ const EGRESS_TIMEOUT_MS = 30_000; /** HMAC-SHA256 over WebCrypto — NOT `node:crypto`, deliberately. This file is on the credential * path and the host it runs on may be workerd (the contract's Cloudflare shell), which is the same * reason credential.ts is WebCrypto-only. Kept local rather than exported: nothing outside the * executor should be signing with a credential's secret. */ async function hmacSha256(secret: string, payload: string, encoding: 'hex' | 'base64'): Promise { const key = await crypto.subtle.importKey('raw', new TextEncoder().encode(secret), { name: 'HMAC', hash: 'SHA-256' }, false, ['sign']); const bytes = new Uint8Array(await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(payload))); if (encoding === 'hex') return [...bytes].map((b) => b.toString(16).padStart(2, '0')).join(''); let binary = ''; for (const b of bytes) binary += String.fromCharCode(b); return btoa(binary); } /** `vendorHosts`: the pack's declared vendor host rules (its descriptor's `hosts`). An absolute https URL * on one of them — an exact `host` rule whose `pathPattern` the path matches — is a second host of the * same vendor that takes the credential (LinkedIn's image uploads on www.linkedin.com/dms-uploads, * Instagram's rupload host); it is sent credentialed like an anchored call, as HTTP Basic when a rule naming * it names a `basic` user. Any other absolute URL is refused. */ /** Where a credential is kept (the head's and refresh's root: head.ts rootCustody): `key` names the credential stably * across rotations and anew when another is sealed in its place (the token cache is keyed by it, not by the secret's value), `open` reads it as sealed now, `seal` keeps a rotated one. */ /** `unsealed`: where a rotation the seal failed to keep is recorded durably (the field and the cause, never a value), since * the root cannot renew once the process holding the new secret ends; a later successful seal clears it. */ export type CredentialCustody = { key: string; open: () => Promise; seal: (credential: CredentialPayload) => Promise | void; unsealed?: (field: string, cause: string) => void }; /** `vendor`: the vendor whose rate budget every call is charged to (D8): the call is priced and reserved before it is * made, refused when the budget is spent, and settled with the vendor's answer (its back-off honoured). */ /** `now`: the instant a signature is made at (the wall clock unless given: an acceptance whose vendor is a fixture World * signs at that World's clock, which its twin checks a signature's date against). */ export type RemoteExecuteOptions = { custody?: CredentialCustody; vendor?: string; now?: () => Date }; export function buildRemoteExecute(origin: URL, credential: CredentialPayload, auth?: TwinAuthStrategy, vendorHosts?: readonly HostRule[], options: RemoteExecuteOptions = {}): RemoteExecute { if (auth?.in === 'lanes') { // each lane's strategy over the same origin and credential, the budget charged once, around them all const own = { ...options, vendor: undefined }; const byLane = new Map(Object.entries(auth.lanes).map(([lane, strategy]) => [lane, buildRemoteExecute(origin, credential, strategy, vendorHosts, own)])); const headers = buildRemoteExecute(origin, credential, undefined, vendorHosts, own); const execute: RemoteExecute = (request) => (byLane.get(request.lane ?? '') ?? headers)(request); return options.vendor === undefined ? execute : budgeted(options.vendor, execute, options.custody?.key ?? JSON.stringify(credential.headers)); } if (auth?.in === 'choice') { const picked = auth.choices.find(c => typeof credential[c.credential] === 'string' && credential[c.credential] !== ''); if (!picked) throw new Error('remote execute: no credential matches the declared strategy choices'); return buildRemoteExecute(origin, credential, picked.strategy, vendorHosts, options); } const execute = auth?.in === 'exchange' ? exchangeExecute(origin, credential, auth, vendorHosts, options.custody) : direct(origin, credential, auth, vendorHosts, options.now); return options.vendor === undefined ? execute : budgeted(options.vendor, execute, options.custody?.key ?? JSON.stringify(credential.headers)); } /** Every live call charged to the vendor's rate budget (rateBudget.ts, D8): a call the budget refuses is never made; * the ledger is the credential's (only its hash names it). */ function budgeted(vendor: string, execute: RemoteExecute, token: string): RemoteExecute { const budget = new RateBudget({ vendor, token }); return async (request) => { const url = new URL(request.path, 'http://budget.invalid'); const weight = budget.weightFor(`${request.method.toUpperCase()} ${url.pathname}`, Object.fromEntries(url.searchParams)); const reservation = budget.checkBudget(weight); const answer = await execute(request); budget.recordCall(weight, answer.headers, { status: answer.status, reservation }); return answer; }; } /** The call made as the root's credential is applied by the strategy (header replacement when none). */ function direct(origin: URL, credential: CredentialPayload, auth?: Exclude, vendorHosts?: readonly HostRule[], now: () => Date = () => new Date(clockForm.machineNow())): RemoteExecute { return async ({ method, path, headers, body, responseType, presigned, issued }) => { // A PRESIGNED UPLOAD URL the vendor returned: its own signature is its authorization, so the // sealed credential never goes with it, whatever host it names. A host other than the root's // passes the same validation the root does; the root's own origin (a twin standing in for the // vendor on loopback) is already validated. if (presigned) { let target: URL; try { target = new URL(path); } catch { throw new Error('remote execute: a presigned request carries an absolute URL'); } if (target.username || target.password) throw new Error('remote execute: a presigned URL carries no userinfo'); // any other host passes the root's own validator: https, no IP literal, no local-only name if (target.origin !== origin.origin) validateRemoteOrigin(target.origin); const response = await fetch(target, { method, headers: new Headers(headers ?? {}), ...(body === undefined ? {} : { body: typeof body === 'string' ? body : new Uint8Array(body) }), redirect: 'manual', signal: AbortSignal.timeout(EGRESS_TIMEOUT_MS), }); const responseHeaders: Record = {}; response.headers.forEach((value, key) => { responseHeaders[key] = value; }); if (responseType === 'bytes') { const bodyBytes = new Uint8Array(await response.arrayBuffer()); return { status: response.status, headers: responseHeaders, body: new TextDecoder().decode(bodyBytes), bodyBytes }; } return { status: response.status, headers: responseHeaders, body: await response.text() }; } // PATH ANCHORING: '@evil.com/x' concatenated after an origin reparses // the origin into USERINFO and ships the credential to evil.com. A path is a path: // it starts with '/', and the parse must land on the validated origin, asserted. let target: URL; // the vendor's own URL, where a loopback root stands in for it: what a signature is made over let vendorUrl: URL | undefined; // the user a host that takes the token as HTTP Basic's password names it under (HostRule.basic) let basicUser: string | undefined; if (/^https:\/\//i.test(path) && vendorHosts?.length) { // a second host the pack declares for this vendor, on a path its rule names: validated as the root is target = new URL(path); if (target.username || target.password) throw new Error('remote execute: a vendor URL carries no userinfo'); validateRemoteOrigin(target.origin); const named = (r: HostRule): boolean => ('host' in r ? r.host === target.hostname : 'suffix' in r ? target.hostname.endsWith(r.suffix) : new RegExp(r.hostPattern).test(target.hostname)) && (r.pathPattern === undefined || new RegExp(r.pathPattern).test(target.pathname)); const declared = vendorHosts.some((r) => !r.exclude && named(r)) && !vendorHosts.some((r) => r.exclude && named(r)); if (!declared) throw new Error(`remote execute: ${target.host}${target.pathname.slice(0, 64)} is not a host this vendor's pack declares for this path`); basicUser = vendorHosts.find((r) => !r.exclude && r.basic !== undefined && named(r))?.basic; // A loopback root is the vendor substitute. Preserve the vendor Host while retaining // the already-validated root's mounted path; an absolute URL never escapes that root. if (isLoopbackHost(origin.hostname)) { vendorUrl = target; target = new URL(origin.href.replace(/\/+$/, '') + target.pathname + target.search); } } else { if (!path.startsWith('/')) throw new Error(`remote execute: path must start with '/' (got ${JSON.stringify(path.slice(0, 64))})`); // the base keeps its path: a served world's twin lives under ///, github.com under / const base = origin.href.replace(/\/+$/, ''); target = new URL(base + path); if (target.origin !== origin.origin || !target.pathname.startsWith(origin.pathname.replace(/\/+$/, ''))) throw new Error('remote execute: path escaped the validated origin'); } const outbound = new Headers(headers ?? {}); // a credential the vendor issued in this perform is the request's authorization; the sealed one stays home if (issued !== undefined) outbound.set('authorization', issued); else for (const [name, value] of Object.entries(credential.headers)) outbound.set(name, value); // A HOST THAT TAKES THE TOKEN AS HTTP BASIC: the sealed authorization header's credentials, after its scheme, are // Basic's password under the rule's user; one sealed as Basic goes as it is, and none sealed refuses before egress if (issued === undefined && basicUser !== undefined) { const sealed = outbound.get('authorization') ?? ''; const token = /^\S+\s+(\S.*)$/.exec(sealed)?.[1]; if (token === undefined) throw new Error(`remote execute: ${target.host} takes the credential as HTTP Basic, and the sealed credential carries no authorization header`); if (!/^basic\s/i.test(sealed)) outbound.set('authorization', `Basic ${btoa(`${basicUser}:${token}`)}`); } // the vendor's host, kept over any the credential carries (a loopback twin routes by it, as the World's proxy's) if (vendorUrl) { outbound.set('host', vendorUrl.host); outbound.set('x-volter-twin-original-host', vendorUrl.host); } // ── THE STRATEGIES BEYOND HEADER REPLACEMENT ────────────────────────────────────────────── // Applied AFTER the anchoring check above, so nothing here can move the request off the // validated origin: `searchParams.set` only ever touches the query, and a header is a header. // // FAIL CLOSED. A strategy with no secret must never send a request that merely LOOKS // authenticated — that silence is the whole defect this exists to remove. The refusals name the // strategy and the parameter, never the secret. // an issued credential is the authorization: nothing of the sealed one signs the request if (issued === undefined) { if (auth?.in === 'signature' && auth.algorithm === 'oauth1-hmac-sha1') { outbound.set('authorization', await oauth1SignedHeader(credential, method, target, outbound, body)); } else if (auth !== undefined) { const secret = credential.secret; if (typeof secret !== 'string' || secret === '') { throw new Error(`remote execute: the ${auth.in} credential strategy needs \`secret\` on the sealed credential, and it is absent`); } if (auth.in === 'query') { // `set`, not `append`: it REPLACES whatever placeholder the pack put in its own path, // exactly as `outbound.set` replaces a placeholder authorization header. target.searchParams.set(auth.name, secret); } else if (auth.in === 'path') { // the key's place in the path, filled after the origin is validated; a secret that could end the segment or // the path (a slash, a query, a fragment, an escape) is refused, so the request cannot leave the validated root if (/[/?#%\\]/.test(secret)) throw new Error('remote execute: the path credential strategy refuses a secret that is not one path segment'); const place = new RegExp(auth.pattern, 'd').exec(target.pathname)?.indices?.[1]; if (!place) throw new Error(`remote execute: the path credential strategy's pattern does not name the key's place in ${target.pathname.slice(0, 64)}`); target.pathname = target.pathname.slice(0, place[0]) + secret + target.pathname.slice(place[1]); } else if (auth.algorithm === 'aws-sigv4') { const keyId = credential.keyId; if (typeof keyId !== 'string' || keyId === '') { throw new Error('remote execute: the aws-sigv4 credential strategy needs `keyId` on the sealed credential, and it is absent'); } // the HOST goes with it: an AWS endpoint names its own region, and only the pack knows how const signedUrl = vendorUrl ?? target; const { region, service } = typeof auth.scope === 'function' ? auth.scope({ method, path, host: signedUrl.host, headers: Object.fromEntries(outbound.entries()), ...(body === undefined ? {} : { body }) }) : auth.scope; const signed = signSigV4({ method, url: signedUrl.href, ...(body === undefined ? {} : { body }), keyId, secret, region, service, headers: Object.fromEntries(outbound), at: now() }); for (const [name, value] of Object.entries(signed)) outbound.set(name, value); } else { // `null` is the vendor's own exemption, declared by the pack — not an error, and not a // reason to send an unsigned header. if (body instanceof Uint8Array) throw new Error('remote execute: this signature canonicalizer accepts text bodies only'); const payload = auth.canonical({ method, path, ...(body === undefined ? {} : { body }) }); if (payload !== null) outbound.set(auth.header, await hmacSha256(secret, payload, auth.encoding)); } } } const response = await fetch(target, { method, headers: outbound, ...(body === undefined ? {} : { body: typeof body === 'string' ? body : new Uint8Array(body) }), redirect: 'manual', // A hung vendor must not hold the isolate store fence open-endedly; // the pull records the abort as ordinary failure health and backs off. signal: AbortSignal.timeout(EGRESS_TIMEOUT_MS), }); const responseHeaders: Record = {}; response.headers.forEach((value, key) => { responseHeaders[key] = value; }); if (responseType === 'bytes') { const bodyBytes = new Uint8Array(await response.arrayBuffer()); return { status: response.status, headers: responseHeaders, body: new TextDecoder().decode(bodyBytes), bodyBytes }; } return { status: response.status, headers: responseHeaders, body: await response.text() }; }; } /** Tokens the exchange strategy holds, per root and credential, for the life of the process: an executor * is built per deploy and per refresh, so a token kept only inside one would cost a fresh exchange on every * write (Bluesky allows 30 sessions in five minutes). In memory only; never written anywhere. */ const exchangedTokens = new Map; expiresAt?: number }>(); /** A rotated credential a seal failed to keep, per custody key: the process spends it (never the spent one the file * still holds) until a seal succeeds or the file moves past the value it replaced. In memory only. */ const unsealedRotations = new Map(); /** The exchange strategy over the ordinary executor: the token request goes out with the credential's * declared fields in its body, the token comes back to this module only, and every non-presigned call * carries it. Presigned calls pass through untouched (they carry their own authorization). */ function exchangeExecute(origin: URL, sealed: CredentialPayload, auth: Extract, vendorHosts?: readonly HostRule[], custody?: CredentialCustody): RemoteExecute { let credential: CredentialPayload = sealed; const anchored = buildRemoteExecute(origin, credential, undefined, vendorHosts); const header = auth.header ?? 'authorization'; const scheme = auth.scheme ?? 'Bearer'; const retryOn = auth.retryOn ?? [401]; if (!credential.headers || typeof credential.headers !== 'object') throw new Error('remote execute: an exchange credential is sealed with a headers object (it may be empty)'); // the sealed headers are applied after the caller's, so one naming the token's header would replace it if (Object.keys(credential.headers).some((name) => name.toLowerCase() === header.toLowerCase())) throw new Error(`remote execute: an exchange credential must not seal its own \`${header}\` header`); const field = (name: string): string => { const held = credential[name]; // fail closed, naming the field and never its value if (typeof held !== 'string' || held === '') throw new Error(`remote execute: the exchange needs \`${name}\` on the sealed credential, and it is absent`); return held; }; const key = custody ? `${origin.href}\n${custody.key}` : `${origin.href}\n${JSON.stringify(sealed)}`; let expiresAt: number | undefined; const exchange = async (): Promise => { // a rotating secret is read as kept NOW (another executor or process may have rotated it since this one was // built), or as this process holds it when its seal failed and the file still holds the spent value. Two // processes reading the same value within one exchange's round trip can still both spend it: there is no lock // across the call. if (auth.rotate && custody) { credential = await custody.open(); const unsealed = unsealedRotations.get(key); if (unsealed && credential[auth.rotate.credential] === unsealed.replaced) credential = unsealed.credential; else unsealedRotations.delete(key); } const fields: Record = {}; for (const [name, value] of Object.entries(auth.request.body)) fields[name] = typeof value === 'string' ? value : field(value.credential); const body = auth.request.format === 'json' ? JSON.stringify(fields) : new URLSearchParams(fields).toString(); const headers: Record = { 'content-type': auth.request.format === 'json' ? 'application/json' : 'application/x-www-form-urlencoded' }; if (auth.request.basicAuth) headers.authorization = `Basic ${btoa(`${field(auth.request.basicAuth.user.credential)}:${field(auth.request.basicAuth.password.credential)}`)}`; const answer = await anchored({ method: auth.request.method, path: auth.request.path, headers, body }); if (answer.status < 200 || answer.status >= 300) { // the vendor's own reason (an error code, never a secret: the answer carries no token on failure) let reason = ''; try { const parsed = JSON.parse(answer.body) as Record; reason = String(parsed.error ?? parsed.message ?? '').slice(0, 120); } catch { /* no JSON */ } throw new Error(`remote execute: the token exchange answered ${answer.status}${reason ? ` (${reason})` : ''}`); } let parsed: unknown; try { parsed = JSON.parse(answer.body); } catch { throw new Error('remote execute: the token exchange answered no JSON'); } const value = auth.token.split('.').reduce((at, k) => (at && typeof at === 'object' ? (at as Record)[k] : undefined), parsed); if (typeof value !== 'string' || value === '') { // an OAuth token endpoint may refuse a grant with a 2xx whose `error` names why (RFC 6749 §5.2's field): carry it, never a secret const code = parsed && typeof parsed === 'object' ? (parsed as Record).error : undefined; throw new Error(`remote execute: the token exchange answered no \`${auth.token}\`${typeof code === 'string' && code !== '' ? ` (${code.slice(0, 120)})` : ''}`); } if (auth.expiresIn) { const seconds = Number(auth.expiresIn.split('.').reduce((at, k) => (at && typeof at === 'object' ? (at as Record)[k] : undefined), parsed)); // a minute short of the stated lifetime, so a call in flight never carries a token that dies on the way expiresAt = Number.isFinite(seconds) && seconds > 0 ? performance.now() + Math.max(0, seconds - 60) * 1000 : undefined; } if (auth.rotate) { const next = auth.rotate.answer.split('.').reduce((at, k) => (at && typeof at === 'object' ? (at as Record)[k] : undefined), parsed); if (typeof next === 'string' && next !== '' && next !== credential[auth.rotate.credential]) { // the spent secret is dead at the vendor: held at once, then sealed; a seal that fails is loud (the root would die // on its next start), and the token the vendor already answered is kept const replaced = String(credential[auth.rotate.credential] ?? ''); credential = { ...credential, [auth.rotate.credential]: next }; if (custody) { try { await custody.seal(credential); unsealedRotations.delete(key); } catch (error) { unsealedRotations.set(key, { replaced, credential }); try { custody.unsealed?.(auth.rotate.credential, error instanceof Error ? error.message : String(error)); } catch { /* the stderr line below still says it */ } console.error(`remote execute: the vendor rotated \`${auth.rotate.credential}\` and sealing the new one failed (${error instanceof Error ? error.message : String(error)}); this process holds it until a seal succeeds`); } } } } return value; }; const current = (): { token: Promise } => { let held = exchangedTokens.get(key); if (held?.expiresAt !== undefined && performance.now() >= held.expiresAt) { exchangedTokens.delete(key); held = undefined; } if (!held) { const token = exchange(); held = { token }; exchangedTokens.set(key, held); const entry = held; token.then(() => { entry.expiresAt = expiresAt; }, () => { if (exchangedTokens.get(key) === entry) exchangedTokens.delete(key); }); } return held; }; const call = async (request: Parameters[0], held: { token: Promise }): Promise>> => { const value = await held.token; const headers: Record = {}; for (const [name, v] of Object.entries(request.headers ?? {})) if (name.toLowerCase() !== header.toLowerCase()) headers[name] = v; headers[header] = scheme ? `${scheme} ${value}` : value; return anchored({ ...request, headers }); }; return async (request) => { if (request.presigned || request.issued !== undefined) return anchored(request); const held = current(); const first = await call(request, held); if (!retryOn.includes(first.status)) return first; if (auth.retryCode !== undefined) { let code: unknown; try { code = (JSON.parse(first.body) as Record).error; } catch { code = undefined; } if (code !== auth.retryCode) return first; } // exchange again only if the token that failed is still the one held (concurrent failures share one) if (exchangedTokens.get(key) === held) exchangedTokens.delete(key); return call(request, current()); }; }