# Threat model

> Generated from the SDK's own source (`docs/durable/security.md`) at build; edit there.

### The operator API

- **Assets.** Every run with its stored input and output, every step
  row with its captured lines, every ledger row with its images (the
  business state before and after each write), the facts, the waits,
  the settings rows (the rate buckets, the schedules' slots, a host's
  configuration rows), the catalogue, and the operator actions: a
  redrive, a dismiss, a cancel, a hold, a signal, an undo, a scrub, a
  bulk redrive, a replay of a window of facts. A host's own entries ride
  the same table (`consoleApi({ routes })`) and answer whatever the host
  stores (a desk, a device roster, a CSV).
- **Trust boundary.** HTTPS from a console, a script, an agent or a CLI
  to the deployment's `/admin/api/*` routes. The table is the contract
  (`packages/durable-core/src/console/contract.ts`, every entry with its
  method, its scope `read`, `write` or `destructive`, its zod input and
  output, its MCP tool; `GET /admin/api` the catalogue; the version
  header `X-Durable-Api` on every answer).
- **Attacker.** A holder of a bearer (leaked from a shell, a log, a
  screenshot, a CI secret); a holder of the session secret who signs as
  anyone; a looping client; a replayed session; a request that reaches a
  handler before authorization; a token in a URL or a cookie.
- **Controls in the tree.**
  - One gate, host-bound: `consoleApi({ authorize })` runs the host's
    gate before any handler, every answer through the table; the
    reference host's gate judges the bearer first, the session second,
    the scope third, the buckets fourth (`app/lib/admin-auth.server.ts`;
    SOC-04 moves the gate into the SDK, **landing**).
  - Two bearers, two scopes: a write bearer (`destructive`: every read,
    every action, every destructive door) and a read bearer (`read`:
    every action 403 `read-only token`, the package's own word
    `READ_ONLY_TOKEN`, before any run exists); compared through
    `safeEqual` (both sides hashed, `timingSafeEqual` over the digests,
    so neither the length nor the mismatch position leaks); the bearer
    in the `Authorization` header alone, a `?token=` query or a cookie
    nobody (`invariants/bearer-in-header-alone`,
    `invariants/gate-compares-constant-time`,
    `invariants/admin-tokens-read-once`).
  - A signed session names the actor: a compact JWS in the header the
    catalogue names (`api.session`), HS256 under the session secret,
    the audience, five minutes of life, sixty seconds of skew, a `jti`
    remembered against replay for the process, the subject `user:`,
    `cli:` or `agent:` and nothing that acts on its own; every secret of
    a rotation judged by one compare with no early exit
    (`app/lib/console-session.server.ts`,
    `invariants/session-verifier-no-early-exit`,
    `invariants/console-gate-one-definition`,
    `invariants/route-passes-one-gate`); the session's `scope` narrows
    the bearer's and never widens it; the session's `abilities` claim is
    the host's role catalogue, refused per door
    (`console-read-parity/host-entry-ability`,
    `invariants/door-abilities-agree`).
  - Bounded and recorded: one token from the actor's bucket, the
    bearer's bucket and, on a mutation, the actor's actions bucket, taken
    in one statement without waiting (`SettingsStore.takeTokens`), 429
    with `Retry-After` and the bucket's name (never the actor: the key is
    the kind and sixteen hex of the actor's digest), one `console.request`
    line per admitted request (`scope`, `actor`, `method`, `path` without
    its query, `bounded`), one `console.rate_limited` per refusal
    (`app/lib/console-rate.ts`; the log names rows of the catalog,
    the `log-catalog` guard).
  - The actor on every write: a run row's `actor`, a ledger row's
    `actor`, a fact's `requestId`; an operator action is one keyed,
    ledgered run under the gate's subject
    (`packages/durable-core/src/operator/`, `operatorAction()`), never a
    name a body spells; a body field never chooses the actor.
  - The shape of every input judged at the door (zod on every entry, the
    lock `contract.lock.json`, a moved shape refused without a version,
    the `console-contract` guard); the answers bounded in
    rows (`console-paging/lists-page`) and, planned, in bytes (FP-041).
