# Guard kit (TypeScript)

Reference for @omazyai/sdk/guard. Decides whether a capability call runs, asks for a confirm on reversible writes, holds sensitive ones for a person with step-up, and records every request. Kill switches, rate limits, tracing, audit rows and a chunked tenant purge.

Source: https://docs.omazy.ai/build-on-omazy/kits/guard/

:::caution[Preview]
The kit is a preview in `@omazyai/sdk` 0.5.3. Its interface may change before 1.0, so pin the exact version. It is TypeScript only.
:::

```ts
import { approver, codeStepUp, createGuard, d1GuardStore, d1RequestLog, d1Switches, policies } from '@omazyai/sdk/guard'
```

The guard sits between every caller (an MCP door, a copilot, an actor, a workflow) and your
[capabilities](/build-on-omazy/kits/capabilities/). It has no dependencies and uses only Web
standard APIs (`crypto.subtle` for tokens and sealing), so it runs on Cloudflare Workers, Node,
Bun and Deno. Your data stays in your database: the guard stores through adapters you choose.

## Set it up

```ts
const codes = codeStepUp<AppCtx>({
  store: d1GuardStore(env.OPS_DB),
  send: (ctx, channel, code) => mail.send(ctx.principal.id, `Your approval code is ${code}`),
})

const guard = createGuard<AppCtx, Permission>({
  registry: reg,
  can: (ctx, permission) => can(ctx, permission),          // live, on every call
  secret: env.GUARD_SECRET,                                 // 32 characters or more
  store: d1GuardStore(env.OPS_DB),
  policies: {
    tenant_self: policies.single({ approver: approver.authorOrRecordOwner(), stepUp: 'code', expires: '24h' }),
    tenant_owner_step_up: policies.single({ approver: approver.authorOrRecordOwner({ role: 'owner' }), stepUp: 'code', expires: '72h' }),
    platform_four_eyes: policies.fourEyes({ approver: approver.role(['platform_admin', 'finance']), stepUp: 'code', expires: '24h' }),
    super_admin_step_up: policies.single({ approver: approver.role('super_admin'), stepUp: ['passkey', 'two_channel'], typedTarget: true, expires: '1h' }),
  },
  recordOwner: (ctx, capability, input) => owners.of(ctx, capability, input),
  rolesOf: (ctx) => roles.of(ctx),
  stepUp: [codes, passkeyVerifier],
  switches: d1Switches(env.DB),
  log: d1RequestLog(env.OPS_DB),
})
```

Then, in a request:

```ts
const out = await guard.call(ctx, 'device_approve', { device_id: 'dev_7' }, { waitUntil: executionCtx.waitUntil.bind(executionCtx) })
```

`call` never throws. It returns an outcome, and the same word is written to the request log.

| `outcome` | Fields | Meaning |
|---|---|---|
| `ok` | `result`, `approvalId?` | It ran. An R1 result is masked |
| `confirm_required` | `preview`, `token`, `expiresAt` | An R2 write: show the preview, then call again with the same arguments and `{ confirmToken: token }` |
| `pending_approval` | `approval: { id, policy, decider, expiresAt, preview, reviewUrl? }` | An R3 or R4 action is waiting for a person. Nothing ran |
| `refused_permission` | `code`, `message` | `can()` said no, or the arguments name another tenant (`cross_tenant`) |
| `refused_tier` | `code`, `message` | The seat's ceiling (`maxTier`) is below the call's tier |
| `read_only` | `code`, `message` | Your `readOnly` rule refused a write |
| `stale` | `code`, `message` | The target changed since the preview |
| `rate_limited` | `retryAfter?` | Over a limit |
| `invalid` | `code`, `issues?` | Unknown tool, bad arguments, or a bad, used, expired or mismatched confirm token |
| `not_found` | `code`, `message` | A lookup found nothing: the arguments were fine, the record is not there. Throw `GuardRefusal('not_found', 'not_found', '...')` from `run` |
| `switched_off` | `switch: { key, scope, subject }` | A kill switch is off |
| `error` | `code` | Something failed; nothing was retried |

