:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(mcp): stash confirmed-action payloads server-side and extend confirm TTL (#75962)
Andrew Maguire9fa51b36eeb2
diff --git a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md b/docs/published/handbook/engineering/ai/implementing-mcp-tools.mdindex e4263579be17..9d8053f34882 100644--- a/docs/published/handbook/engineering/ai/implementing-mcp-tools.md+++ b/docs/published/handbook/engineering/ai/implementing-mcp-tools.md@@ -303,7 +303,7 @@ Product teams own their definitions and control which operations are exposed as- `message` (required) – prompt text shown to the user. Supports `{paramName}` placeholders interpolated from the validated tool args at runtime.- `action_label` (optional) – short human-readable label for the action (e.g. "delete project"). Surfaced in refusal messages. Defaults to the tool's title.- **Security model:** the prepare step signs the validated args, user identity, tool purpose, the active project/organization scope, a TTL, and a single-use nonce into an HMAC-SHA256 token. The execute step has a strict confirmation-only schema, verifies the signature, re-checks that the active scope still matches the one signed at prepare time, burns the nonce, and only then runs the original handler with the signed payload. Action args belong only on prepare; extra execute-time fields are rejected, and a confirmation prepared while one project was active can't be replayed against another after `switch-project`.+ **Security model:** the prepare step stashes the validated args and the active project/organization scope in Redis, and signs their SHA-256 digest together with the user identity, tool purpose, a TTL, and a single-use nonce into an HMAC-SHA256 token. The token stays small and constant-size no matter how large the args are, because the model relays only a reference to the payload. The execute step has a strict confirmation-only schema, verifies the signature, fetches-and-burns the stashed payload (the burn is the single-use enforcement), checks it against the signed digest, re-checks that the active scope still matches the one bound at prepare time, and only then runs the original handler with the verified payload. Action args belong only on prepare; extra execute-time fields are rejected, and a confirmation prepared while one project was active can't be replayed against another after `switch-project`.The confirmation word is supplied through model-authored tool arguments. This is an instruction-backed workflow guard, not client-attested proof that the human typed the word. API scopes remain the authorization boundary.diff --git a/services/mcp/scripts/generate-tools.ts b/services/mcp/scripts/generate-tools.tsindex 53d0d5818d60..464e39af0717 100644--- a/services/mcp/scripts/generate-tools.ts+++ b/services/mcp/scripts/generate-tools.ts@@ -1412,6 +1412,7 @@ ${scopeResolveBlock}${prepareFallbackBlock} return await prepareConfirmedactionLabel: ${JSON.stringify(actionLabel)},messageTemplate: ${JSON.stringify(messageTemplate)},codec: __runtime.codec,+ stash: __runtime.stash,${prepareScopeField} })`@@ -1424,6 +1425,7 @@ ${scopeResolveBlock} const __guard = await executeConfirmedAction<z.inferpurpose: ${JSON.stringify(toolName)},codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,${executeScopeField} })if (!__guard.ok) {return __guard.result as neverdiff --git a/services/mcp/src/hono/app.ts b/services/mcp/src/hono/app.tsindex 95ea4042880e..5974bf234c11 100644--- a/services/mcp/src/hono/app.ts+++ b/services/mcp/src/hono/app.ts@@ -1,7 +1,13 @@import { Hono } from 'hono'import { env } from '@/lib/env'-import { loadSigningKeyFromEnv, NonceLedger, SignedStateCodec } from '@/lib/signed-state'+import {+ loadSigningKeyFromEnv,+ NonceLedger,+ PayloadStash,+ type PayloadStashRedis,+ SignedStateCodec,+} from '@/lib/signed-state'import { setConfirmedActionRuntime } from '@/tools/confirmed-action-registry'import { confirmedActionRuntimeInstalled } from './metrics'@@ -25,7 +31,7 @@ const sseRedirect = (c: HonoCtx): Response => {return c.redirect(target.toString(), 308) as unknown as Response}-export function createApp(redis: RedisWithPing): App {+export function createApp(redis: RedisWithPing & Pick<PayloadStashRedis, 'incrby'>): App {const app = new Hono()const lifecycle: Lifecycle = { shuttingDown: false }@@ -44,6 +50,7 @@ export function createApp(redis: RedisWithPing): App {setConfirmedActionRuntime({codec: new SignedStateCodec(loadSigningKeyFromEnv()),ledger: new NonceLedger(redis),+ stash: new PayloadStash(redis),})confirmedActionRuntimeInstalled.set(1)} catch (err) {diff --git a/services/mcp/src/lib/signed-state/codec.ts b/services/mcp/src/lib/signed-state/codec.tsindex 87dbd83da4dc..e715967af95e 100644--- a/services/mcp/src/lib/signed-state/codec.ts+++ b/services/mcp/src/lib/signed-state/codec.ts@@ -56,7 +56,8 @@ export interface SignedStateCodecOptions {export class SignedStateCodec {private readonly key: Uint8Array- private readonly ttlSeconds: number+ /** TTL stamped on tokens at encode time. Public so callers can surface the window in user-facing copy. */+ readonly ttlSeconds: numberprivate readonly now: () => numberprivate readonly randomNonce: () => stringdiff --git a/services/mcp/src/lib/signed-state/constants.ts b/services/mcp/src/lib/signed-state/constants.tsindex 80babfa216ce..37412630cd65 100644--- a/services/mcp/src/lib/signed-state/constants.ts+++ b/services/mcp/src/lib/signed-state/constants.ts@@ -7,12 +7,13 @@*//**- * Default TTL on a signed state token, in seconds. 5 minutes is long enough- * for a model to surface the prepare result to the user and for the user to- * reply with "confirm", short enough to bound the window a leaked or guessed- * token is usable.+ * Default TTL on a signed state token, in seconds. 15 minutes gives the user+ * time to review a large prepared payload (a full scout definition, say)+ * before typing "confirm" — 5 minutes proved too short for that in practice —+ * while still bounding the window a leaked or guessed token is usable. Matches+ * the 15-minute expiry of the workflows blast-radius confirm token.*/-export const DEFAULT_STATE_TTL_SECONDS = 300+export const DEFAULT_STATE_TTL_SECONDS = 900/** Minimum acceptable length of the signing key, in bytes (HMAC-SHA256 output size). */export const SIGNING_KEY_MIN_BYTES = 32@@ -20,5 +21,47 @@ export const SIGNING_KEY_MIN_BYTES = 32/** Redis key prefix for the single-use nonce ledger. */export const NONCE_KEY_PREFIX = 'mcp:signed-state:nonce'+/** Redis key prefix for stashed prepare payloads awaiting execute. */+export const PAYLOAD_KEY_PREFIX = 'mcp:signed-state:payload'++/** Redis key prefix for the per-user stashed-bytes quota window. */+export const PAYLOAD_QUOTA_KEY_PREFIX = 'mcp:signed-state:payload-quota'++/**+ * Extra lifetime a stashed payload gets beyond its token's TTL. Ensures the+ * Redis entry never expires before the token does under clock skew — an+ * expired token must refuse as 'expired' (from the JWT check), not as+ * 'already used' because the stash entry vanished first.+ */+export const PAYLOAD_STASH_TTL_MARGIN_SECONDS = 30++/**+ * Maximum serialized size of a single stashed prepare payload, in bytes.+ * Matches the Hono dispatcher's 1 MiB request-body cap (`MAX_BODY_BYTES`),+ * so it never rejects args the transport can deliver — anything tighter+ * would refuse scout definitions the backend accepts (1 MB per body/file).+ * It exists as a backstop so a future request-limit raise can't silently+ * widen Redis retention. The aggregate exposure is bounded separately by+ * `STASH_QUOTA_BYTES_PER_WINDOW`.+ */+export const MAX_STASHED_PAYLOAD_BYTES = 1_048_576++/**+ * Aggregate bytes one user may stash per quota window. Stashed payloads+ * share Redis with session and rate-limit state, so per-payload and+ * per-request limits alone still allow a caller at the rate limit to+ * retain gigabytes within one token TTL. 20 MiB per window is far above+ * legitimate use (a burst of large scout definitions is still a few MiB)+ * while capping worst-case retention per user near the quota. The window+ * spans the payload TTL, so the counter outlives every entry it charged+ * for; it is not decremented on execute — a consumed confirmation still+ * counts until the window rolls. Fixed windows admit a boundary burst:+ * filling the quota at the end of one window and again at the start of+ * the next transiently retains up to 2× this value. That is accepted —+ * the alternative (refreshing the expiry on every charge) never resets+ * for a steadily active caller, eventually locking out legitimate use.+ */+export const STASH_QUOTA_BYTES_PER_WINDOW = 20 * 1_048_576+/** Env var name. */export const SIGNING_KEY_ENV_VAR = 'MCP_SIGNED_STATE_KEY'diff --git a/services/mcp/src/lib/signed-state/index.ts b/services/mcp/src/lib/signed-state/index.tsindex 793b6d45ab91..349648beb577 100644--- a/services/mcp/src/lib/signed-state/index.ts+++ b/services/mcp/src/lib/signed-state/index.ts@@ -6,7 +6,13 @@* implementation detail.*/-export { DEFAULT_STATE_TTL_SECONDS, SIGNING_KEY_ENV_VAR } from './constants'+export {+ DEFAULT_STATE_TTL_SECONDS,+ MAX_STASHED_PAYLOAD_BYTES,+ PAYLOAD_STASH_TTL_MARGIN_SECONDS,+ SIGNING_KEY_ENV_VAR,+ STASH_QUOTA_BYTES_PER_WINDOW,+} from './constants'export {SignedStateAlreadyConsumed,SignedStateError,@@ -20,3 +26,5 @@ export { loadSigningKeyFromEnv, SignedStateCodec } from './codec'export type { SignedStateClaims, SignedStateCodecOptions } from './codec'export { NonceLedger } from './nonce-ledger'export type { NonceLedgerRedis } from './nonce-ledger'+export { PayloadStash } from './payload-stash'+export type { PayloadStashRedis } from './payload-stash'diff --git a/services/mcp/src/lib/signed-state/payload-stash.ts b/services/mcp/src/lib/signed-state/payload-stash.tsnew file mode 100644index 000000000000..e3b008ad8ef7--- /dev/null+++ b/services/mcp/src/lib/signed-state/payload-stash.ts@@ -0,0 +1,107 @@+/**+ * Server-side stash for prepared confirmed-action payloads.+ *+ * Signing the full validated args into the confirmation token means the+ * whole payload transits the model's context twice, base64-inflated —+ * unbounded fields (a scout's body + files, say) produce tokens tens of+ * kilobytes long, and long opaque strings invite truncation, which fails+ * as a bad signature. So the payload lives here instead, keyed by the+ * token's nonce, and only its SHA-256 digest is signed: the token stays+ * small and constant-size no matter how large the action args are.+ *+ * `take()` doubles as the single-use guard on this path: GET-then-DEL is+ * not atomic, but only the caller whose DEL returns 1 proceeds, so two+ * concurrent executes can both read the payload while exactly one gets to+ * act on it. No separate nonce-ledger round-trip is needed.+ *+ * Requiring Redis here does not weaken the paradigm's "any server instance+ * can serve execute" property — the single-use nonce ledger already made+ * every execute depend on shared Redis.+ */++import { PAYLOAD_KEY_PREFIX, PAYLOAD_QUOTA_KEY_PREFIX } from './constants'++/**+ * Minimal Redis surface — just what the stash needs. Both `ioredis` (prod)+ * and the in-memory test stubs satisfy this.+ */+export interface PayloadStashRedis {+ set(key: string, value: string, ...args: (string | number)[]): Promise<string | null>+ get(key: string): Promise<string | null>+ del(...keys: string[]): Promise<number>+ incrby(key: string, increment: number): Promise<number>+ expire(key: string, seconds: number): Promise<number>+ ttl(key: string): Promise<number>+}++export class PayloadStash {+ constructor(private readonly redis: PayloadStashRedis) {}++ /**+ * Store the serialized payload under the token's nonce. `ttlSeconds`+ * should be the token TTL plus a margin (see+ * `PAYLOAD_STASH_TTL_MARGIN_SECONDS`) so the entry outlives the token.+ */+ async put(nonce: string, payload: string, ttlSeconds: number): Promise<void> {+ const key = `${PAYLOAD_KEY_PREFIX}:${nonce}`+ const safeTtl = Math.max(1, Math.ceil(ttlSeconds))+ const result = await this.redis.set(key, payload, 'EX', safeTtl, 'NX')+ if (result === null) {+ // 128 random bits per nonce: a collision here is a bug (nonce reuse), not chance.+ throw new Error(`Payload stash entry already exists for nonce ${nonce}`)+ }+ }++ /**+ * Charge `bytes` against the user's fixed-window stash quota and return+ * the window's running total. First write in a window sets the expiry+ * (same shape as the request rate limiter); the caller compares the+ * total against `STASH_QUOTA_BYTES_PER_WINDOW` and refuses above it.+ * The counter is deliberately not decremented on take or expiry —+ * over-counting consumed entries keeps the bookkeeping one atomic+ * INCRBY instead of a reconciliation problem, and the window is sized+ * so legitimate use never notices.+ */+ async charge(sub: string, bytes: number, windowSeconds: number): Promise<number> {+ const key = `${PAYLOAD_QUOTA_KEY_PREFIX}:${sub}`+ const total = await this.redis.incrby(key, bytes)+ if (total === bytes) {+ await this.redis.expire(key, Math.max(1, Math.ceil(windowSeconds)))+ }+ return total+ }++ /**+ * Re-arm the quota window's expiry if it was lost. A crash between the+ * first INCRBY and its EXPIRE leaves the counter immortal, which would+ * refuse the user forever once it crosses the quota. Called on the+ * refusal path only (mirrors the rate limiter's stuck-key repair) so+ * the happy path stays at one round-trip. A live TTL is left alone —+ * re-arming it would extend the window.+ */+ async repairQuotaExpiry(sub: string, windowSeconds: number): Promise<void> {+ const key = `${PAYLOAD_QUOTA_KEY_PREFIX}:${sub}`+ const ttl = await this.redis.ttl(key)+ if (ttl < 0) {+ await this.redis.expire(key, Math.max(1, Math.ceil(windowSeconds)))+ }+ }++ /**+ * Fetch and burn the payload for a nonce. Returns `null` when the entry+ * is gone — already consumed, expired, or evicted — or when a concurrent+ * take won the DEL race. A non-null return is the exclusive right to act.+ */+ async take(nonce: string): Promise<string | null> {+ const key = `${PAYLOAD_KEY_PREFIX}:${nonce}`+ const value = await this.redis.get(key)+ if (value === null) {+ return null+ }+ const deleted = await this.redis.del(key)+ if (deleted === 0) {+ return null+ }+ return value+ }+}diff --git a/services/mcp/src/tools/confirmed-action-registry.ts b/services/mcp/src/tools/confirmed-action-registry.tsindex 223b33a97ebe..17ea60db7b5e 100644--- a/services/mcp/src/tools/confirmed-action-registry.ts+++ b/services/mcp/src/tools/confirmed-action-registry.ts@@ -11,11 +11,12 @@* installed once, read by many.*/-import type { NonceLedger, SignedStateCodec } from '@/lib/signed-state'+import type { NonceLedger, PayloadStash, SignedStateCodec } from '@/lib/signed-state'export interface ConfirmedActionRuntime {codec: SignedStateCodecledger: NonceLedger+ stash: PayloadStash}let installed: ConfirmedActionRuntime | undefineddiff --git a/services/mcp/src/tools/confirmed-action-runtime.ts b/services/mcp/src/tools/confirmed-action-runtime.tsindex 5ed845fb0253..98e9de7104cb 100644--- a/services/mcp/src/tools/confirmed-action-runtime.ts+++ b/services/mcp/src/tools/confirmed-action-runtime.ts@@ -10,8 +10,10 @@** - Works on every MCP client today (no protocol-level elicitation* dependency).- * - Stateless: the signed hash carries the action context through the- * model — any server instance can serve `execute`.+ * - The signed hash carries a reference to the action context through+ * the model; the payload itself waits in Redis, which execute already+ * depends on for single-use enforcement — any server instance sharing+ * that Redis can serve `execute`.* - The security model is weaker than client-rendered elicitation* (the LLM controls the `confirmation` argument), but strictly* stronger than a single destructive tool. Honest tradeoff documented@@ -20,13 +22,17 @@* What each helper does:** - `prepareConfirmedAction()` — runs at the top of the `-prepare` tool- * handler. Signs the validated args + user identity into a hash and- * returns a result the model surfaces to the user.+ * handler. Stashes the validated args server-side and signs their+ * SHA-256 digest + user identity into a small constant-size hash the+ * model surfaces to the user. Args can be arbitrarily large (a scout+ * body plus reference files, say) without bloating what the model has+ * to relay verbatim between the two calls.* - `executeConfirmedAction()` — runs at the top of the `-execute` tool- * handler. Verifies the hash, the literal "confirm" string, and the- * single-use nonce ledger. Returns the validated payload (the original- * args) for the rest of the handler to act on, or a `ToolErrorResult`- * to short-circuit the call.+ * handler. Verifies the hash and the literal "confirm" string, then+ * fetches-and-burns the stashed payload (the burn is the single-use+ * guard) and checks it against the signed digest. Returns the+ * validated payload (the original args) for the rest of the handler+ * to act on, or a `ToolErrorResult` to short-circuit the call.** Failure UX note: the nonce is consumed before the underlying handler* runs. If the downstream API call then fails, the user must run@@ -36,12 +42,24 @@* user thought it had been canceled.*/+import { createHash } from 'node:crypto'+import {confirmedActionExecutesTotal,confirmedActionPreparesTotal,confirmedActionRefusalsTotal,} from '@/hono/metrics'-import { NonceLedger, SignedStateAlreadyConsumed, SignedStateCodec, SignedStateError } from '@/lib/signed-state'+import { ToolInputValidationError } from '@/lib/errors'+import {+ MAX_STASHED_PAYLOAD_BYTES,+ NonceLedger,+ PAYLOAD_STASH_TTL_MARGIN_SECONDS,+ PayloadStash,+ SignedStateAlreadyConsumed,+ SignedStateCodec,+ SignedStateError,+ STASH_QUOTA_BYTES_PER_WINDOW,+} from '@/lib/signed-state'import type { Context } from './types'@@ -77,25 +95,50 @@ export interface PrepareConfirmedActionOptions<P extends Record<string, unknown>messageTemplate: string/** Codec — instantiated once at startup, reused across requests. */codec: SignedStateCodec+ /** Stash the payload waits in between prepare and execute. Single instance reused across requests. */+ stash: PayloadStash/*** Ambient scope resolved from current state at prepare time (e.g. the- * active project the action targets). Signed into the hash; `execute`- * refuses if the scope active at execute time no longer matches. Omit- * for actions with no project/org scope.+ * active project the action targets). Stashed with the args and+ * digest-bound into the hash; `execute` refuses if the scope active at+ * execute time no longer matches. Omit for actions with no project/org+ * scope.*/boundScope?: ConfirmedActionScope}/**- * Shape of the signed payload. The runtime wraps the caller's args- * together with the bound scope so both travel — and are tamper-checked —- * inside the single opaque `payload` claim the codec signs.+ * Shape of the stashed payload. The runtime wraps the caller's args+ * together with the bound scope so both travel — and are digest-checked —+ * as one serialized unit.*/interface SignedConfirmedActionPayload {args: Record<string, unknown>scope: ConfirmedActionScope | null}+/**+ * Shape of the `payload` claim signed into the token: a reference to the+ * stashed payload, not the payload itself. The nonce (a standard claim)+ * keys the stash entry; the digest tamper-proofs it.+ */+interface SignedPayloadReference {+ digest: string+}++function isPayloadReference(value: unknown): value is SignedPayloadReference {+ return (+ value !== null &&+ typeof value === 'object' &&+ !Array.isArray(value) &&+ typeof (value as Partial<SignedPayloadReference>).digest === 'string'+ )+}++function sha256Hex(value: string): string {+ return createHash('sha256').update(value).digest('hex')+}+export interface PrepareConfirmedActionResult {confirmation_hash: stringconfirmation_word: typeof CONFIRMATION_WORD@@ -126,11 +169,39 @@ export async function prepareConfirmedAction<P extends Record<string, unknown>>(args: options.args,scope: options.boundScope ?? null,}- const { token } = await options.codec.encode({+ // Digest the exact string that gets stashed — execute re-hashes the+ // stored string, so serialization only has to be stable across this+ // one round-trip, not canonical.+ const serialized = JSON.stringify(payload)+ const serializedBytes = Buffer.byteLength(serialized, 'utf8')+ if (serializedBytes > MAX_STASHED_PAYLOAD_BYTES) {+ confirmedActionPreparesTotal.inc({ tool: options.purpose, status: 'refused' })+ confirmedActionRefusalsTotal.inc({ tool: options.purpose, reason: 'payload_too_large' })+ throw new ToolInputValidationError(+ `${options.purpose} was not prepared: the action arguments are too large to confirm ` ++ `(${serializedBytes} bytes; limit ${MAX_STASHED_PAYLOAD_BYTES}). Trim the arguments, ` ++ `for example by shortening bundled file contents, and try again.`+ )+ }+ const stashWindowSeconds = options.codec.ttlSeconds + PAYLOAD_STASH_TTL_MARGIN_SECONDS+ const quotaTotal = await options.stash.charge(sub, serializedBytes, stashWindowSeconds)+ if (quotaTotal > STASH_QUOTA_BYTES_PER_WINDOW) {+ await options.stash.repairQuotaExpiry(sub, stashWindowSeconds)+ confirmedActionPreparesTotal.inc({ tool: options.purpose, status: 'refused' })+ confirmedActionRefusalsTotal.inc({ tool: options.purpose, reason: 'stash_quota_exceeded' })+ throw new ToolInputValidationError(+ `${options.purpose} was not prepared: too much pending confirmation data for this user ` ++ `(${quotaTotal} bytes in the current window; limit ${STASH_QUOTA_BYTES_PER_WINDOW}). ` ++ `Wait a few minutes for pending confirmations to expire and try again.`+ )+ }+ const reference: SignedPayloadReference = { digest: sha256Hex(serialized) }+ const { token, claims } = await options.codec.encode({sub,purpose: options.purpose,- payload,+ payload: reference,})+ await options.stash.put(claims.nonce, serialized, options.codec.ttlSeconds + PAYLOAD_STASH_TTL_MARGIN_SECONDS)confirmedActionPreparesTotal.inc({ tool: options.purpose, status: 'ok' })return {confirmation_hash: token,@@ -141,7 +212,9 @@ export async function prepareConfirmedAction<P extends Record<string, unknown>>(`Surface the message above to the user. Wait for them to reply with the literal word "${CONFIRMATION_WORD}". ` +`Then call the matching \`-execute\` tool with \`${CONFIRMATION_HASH_ARG}\` set to the confirmation_hash from this result, ` +`and \`${CONFIRMATION_WORD_ARG}\` set to the user's literal reply. The signed hash already contains the action arguments. ` +- `If the user does not reply with "${CONFIRMATION_WORD}", do not call the execute tool.`,+ `If the user does not reply with "${CONFIRMATION_WORD}", do not call the execute tool. ` ++ `The confirmation expires ${Math.round(options.codec.ttlSeconds / 60)} minutes after this call. ` ++ `If the user confirms later than that, call this prepare tool again with the same arguments to get a fresh hash.`,}}@@ -150,8 +223,10 @@ export interface ExecuteConfirmedActionOptions {incomingArgs: { [CONFIRMATION_HASH_ARG]: string; [CONFIRMATION_WORD_ARG]: string }/** Same `purpose` value used at prepare time. */purpose: string- /** Codec + ledger; both single instances reused across requests. */+ /** Codec + stash + ledger; all single instances reused across requests. */codec: SignedStateCodec+ stash: PayloadStash+ /** Single-use guard for inline-payload tokens only; stash-referenced tokens burn via `take()`. */ledger: NonceLedger/*** Scope resolved from *current* state at execute time. Compared against@@ -187,7 +262,7 @@ export async function executeConfirmedAction<P extends Record<string, unknown>>(return refuse(options.purpose,'wrong_word',- `${options.purpose} was not executed — the \`${CONFIRMATION_WORD_ARG}\` argument must be the literal string "${CONFIRMATION_WORD}", typed by the user. The user did not confirm.`+ `${options.purpose} was not executed: the \`${CONFIRMATION_WORD_ARG}\` argument must be the literal string "${CONFIRMATION_WORD}", typed by the user. The user did not confirm.`)}@@ -196,48 +271,85 @@ export async function executeConfirmedAction<P extends Record<string, unknown>>(claims = await options.codec.decode(hash, sub, options.purpose)} catch (err) {if (err instanceof SignedStateError) {- return refuse(options.purpose, err.kind, `${options.purpose} was not executed — ${reasonFor(err)}.`)+ return refuse(options.purpose, err.kind, `${options.purpose} was not executed: ${reasonFor(err)}.`)}throw err}- // Single-use enforcement. Bind the ledger TTL to the token's remaining- // life so abandoned nonces self-clean exactly when the token they- // protect can no longer be replayed. The remaining TTL comes from the- // codec's clock, not the wall clock — clock drift between the signer- // and the consumer could otherwise shrink the ledger TTL enough to- // re-allow replay.- try {- await options.ledger.consume(claims.nonce, options.codec.secondsUntilExpiry(claims))- } catch (err) {- if (err instanceof SignedStateAlreadyConsumed) {+ let wrapper: Partial<SignedConfirmedActionPayload>+ if (isPayloadReference(claims.payload)) {+ // Stash-referenced token: the burn inside `take()` IS the+ // single-use enforcement — a second execute (or a lost DEL race)+ // gets `null` here.+ const stored = await options.stash.take(claims.nonce)+ if (stored === null) {return refuse(options.purpose,'replay',- `${options.purpose} was not executed — this confirmation has already been used. Start a new prepare-then-execute cycle if you need to perform the action again.`+ `${options.purpose} was not executed: this confirmation has already been used or its prepared payload has expired. Start a new prepare-then-execute cycle if you need to perform the action again.`)}- throw err+ if (sha256Hex(stored) !== claims.payload.digest) {+ return refuse(+ options.purpose,+ 'digest_mismatch',+ `${options.purpose} was not executed: the stored confirmation payload does not match the signed digest. Run the prepare step again.`+ )+ }+ let parsed: unknown+ try {+ parsed = JSON.parse(stored)+ } catch {+ parsed = null+ }+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {+ return refuse(+ options.purpose,+ 'malformed_payload',+ `${options.purpose} was not executed: confirmation payload is malformed.`+ )+ }+ wrapper = parsed as Partial<SignedConfirmedActionPayload>+ } else {+ // Inline-payload token — args signed directly into the claim+ // instead of stashed. Minted by servers on the older token format;+ // honored so a confirmation spanning a mixed-version deploy still+ // executes. Here the ledger supplies the single-use guarantee that+ // `take()` gives the stash path, with its TTL bound to the token's+ // remaining life (per the codec's clock, not the wall clock — drift+ // between signer and consumer could otherwise shrink the ledger TTL+ // enough to re-allow replay).+ try {+ await options.ledger.consume(claims.nonce, options.codec.secondsUntilExpiry(claims))+ } catch (err) {+ if (err instanceof SignedStateAlreadyConsumed) {+ return refuse(+ options.purpose,+ 'replay',+ `${options.purpose} was not executed: this confirmation has already been used. Start a new prepare-then-execute cycle if you need to perform the action again.`+ )+ }+ throw err+ }+ const verified = claims.payload+ if (verified === null || typeof verified !== 'object' || Array.isArray(verified)) {+ return refuse(+ options.purpose,+ 'malformed_payload',+ `${options.purpose} was not executed: confirmation payload is malformed.`+ )+ }+ wrapper = verified as Partial<SignedConfirmedActionPayload>}- // The payload was signed at prepare time; treat it as untrusted JSON- // and shape-check before returning. The runtime wraps `{ args, scope }`,- // so validate the wrapper and the args object it carries.- const verified = claims.payload- if (verified === null || typeof verified !== 'object' || Array.isArray(verified)) {- return refuse(- options.purpose,- 'malformed_payload',- `${options.purpose} was not executed — confirmation payload is malformed.`- )- }- const wrapper = verified as Partial<SignedConfirmedActionPayload>+ // Whichever path produced the wrapper, treat it as untrusted JSON and+ // shape-check the args object it carries before returning.const args = wrapper.argsif (args === null || typeof args !== 'object' || Array.isArray(args)) {return refuse(options.purpose,'malformed_payload',- `${options.purpose} was not executed — confirmation payload is malformed.`+ `${options.purpose} was not executed: confirmation payload is malformed.`)}@@ -249,7 +361,7 @@ export async function executeConfirmedAction<P extends Record<string, unknown>>(return refuse(options.purpose,'scope_mismatch',- `${options.purpose} was not executed — the confirmation was issued for a different project or organization than the one currently active. Switch back to the project the action was prepared in, or run the prepare step again in the current one.`+ `${options.purpose} was not executed: the confirmation was issued for a different project or organization than the one currently active. Switch back to the project the action was prepared in, or run the prepare step again in the current one.`)}diff --git a/services/mcp/src/tools/generated/customer_analytics.ts b/services/mcp/src/tools/generated/customer_analytics.tsindex af6fab7bdf73..d30f03e9d573 100644--- a/services/mcp/src/tools/generated/customer_analytics.ts+++ b/services/mcp/src/tools/generated/customer_analytics.ts@@ -604,6 +604,7 @@ const announcementsCreatePrepare = (): ToolBase<typeof AnnouncementsCreateSchemamessageTemplate:"About to send this announcement as the SupportHog bot — a real, outward-facing Slack message to customers that cannot be recalled once posted. The message body is: {message}. The destination channel list was signed at prepare time and cannot be changed afterwards — review the channels you asked to target before confirming. Reply 'confirm' to send.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -620,6 +621,7 @@ const announcementsCreateExecute = (): ToolBase<typeof AnnouncementsCreateSchemapurpose: 'announcements-create',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {diff --git a/services/mcp/src/tools/generated/data_catalog.ts b/services/mcp/src/tools/generated/data_catalog.tsindex 9da0c2e49e53..9a36c651768c 100644--- a/services/mcp/src/tools/generated/data_catalog.ts+++ b/services/mcp/src/tools/generated/data_catalog.ts@@ -52,6 +52,7 @@ const dataCatalogCertificationCertifyPrepare = (): ToolBase<messageTemplate:"About to mark certification '{id}' as certified (agents should prefer this source). Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -74,6 +75,7 @@ const dataCatalogCertificationCertifyExecute = (): ToolBase<purpose: 'data-catalog-certification-certify',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {@@ -116,6 +118,7 @@ const dataCatalogCertificationDeprecatePrepare = (): ToolBase<messageTemplate:"About to mark certification '{id}' as deprecated (agents should avoid this source). Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -138,6 +141,7 @@ const dataCatalogCertificationDeprecateExecute = (): ToolBase<purpose: 'data-catalog-certification-deprecate',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {@@ -213,6 +217,7 @@ const dataCatalogMetricApprovePrepare = (): ToolBase<messageTemplate:"About to approve metric '{name}' as a canonical, human-vouched metric. Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -232,6 +237,7 @@ const dataCatalogMetricApproveExecute = (): ToolBase<purpose: 'data-catalog-metric-approve',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {@@ -420,6 +426,7 @@ const dataCatalogRelationshipAcceptPrepare = (): ToolBase<messageTemplate:"About to accept relationship proposal '{id}', promoting it to a real warehouse join. Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -442,6 +449,7 @@ const dataCatalogRelationshipAcceptExecute = (): ToolBase<purpose: 'data-catalog-relationship-accept',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {@@ -531,6 +539,7 @@ const dataCatalogRelationshipRejectPrepare = (): ToolBase<messageTemplate:"About to reject relationship proposal '{id}'. This permanently suppresses re-proposing the pair. Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -553,6 +562,7 @@ const dataCatalogRelationshipRejectExecute = (): ToolBase<purpose: 'data-catalog-relationship-reject',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {diff --git a/services/mcp/src/tools/generated/platform_features.ts b/services/mcp/src/tools/generated/platform_features.tsindex 2fa82bcae245..2e38d732ad4f 100644--- a/services/mcp/src/tools/generated/platform_features.ts+++ b/services/mcp/src/tools/generated/platform_features.ts@@ -237,6 +237,7 @@ const changeRequestsApprovePrepare = (): ToolBase<messageTemplate:"About to APPROVE change request {id}. If this reaches the required quorum, the underlying change is applied immediately. Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -256,6 +257,7 @@ const changeRequestsApproveExecute = (): ToolBase<purpose: 'change-requests-approve',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {@@ -370,6 +372,7 @@ const changeRequestsRejectPrepare = (): ToolBase<typeof ChangeRequestsRejectSchemessageTemplate:"About to REJECT change request {id}. This blocks the proposed change and notifies the requester. Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -389,6 +392,7 @@ const changeRequestsRejectExecute = (): ToolBase<purpose: 'change-requests-reject',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {@@ -585,6 +589,7 @@ const organizationEnforce2faPrepare = (): ToolBase<messageTemplate:"About to set organization-wide two-factor-authentication enforcement to {enforce_2fa}. This immediately affects every member of the organization — when enabled, all members must set up 2FA before they can continue using PostHog. Reply 'confirm' to proceed.\n",codec: __runtime.codec,+ stash: __runtime.stash,})},})@@ -602,6 +607,7 @@ const organizationEnforce2faExecute = (): ToolBase<purpose: 'organization-enforce-2fa',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,})if (!__guard.ok) {return __guard.result as neverdiff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex 91b93cbb82a9..c416985fbb8d 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -650,6 +650,7 @@ const scoutCreatePrepare = (): ToolBase<typeof ScoutCreateSchema, PrepareConfirmmessageTemplate:"About to create scout '{name}', a persistent automation that can run unattended on its configured schedule and write reports to the inbox when enabled with emit on. Reply 'confirm' to create it.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -666,6 +667,7 @@ const scoutCreateExecute = (): ToolBase<typeof ScoutCreateSchemaExecute, Schemaspurpose: 'scout-create',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {diff --git a/services/mcp/src/tools/generated/tasks.ts b/services/mcp/src/tools/generated/tasks.tsindex f9b56ce5ca60..7c2c11176c26 100644--- a/services/mcp/src/tools/generated/tasks.ts+++ b/services/mcp/src/tools/generated/tasks.ts@@ -54,6 +54,7 @@ const loopsCreatePrepare = (): ToolBase<typeof LoopsCreateSchema, PrepareConfirmmessageTemplate:"About to create the loop '{name}', a persistent automation that will run unattended with your GitHub and connector access whenever its triggers fire. Reply 'confirm' to create it.\n",codec: __runtime.codec,+ stash: __runtime.stash,boundScope: { projectId: String(__scopeProjectId) },})},@@ -70,6 +71,7 @@ const loopsCreateExecute = (): ToolBase<typeof LoopsCreateSchemaExecute, Schemaspurpose: 'loops-create',codec: __runtime.codec,ledger: __runtime.ledger,+ stash: __runtime.stash,expectedScope: { projectId: String(__scopeProjectId) },})if (!__guard.ok) {diff --git a/services/mcp/tests/hono/app-routes.test.ts b/services/mcp/tests/hono/app-routes.test.tsindex bbd4ee06a5e1..754df178d00e 100644--- a/services/mcp/tests/hono/app-routes.test.ts+++ b/services/mcp/tests/hono/app-routes.test.ts@@ -15,6 +15,7 @@ beforeAll(() => {})interface MockRedis extends RedisLike {+ incrby(key: string, increment: number): Promise<number>ping: Mock<() => Promise<string>>_store: Map<string, string>}diff --git a/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts b/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.tsindex 6ff5f2fd9bae..e53ad566359a 100644--- a/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts+++ b/services/mcp/tests/hono/helpers/redis-rate-limit-stubs.ts@@ -1,12 +1,14 @@export interface RedisRateLimitStubs {incr: (key: string) => Promise<number>+ incrby: (key: string, increment: number) => Promise<number>expire: (key: string, seconds: number) => Promise<number>ttl: (key: string) => Promise<number>}-// Trivial in-memory stubs for the rate-limit ops on RedisLike. Test files that-// only need to satisfy the interface (no rate-limit assertions of their own)-// can spread the return value into their fake-redis builder.+// Trivial in-memory stubs for the counter ops on RedisLike (rate limiting and+// the confirmed-action stash quota). Test files that only need to satisfy the+// interface (no counter assertions of their own) can spread the return value+// into their fake-redis builder.export function makeRedisRateLimitStubs(): RedisRateLimitStubs {const counts = new Map<string, number>()return {@@ -15,6 +17,11 @@ export function makeRedisRateLimitStubs(): RedisRateLimitStubs {counts.set(key, next)return next},+ incrby: async (key, increment) => {+ const next = (counts.get(key) ?? 0) + increment+ counts.set(key, next)+ return next+ },expire: async () => 1,ttl: async () => 60,}diff --git a/services/mcp/tests/hono/mcp-protocol.test.ts b/services/mcp/tests/hono/mcp-protocol.test.tsindex a31963e31d40..0c2002375064 100644--- a/services/mcp/tests/hono/mcp-protocol.test.ts+++ b/services/mcp/tests/hono/mcp-protocol.test.ts@@ -23,7 +23,10 @@ import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'const mswServer = setupServer(...handlers, contextMillHandler)-function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {+function createInMemoryRedis(): RedisLike & {+ ping(): Promise<string>+ incrby(key: string, increment: number): Promise<number>+} {const store = new Map<string, string>()return {get: async (key) => store.get(key) ?? null,diff --git a/services/mcp/tests/hono/session-mode-pool.test.ts b/services/mcp/tests/hono/session-mode-pool.test.tsindex ef0711a2fdb3..19688d8ff6a1 100644--- a/services/mcp/tests/hono/session-mode-pool.test.ts+++ b/services/mcp/tests/hono/session-mode-pool.test.ts@@ -25,7 +25,10 @@ import { makeRedisRateLimitStubs } from './helpers/redis-rate-limit-stubs'const mswServer = setupServer(...handlers, contextMillHandler)-function createInMemoryRedis(): RedisLike & { ping(): Promise<string> } {+function createInMemoryRedis(): RedisLike & {+ ping(): Promise<string>+ incrby(key: string, increment: number): Promise<number>+} {const store = new Map<string, string>()return {get: async (key) => store.get(key) ?? null,diff --git a/services/mcp/tests/unit/confirmed-action-runtime.test.ts b/services/mcp/tests/unit/confirmed-action-runtime.test.tsindex 66bd6a107025..cbb46bcb6cc0 100644--- a/services/mcp/tests/unit/confirmed-action-runtime.test.ts+++ b/services/mcp/tests/unit/confirmed-action-runtime.test.ts@@ -5,7 +5,7 @@ import {confirmedActionPreparesTotal,confirmedActionRefusalsTotal,} from '@/hono/metrics'-import { NonceLedger, SignedStateCodec } from '@/lib/signed-state'+import { NonceLedger, PayloadStash, SignedStateCodec } from '@/lib/signed-state'import {CONFIRMATION_HASH_ARG,CONFIRMATION_WORD,@@ -52,15 +52,50 @@ function makeLedger(): { ledger: NonceLedger; consumed: Set<string> } {return { ledger, consumed }}+function makeStash(): { stash: PayloadStash; store: Map<string, string>; quotas: Map<string, number> } {+ const store = new Map<string, string>()+ const quotas = new Map<string, number>()+ const stash = new PayloadStash({+ set: async (key, value, ..._args) => {+ const args = _args.map((a) => (typeof a === 'string' ? a.toUpperCase() : a))+ if (args.includes('NX') && store.has(key)) {+ return null+ }+ store.set(key, value)+ return 'OK'+ },+ get: async (key) => store.get(key) ?? null,+ del: async (...keys) => {+ let deleted = 0+ for (const key of keys) {+ if (store.delete(key)) {+ deleted += 1+ }+ }+ return deleted+ },+ incrby: async (key, increment) => {+ const next = (quotas.get(key) ?? 0) + increment+ quotas.set(key, next)+ return next+ },+ expire: async () => 1,+ ttl: async () => 60,+ })+ return { stash, store, quotas }+}+describe('prepareConfirmedAction', () => {it('returns the canonical payload shape with a signed token', async () => {const codec = makeCodec()+ const { stash } = makeStash()const result = await prepareConfirmedAction(makeContext('did-1'), {args: { orgId: 'acme' },purpose: 'organization-enforce-2fa-update',actionLabel: 'enforce 2FA',messageTemplate: 'About to enable enforce 2FA on organization {orgId}.',codec,+ stash,})expect(result.confirmation_word).toBe(CONFIRMATION_WORD)expect(result.action).toBe('enforce 2FA')@@ -69,40 +104,125 @@ describe('prepareConfirmedAction', () => {expect(result.next_steps).toContain('"confirm"')})+ it('keeps the hash small and constant-size regardless of args size', async () => {+ // The args live in the stash, not the token. If someone regresses to+ // signing them inline, a large payload (a scout body + files) makes+ // the hash tens of kilobytes that the model must relay verbatim —+ // this catches that by preparing ~200 KB of args.+ const codec = makeCodec()+ const { stash } = makeStash()+ const result = await prepareConfirmedAction(makeContext('did-1'), {+ args: { name: 'signals-scout-big', body: 'x'.repeat(200_000) },+ purpose: 'scout-create',+ actionLabel: 'create scout',+ messageTemplate: 'msg',+ codec,+ stash,+ })+ expect(result.confirmation_hash.length).toBeLessThan(1024)+ })++ it('refuses to stash a payload over the size cap', async () => {+ // Stashed payloads sit in shared Redis for the token TTL. Without+ // the cap, a caller at the rate limit can retain rate × TTL ×+ // request-size bytes and pressure eviction of session state.+ const codec = makeCodec()+ const { stash, store } = makeStash()+ await expect(+ prepareConfirmedAction(makeContext('did-1'), {+ args: { body: 'x'.repeat(1_100_000) },+ purpose: 'scout-create',+ actionLabel: 'create scout',+ messageTemplate: 'msg',+ codec,+ stash,+ })+ ).rejects.toThrow('too large')+ expect(store.size).toBe(0)+ })++ it('refuses to stash once the per-user window quota is exhausted', async () => {+ // Per-payload and per-request caps alone still let a caller at the+ // rate limit retain gigabytes within one token TTL; the aggregate+ // quota is what bounds that. Dropping it reopens the exposure.+ // Unique nonces per prepare — the shared makeCodec pins one nonce,+ // which would collide in the stash across repeated prepares.+ let nonceCounter = 0+ const codec = new SignedStateCodec(Buffer.alloc(32, 0x42), {+ now: () => 1_700_000_000_000,+ randomNonce: () => `nonce-${nonceCounter++}`,+ ttlSeconds: 300,+ })+ const { stash, store } = makeStash()+ const args = { body: 'x'.repeat(900_000) }+ for (let i = 0; i < 23; i++) {+ await prepareConfirmedAction(makeContext('did-1'), {+ args,+ purpose: 'scout-create',+ actionLabel: 'create scout',+ messageTemplate: 'msg',+ codec,+ stash,+ })+ }+ await expect(+ prepareConfirmedAction(makeContext('did-1'), {+ args,+ purpose: 'scout-create',+ actionLabel: 'create scout',+ messageTemplate: 'msg',+ codec,+ stash,+ })+ ).rejects.toThrow('too much pending confirmation data')+ expect(store.size).toBe(23)+ })+it('leaves unknown placeholders literal so authors notice missing keys', async () => {const codec = makeCodec()+ const { stash } = makeStash()const result = await prepareConfirmedAction(makeContext(), {args: {},purpose: 'p',actionLabel: 'a',messageTemplate: 'Delete {missing}',codec,+ stash,})expect(result.message).toBe('Delete {missing}')})it('leaves non-scalar placeholders literal (no "[object Object]" in user prompts)', async () => {const codec = makeCodec()+ const { stash } = makeStash()const result = await prepareConfirmedAction(makeContext(), {args: { filters: { team: 1 }, tags: ['a', 'b'] },purpose: 'p',actionLabel: 'a',messageTemplate: 'Apply {filters} for {tags}',codec,+ stash,})expect(result.message).toBe('Apply {filters} for {tags}')})})describe('executeConfirmedAction', () => {- function setup(): { codec: SignedStateCodec; ledger: NonceLedger; consumed: Set<string> } {+ function setup(): {+ codec: SignedStateCodec+ ledger: NonceLedger+ stash: PayloadStash+ store: Map<string, string>+ } {const codec = makeCodec()- const { ledger, consumed } = makeLedger()- return { codec, ledger, consumed }+ const { ledger } = makeLedger()+ const { stash, store } = makeStash()+ return { codec, ledger, stash, store }}async function mintToken(codec: SignedStateCodec,+ stash: PayloadStash,distinctId: string,purpose: string,payload: unknown@@ -114,13 +234,14 @@ describe('executeConfirmedAction', () => {actionLabel: 'x',messageTemplate: 'msg',codec,+ stash,})return result.confirmation_hash}it('verifies a fresh token and returns verifiedArgs', async () => {- const { codec, ledger } = setup()- const hash = await mintToken(codec, 'did-1', 'enforce-2fa', { orgId: 'acme' })+ const { codec, ledger, stash } = setup()+ const hash = await mintToken(codec, stash, 'did-1', 'enforce-2fa', { orgId: 'acme' })const outcome = await executeConfirmedAction(makeContext('did-1'), {incomingArgs: {[CONFIRMATION_HASH_ARG]: hash,@@ -129,6 +250,7 @@ describe('executeConfirmedAction', () => {purpose: 'enforce-2fa',codec,ledger,+ stash,})expect(outcome.ok).toBe(true)if (outcome.ok) {@@ -137,13 +259,14 @@ describe('executeConfirmedAction', () => {})it('refuses if the literal confirmation word is wrong', async () => {- const { codec, ledger } = setup()- const hash = await mintToken(codec, 'did-1', 'p', {})+ const { codec, ledger, stash } = setup()+ const hash = await mintToken(codec, stash, 'did-1', 'p', {})const outcome = await executeConfirmedAction(makeContext('did-1'), {incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'yes' },purpose: 'p',codec,ledger,+ stash,})expect(outcome.ok).toBe(false)if (!outcome.ok) {@@ -152,13 +275,14 @@ describe('executeConfirmedAction', () => {})it('refuses on user mismatch', async () => {- const { codec, ledger } = setup()- const hash = await mintToken(codec, 'did-victim', 'p', {})+ const { codec, ledger, stash } = setup()+ const hash = await mintToken(codec, stash, 'did-victim', 'p', {})const outcome = await executeConfirmedAction(makeContext('did-attacker'), {incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'p',codec,ledger,+ stash,})expect(outcome.ok).toBe(false)if (!outcome.ok) {@@ -167,13 +291,14 @@ describe('executeConfirmedAction', () => {})it('refuses on purpose mismatch', async () => {- const { codec, ledger } = setup()- const hash = await mintToken(codec, 'did-1', 'tool-A', {})+ const { codec, ledger, stash } = setup()+ const hash = await mintToken(codec, stash, 'did-1', 'tool-A', {})const outcome = await executeConfirmedAction(makeContext('did-1'), {incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'tool-B',codec,ledger,+ stash,})expect(outcome.ok).toBe(false)if (!outcome.ok) {@@ -182,13 +307,14 @@ describe('executeConfirmedAction', () => {})it('refuses on replay of the same hash', async () => {- const { codec, ledger } = setup()- const hash = await mintToken(codec, 'did-1', 'p', { orgId: 'x' })+ const { codec, ledger, stash } = setup()+ const hash = await mintToken(codec, stash, 'did-1', 'p', { orgId: 'x' })const first = await executeConfirmedAction(makeContext('did-1'), {incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'p',codec,ledger,+ stash,})expect(first.ok).toBe(true)const second = await executeConfirmedAction(makeContext('did-1'), {@@ -196,6 +322,63 @@ describe('executeConfirmedAction', () => {purpose: 'p',codec,ledger,+ stash,+ })+ expect(second.ok).toBe(false)+ if (!second.ok) {+ expect(second.result.content[0]!.text).toContain('already been used')+ }+ })++ it('refuses when the stashed payload does not match the signed digest', async () => {+ // Redis contents are not covered by the token signature — only the+ // digest binds them. Without this check, anything able to write the+ // stash key could swap in arbitrary args under a valid confirmation.+ const { codec, ledger, stash, store } = setup()+ const hash = await mintToken(codec, stash, 'did-1', 'p', { orgId: 'acme' })+ for (const key of store.keys()) {+ store.set(key, JSON.stringify({ args: { orgId: 'evil' }, scope: null }))+ }+ const outcome = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'p',+ codec,+ ledger,+ stash,+ })+ expect(outcome.ok).toBe(false)+ if (!outcome.ok) {+ expect(outcome.result.content[0]!.text).toContain('does not match the signed digest')+ }+ })++ it('executes an inline-payload token once and refuses its replay via the ledger', async () => {+ // Mixed-version deploys: a server on the older token format signs+ // {args, scope} directly into the claim instead of stashing. The+ // newer execute path must still honor it exactly once.+ const { codec, ledger, stash } = setup()+ const { token } = await codec.encode({+ sub: 'did-1',+ purpose: 'p',+ payload: { args: { orgId: 'acme' }, scope: null },+ })+ const first = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: token, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'p',+ codec,+ ledger,+ stash,+ })+ expect(first.ok).toBe(true)+ if (first.ok) {+ expect(first.verifiedArgs).toEqual({ orgId: 'acme' })+ }+ const second = await executeConfirmedAction(makeContext('did-1'), {+ incomingArgs: { [CONFIRMATION_HASH_ARG]: token, [CONFIRMATION_WORD_ARG]: 'confirm' },+ purpose: 'p',+ codec,+ ledger,+ stash,})expect(second.ok).toBe(false)if (!second.ok) {@@ -207,13 +390,14 @@ describe('executeConfirmedAction', () => {// Cross-project replay: prepare while project A is active, then run// execute after switch-project made B active. The signed scope (A)// must not authorize the action against B.- const { codec, ledger } = setup()+ const { codec, ledger, stash } = setup()const prep = await prepareConfirmedAction(makeContext('did-1'), {args: { name: 'mrr' },purpose: 'metric-approve',actionLabel: 'approve metric',messageTemplate: 'msg',codec,+ stash,boundScope: { projectId: '1' },})const outcome = await executeConfirmedAction(makeContext('did-1'), {@@ -224,6 +408,7 @@ describe('executeConfirmedAction', () => {purpose: 'metric-approve',codec,ledger,+ stash,expectedScope: { projectId: '2' },})expect(outcome.ok).toBe(false)@@ -233,13 +418,14 @@ describe('executeConfirmedAction', () => {})it('succeeds when the active scope still matches the scope bound at prepare time', async () => {- const { codec, ledger } = setup()+ const { codec, ledger, stash } = setup()const prep = await prepareConfirmedAction(makeContext('did-1'), {args: { name: 'mrr' },purpose: 'metric-approve',actionLabel: 'approve metric',messageTemplate: 'msg',codec,+ stash,boundScope: { projectId: '1' },})const outcome = await executeConfirmedAction(makeContext('did-1'), {@@ -250,6 +436,7 @@ describe('executeConfirmedAction', () => {purpose: 'metric-approve',codec,ledger,+ stash,expectedScope: { projectId: '1' },})expect(outcome.ok).toBe(true)@@ -259,8 +446,8 @@ describe('executeConfirmedAction', () => {})it('refuses on tampered signature', async () => {- const { codec, ledger } = setup()- const hash = await mintToken(codec, 'did-1', 'p', {})+ const { codec, ledger, stash } = setup()+ const hash = await mintToken(codec, stash, 'did-1', 'p', {})const segs = hash.split('.')const tampered = `${segs[0]}.${segs[1]}.${segs[2]!.slice(0, -1)}A`const outcome = await executeConfirmedAction(makeContext('did-1'), {@@ -268,6 +455,7 @@ describe('executeConfirmedAction', () => {purpose: 'p',codec,ledger,+ stash,})expect(outcome.ok).toBe(false)if (!outcome.ok) {@@ -275,13 +463,14 @@ describe('executeConfirmedAction', () => {}})- it('sources the ledger TTL from the codec clock, not the wall clock', async () => {+ it('sources the ledger TTL from the codec clock, not the wall clock, for inline-payload tokens', async () => {// Pin the codec's clock 100s before exp. If the runtime ever// sources the TTL from the wall clock instead, the codec's fake// clock and real Date.now() will diverge by ~years and the// observed TTL will collapse to 1 — re-allowing replay against- // a real Redis.+ // a real Redis. Only inline-payload tokens touch the ledger.const codec = makeCodec() // ttlSeconds: 300, clock pinned 100s before exp+ const { stash } = makeStash()let observedTtl: number | undefinedconst ledger = new NonceLedger({set: async (_key, _value, ..._args) => {@@ -290,12 +479,17 @@ describe('executeConfirmedAction', () => {return 'OK'},})- const hash = await mintToken(codec, 'did-1', 'tool-A', { x: 1 })+ const { token } = await codec.encode({+ sub: 'did-1',+ purpose: 'tool-A',+ payload: { args: { x: 1 }, scope: null },+ })const outcome = await executeConfirmedAction(makeContext('did-1'), {- incomingArgs: { [CONFIRMATION_HASH_ARG]: hash, [CONFIRMATION_WORD_ARG]: 'confirm' },+ incomingArgs: { [CONFIRMATION_HASH_ARG]: token, [CONFIRMATION_WORD_ARG]: 'confirm' },purpose: 'tool-A',codec,ledger,+ stash,})expect(outcome.ok).toBe(true)expect(observedTtl).toBe(300)@@ -311,19 +505,6 @@ describe('confirmed-action metrics', () => {confirmedActionRefusalsTotal.reset()})- function makeLedger(): NonceLedger {- const consumed = new Set<string>()- return new NonceLedger({- set: async (key, _v, ..._args) => {- if (consumed.has(key)) {- return null- }- consumed.add(key)- return 'OK'- },- })- }-async function metricValue(counter:| typeof confirmedActionPreparesTotal@@ -341,25 +522,29 @@ describe('confirmed-action metrics', () => {it('increments prepares_total on a successful prepare', async () => {const codec = makeCodec()+ const { stash } = makeStash()await prepareConfirmedAction(makeContext('did-1'), {args: {},purpose: 'tool-A',actionLabel: 'A',messageTemplate: 'msg',codec,+ stash,})expect(await metricValue(confirmedActionPreparesTotal, { tool: 'tool-A', status: 'ok' })).toBe(1)})it('increments executes_total ok on a successful execute', async () => {const codec = makeCodec()- const ledger = makeLedger()+ const { ledger } = makeLedger()+ const { stash } = makeStash()const prep = await prepareConfirmedAction(makeContext('did-1'), {args: { id: 'x' },purpose: 'tool-B',actionLabel: 'B',messageTemplate: 'msg',codec,+ stash,})await executeConfirmedAction(makeContext('did-1'), {incomingArgs: {@@ -369,19 +554,22 @@ describe('confirmed-action metrics', () => {purpose: 'tool-B',codec,ledger,+ stash,})expect(await metricValue(confirmedActionExecutesTotal, { tool: 'tool-B', status: 'ok' })).toBe(1)})it('increments refusals_total with the right reason label per failure mode', async () => {const codec = makeCodec()- const ledger = makeLedger()+ const { ledger } = makeLedger()+ const { stash } = makeStash()const prep = await prepareConfirmedAction(makeContext('did-1'), {args: {},purpose: 'tool-C',actionLabel: 'C',messageTemplate: 'msg',codec,+ stash,})// wrong wordawait executeConfirmedAction(makeContext('did-1'), {@@ -389,6 +577,7 @@ describe('confirmed-action metrics', () => {purpose: 'tool-C',codec,ledger,+ stash,})// user mismatchawait executeConfirmedAction(makeContext('did-attacker'), {@@ -396,6 +585,7 @@ describe('confirmed-action metrics', () => {purpose: 'tool-C',codec,ledger,+ stash,})expect(await metricValue(confirmedActionRefusalsTotal, { tool: 'tool-C', reason: 'wrong_word' })).toBe(1)expect(await metricValue(confirmedActionRefusalsTotal, { tool: 'tool-C', reason: 'user_mismatch' })).toBe(1)diff --git a/services/mcp/tests/unit/signed-state.test.ts b/services/mcp/tests/unit/signed-state.test.tsindex 681985fb1ad5..95254335a331 100644--- a/services/mcp/tests/unit/signed-state.test.ts+++ b/services/mcp/tests/unit/signed-state.test.ts@@ -4,6 +4,7 @@ import {loadSigningKeyFromEnv,NonceLedger,type NonceLedgerRedis,+ PayloadStash,SignedStateAlreadyConsumed,SignedStateCodec,SignedStateExpired,@@ -176,3 +177,61 @@ describe('NonceLedger', () => {expect(args).toEqual(['mcp:signed-state:nonce:nonce-1', '1', 'EX', 300, 'NX'])})})++describe('PayloadStash', () => {+ it('yields the payload to only one of two concurrent takes', async () => {+ // take() is GET then DEL; the DEL return value is the single-use+ // guard. If take() ever stops checking it, two racing executes both+ // GET the payload and both proceed — a destructive action runs twice.+ const stored = new Map<string, string>([['mcp:signed-state:payload:nonce-1', '{"args":{}}']])+ let delCalls = 0+ const stash = new PayloadStash({+ set: async () => 'OK',+ get: async (key: string) => stored.get(key) ?? null,+ del: async (...keys: string[]) => {+ // Both takes GET before either DELs; only the first DEL wins.+ delCalls += 1+ if (delCalls > 1) {+ return 0+ }+ for (const key of keys) {+ stored.delete(key)+ }+ return 1+ },+ incrby: async (_key: string, increment: number) => increment,+ expire: async () => 1,+ ttl: async () => 60,+ })+ const winner = await stash.take('nonce-1')+ stored.set('mcp:signed-state:payload:nonce-1', '{"args":{}}')+ const loser = await stash.take('nonce-1')+ expect(winner).toBe('{"args":{}}')+ expect(loser).toBeNull()+ })++ it('re-arms a quota key that lost its expiry, and leaves a live one alone', async () => {+ // A crash between the first INCRBY and its EXPIRE leaves the quota+ // counter immortal; without the repair, a user crossing the quota is+ // refused forever. Re-arming a live TTL would be wrong too — it+ // extends the window on every refusal.+ const expireCalls: Array<[string, number]> = []+ let ttlValue = -1+ const stash = new PayloadStash({+ set: async () => 'OK',+ get: async () => null,+ del: async () => 0,+ incrby: async (_key: string, increment: number) => increment,+ expire: async (key: string, seconds: number) => {+ expireCalls.push([key, seconds])+ return 1+ },+ ttl: async () => ttlValue,+ })+ await stash.repairQuotaExpiry('user-1', 930)+ expect(expireCalls).toEqual([['mcp:signed-state:payload-quota:user-1', 930]])+ ttlValue = 500+ await stash.repairQuotaExpiry('user-1', 930)+ expect(expireCalls).toHaveLength(1)+ })+})