- **Residual risk.** A bearer with no session is the anonymous
  `user:console` with every door open (R-03, SOC-04); one secret signs
  on every environment and every holder can sign as anyone, with replay
  caught per process alone (R-03, SOC-04: asymmetric sessions through a
  KMS, an audience per environment, replay ids in the store); the two
  bearers are one value on every environment of the reference host
  (R-01, SOC-05); the limiter fails open when the store cannot answer
  the take, by design for the health reads and the wrong default for a
  write under attack (R-19, SOC-17); a token per person for a script or
  an agent does not exist (R-28, SOC-04); the gate is host code, so a
  new host could bind a gate with no bearer and no session (SOC-04
  ships the gate in the SDK with a doctor rule refusing a gate without
  one).

### The relay

- **Assets.** The facts a member publishes to its peers (a copy of each
  outbox row under the peer's own id, its payload through the
  receiver's redaction policy), the members' sequence numbers, the
  ephemeral members' registrations, and the listeners a copy may run.
- **Trust boundary.** HTTPS between two named members of
  `durable.peers.json` (`POST /internal/relay`), each pair under its own
  secret; an ephemeral member (a preview, a laptop) under the one
  preview secret of the member it joins.
- **Attacker.** A stranger posting batches; a peer's secret leaked; a
  replayed or re-ordered batch; an oversized body; a copy that bounces
  back; a peer that claims another's name; a fact name no catalog knows;
  a laptop on the mesh announcing a URL it does not own.
- **Controls in the tree.**
  - The signature is the whole authentication: HMAC-SHA256 under the
    pair secret over `timestamp.body`, checked against every configured
    peer's secret and the rotation's second secret in one constant-time
    pass with no early exit, 401 with no detail
    (`packages/durable-core/src/relay/receiver.ts`,
    `relay-boundaries/constant-time-verify`); the member's name held to
    the signing peer's after the own-name check (400 `from does not
match the signing peer`, `from is this app`).
  - The window: a signed timestamp within `RELAY_MAX_AGE_MS` (five
    minutes), a stale one logged `relay.stale_timestamp` so a clock's
    skew shows and a bad signature logs nothing
    (`packages/durable-core/src/events/relay.ts`).
  - The caps, before the body is read: `RELAY_MAX_BODY_BYTES` (1 MB,
    declared or measured, 413), `RELAY_MAX_EVENTS` (500 a batch),
    `RELAY_KEY_MAX` (512), `RELAY_EVENT_NAME`'s grammar, the moments
    bounded (`validateRelayEvent`).
  - The sequence: `in:<peer>.lastSeq`, a gap refused 409 `out of
sequence` so the sender resends in order, a repeat answered with the
    ids already held; one lease per peer on the sender (`claimPeer`), so
    one tick posts at a time (ADR-0046 §H).
  - The landing: a copy under its own id with the origin in `peerId`,
    the partition `relay:<origin>:<partition>`, the payload through the
    bound redaction policy (`storedPayload`), its listeners under the
    per-listener, per-origin policy (`record` by default: a copy never
    acts; an `execute` listener's body held off every scope resolver by
    `assertLocalFact()` and the execute-listener guard,
    `invariants/execute-listener-off-the-world`); copies never bounce
    (the sender selects origin-null rows alone,
    `environment-corruption/copy-never-bounces`).
  - The secrets: a `Secret<string>` revealed at the signature and at
    the check alone, read by the adapter's `peersFromEnv` from
    `DURABLE_PEER_SECRET_<NAME>` (`relay-boundaries/symbol-boundaries`,
    `relay-boundaries/no-log-carries-secret`,
    `invariants/secret-reveals-at-the-wire`); a secret shorter than 32
    characters drops the peer with one line; a rotation staged,
    promoted and finished with a deploy after each stage, never a broken
    pair (`durable-sdk peer secret rotate`).
  - The ephemeral members: a name of the grammar `preview:<branch>` or
    `local:<user>` alone, registered at the receiver from the batch's
    own announcement, an announced URL on the member's own host or a
    declared peer's refused (`relay.ephemeral_url_refused`), forgotten a
    day after the last contact (ADR-0053).
  - The receiver reads no environment and fetches nothing; only the
    sender fetches a peer (`relay-boundaries/receiver-reads-no-environment`,
    `relay-boundaries/only-sender-fetches-peer`).
- **Residual risk.** No per-peer rate limit and no bound on a stranger's
  attempts beyond the signature's cost (R-20, SOC-17); a relayed fact
  whose name no catalog knows is stored (R-22, SOC-18: quarantined); the
  pair secrets are written readable so the rotation can read them back
  (R-27, SOC-14); a production member publishing every fact to a
  development member is a data-exposure choice of the reference host
  (R-02, SOC-05).

### The webhooks

- **Assets.** The facts a provider's delivery becomes, the audit row of
  each delivery, and whatever the listeners do with the fact.
- **Trust boundary.** HTTPS from a provider to a route the host binds
  with `webhookRoute({ durable, verify, toFacts, record })`
  (`@durable-sdk/vercel/react-router`).
- **Attacker.** A forged delivery; a replayed one; an oversized or
  malformed body; a provider whose delivery is unsigned by design.
- **Controls in the tree.**
  - `verify` first, before anything is read or emitted: the provider's
    own check in one module per provider under `app/lib/webhooks/`,
    the route file spelling no handler and no `emit(` of its own
    (`invariants/webhook-route-is-the-package-binding`,
    `invariants/webhook-verify-in-webhooks-dir`).
  - A delivery only emits: the facts under the catalog's keys, so a
    burst collapses on its key and nothing runs inline; every fact a
    webhook route emits declares a schema the door judges before any
    insert (`events/webhook-facts-declare-a-schema`,
    `event.payload.invalid`).
  - The record: the audit row written inside the binding; its failure
    is `webhook.record_failed`, never the answer.
  - A moment in a key is the provider's own stamp, declared under
    `moments` (ADR-0060 decision 6; the `key-parts` guard).
- **Residual risk.** No body cap and no rate limit on a webhook route
  (R-20, SOC-17 **planned**: body caps); a provider whose delivery is
  unsigned is authenticated by a secret in the URL's query (R-21, SOC-17:
  out of the URL); schemas on every fact, not only the webhooks' (R-22,
  SOC-18).

### The cron and the wake

- **Assets.** The dispatcher's tick (what delivers every fact and
  resumes every run) and the partition wakes.
- **Trust boundary.** The platform's cron calling `/jobs/dispatch`; the
  queue's consumer function (`api/durable/wake.ts`) forwarding a wake to
  the deployment's own `/jobs/dispatch?wake=`.
- **Attacker.** A caller of the cron route; a forged or replayed queue
  message; a message published by another deployment.
- **Controls in the tree.**
  - The cron route behind the cron bearer, judged by the package's
    binding (`dispatchLoader({ durable })`, `bearerMatches` in the
    adapter; `invariants/cron-route-binds-through-stub`,
    `invariants/invocation-wraps-attempt-routes`).
  - The wake message carries ids, a partition string and a mac alone:
    HMAC-SHA256 under the cron secret over the version, the publishing
    deployment and the ids (`packages/durable-vercel/src/mac.ts`),
    verified in constant time by the consumer before anything is built
    from it (`invariants/mac-verify-constant-time`); a message another
    deployment published or the secret did not sign is acknowledged with
    no forward (`wake.stale`, `wake.unsigned`); the consumer trusts the
    message, never the transport, and reaches the deployment-unique host
    alone (`invariants/consumer-forwards-to-deployment-host`,
    `invariants/consumer-imports-package-alone`).
  - `maxDeliveries: 1` on the trigger and the queue's concurrency as the
    adapter declares it (`invariants/vercel-json-declares-consumer-trigger`).
  - A wake carries no payload, only ids; the cron tick is the fallback
    for every wake lost (ADR-0045).
- **Residual risk.** One secret is the cron bearer and the mac key, on
  every environment of the reference host (R-01, R-27: SOC-05, SOC-14,
  one key per purpose).

### The ledger

- **Assets.** The hash-chained record of every state change: who, what,
  the before and after images, the attempt, the moment; the head row per
  store; the operator's trust that the record is what happened.
- **Trust boundary.** The database role the deployment connects as; the
  store's append statement; the verification walk.
- **Attacker.** A role that edits or deletes rows; a restore from an
  older backup presented as current; a `TRUNCATE`; a recomputed chain
  after a rewrite; an image carrying a value that should never be at
  rest.
- **Controls in the tree.**
  - Append-only at the database: the trigger `ledger_append_only`
    refuses UPDATE and DELETE on every role
    (`packages/durable-postgres/src/ddl.ts`,
    `invariants/ledger-rows-append-only`, `invariants/ledger-schema-expand-only`).
  - The chain: every row's `hash` over its content and `prevHash`,
    `occurredAt` inside the hash since epoch `v4`, per-store and
    serialized under an advisory lock; the head row pinned with every
    append in the same statement, so a lost or replaced tail contradicts
    the head and every further append of that store is refused until a
    person records the incident (`LedgerHeadContradiction`,
    `invariants/ledger-head-one-writer`,
    `invariants/ledger-append-fences-attempt`).
  - The verification: `GET verify` walks every store from genesis under
    a bound (`ScanPage.to`), reads the heads first, names `brokenAt`,
    `interleaved` and the head's reason (`ahead`, `cut`, `rewritten`),
    and the trigger's state; CI walks the chain and checks the trigger
    on every release.
  - Every write goes through the recorder: `appendLedger` from the
    external step and the recorded write alone, the attempt fenced on
    the row (`invariants/append-ledger-closed-callers`,
    `invariants/store-verbs-called-from-their-modules`).
- **Residual risk.** `TRUNCATE` is admitted, the app's role owns the
  table and can disable the trigger, the chain is plain SHA-256 with no
  key and nothing outside the database records a head (R-05, SOC-16
  **planned**: `BEFORE TRUNCATE`, the grants revoked, a daily keyed head
  record in write-once storage, `ledger verify --file` over an export);
  the images are stored verbatim, never through the redaction policy, so
  a value that should never be at rest can be (R-35, FP-039: the image
  through the policy before the hash), and erasure of a subject's data
  in an image needs per-subject keys (R-35, FP-040).

### The MCP

- **Assets.** Everything the operator API answers, handed to a model;
  the operator actions when enabled.
- **Trust boundary.** A model's host process holding the read bearer,
  speaking to the deployment's operator API over HTTPS.
- **Attacker.** A model steered by what it reads (a run's input, a
  captured line, a fact's payload: data that came from the outside); a
  shell that holds the write bearer longer than its task; a committed
  configuration carrying a token.
- **Controls in the tree.**
  - Read-only by default: the read bearer alone starts the server; the
    write bearer alone refuses to start, naming the two variables and
    the flag (`packages/durable-mcp/src/config.ts`).
  - Actions behind three variables: `DURABLE_MCP_ALLOW_ACTIONS=1`, the
    write bearer, an agent name recorded as `agent:<name>` on every run
    and a session secret signing a five-minute session per request;
    destructive doors behind a fourth (`DURABLE_MCP_ALLOW_DESTRUCTIVE=1`),
    and the undo, the reset and the scrub have no tool by the contract
    (`console-read-parity/table-actions-name-tools`,
    `console-read-parity/no-tool-by-design-exact`).
  - Every tool annotated (`readOnlyHint`, `destructiveHint`); a 429 is
    a tool error naming the moment; the startup line says the mode and
    the bearer's name, never a value; the committed client
    configurations reference an environment variable and never a value
    (the `console-read-parity` guard; the package's
    `repo-config` test).
  - The catalogue read at start, the host's tools under their entries
    and abilities; the host's tools answer no customer field by name
    (`console-read-parity/host-tool-no-pii`).
- **Residual risk.** Data that arrived through a webhook or a fact
  reaches a model that may hold write access (prompt injection; R-25,
  SOC-17: a destructive tool needs a person, tool output marked
  untrusted); the MCP servers of the committed configurations are
  started with `npx -y …@latest` (R-29, SOC-13); one read token in many
  shells (R-28, SOC-04).

### Stored data and secrets

- **Assets.** Every stored copy of run data (inputs, outputs, errors,
  captured lines, step rows, images, facts) and the credentials the
  engine is handed.
- **Trust boundary.** The serializer every stored copy passes
  (`serializeStored` under the bound redaction policy), the `Secret<T>`
  wrapper and the secrets channel of `execute`.
- **Attacker.** A credential or an address written into a row or a log
  line; a stored input that re-keys to another run; an output a row
  cannot replay.
- **Controls in the tree.**
  - The policy, installed once by the factory (`createDurable({
redaction })`): a key redacted by name (`secret`, `token`,
    `password`, `apiKey`, `privateKey`, `credential`, …; a host's own
    names through its policy), a value by shape (an address, a provider
    key's prefix, a credential inside a URL's query or userinfo), a
    text's shapes inside a thrown message or a log line
    (`invariants/stored-data-through-serializer`,
    `invariants/stored-policy-installed-by-factory`,
    `step-bodies/log-fields-declared`,
    `step-bodies/step-output-keys-declared`).
  - A credential in memory is a `Secret<T>` revealed at the wire alone,
    handed to a run on `execute` options as `secrets: { … }` and present
    in the forward phase of that attempt alone, never on a stored input,
    a step row or an undo (`step-context/secrets-is-context-key`,
    `workflow-identity/secret-inputs-listed` empty); a client never
    enters an input (`input.unstorable`).
  - An output the row cannot replay (truncated or redacted) is refused
    for every effect but `read` (`step.output.truncated`,
    `step.output.redacted`), so a secret never rides as output: a
    one-time value goes back through `ctx.reply`.
  - A host that must seal stored data binds a codec (`createDurable({
codec })`), with an ADR line beside it (`invariants/codec-needs-adr`);
    the first host binds the subject codec `mky-subject-v1` (ADR-0076
    FP-040): a value a door tags with a subject is sealed under that
    subject's own key, and the erasure shreds the key, so the copy reads
    `[encoded]` while the row and the chain stand
    (`invariants/subject-codec-seals-by-tag`: the key store off the
    barrel, the data key through the site secrets module alone, the key
    on no image).
- **Residual risk.** The ledger's images bypass the policy (R-35,
  FP-039); a console line written outside a step passes unredacted
  (R-38, SOC-14: the planted-secret log search); no key ids or versions
  on the host's sealing key (R-27, SOC-14).

### The operator actions and the undo

Every operator action is `operatorAction()`: one keyed, ledgered run per
target and request under the gate's subject, answering `not_found`,
`refused` or the run's outcome, never a throw past the door; the redrive
is the one caller of `execute` with a ticket minted in the package's
redrive module alone (`execute.redrive_ticket`,
`invariants/testing-package-off-app-and-core`); the undo reverts every
row by compare-and-set through the bound reverters, a moved row refused
as a value and never overwritten, `UndoStopped` where the world moved
(`invariants/package-undo-names-no-reverter`,
`invariants/warehouse-reverters-compare-and-set`). The residual risk is
the actor's identity (R-03) and nothing of the mechanism.

---

Prompt for an agent:

```text
Read https://durablesdk.com/docs/security/threat-model.md, then apply what it says to this app; run durable-sdk doctor --host before and after; a refused line is a refusal id: durable-sdk explain <id>
```