Every outcome carries `requestId` and, once the tool is known, `tier`. `message` is one plain
sentence a person or a model can act on.

## The order of checks

1. **Kill switches**, deny first.
2. **Rate limits**, per seat for reads and writes, and per tenant.
3. **Parse** through the registry. The tier of the call comes from `riskFor` when the capability has one.
4. **Tenant isolation**, then **your `can()`**.
5. **The tier**: the seat's ceiling, then your read-only rules for writes.
6. **R0 and R1 run.** An R1 result goes through `mask` (by default the capability's `pii` fields are redacted).
7. **R2 needs a confirm token.**
8. **R3 and R4 create an approval** and return `pending_approval`.
9. **Run.**
10. **The request log**, written after the response.

A capability's `preview` or `run` can end a call with a given outcome by throwing
`GuardRefusal('stale', 'precondition', 'The device was already approved.')`. Any other error
ends as `error` with a generic sentence; the error goes to `onError`.

## Preview without running

`guard.preview(ctx, name, args, opts?)` is for a dry run. It runs the checks of `call` (switches,
the arguments, the tenant, your `can()`, the seat's tier ceiling and `readOnly`), then the
capability's `preview`. It never runs the capability, mints no confirm token and asks for no
approval. It is not rate limited, and its request log row has the method `tools/preview`.

```ts
const p = await guard.preview(ctx, 'tenant_level_set', { tenant_id: 'tA', level: 'professional' })
if (p.outcome === 'ok') {
  p.preview.summary // "set tA from essential to professional"
  p.next            // 'run' | 'confirm' | 'approval': what guard.call would do next
  p.approval        // for 'approval': { policy, decider }
} else {
  p.outcome         // refused_permission, refused_tier, read_only, invalid, switched_off...
}
```

`{ confirm: 'upstream' }` makes an R2 preview answer `next: 'run'`. An ephemeral guard answers the
refusals its `call` would give (`confirm_unavailable`, `no_approvals`), and a missing policy is
`no_policy`, so a dry run finds them before the run goes live. The flows kit's dry run uses it,
so permission applies in dry run too.

## Tenants

A seat with a tenant acts only in that tenant. The guard refuses a call when:

- the ctx's `tenant` is not the seat's tenant;
- an argument at any of `tenantFields` (default `['tenant_id']`) names another tenant;
- your `tenantsOf(ctx, capability, input)` returns another tenant for the records the arguments name (a device id, a staff id).

A seat without a tenant (a platform door) is not limited this way; your `can()` and `readOnly` decide.

## Confirm tokens (R2)

The first call returns the preview and a token. The token is an HMAC over the seat, the tool,
the SHA-256 of the canonical arguments, the preview's `stateVersion` and a nonce. The nonce is
stored for 10 minutes (`confirmTtlMs`) and taken on use, so a token works once.

The second call must carry the same arguments. A token for other arguments, another seat or
another tool is refused `invalid` (`confirm_mismatch`) and stays usable for the right ones. When
the preview's `stateVersion` has moved, the call is refused `stale`.

Over MCP the token goes back to the client, which can send it again. The tool result names it
as `call` does: `outcome`, `token`, `expiresAt` and `preview` in `_meta["ai.omazy/outcome"]` (see
the MCP kit). A confirm protects against
drift between the preview and the change, not against a model acting alone. Keep anything that
reaches outside your product above R2.

### Confirmed upstream

Some callers confirm with the person themselves before they call: Omazy's agent with
`write_mode: 'confirm'` shows the person a card, and a form the person submitted is its own
confirmation. Asking again is a double confirm. Pass `{ confirm: 'upstream' }`:

```ts
await guard.call(ctx, 'brief_draft_save', { text }, { confirm: 'upstream' })
```

The call then runs in one step. The guard still mints its token, checks it at once, refuses a
stale preview and writes both steps to the request log (`confirm_required`, then the result).
R3 and R4 are unchanged: they still create an approval. Over MCP, give the seat
`confirm: 'upstream'` in `resolveSeat` and the door does this for it. Give it only to a caller you
know confirms with the person.

## A stateless door

```ts
const guard = createGuard({ registry: reg, can, ephemeral: true, log: d1RequestLog(env.DB) })
```

`ephemeral: true` needs no store and no secret. Confirm nonces live in memory for one call and
the key is random, so nothing outlives the request. That makes it fit for a door whose writes are
all confirmed upstream, and nothing else:

- an R2 call confirmed upstream runs;
- an R2 call the client would confirm is refused `refused_tier` (`confirm_unavailable`), since the
  token could never be checked on a later request;
- R3 and R4 are refused `refused_tier` (`no_approvals`): there is nowhere to keep an approval.

## Routes that are not MCP

```ts
const rest = guard.http(req, {
  principal: { kind: 'service', id: 'partner' },
  seat: { id: 'partner-key', door: 'rest', tenant: null },
  confirm: 'upstream',                       // a form post is its own confirmation
  waitUntil: (p) => exec.waitUntil(p),
  ctx: (base) => ({ ...base, deps }),        // when your ctx has more than the base fields
})
const out = await rest.call('ticket_file', body)
return Response.json(out.outcome === 'ok' ? out.result : { error: 'message' in out ? out.message : out.outcome }, { status: rest.status(out), headers: rest.headers })
```

`guard.http` builds the ctx (channel `rest`, the request id from `X-Omazy-Request-Id` or a new
one) and calls through the guard with the method `POST /path` and the request's country, so a
REST route gets the same switches, checks and request log as a door. `status(out)` maps an
outcome to 200, 202 (`pending_approval`), 400 (`invalid`), 403 (refusals), 404 (`not_found`), 409
(`confirm_required`, `stale`), 429, 500 or 503 (`switched_off`).

## Approvals (R3 and R4)

The call does not run. The guard stores an approval with the action, the requester, seat,
channel and tenant, the canonical arguments sealed with AES-GCM (bound to the approval id) and
their hash, the preview and its state version, the policy and the expiry. Later it holds the
decision, the decider, the step-up method, the result and your audit row id.

```ts
const row = await guard.approval(id)                       // arguments still sealed
const args = await guard.approvalArgs(id)                  // for the review page
await codes.start(deciderCtx, row)                         // sends a code to the decider
const d = await guard.decide(id, deciderCtx, { approve: true, proof: { method: 'code', codes: { email: '482913' } } })
// d.outcome: approved (with d.execution) | refused | not_allowed | step_up_required | step_up_failed
//            | reason_required | typed_target_mismatch | expired | already_decided | not_found
```

- **The approver comes from the policy, never from the caller.** `approver.authorOrRecordOwner({ role? })` lets the request's author or an owner of the target record (from your `recordOwner`) decide. `approver.role(roles)` lets anyone with one of the roles (from your `rolesOf`) decide. `policies.fourEyes` refuses the requester as decider. A decider in another tenant is always refused.
- **Step-up on every approval.** Every policy names at least one step-up method; a policy without one is refused when the call is made. The guard dispatches the proof to the verifier for its method and binds it to the approval id, the arguments' hash and the decider, so a proof for one approval does not decide another.
- **A refusal needs a reason.** Refusing asks for no step-up.
- **Decisions are a compare-and-swap** on `waiting`: of two deciders at once, one wins.
- **Expiry.** A decision after the expiry is refused and the row marked `expired`. Run `guard.expireDue()` from a cron to mark the rest.
- **Withdraw.** `guard.withdraw(id, ctx, reason)` takes back an approval while it waits: a compare-and-swap from `waiting` to `withdrawn`, so nobody can approve it and it never runs. Only its requester (the same principal in the same tenant) or a principal of kind `system` (`SYSTEM_PRINCIPAL_KIND`) may: the product's own code, in the approval's tenant, or in any tenant with a null `ctx.tenant`. A decider cannot; they refuse instead. The reason is required and kept on the row. Every attempt is a request-log row with method `approval/withdraw`; a withdrawal sends a `withdrawn` event. The outcome is `withdrawn`, `not_allowed`, `reason_required`, `already_decided` (decided, run or withdrawn already), `expired` or `not_found`. The copilot uses it to take back an approval when another call in the same batch is refused.
- **Execution** runs at once on approval, or later through `guard.execute(id)`. It re-checks both people as of now (the requester's `can()`, the decider against the rule), re-runs the preview and refuses `stale` when the state version moved, and runs the stored arguments only. It is idempotent on the approval id: a second `execute` returns the stored result. The capability's `run` sees `ctx.approvalId`. A write that fails is marked `failed` and never retried. If `run` returns an object with a string `auditId`, it is kept on the row.
- **Restoring people.** Execution after the request needs the requester's ctx. Give `restoreCtx(who, approval)` when your ctx carries more than the base fields; return `null` when the person or seat is gone.
- **Notices.** `onApproval` gets `requested`, `decided`, `executed`, `failed`, `stale`, `expired` and `withdrawn` events after the response. `failed` and `stale` come from execution: the approved change failed, a check at execution refused it (`approval.error` holds the code), or the target moved since the request. Each is sent once, when the row changes; a second `execute` sends nothing. Send Slack or email from it, with a link (`reviewUrl`), never a button.

### Step-up

`codeStepUp({ store, send, channels?, ttlMs?, maxAttempts? })` is the kit's one-time code: six
digits per channel, stored only as a hash bound to the approval, 10 minutes, five wrong tries.
With two channels (`['email', 'phone']`) its method is `two_channel` and both codes are needed.
You send the code. A passkey is your own verifier:

```ts
const passkeyVerifier: StepUpVerifier<AppCtx> = {
  methods: ['passkey'],
  verify: async (ctx, proof, binding) => (await webauthn.verify(ctx.principal.id, proof.assertion, binding.approvalId)) ? { ok: true, method: 'passkey' } : { ok: false, reason: 'The passkey did not verify.' },
}
```

`typedTarget: true` makes the decider type the target (the tenant, or the arguments'
`tenant_id`) in `decide(..., { typedTarget })`. With a single super admin, use
`policies.single({ approver: approver.role('super_admin'), stepUp: ['passkey', 'two_channel'], typedTarget: true, expires: '1h' })`.
A single-person policy with step-up is a policy in its own right, not a weaker four eyes.

### Tenants tighten, never loosen

`tenantPolicy(tenant, policy)` returns a tenant's own rule. The guard joins it to the base:
four eyes and typed target are or-ed, the expiry is the shorter, the step-up methods are those
both accept, and the decider must pass both approver rules. A tenant rule can only narrow who
decides. `guard.policyFor(policy, tenant)` shows the result.

## Kill switches

A switch is `{ key, scope, subject, on, reason? }`. On every call the guard reads every key it
needs in one read, once per call (an upstream-confirmed write is one call):

| Key | Stops |
|---|---|
| `all` | Everything through the guard |
| `door:<seat.door>` | One door |
| `unit:<ctx.channel>` | One kind of caller: `unit:copilot`, `unit:actor`, `unit:mcp` |
| `tool:<name>` | One capability |
| From `switchKeys(ctx, name)` | Your own, such as `ai.off` for every AI channel |

Each key is read at global scope, then for the call's tenant, then for its person. Only a switch
that is off counts, so a tenant switch that is on never overrides a global one that is off. If
the switches cannot be read, nothing runs.

`d1Switches(db)` reads D1 every time. `d1Switches(db, { cacheMs: 2000 })` keeps each read that
long, for a door where a D1 round trip on every call costs too much. A cache delays an emergency
stop by up to `cacheMs` on every isolate that cached the switch, so keep it short, and create the
store once in module scope (one made per request starts empty). `set()` clears the cache of the
isolate that calls it, not of the others.

`guard.doorSwitch(door, ctx?)` reads only `all` and `door:<door>`, at global scope and, with a
ctx, for its tenant and person. It returns the first switch that is off, or null, and throws
when the switches cannot be read. The mcp kit calls it on every request, so a door that is off
answers nothing at all, not only tool calls.

Turning a switch off must never wait for approval. Give your switch capability
`riskFor: (i) => (i.enabled ? 'R3' : 'R2')` and put it in `switchExempt` so a global stop does
not stop the tool that lifts it.

## Rate limits

```ts
rateLimit: rateLimitBindings({ read: env.RL_READ, write: env.RL_WRITE, tenant: env.RL_TENANT })
```

One [Rate Limiting binding](https://developers.cloudflare.com/workers/runtime-apis/bindings/rate-limit/)
per limit, since each binding carries its own limit and period. Keys are `seat:<id>:read`,
`seat:<id>:write` and `tenant:<id>`. The binding is approximate (per location). Where you need a
strict count, implement `RateLimiter` over a Durable Object. `memoryRateLimiter` is for tests.

## Request log and tracing

One record per request, written after the response through `waitUntil` (per call, or the
guard's default). A log that is slow or fails never delays or fails a call. Columns: id, time,
request id, door, seat, principal, tenant, channel, client id, name and version, method, tool,
tier, arguments (redacted through the capability's `pii`, 4 KB cap, none for R0), arguments
hash, outcome, error code, approval id, milliseconds, country and sample rate.

`guard.logRequest(ctx, { method: 'tools/list' })` records requests that are not tool calls.
`tools/list` and `initialize` keep one in ten (`sample`); multiply counts by `sampleRate`.
`guard.logAnonymous({ door, method, requestId })` records a request refused before it had a
principal (no token, a bad one, or one for another door) with the outcome `refused_auth` and no
principal, seat or tenant. These rows are never sampled.

The request id travels in `X-Omazy-Request-Id`: `requestIdFrom(request)` reads it or makes one,
`withRequestId(headers, id)` and `tracedFetch(id)` send it on to your other Workers.

## Audit rows

```ts
await env.DB.batch([
  env.DB.prepare('UPDATE devices SET state = ? WHERE id = ?').bind('approved', id),
  auditStatement(env.DB, ctx, { action: 'device.approve', target: id, actor_id: ctx.principal.id }),
])
```

`auditStatement` returns, without running it, an insert into your audit table (`audit_log` by
default) with `via` (the channel), `approval_id` and `request_id` from the ctx, plus your columns.
`columns` renames the three when yours differ.

## Deleting a tenant

```ts
let cursor = await purgeTenant(env.DB, tenantId, plan, { chunk: 500, maxChunks: 40 })
while (!cursor.done) cursor = await purgeTenant(env.DB, tenantId, plan, { cursor })   // or one step per Workflow step
```

The plan lists tables in order (children first), the tenant column and key of each, and rows to
keep (`keepWhere: { sql: 'kind = ?', params: ['payment'] }`). `keep` lists tables never purged and
`protectedTenants` tenants never purged. Each statement binds a few values, far under D1's 100,
deletes at most `chunk` rows, and the cursor lets the next step carry on. Export the tenant
first; the purge does not. `checkPurgePlan(plan)` in a test fails a bad plan before it meets data.

## Stores

| Interface | Cloudflare D1 | Memory (tests) |
|---|---|---|
| `GuardStore`: confirm nonces, approvals, step-up codes | `d1GuardStore(db)` | `memoryGuardStore()`, or `ephemeral: true` for a stateless door |
| `RequestLogSink` | `d1RequestLog(db)` | `memoryRequestLog()` |
| `SwitchStore` | `d1Switches(db)` | `memorySwitches()` |
| `RateLimiter` | `rateLimitBindings({ ... })` | `memoryRateLimiter({ ... })` |

The D1 adapters need the guard's tables. `guardMigrationSql()` gives them as one SQL text for a
wrangler migration; `applyGuardMigrations(db)` runs them (they are idempotent). The tables are
`guard_nonces`, `guard_approvals`, `guard_challenges`, `guard_switches` and `guard_requests`.
`d1GuardStore(db).prune(now)` deletes spent nonces and codes and clears the sealed arguments of
approvals decided more than 90 days ago; run it daily.

Put the busy tables (the request log, approvals) in a second D1 database if your main one is
busy, so log writes never queue behind your own. The adapters take any D1 binding.

## Secrets

`secret` keys the confirm tokens and the sealed arguments, through two keys derived with HKDF.
To rotate it, pass `{ current, previous: [old] }` until every token and waiting approval made
with the old one has expired.
