> ## Documentation Index
> Fetch the complete documentation index at: https://docs.tuturuuu.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Mastermind secret entry

> End-to-end encrypted secret requests answered from the Mastermind phone app, with pairing, the protocol, threat model, phone hygiene, machine delivery and the T3 hook.

An agent that needs a password (for example `sudo` on a fleet machine) can ask
the owner through the Mastermind Inbox. The owner reads the exact command that
will receive the value, then types the value on the phone. Only that command,
on the requesting machine, receives it. Web, the Mastermind store Worker and
the fleet publisher carry ciphertext only, and the agent that asked never
receives the value.

This page is the design and security contract. Product rules for the phone
live in [Mobile Mastermind](https://docs.tuturuuu.com/platform/features/mobile-mastermind.md#secret-requests).

## Scope

| Part | Where |
| - | - |
| HPKE on the machine (CryptoKit) | `scripts/mastermind-fleet/secret-hpke/` builds `mm-secret-hpke` |
| Pairing, requests, signatures and delivery on the machine | `scripts/mastermind-fleet/secret-request.mjs` and `secret-*.mjs` |
| Decision kind `secret` in the publisher | `scripts/mastermind-fleet/decision-extras.mjs`, `publish.mjs` |
| Relay rules (contract, answer route, store) | `apps/web/src/lib/mastermind/fleet/` |
| HPKE, signing and the owner key on the phone (CryptoKit) | `apps/mobile/ios/Runner/MastermindSecret*.swift` |
| Secret card, pairing, step-up, secure field | `apps/mobile/lib/features/mastermind/fleet/` |
| `request_secret` cards answered from the phone | T3 server (see [T3 hook](#t3-hook)) |

**Platforms.** Machines: macOS 14 or later. Phone: iOS 17 or later. Android,
older iOS, older macOS, other systems and the Mastermind web app never offer
secret entry (see [fail closed](#platform-checks-fail-closed)).

Version 1 serves requests made on the orchestrator Mac, where the publisher
runs. A linked machine needs the T3 hook.

## Actors and trust

* **Owner:** the only account allowed to answer: the fleet allowlist plus the
  root Mastermind permission, the same rule as every fleet answer.
* **Phone:** the owner's Mastermind app. It holds an Ed25519 **owner key** in
  the iOS Keychain (this device only, never synced, per signed-in user) and a
  pin of each paired machine's key. The pins, the pairings already used and
  the saved wrong-code counts sit in a Keychain service of their own
  (`tuturuuu.mastermind-secret`: this device only, readable only while
  unlocked), so erasing them at sign-out lists no other item, and lists it
  by name without reading any value. The app's own plugin stores them
  (`MastermindSecretStore.swift`): a write updates the item in place and adds
  only a missing one, and nothing on that path deletes. When the Keychain refuses a write, the old item stays and the
  page ends "failed" with nothing sent; a refused read is an error too, never
  "no pin". The secure-storage plugin is not used for these items because it
  deletes and re-adds an item whose update fails, which would lose a user's
  pins and used pairings on a failed add. Sign-out erases pins and owner keys
  on every iPhone whatever the capability check last answered, and a check
  that fails is asked again; off iOS the erase reads nothing. Every deletion
  is attempted even after one is refused. The trust is also bound to the
  sign-in session that created it (the access token's `session_id`,
  recorded in a preference). Before a secret page verifies anything it
  admits that trust only for the same session with no erase pending;
  after any new sign-in, a reinstall, or a missing or mismatched record it
  erases every owner key, pin and saved count first, and stays blocked
  until that erase completes; a record it cannot read, or no session at
  all, blocks admission outright. A refused deletion, or a preference write
  lost at sign-out, therefore never leaves old trust usable after the next
  sign-in. A page that is not admitted reads, offers and changes no pin.
  The guarantee is per sign-in session; the erase at an account switch is
  best effort. A multi-account switch away and back restores the first
  account's saved session with its original `session_id`, so if that
  switch's Keychain erase and every preference write all failed, that same
  account gets its own earlier trust back. Another account never can, and
  a real sign-out always forces a new session and the erase.
* **Machine:** the requesting Mac. It holds an Ed25519 **machine key**, the
  owner keys it paired with, and the owner-written **operations file** that
  says which commands may receive a secret.
* **Requester:** one `secret-request.mjs` process and its `mm-secret-hpke`
  child. The child holds the one-use X25519 private key in memory only.
* **Agent:** asks for an operation. It never receives the value and, by
  default, never sees the command's output.
* **Relay:** the publisher's file queue, Web (`tuturuuu.com`) and the store
  Worker. Trusted to deliver, never with plaintext or with deciding who
  answered.

### OS user boundary

The machine key, owner keys, operations file, helpers and the value in transit
all live under the owner's macOS user, in mode-0600 files and in process
memory: the same boundary as T3's `request_secret` files. **Any process running
as that user can read or change them**, including an agent with shell access,
the publisher, or a compromised tool. Such a process can sign a request in the
machine's name, change the operations file, or read the value while the helper
holds it. The phone still shows the exact command, so the owner sees what will
run, but a process with that level of access can also make the machine lie.

Version 1 does not defend against a hostile process under the owner's user.
It defends against the relay, a lost phone, replay, and agents that ask through
the normal interface. Moving the machine key, the operations file and delivery
into a broker under a dedicated macOS user is a recorded follow-up.

## Platform checks (fail closed)

* **Machine.** Before `pair` or `request` does anything, `secret-request.mjs`
  checks, in this order:

  1. `process.platform === "darwin"` and `/usr/bin/sw_vers -productVersion`
     with major version 14 or later;
  2. the helper is exactly `~/.local/share/fleet-sync/bin/mm-secret-hpke`, a
     regular file (not a link) owned by the user and not writable by group or
     others, in directories owned by the user and not writable by group or
     others;
  3. its SHA-256 equals `mm-secret-hpke.sha256` beside it (same ownership and
     mode rules), recorded at install;
  4. only then, `mm-secret-hpke version` reports protocol `1` (the binary is
     built for macOS 14 and also checks `#available(macOS 14, *)`).

  No helper code runs before steps 2 and 3 pass. Any failure stops with a
  closed error (`secret_unsupported_os`, `secret_helper_missing`,
  `secret_helper_mismatch`) and publishes nothing. Under the OS user boundary
  these checks catch a damaged or stale install, not a hostile same-user
  process.
* **Phone.** The app declares the `secret` fleet feature only on iOS 17 or
  later with the CryptoKit plugin present, and only while the Inbox renders
  secret cards (`fleetSecretCardsReady`, on). Web hides secret decisions from any
  client that does not declare it.

## Pairing

Each machine pairs once per phone before it can ask. Pairing authenticates
both keys through a code the owner reads off the machine through a path that
is not Web (T3 Code, a terminal or the WhatsApp desk). Never send the code
through Mastermind. Without an active pairing the phone shows no input.

1. On the machine, `secret-request.mjs pair` creates the machine key if
   missing, a `pairingId` (`pair-` plus 24 random hex characters) and an 80-bit
   **pairing code** (16 Crockford base32 characters, shown as
   `XXXX-XXXX-XXXX-XXXX`). The code exists only in that process and its
   printout; it expires after 10 minutes. The process publishes a `secret`
   decision in `pair` mode with `machineId`, `machineLabel`, `signerKey`,
   `expiresAt` and `machineMac = HMAC-SHA256(k, B(pair-machine))`, where
   `k = HKDF-SHA256(ikm = code bytes, salt = pairingId, info =
   "tuturuuu-mm-secret-pair-v1", 32 bytes)`.
2. After the step-up, the owner types the code on the phone. The phone checks
   `machineMac` in constant time (five wrong codes lock that card), makes its
   owner key if it has none, records a **pending** pin for `machineId`, and
   answers `{"action":"pair","pair":{"ownerKey","ownerMac"}}`. The wrong-code
   count is kept per signed challenge (the hash of `B(pair-machine)`, so a
   substituted card cannot change the genuine card's count or expiry) in the
   pins' Keychain account until that challenge's `expiresAt`, at most 24
   hours. Restarting the app does not reset it, and erasing the pins erases
   the counts. Checks run one at a time; when the count cannot be read or
   saved, the card takes no code.
3. The relay keeps up to five `pair` answers for one pairing (each a new
   revision), so a forged answer cannot take the only slot. The pair process
   checks every revision it receives, accepts exactly the first whose
   `ownerMac` verifies, adds the owner key to `secret-owner-keys.json` (at
   most four keys), signs the outcome `paired` with `answerDigest` = that
   owner key's id, and exits. It stops at `expiresAt` either way.
4. The phone activates the pin only when it sees that machine-signed outcome
   naming its own key id. A request from a machine with only a pending pin is
   refused.
5. Re-pairing a machine that already has an active pin keeps that pin in use.
   The new key waits beside it as a candidate until the machine-signed
   `paired` outcome for that pairing arrives before its `expiresAt`; the
   candidate then replaces the active key in one Keychain write. Until then a
   request signed by the new key waits as pending and the old key still
   verifies requests. Expiry is checked inside that serialized write, so a
   confirmation queued behind another Keychain operation cannot activate
   late, and a pending pin with no stored expiry never activates. A pairing
   that activated is remembered until its expiry, even after "Forget this
   machine", and is never staged again. Each machine has a trust revision
   that every change advances, Forget included even when no pin remains.
   Staging requires the revision seen before the code check, so a Forget or
   newer pairing during the check refuses it. Every dispatch, a value,
   decline or pair answer alike, requires the screen still open, the same
   account, no erase since, and the revision the flow verified or staged; the
   transport checks this again immediately before each dispatch (session
   refresh, step-up and verification replays included). The phone also
   keeps an in-memory twin of each revision: Forget advances it the moment
   it is asked for, so a Forget tapped while a guard's pin read waits
   refuses that dispatch, and a stage or activation advances it only once
   its Keychain write succeeds, so a duplicate or failed one never stops a
   valid request. A stage,
   activation or Forget queued while the guard's pin read waits sends the
   guard to read again behind it, so a committed swap refuses. The page
   stops dispatching as soon as its route completes (Close, Done, system
   Back, or removal under a parent page), before the exit transition or
   disposal, and a pairing page that leaves while its owner MAC runs, or
   before its staging write is issued, never stages (the check runs again
   inside the pin queue, after the read); a Keychain write already issued can
   still commit, but its pair answer is never sent. A reply to an answer already dispatched is still handled; one
   that arrives after the page closed still clears the Inbox card once,
   while the same account and erase generation hold. Any trust change
   for the machine therefore stops an open request, even a re-pairing that
   leaves the active key in place. To stop trusting the old key at once, the
   owner uses "Forget this machine", which a pairing page offers whenever
   the machine has a pin (the page stays open to pair afresh) and a request
   page offers while a re-pairing waits.

The relay sees both MACs but cannot test codes offline in any useful time: the
code carries 80 random bits and dies with its process.

**Changes and revocation.**

* A request signed by any key other than the active pin (or its pending
  re-pairing) is blocked with "This machine's key changed. Pair it again."
  The pin is replaced only by a confirmed new pairing with a new code.
* On the machine, `secret-request.mjs owners` lists paired owner keys and
  `secret-request.mjs revoke <ownerKeyId>` removes one, for a lost phone.
* On the phone, "Forget this machine" removes the pin. Signing out or
  switching accounts erases the owner key and every pin.
* Every answer is checked against the owner keys enrolled **at acceptance
  time** and against the signed `audience`.
* Enrolling a key, revoking one, and claiming an answer all run under one
  exclusive lock (`secret-owner-keys.lock`), and each re-reads the owner keys
  inside it. A revoke therefore either lands before a claim, which then
  refuses that key, or after the claim has already settled; a stale
  enrollment can never write a revoked key back.
* A request or pairing waits for that lock on a timer, so its signal handlers
  keep running. Its own cancel and `expiresAt` end the wait, and both are read
  again with the lock held, for a pairing proof and for an answer alike. A
  proof or answer that arrives in time but is still waiting at `expiresAt`
  enrolls or claims nothing and ends `expired`; a cancel during the wait ends
  `cancelled`, whether or not the lock is ever released. A lock whose holder
  died is cleared after 30 seconds.

## Protocol v1

### Algorithms and libraries

| Use | Machine | Phone |
| - | - | - |
| HPKE base mode, `DHKEM(X25519, HKDF-SHA256)`, `HKDF-SHA256`, `ChaCha20-Poly1305` ([RFC 9180](https://www.rfc-editor.org/rfc/rfc9180)), `info` = `tuturuuu-mm-secret-v1` | CryptoKit `HPKE.Recipient` in `mm-secret-hpke` | CryptoKit `HPKE.Sender` |
| Ed25519 signatures | `node:crypto` (OpenSSL) | CryptoKit `Curve25519.Signing` |
| Pairing HKDF-SHA256 and HMAC-SHA256 | `node:crypto` (OpenSSL) | CryptoKit `HKDF`, `HMAC` |
| SHA-256 for digests and display codes | `node:crypto` | Dart `crypto` |

Nothing in this protocol implements a primitive or HPKE by hand. The CryptoKit
code is one Swift file, `MastermindSecretCrypto.swift`, compiled into both the
iOS app and `mm-secret-hpke`, so both ends run the same calls.

### Wire format

* Every bound field is a string. `v` is the string `"1"`.
* Keys, MACs, signatures, `enc` and `ct` are canonical unpadded base64url:
  re-encoding the decoded bytes must give the same text, or the value is
  refused. They are bound as that text.
* Times are UTC ISO 8601 with milliseconds and `Z`
  (`2026-11-22T10:10:00.000Z`).
* A decision's `id` must equal its signed `requestId` (or `pairingId`); the
  phone and Web refuse a mismatch.
* `scripts/mastermind-fleet/secret-fixture.json` freezes example inputs and the
  exact binding bytes, signatures, MACs and plaintext encoding. The Node, Web,
  Swift and Dart tests all check against it.

### Binding strings

`B(domain, fields)` is the domain label, then each field, each encoded as a
4-byte big-endian byte length followed by its UTF-8 bytes. Every receiver
rebuilds a binding from its own verified copy of the fields, never from relay
text it has not verified.

| Domain | Fields after the domain |
| - | - |
| `tuturuuu-mm-secret-request-v1` (machine signature) | `v`, `requestId`, `machineId`, `requester`, `operation`, `command`, `output`, `purpose`, `expiresAt`, `publicKey`, `signerKey`, `audience` |
| `tuturuuu-mm-secret-answer-v1` (HPKE AAD) | the same fields |
| `tuturuuu-mm-secret-owner-v1` (owner signature) | `requestId`, SHA-256 hex of the request binding, `action`, `enc`, `ct`, `signedAt`, `ownerKeyId` |
| `tuturuuu-mm-secret-outcome-v1` (machine signature) | `requestId`, `outcome`, `answerDigest` |
| `tuturuuu-mm-secret-pair-machine-v1` (MAC) | `pairingId`, `machineId`, `machineLabel`, `signerKey`, `expiresAt` |
| `tuturuuu-mm-secret-pair-owner-v1` (MAC) | `pairingId`, `machineId`, `signerKey`, `ownerKey`, `expiresAt` |

* `requestId`: `secret-` plus 24 random hex characters.
* `requester`: `lane-<16 hex>`, the publisher's one-way id of the T3 thread
  named by `T3CODE_THREAD_ID` in the helper's environment (T3 sets it for agent
  tool processes), or `terminal` when unset. It is **reported by the machine**:
  under the OS user boundary a caller can set its own environment, and the
  phone labels it that way.
* `operation`: the operations-file id. `command`: JSON text
  `{"argv":[…]}` for a local operation or `{"argv":[…],"remote":[…]}` for an
  SSH operation. `argv` is the exact local argument list the helper runs;
  `remote` is the argument list the remote command receives. The text is bound
  verbatim and parsed only for display and the quoting check.
  `output`: `withheld` or `agent`.
* `purpose`: the operation's own purpose from the operations file (at most 120
  characters, a fixed point of the fleet scrubber).
* `audience`: the sorted, comma-joined owner key ids the machine accepts.
  `ownerKeyId` is the first 16 bytes of SHA-256 of the owner key, as lowercase
  hex.
* `action`: `secret` or `decline`; `enc` and `ct` are empty strings for a
  decline.
* `outcome`: `delivered`, `failed`, `declined`, `expired`, `cancelled` or
  `paired`. `answerDigest`: SHA-256 hex of the winning owner transcript, the
  owner key id for `paired`, or the empty string when no answer won.

### Operations file

`~/.local/share/fleet-sync/secret-operations.json`, written by the owner, mode
0600 and owned by the user (refused otherwise):

```json theme={null}
{
  "version": 1,
  "operations": {
    "studio-sudo": {
      "purpose": "MacStudio1 sudo password",
      "ssh": [
        "/usr/bin/ssh", "-F", "/usr/local/etc/fleet/ssh_config",
        "-o", "BatchMode=yes", "-T", "macstudio1"
      ],
      "remote": ["sudo", "-S", "-p", ""],
      "extraArgs": true,
      "delivery": "stdin",
      "newline": true,
      "output": "withheld",
      "maxTtlMinutes": 10
    },
    "local-key": {
      "purpose": "Unlock the signing key",
      "argv": ["/usr/bin/security", "unlock-keychain", "-p", "/dev/fd/3"],
      "delivery": "fd3",
      "maxTtlMinutes": 5
    }
  }
}
```

* An operation has either `argv` (local) or `ssh` plus `remote`. The first
  element of `argv` or `ssh` is an absolute path. The owner fixes the
  destination and the execution settings there (for SSH: the config file,
  options and host).
* With `extraArgs`, the agent appends arguments after `--`, to `argv` or to
  `remote`. They are bound into `command`, and the phone shows the full
  command, which the owner approves or declines as a whole.
* **SSH quoting.** SSH joins the remote arguments with spaces into one line
  that the remote login shell parses again, so an empty argument or one with a
  space would not arrive as shown. The helper therefore passes SSH a single
  argument after `--`: every `remote` argument in POSIX single quotes (`'`
  inside becomes `'\''`), joined by spaces. The remote login shell must be
  POSIX-compatible (the macOS default zsh, or bash). The phone recomputes that
  quoting from `remote` and refuses a request whose last `argv` element
  differs, then shows `remote` one argument per line, so boundaries and empty
  arguments are visible.
* Arguments with control characters (U+0000 to U+001F, U+007F) are refused
  when the request is made. The phone still renders any such character as a
  visible escape.
* `delivery`: `stdin` (the value, then a newline when `newline`) or `fd3` (the
  value on descriptor 3, so an argument can name `/dev/fd/3` where a tool wants
  a file path). Both are private inherited pipes: the value never reaches the
  disk.
* `output`: `withheld` (default) sends the child's standard output and error to
  `/dev/null`; `agent` passes them through and the phone says so.
* The child runs in `/` with only `PATH=/usr/bin:/bin:/usr/sbin:/sbin`,
  `HOME`, `USER` and `LOGNAME` from the OS account database, and
  `LANG=en_US.UTF-8`. Nothing comes from the requesting process's
  environment. `SSH_AUTH_SOCK` is set only from the operation's optional
  `sshAuthSock` (an absolute path); an `IdentityAgent` line in the owner's SSH
  config file does the same job.
* The agent gets a fixed status as the exit code: `0` the command succeeded,
  `1` it failed, `3` declined, `4` expired, `5` cancelled, `6` not delivered,
  `64` refused before asking.

### Request

1. `secret-request.mjs request --operation <id> [--ttl 10m] [-- args…]` runs
   the platform checks, then reads the machine id (`config.json`), the machine
   key, the owner keys and the operation. With no paired owner key it refuses.
   It also refuses a `command` over 8,192 UTF-8 bytes, or an answer binding
   (the HPKE AAD) over 16,384 bytes: the phone seals no more, and
   `mm-secret-hpke` reads an input line of up to 32 KiB, which fits the largest
   AAD and ciphertext once they are base64url-encoded.
2. It starts `mm-secret-hpke serve`, which makes a one-use X25519 key in its
   own memory and prints only the public key.
3. It signs the request binding and writes
   `decisions/open/<requestId>.json` (mode 0600, atomic rename) with
   `kind: "secret"`, `title` = the purpose, and `secret` = `{mode: "request"}`
   plus every bound field and `sig`. It prints the request code (first 4 bytes
   of SHA-256 of the request binding, `XXXX-XXXX`).
4. The publisher validates the shape and publishes it on its next run (it runs
   on every decision file change), and drops it once `expiresAt` has passed.

Lifetime: 10 minutes by default, at most the operation's `maxTtlMinutes` and
never over 30. At most 3 open requests per machine and 10 in a snapshot, on
top of the ask and login budgets.

### Phone

1. **Verify:** the decision id equals `requestId`; every field's shape; the
   active pin for `machineId`; the machine signature; this phone's key id in
   `audience`; `expiresAt` at least 45 seconds ahead on the phone's clock. Any
   failure says why and shows no input.
2. **Show only verified fields:** the pinned machine label and id, the
   purpose, the full command in monospace (never shortened), where the output
   goes, the requester id "reported by the machine" (with the lane title from
   the snapshot when there is one, marked as fleet data), the expiry countdown
   and the request code.
3. **Step-up before input:** the existing Mastermind step-up (this device's
   authenticator unlock, or a six-digit authenticator code). The field appears
   only after it passes.
4. **Seal and sign:** encode the plaintext, seal it with CryptoKit HPKE to
   `publicKey` with the answer binding as AAD, zero the buffers, clear the
   field, then sign the owner transcript with the owner key.
5. **Send:** `POST /api/v1/mastermind/fleet/decisions/<id>/answer` with
   `{"action":"secret","sealed":{"enc","ct"},"owner":{"publicKey","keyId","signedAt","sig"}}`
   and a fresh Idempotency-Key. It is never written to the answer outbox:
   retries run in memory while the screen is open, and leaving the screen drops
   them.
6. **Decline:** `{"action":"decline","owner":{…}}`, signed the same way. The
   phone asks for no step-up before a decline: it is owner-signed and fails
   safe, since the command never receives a value. When Web requires a
   step-up for the answer anyway, the phone shows that step-up.
7. **Outcome:** "Sent" on the 202; "Picked up by the machine" once the
   publisher acknowledges it; the final outcome only from the machine-signed
   outcome whose `answerDigest` matches this phone's own transcript, checked
   against the pin.

Plaintext: byte `0x01`, a 2-byte big-endian length `L` (1 to 4096 UTF-8
bytes), the value, then zero bytes up to the next multiple of 256 (at most 17
blocks). The machine checks the version, length, zero padding, smallest bucket
and UTF-8.

### Relay (Web and store)

* **Who:** the fleet owner only. `secret` and `pair` answers also need a
  second-factor proof of this very session no older than
  `MASTERMIND_SECRET_MFA_MAX_AGE_SECONDS` (default 300, bounded 60 to 300),
  checked with `replyAssurance`; otherwise `401 mfa_required`.
* **Owner signature first:** before it claims the slot, Web checks a `secret`
  or `decline` answer's owner signature: the key's id equals `keyId`, `keyId`
  is in the signed `audience`, and the Ed25519 signature verifies over the
  owner transcript rebuilt from the stored request. Otherwise `422
  invalid_answer`. A `pair` answer is checked for shape only; the machine
  checks its MAC.
* **What:** a `secret` decision accepts only `secret` and `decline` (request
  mode) or `pair` (pair mode), and those actions exist nowhere else. Shapes:
  `enc` 32 bytes; `ct` `256·k + 16` bytes with `1 ≤ k ≤ 17`; keys and MACs 32
  bytes; signatures 64 bytes; `signedAt` an ISO time no later than
  `expiresAt`.
* **Once, atomically:** in request mode the answer is written with
  compare-and-set on the request's answer key from empty only. A later answer
  with another Idempotency-Key is `409 secret_closed`. In pair mode up to five
  answers are kept as revisions; a sixth is `409 secret_closed`. The same key,
  actor and payload replays the original receipt.
* **When:** later than 15 seconds before `expiresAt` on the server clock, or
  once the decision has left the snapshot, a new answer is `409
  secret_closed`. The owner read shows an expired request as closed and strips
  its keys.
* **Pullable until acknowledged:** recording a secret answer also adds its
  decision id to a small pending index (`mastermind:fleet:v1:secret-pending`)
  that the answers pull always covers, so an accepted answer stays pullable
  until the publisher acknowledges it, however many other decisions close in
  the meantime. The acknowledgement removes the id.
* **Keep briefly:** the acknowledgement rewrites the record without the sealed
  payload, keeping the receipt and a SHA-256 digest of the payload, so a retry
  with the same key, actor and payload still replays its receipt, also after
  the decision is withdrawn. The record, and with it that replay, lives until
  `expiresAt` plus 10 minutes.
* **Logs:** for secret decisions, only the time, request id and outcome.
  Never sealed payloads, MACs, signatures, actor or session ids.
* **No push:** decision pushes cover `ask` decisions only, so a secret request
  never shows its purpose on a lock screen.

### Delivery on the machine

The requester is one process with one state per request: `waiting`, then
`claimed`, then exactly one terminal outcome.

1. The publisher pulls answers and writes
   `decisions/answers/<requestId>.r<rev>.json` (mode 0600), then acknowledges
   them. It deletes `secret-*` and `pair-*` spool files older than 10 minutes on
   every run, whether or not a helper is alive.
2. While `waiting`, the helper reads only spool files for its own request id
   and verifies each, inside the owner-key lock: the owner key is enrolled now
   and listed in `audience`, the signature verifies, `signedAt ≤ expiresAt`,
   and the machine's own clock is still before `expiresAt`. The first valid
   answer moves the state to `claimed`. Invalid answers are deleted and
   ignored; they cannot answer or cancel. There is no grace period: a relay
   that delays a signed answer past `expiresAt` only makes the request expire.
3. Cancel (SIGINT, SIGTERM) and expiry act only in `waiting`. At `expiresAt`
   the helper stops `mm-secret-hpke`, which destroys the key. Once `claimed`,
   the outcome is decided by delivery alone, and delivery is bounded: the
   command must take the value within 30 seconds of the claim or it is
   stopped and the outcome is `failed`.
4. `decline` → `declined`. `secret` → the helper passes `enc`, `ct` and the
   answer binding it built itself to `mm-secret-hpke`, which opens once and
   exits either way. The helper decodes the plaintext, writes it to the child's
   pipe, closes the pipe and zeroes its buffers. `delivered` means every byte
   entered the command's private input pipe before it closed ("Written to the
   command's input" on the phone). It does not prove the command read the
   value; the command's exit status, which the agent receives, says how it
   went. Any failure before the write completes, including a pipe the command
   closed early, is `failed`.
5. The helper deletes its spool files, removes the open decision, appends the
   audit line and writes a resolved record whose outcome is machine-signed with
   the `answerDigest` of the winning transcript.
6. **Audit:** `~/.local/share/fleet-sync/logs/secret-requests.jsonl` (mode
   0600\), one line per transition: time, request id, outcome.
7. **Crash:** if the helper dies, `mm-secret-hpke` sees its input close and
   exits, taking the key with it. The publisher stops publishing the request at
   `expiresAt`, and every later helper start removes open secret files past
   their expiry. A stray answer then has no key to open.

### Cancellation and timeouts

| Event | Effect |
| - | - |
| Agent stops the helper while waiting | Withdraws the decision, signs `cancelled`, exits `5`. |
| `expiresAt` while waiting | Stops `mm-secret-hpke` (the key is destroyed), withdraws the decision, signs `expired` and exits `4`. Web refuses answers from 15 seconds before `expiresAt`; the phone stops input 45 seconds before. |
| Owner declines | Signed `decline`; the helper signs `declined` and exits `3`. |
| Owner leaves, backgrounds or locks the app | The field is cleared; nothing is sent; the request stays open. |
| Request closes while the screen is open | A 409 or the decision leaving the snapshot closes the screen with "This request has closed". |

## Threat model

| Threat | Defence | What remains |
| - | - | - |
| **Passive relay compromise** (store data, logs, backups, the publisher's spool) | Only ciphertext under a one-use key the relay never sees; dropped at pickup; spools deleted within 10 minutes; padded to 256-byte buckets. | Metadata: purpose, command, machine, timing, length bucket. |
| **Active relay compromise** | Machine signatures checked against a pin made with the out-of-band code; every displayed field is signed and bound into the AAD; answers and declines need the owner signature; outcomes are machine-signed and name the winning answer. | The relay can drop, delay or replay messages: a request may never arrive or may expire unanswered. |
| **Phone loss or theft** | Needs the unlocked phone and the owner session for every answer, the phone step-up before any value, and a fresh second factor wherever Web requires one. No value, ciphertext or outbox entry is stored. | Someone with the unlocked phone and session can decline requests without the phone step-up; a decline fails safe because the command never receives a value. Someone past the step-up can answer for paired machines until the owner signs the device out and runs `revoke` on each machine. Earlier values stay safe because each request key was destroyed after one use. |
| **Stolen web session, even with a fresh second factor** | Cannot make an owner signature, so Web and the machine refuse its answers. | Rate-limited noise. |
| **Agent asking through the interface** | Only owner-listed operations run; the owner's purpose and the exact command are shown and approved; the value goes only to that command's pipe; output is withheld by default; open requests are capped. | Within `extraArgs` the agent picks the command's arguments, which the owner reads before answering. |
| **Hostile process under the owner's OS user** | Out of scope for version 1 (see [OS user boundary](#os-user-boundary)). | Can make the machine sign or run anything. |
| **Replay** | One-use key and `requestId` per request, bound and signed; one answer per request at the relay; one claimed answer per helper, then no key; owner signatures cover the request and time. | A replayed old request names a key that no longer exists. |
| **Orchestrator Mac as recipient** | It is the requesting machine for its own requests. | Its compromise exposes its own requests. |
| **Orchestrator Mac as relay** (T3 hook) | For a linked machine it only forwards; keys, pins and owner keys belong to that machine. | It can delay or drop those requests. |
| **Account switch with every erase write refused** | Trust is admitted only for the sign-in session that created it; pins and owner keys are per account. | Switching away and back to the same still-signed-in account can restore that account's own earlier trust when the switch-time erase and every preference write failed. Rotating a local activation ID on each account activation is a tracked follow-up. |
| **Notifications and metadata** | No push for secret requests; logs keep only time, request id and outcome. | The snapshot shows the purpose and command to the owner's clients. |

## Phone hygiene

* The field is obscured, with autocorrect, suggestions, smart quotes and
  dashes and IME personalised learning off, `TextInputType.visiblePassword`
  (iOS secure text entry, which also forces the system keyboard), no autofill
  hints, and at most 4096 UTF-8 bytes.
* No clipboard: copy, cut and paste are all off, including the selection menu.
* Cleared on backgrounding, app lock, expiry, request close, sign-out and
  account switch.
* iOS offers no screenshot block; the field stays obscured and the
  app-switcher shield covers the snapshot.
* Never logged, persisted, put in app state, analytics, error reports or route
  arguments. At send the text is read once, encoded to bytes, passed to the
  plugin, sealed, and the Dart and Swift buffers are zeroed. Dart strings are
  immutable, so the typed string stays in the heap until it is garbage
  collected.
* The owner key never leaves the Keychain item
  (`kSecAttrAccessibleWhenUnlockedThisDeviceOnly`, not synchronizable);
  signing happens in the plugin.

## T3 hook

Version 1 does not change T3. For every agent's `request_secret` to appear in
Mastermind and close in both places:

1. **Pairing:** each T3 environment keeps its own machine key and owner keys,
   paired through the same code ceremony; T3 shows the code and fingerprint in
   its settings. The environment needs macOS 14 or later (or another platform
   with an audited HPKE recipient); otherwise it never offers phone answers.
2. **Request:** when `request_secret` opens a private card, T3 makes a one-use
   X25519 key in server memory, sets `requester` from the calling thread (T3
   knows the real caller, so this field becomes verified), and binds the
   consumer the owner approves: `operation` is `t3-secret-ref` or `t3-file`,
   and `command` names the one tool call or command that will consume the
   value, as T3 will run it (`{"argv":[…]}` for a command; for a `secretRef`,
   the tool name and its arguments). `output` is `withheld` unless the card
   says otherwise. T3 signs the request binding. The phone shows the consumer
   exactly like any other command.
3. **List and answer:** `t3_pending_request list`/`read` returns the signed
   request; the publisher publishes it. The publisher hands the signed, sealed
   answer back with `t3_pending_request respond` and
   `answers: {"mastermind": {...}}`. T3 checks the owner signature, claims the
   card, opens the box with its in-memory key and its own binding, destroys the
   key, and completes the card.
4. **`secretRef` redemption:** the reference is redeemable once, atomically,
   and only by the bound consumer: that tool call, in the requesting
   environment, thread and turn. Any other caller, tool or turn is refused and
   the attempt is logged by request id. It is destroyed at first redemption,
   when the turn ends, or at `expiresAt` plus 10 minutes, whichever comes
   first.
5. **`delivery:"file"`:** a new mode-0600 file in a new mode-0700 directory,
   handed only to the bound command. It is deleted when that command exits,
   when it fails to start, or when the turn ends, whichever comes first. T3
   empties its secret-file directory at startup, so a crash or restart leaves
   no file behind.
6. **Failure after claim:** if delivery fails after the card was claimed, the
   card reads "Failed", T3 signs `failed`, and the owner answers a new request;
   a claimed answer is never reused.
7. **Arbitration:** the card's state machine claims the first of the T3 card,
   the phone answer, cancel and timeout; the others close.

## Install and use

**Build** on a macOS 14 or later test host with the Xcode command line tools
(never on the orchestrator Mac):

```sh theme={null}
scripts/mastermind-fleet/secret-hpke/build.sh ~/secret-hpke-out
```

It builds a universal `mm-secret-hpke`, runs the CryptoKit self-test, and
writes `mm-secret-hpke.sha256`. Copy both files into
`~/.local/share/fleet-sync/bin/` on each fleet Mac next to the publisher
scripts (mode 0755 and 0644, owned by that user); the request helper refuses
any other placement, mode or digest. The helper's own scripts install in the
same folder: `secret-request.mjs`, `secret-flow.mjs`, `secret-machine.mjs`,
`secret-pairing.mjs`, `secret-deliver.mjs`, `secret-hpke-child.mjs`,
`secret-protocol.mjs` and `secret-spool.mjs`, beside the publisher's
`fleet-state.mjs` (with its imports), `scrub.mjs` and `private-files.mjs`.
The publisher itself also needs `secret-decision.mjs`, `secret-protocol.mjs`
and `secret-spool.mjs`; install them together with `publish.mjs`.

**Pair** once per machine and phone, with the owner watching T3 or a terminal
on that machine:

```sh theme={null}
node ~/.local/share/fleet-sync/bin/secret-request.mjs pair
```

The owner opens the "Pair machine" card in the Mastermind Inbox, passes the
step-up and types the printed code. `secret-request.mjs owners` lists paired
phones; `secret-request.mjs revoke <ownerKeyId>` removes one.

**Operations.** The owner writes `secret-operations.json` (see
[operations file](#operations-file)). Agents cannot add operations.

**Ask** from an agent, for example to run one command with `sudo` on another
Mac:

```sh theme={null}
node ~/.local/share/fleet-sync/bin/secret-request.mjs request \
  --operation studio-sudo -- softwareupdate --install --all
```

The helper prints the request code and waits; its exit code says what
happened (see [operations file](#operations-file)). The value and, by
default, the command's output never reach the agent. `secret-request.mjs
sweep` removes leftovers of a helper that died.

## Follow-ups

* A broker under a dedicated macOS user (moves the OS user boundary).
* Android support through Tink's HPKE.
* Hardware-bound owner keys.
* Several fields per request (the plaintext version byte leaves room).
* Answering from the Mastermind web app.

## Regression coverage

* `scripts/mastermind-fleet/secret-hpke/selftest.swift` (run on a macOS 14+
  test host): RFC 9180 A.2.1 vectors opened by CryptoKit, seal and open round
  trips, small-order and malformed keys, tampered `enc`, ciphertext, tag, AAD
  and info, and the shared fixture's signatures and pairing values.
* `scripts/mastermind-fleet/secret-protocol.test.mjs`,
  `secret-pairing.test.mjs` and `secret-request.test.mjs`: the fixture,
  pairing, the operations file, platform checks, unsigned, foreign, late and
  second answers, claim ordering against cancel and expiry, decline, delivery
  over stdin and fd 3, withheld output, spool purge, crash cleanup and the
  audit lines (with a stub `mm-secret-hpke` where no Mac runs the tests).
* `scripts/mastermind-fleet/secret-request-limits.test.mjs`: the command's
  environment against the requester's, the `sshAuthSock` rule, `delivered` for
  a command that never reads its input, a refused pipe write, the byte limit
  on `command`, cancel and expiry while a proof or an answer waits for the
  owner-key lock, and a machine key path that already holds a refused file or
  a symlink.
* `scripts/mastermind-fleet/secret-request.e2e.test.mjs` (with the binaries
  `build.sh` produces): a CryptoKit seal opened by `mm-secret-hpke` and
  delivered, a changed binding that fails to open, and a maximum-length
  command with a 4,096-byte value.
* `apps/web/src/app/api/v1/mastermind/fleet/fleet-secret.test.ts`: owner, MFA
  and owner-signature gates, shapes, once-only compare-and-set, expiry, replay
  after acknowledgement, logs and the feature gate.
* `apps/mobile/test/features/mastermind/fleet/fleet_secret_*_test.dart`: the
  fixture bindings, verification, pins and activation, the pins' Keychain
  account and erase, pairing, re-pairing and its expiry, replay and Forget
  races, the persisted wrong-code count, the dispatch guard, step-up gate,
  secure field, clearing, feature declaration by platform and the
  never-persisted answer; `apps/mobile/test/data/sources/api_client_before_dispatch_test.dart`
  for the guard on every dispatch.
* `scripts/mastermind-fleet/secret-hpke/store-selftest.swift` (built and run by
  `build.sh` on a macOS 14+ host): the phone's Keychain store against a
  stand-in Keychain that can refuse any call. A write updates in place and
  adds only a missing item; every refused update or add leaves the old item,
  throws that status and never deletes; a refused or undecodable read throws;
  items are listed by name only, so an item whose value cannot be read is
  still erased. `store-selftest-ios.sh <booted-device-udid>` runs the same
  test as a minimal app on an iOS simulator, where it also updates, lists,
  reads and deletes several items in the device's real Keychain.
* `apps/mobile/test/features/mastermind/fleet/fleet_secret_keychain_test.dart`:
  the Dart adapter over that store, and the flows on a refusing Keychain: a
  pairing whose pin cannot be stored sends nothing, a value is neither sealed
  nor sent when trust cannot be read, and Forget that cannot be stored keeps
  the pin and says so. It also reads the Swift source to hold the write path
  free of any delete.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.