> ## 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.

# Secrets vault

> Design and threat model for the end-to-end encrypted secrets and environment-variable vault: trust anchors, key hierarchy, passkey and MFA unlock, machine, CI and workload access, sync targets and delivery slices.

Status: **Design, in independent cryptography and security review.** No code
ships before that review approves. Every rule below is **Planned** until its
slice lands with the listed regression coverage.

The vault stores workspace secrets and environment variables so that people,
fleet machines, agents and CI can use them from any machine without copying
files. Values are encrypted and signed on clients. The Tuturuuu server stores
ciphertext, wraps, signatures and metadata.

**Scope:** Web, the `ttr` CLI, CI and deploy runners, fleet agents and
Cloudflare workloads. **Out of scope:** `public.workspace_secrets`, which
remains a plaintext feature-flag and configuration table.
`private.mobile_deployment_*` and the other server-held vaults keep their
custodial model until they are migrated onto this vault.

## Guarantees

1. **End-to-end environments.** For an environment with no workload grant and
   no unattended service credential, the Tuturuuu server, including a full
   database dump and every Tuturuuu server secret, cannot decrypt a value and
   cannot make a client accept a value, key or recipient it did not get from
   an authorised signer.
2. **Custodial environments are labelled.** An environment granted to a
   [workload](#workload-principals) is **server-readable**: whoever controls
   that Worker's secrets or code can decrypt it. An environment granted to an
   [unattended CI credential](#unattended-ci-credential) is readable by
   whoever controls that CI secret store. The UI, CLI and audit show these
   labels, and guarantee 1 does not apply to them.
3. A person unlocks with a vault passkey or a recovery key on any machine with
   no local state. MFA plus PIN unlock is a separate, weaker tier with its own
   identity, off by default (see [MFA unlock](#mfa-unlock-tier)).
4. Machines and agents receive short-lived, scoped, device-bound grants that an
   environment admin approves. Nothing durable is written to the machine.
5. Every reveal, copy, run, pull, sync, grant and key change is audited by
   name, never by value. Audit is server-trusted (see [Audit](#audit)).

## Explicit limits

* **Web E2EE trusts the served code.** Malicious JavaScript delivered to an
  unlocked vault page can read what that page decrypts. The vault runs on an
  isolated origin with a strict CSP; the signed CLI is the stronger client.
* **A decrypting client can always exfiltrate.** A machine that receives the
  sensitive key can reveal sensitive values locally. "Sensitive" is
  cryptographic for members without that key and policy for everyone else.
* **Scope is per environment.** Every grant decrypts the whole environment at
  the granted level. Finer scopes use separate environments.
* **Metadata is plaintext.** Workspace, project, environment and variable
  names, types, flags, timestamps, expiry, version numbers, sizes and audit
  events. Values, descriptions and notes are encrypted.
* **Freshness depends on the witness.** A client with no local state learns
  the current state from the [witness](#witness). A party that controls both
  the vault API and the witness can present a stale or forked view to such a
  client. A client that sees no fresh witness checkpoint fails closed, so a
  witness outage stops reads and changes.
* **Removal cannot unsee.** A removed principal keeps whatever plaintext or
  keys it already holds. Removal fences future access and lists values to
  rotate at their source.
* **Losing every strong unlock method loses the data.** There is no escrow.

## Primitives

Only standard constructions with published test vectors. No custom
cryptography.

| Use | Construction | Implementation |
| - | - | - |
| Value encryption | AES-256-GCM, 96-bit random nonce, one-time subkey per encryption | WebCrypto |
| Subkeys | HKDF-SHA256 (RFC 5869) | WebCrypto |
| Public-key wraps | HPKE base mode (RFC 9180), `DHKEM(X25519, HKDF-SHA256)`, `HKDF-SHA256`, `AES-256-GCM` | `@hpke/core`, `@hpke/dhkem-x25519` |
| Deterministic key pairs | HPKE `DeriveKeyPair` (RFC 9180 §7.1.3) | same |
| Signatures | Ed25519 (RFC 8032) | WebCrypto, `@noble/curves` fallback |
| PIN gating | OPRF (RFC 9497, `ristretto255-SHA512`), then Argon2id (RFC 9106) | `@cloudflare/voprf-ts`, `hash-wasm` |
| Canonical encoding | Deterministic CBOR (RFC 8949 §4.2) | `cborg` |
| WebAuthn verification | WebAuthn Level 3 | `@simplewebauthn/server` |

Library choices are confirmed in the slice 1 review; formats below do not
depend on them. Versions are pinned, and CI runs the RFC test vectors.

### Encoding and suites

Every stored object is a deterministic CBOR map with `v` (format version) and
`suite`. Version 1 has exactly one suite, `1`: the primitives above. A client
rejects an unknown `v` or `suite`, a missing field, an extra field, or a
non-canonical encoding. There is no negotiation and no fallback.

### Context binding

Every AEAD `aad`, HPKE `info` and `aad`, HKDF `info` and signature input starts
with a domain label (`tuturuuu/vault/<purpose>/v1`) followed by the canonical
CBOR of its context. Every context carries `deployment` (the pinned vault
deployment identifier). Workspace-scoped contexts also carry `vault_id` (the
workspace genesis hash); `unlock` and `keyring` contexts are user-scoped and
carry `vault_user_id` instead. Strings must be well-formed Unicode.

| Purpose | Context |
| - | - |
| `value` | `env, variable_id, version, epoch, enc_id, cipher (aead-edk, hpke-intake, hpke-esk)` |
| `wrap` | `scope_id, epoch, key_kind (edk, intake, esk, history-normal, history-sensitive, identity), recipient_kind, recipient_id, recipient_key_fingerprint, enc_id` |
| `unlock` | `vault_user_id, identity_tier, method, method_id, params_version, enc_id` |
| `keyring` | `vault_user_id, counter, enc_id` |
| `grant` | `grant_id, transcript_hash` |

`vault_user_id` is a random identifier created at first enrolment and is
independent of the identity provider's user ID. A fingerprint is `SHA-256` of
the canonical public key, shown as the first 128 bits in base32 when people
compare it.

### Value encryption

Every encryption has a fresh 128-bit random `enc_id`. Symmetric encryption
always uses a one-time key, `HKDF(K, salt = enc_id, info = label ‖ ctx)`, where
`K` is the EDK, an unlock KEK or the keyring key. A key is therefore never used
for more than one AES-GCM message, including retries and concurrent writers,
and no shared nonce budget exists. HPKE seals (intake, ESK and wraps) use a
fresh ephemeral key per message as RFC 9180 specifies, with `enc_id` in
`info`.

### Writer signatures

HPKE base mode does not authenticate the sender, and anyone holding a public
key can create a ciphertext. Every value version therefore carries a
**version record** signed by its writer's Ed25519 key:

`{deployment, vault_id, env, variable_id, name, type, sensitive, version, epoch, cipher, enc_id, ciphertext_hash, prev_record_hash, auth_seq, writer_id, written_at}`

* `auth_seq` is the key-log position whose state authorises the writer. The
  witness accepts a record only if the writer holds a writing role at
  `auth_seq`, no later entry before the current head revoked it, `epoch` is
  the environment's current epoch, and `prev_record_hash` is the environment's
  current value head.
* Before sealing, a writer verifies the environment's **epoch descriptor**
  (below) to authenticate the intake and ESK public keys it seals to.
* A consumer accepts a value only if the record verifies, its hash is reachable
  from the environment value head in a fresh witness checkpoint, and
  `ciphertext_hash` matches.
* **Re-encryption** into a new epoch writes a record signed by the
  re-encrypting admin that carries the original record's hash and signature,
  so provenance survives and the consumer verifies both.
* Verification ships in the same slice as the first client that reads values.

## Trust anchors

### Workspace root

There is no shared root private key. Creating a vault writes a **genesis
entry** listing the owner set: each owner's strong-identity Ed25519 key, a
threshold `t` (default 1; the UI recommends 2 once there are two owners), the
deployment and a random nonce. The `vault_id` is the SHA-256 of the canonical
genesis body, which does not contain the `vault_id` itself; the owners'
signatures cover that body. Clients pin the `vault_id`.

* Owner-set changes (add, remove, rotate an owner key, change `t`) need `t`
  signatures from keys in the current owner set. A removed or rotated owner
  key loses all authority from that entry on.
* Admin-set changes need `t` owner signatures, the same quorum as owner-set
  changes, because admins control future epoch keys. Member, role, grant and
  epoch entries need one current admin signature. Only strong-identity keys
  sign administrative entries; a PIN identity never does.
* **Compromise beyond the threshold** (an attacker who can sign as `t` owners)
  cannot be repaired inside the log. The remaining owners create a new vault
  with a new `vault_id`, and every member re-pins it through a new invite. The
  old vault is marked compromised by a final signed entry where possible.

### Keyring

The keyring is a per-user object encrypted under a key derived from the strong
identity. It holds the pinned `vault_id` of each workspace, the last key-log
`seq` it verified per workspace (a client floor), and a monotonic counter. One
witness Durable Object per `vault_user_id` is the single keyring authority: it
accepts a new head only with a strong-identity signature and the previous
head, and signs `(counter, hash, issued_at)` on request. A client accepts a
keyring only if it matches a fresh signed head. The keyring follows the user across machines, and a replayed
older keyring fails the witness check.

### Recipient binding

Before any client wraps a key to a public key, that key must be bound by an
independent channel:

| Recipient | Binding |
| - | - |
| New member | Invite (below) |
| Machine or agent | [Pairing](#pairing) |
| CI credential, workload | Generated by the admin's own client, which registers the public key in a signed key-log entry |
| Existing member, new device | Nothing new: devices are unlock methods of the same identity |

**Invites.** An admin's client creates a 256-bit invite secret and an invite
link whose fragment carries the secret and the `vault_id`. The fragment never
reaches the server. The admin delivers the link through a confidential,
authenticated channel they choose; the server's email carries no secret.
The invite context is the canonical CBOR of `{deployment, vault_id, invite_id,
intended recipient (user ID and verified email hash), environments and level,
expires_at}`, signed by the inviting admin into a pending key-log entry.

1. The invitee's client publishes its identity public keys with
   `HMAC-SHA256(invite_secret, "tuturuuu/vault/invite/v1" ‖ 0x00 ‖ CBOR({context, keys}))`
   and an Ed25519 signature over the same labelled bytes by the proposed
   signing key.
2. The admin's client sends an HPKE-sealed challenge to the proposed X25519
   key; the invitee returns it, proving possession of both keys.
3. The admin's client verifies all three, then signs the membership entry. The
   witness consumes `invite_id` atomically with that entry, so an invite is
   used once. Invites expire after 7 days.

### Key log

Each workspace has an append-only, hash-chained key log. An entry holds
`{seq, prev_hash, kind, subject, payload, issued_at}` and the signatures its
kind requires. Clients verify from genesis against the pinned `vault_id`.

* An **epoch descriptor** entry declares an environment epoch: its EDK
  identifier, the intake and ESK public keys, the PIN policy, and the digest of
  every wrap issued for the epoch, keyed by `(recipient fingerprint, key_kind,
  epoch)`. Wraps added later in the same epoch are listed in signed
  wrap-addition entries. A client unwraps only wraps listed in an entry it
  verified.
* Grant, credential and workload entries carry the digest of their wraps the
  same way.

### Witness

The **witness** is a Cloudflare Worker with one Durable Object per workspace,
deployed from a separate Cloudflare account with separate deploy credentials
and its own signing key, which the vault API cannot read. It is the commit
point for every state change.

* **Compare-and-append.** A transition (key-log entry, version record, audit
  head, keyring head) names the head it extends. The Durable Object validates
  it against its own copy of the public key-log state (signatures, thresholds,
  roles at `auth_seq`, epoch, invite consumption) and appends it in one
  storage transaction, or rejects it. Durable Object single-threading
  serialises a workspace; it stores signed entries and record metadata, never
  ciphertext.
* **Snapshots.** The witness keeps, per environment, an authenticated map
  from `variable_id` to the hash of its latest record or tombstone. On request,
  without appending, it signs a fresh attestation `(deployment, vault_id, seq,
  key_log_head, env map roots, audit_head, issued_at)`, and it returns an
  inclusion proof for each variable read. Clients require an attestation at
  most 10 minutes old for **every read and every change**, and accept a value
  only if it is the latest record in the map; a superseded or tombstoned
  value is rejected. Cached values expire with their attestation.
* **Publication order.** A client first stages its payloads (ciphertext and
  wraps) bound to their hashes, then submits the transition naming those
  hashes to the witness. A publisher promotes only staged payloads whose hashes
  a committed transition names, idempotently and after a crash; payloads of a
  rejected or stale-epoch transition are never promoted and expire after 24
  hours. A read whose database state is behind the witness fails closed until
  publication catches up.
* **Restore fencing.** If Postgres is restored from a backup, its heads are
  behind the witness, and clients refuse it until it is reconciled. Values
  whose ciphertext was lost are reported by name.
* The witness public key is pinned in the client build. A later step can
  mirror checkpoints to a public transparency log.
* The witness is metered: it bounds request size and entries per minute per
  workspace, and has a tested durable stop flag.

## Key hierarchy

```text theme={null}
strong unlock ─KEK─▶ strong identity (X25519 + Ed25519) ─▶ keyring, PIN identity keys
PIN unlock ────KEK─▶ PIN identity (X25519 + Ed25519, never signs admin entries)
                        │ HPKE (only environments whose policy allows PIN)
                        ▼
      environment epoch keys: EDK + intake key pair (normal), ESK key pair (sensitive)
                        │
  normal values: AES-GCM(EDK subkey) or HPKE(intake)   sensitive values: HPKE(ESK)
```

* **Identities.** Each user has a strong identity and, if enabled, a separate
  PIN identity. Environments are wrapped to the PIN identity only when their
  policy allows PIN unlock.
* **Epochs.** The EDK, the intake key pair and the ESK key pair exist per
  environment and epoch. A new epoch starts on any removal, downgrade, grant
  revocation, PIN-policy disable or suspected compromise.
* **History stays separated by sensitivity.** The new EDK wraps the previous
  EDK and intake private key (`history-normal`); the new ESK wraps the previous
  ESK (`history-sensitive`). A principal reaches only history at the level it
  holds in the current epoch, so a normal reader never reaches sensitive
  history.
* **New members** receive history at their granted level. Version 1 has no
  "from now on" access, because current epoch keys reach history.
* **Projects** group environments and carry RBAC defaults; they hold no keys.

## Unlock methods

### Vault passkey (WebAuthn PRF)

A passkey with `rpId` `tuturuuu.com` can be exercised from every
`*.tuturuuu.com` origin, so the vault never uses login passkeys for PRF. It
registers a **vault passkey** with `rpId` `vault.tuturuuu.com` and
`userVerification: "required"`.

* **Trust boundary.** No host below `vault.tuturuuu.com` may exist (DNS policy
  and a CI check), and the vault publishes no WebAuthn related-origins file, so
  only the exact origin `https://vault.tuturuuu.com` can use the credential.
* PRF input: the constant `SHA-256("tuturuuu/vault/prf/v1")`.
* `KEK = HKDF(prf.first, salt = wrap_salt, info = "tuturuuu/vault/kek/passkey/v1" ‖ unlock_ctx)`,
  where `unlock_ctx` uses the stable `vault_user_id`, so a change of identity
  provider or login user ID does not change derivation.
* The vault server stores the credential public key and verifies each
  assertion (challenge, origin, RP ID, UV flag, credential belongs to this
  `vault_user_id`, signature counter where present) before releasing the wrap,
  using `@simplewebauthn/server`.
* PRF output stays on the client. The assertion sent for verification is built
  from an allowlist (`id`, `rawId`, `type`, `clientDataJSON`,
  `authenticatorData`, `signature`, `userHandle`) and never includes client
  extension results. PRF bytes are discarded after deriving the KEK. The
  `vault.tuturuuu.com` host serves only the vault.
* Enrolment completes only after the first verified assertion returns a usable
  PRF result. Slice 3 records a PRF continuity matrix per provider (iCloud
  Keychain, Google Password Manager, Windows Hello, security keys), browser and
  transport, including cross-device (hybrid) use.
* Synced passkeys carry the PRF secret across a user's devices, which is what
  makes unlock work on a new machine.

### Recovery key

At enrolment the client generates a 256-bit recovery key, shows it once in
base32 groups, and requires the user to re-enter one group.
`KEK = HKDF(recovery, wrap_salt, "tuturuuu/vault/kek/recovery/v1" ‖ unlock_ctx)`.
It unlocks the strong identity.

### MFA unlock tier

TOTP is a secret the server also holds, so TOTP alone would give the server
custody. This tier combines a fresh MFA step-up with a PIN gated by an
**OPRF** (RFC 9497), so every PIN guess needs one online evaluation by the
share service. It is off by default and **gated on slice 7**, which needs its
own protocol review against the requirements below.

* **Derivation.** The client blinds the PIN (`NFKC`, UTF-8, at least 8
  characters); the service evaluates with the per-user key `k_u`; the client
  unblinds to `y` and derives `rwd = Argon2id(y, salt = pin_salt (16 random
  bytes), m = 64 MiB, t = 3, p = 1, len = 32)` and
  `KEK = HKDF(rwd, wrap_salt, "tuturuuu/vault/kek/pin/v1" ‖ unlock_ctx)`.
  Parameters are stored in the wrap as `params_version`.
* **One enforcement point.** One Durable Object per `vault_user_id` handles
  enrolment, reset and evaluation for every version and region. It consumes
  the replay identifiers, then checks session liveness, and only then charges
  the quota and evaluates in a later transaction; it rejects an invalid or
  identity group element.
* **Quota.** 5 evaluations per 24 hours and 20 per 30 days. Exhausting the
  quota locks the PIN identity until the user unlocks with a strong method and
  signs a reset, so an attacker who exhausts it causes only a lockout of this
  tier.
* **Enrolment and reset** require a signature by the user's strong identity,
  verified by the Durable Object against the witnessed key log.
* **Step-up proof.** Each evaluation needs a central-session `ttr+stepup`
  proof (ES256) with `iss` and `env` pinned, `aud: stepup:vault-share`,
  `act: vault.pin-eval`, `sub` this user, `amr` a non-empty subset of
  `totp` and `passkey`, `aal2`, `auth_time` (the step-up ceremony) at most
  300 seconds before `iat`, and a lifetime of at most 300 seconds. The
  session `sid` must still be live.
* **Binding.** The service issues a single-use challenge and stores it with
  the wrap version, the client's ephemeral HPKE key and the hash of the
  blinded element. The proof's `ph` covers all four and is computed with
  `paramsHash` from `@tuturuuu/session/stepup`. The Durable Object recomputes it from
  its stored values and rejects any mismatch. It implements the session's
  `StepUpConsumePort`: a verified proof authorizes nothing until `consume`
  returns `consumed` for its `nonce`, `jti` and challenge in one transaction;
  `unavailable` fails closed. It encrypts its response to the stored HPKE
  key.
* **Proof delivery.** The vault page starts step-up as a top-level navigation
  to the Web confirmation page with the action and parameters hash. Web returns
  a one-time code valid for at most 60 seconds, and the vault server redeems it
  with Web server to server. The proof never reaches page script or a URL. A
  device rotation between grant and mint fails closed, and the UI asks the user
  to repeat the step-up.
* **Key custody.** `k_u` is derived from a per-user random seed stored in the
  Durable Object, encrypted under a Worker secret. Rotating the service key
  re-encrypts seeds; rotating `k_u` requires re-enrolment.

| Attacker holds | Strong identity | PIN identity |
| - | - | - |
| Database dump | Nothing | Nothing (missing `k_u`) |
| Database + share service (or its key) | Nothing | Offline Argon2id search over the PIN |
| Password + TOTP, or a compromised step-up issuer | Nothing | Online guesses only, within the quota |
| Malicious code on an unlocked vault page | What that page decrypts | Same, plus the PIN |

The PIN identity receives only environments whose policy allows it, so its
compromise never exposes the strong identity, the keyring or administrative
signing.

## Principals and grants

| Principal | Recipient keys | Lifetime | Custodial |
| - | - | - | - |
| Member | Strong identity (and PIN identity where allowed) | Membership | No |
| Machine or agent | Ephemeral X25519 + Ed25519 in process memory | Default 8 h, max 24 h | No |
| Attended CI job | Ephemeral per-job keys | One job | No |
| Unattended CI credential | Derived from a stored credential | Max 90 days | Yes, the CI secret store |
| Workload | Worker secrets | Until revoked | Yes, the Worker operator |

Grant-producing slices ship only after epoch revocation works end to end.

### Pairing

Version 1 pairs a machine or agent only through a **fragment link**:

1. `ttr secrets login` generates its X25519 and Ed25519 keys in memory and
   creates a pairing request with a random `request_id`.
2. It prints an approval URL `https://vault.tuturuuu.com/pair/<request_id>`
   whose fragment carries the full key fingerprints and a 128-bit pairing
   secret. The owner opens it from the machine's own output (terminal, T3
   thread). The fragment never reaches the Tuturuuu server.
3. The approval page fetches the request, checks that its keys match the
   fragment and that the device's signature over `(request_id, keys, scope
   requested, machine label)` verifies, and shows scope, environments, level,
   `not_after` and the machine label.
4. The approver signs the **transcript** (request ID, device keys, scope,
   environments, level, `not_after`, machine label, central-session `sid`,
   pairing secret hash) and the exact wraps, and the witness appends the grant.
   A request can be approved once; a second transcript for the same request is
   rejected.
5. Redemption requires a fresh Ed25519 signature by the device key over a
   server challenge and the transcript hash, and the central-session `sid` must
   still be live. Nothing is derived from the central session's device secret.

The Mastermind fleet card only notifies the owner that a request is waiting;
it never carries the fragment, because the server delivers it. Its link is
matched against the exact origin `https://vault.tuturuuu.com` and path prefix
`/pair/`, with no subdomain match. Numeric-comparison pairing from the card is
deferred until a reviewed protocol (for example ZRTP-style commitment, RFC 6189
§4.4.1.1) is specified and reviewed.

**No durable machine state.** `ttr secrets agent` holds the device keys, its
own central `cli` session and decrypted environment keys in process memory,
and serves the same user's `ttr` invocations over a Unix socket (mode 0600,
peer UID checked; a named pipe with an owner-only ACL on Windows). It does not
read or write the persistent CLI configuration. It never uses a keychain.
Leases end on agent exit, `not_after` or revocation; renewal needs approval.

On a hostile host, memory-only storage, TTL and revocation limit only future
access: anything decrypted during the lease may already be copied.

### Attended CI jobs

The preferred path has no stored decryption key.

1. The job generates ephemeral keys and requests a GitHub OIDC token whose
   audience is `tuturuuu-vault:<vault_id>:<job key fingerprint>`, binding the
   token to those keys.
2. An environment admin (or an approver workload, which makes the environment
   custodial) independently verifies the token: signature against GitHub's
   keys, the audience, `iat` within 5 minutes, `exp − iat` at most 10 minutes,
   and the [CI policy](#ci-policy). The witness consumes `jti` atomically.
3. The approver signs a grant to the job's keys for one job.

### CI policy

A signed key-log entry per CI binding lists what a token must match:
`repository_id` and `repository_owner_id` (immutable IDs), the caller workflow
(`workflow_ref` with an allowlist of `workflow_sha` values, or `ref_protected`
true plus a GitHub environment with required reviewers), the reusable workflow
when used (`job_workflow_ref` plus pinned `job_workflow_sha` values), allowed
`event_name` values (never `pull_request_target` or fork-originated events),
`environment`, and `runner_environment`. Changing the allowlist is an admin
entry.

### Unattended CI credential

For jobs without an online approver, an admin's client creates a 256-bit
credential `cred`, stored by the operator as a GitHub environment secret.

* `auth = HKDF(cred, "tuturuuu/vault/svc/auth/v1")`; the server stores
  `HMAC-SHA256(server_pepper, auth)`.
* `(svc_sk, svc_pk) = DeriveKeyPair(HKDF(cred, "tuturuuu/vault/svc/key/v1"))`.
  The admin's client wraps the granted keys to `svc_pk` and registers it, with
  the wrap digests, in the key log.
* Delivery needs `auth` and a GitHub OIDC token that satisfies the
  [CI policy](#ci-policy), the audience `tuturuuu-vault:<vault_id>`, and the
  lifetime checks above; `jti` is consumed atomically. Non-GitHub runners are
  not supported in version 1.
* **Exposure:** anyone holding `cred` and a delivered wrap can decrypt. A
  15-minute delivery lease does not expire keys already delivered. The
  environment is labelled custodial to the CI secret store, credentials expire
  within 90 days, and rotation creates a new epoch.

`ttr secrets pull --stdout --format dotenv|json` prints to stdout only.

### Workload principals

An admin's `ttr` generates a workload's X25519 and Ed25519 keys and, using the
admin's own Cloudflare credentials, verifies the target account ID and Worker
script name through the Cloudflare API before installing the private keys as
that Worker's secrets. The key-log entry records the public keys, account ID
and script name. Only environments created for workloads can be granted to
one, and they are labelled server-readable.

* **Requests** are signed with HTTP Message Signatures (RFC 9421) over
  `@method`, `@target-uri` (scheme, authority, path and query),
  `content-digest`, and the `created`, `nonce` and `keyid` parameters, plus
  headers naming the workspace, environment and lease. `created` must be
  within 60 seconds.
* A Durable Object per workload consumes each nonce atomically until expiry,
  across instances, and checks lease revocation on every use.
* A lease lasts 1 hour, is bound to `(workload, workspace, environment)` and is
  rejected for any other workspace. One version-poll call returns current
  versions for a list of names; the workload refetches changed values at most
  once per lease renewal. A Durable Object may keep plaintext in memory for the
  lease. Rotation notifications are advisory, because an evicted Durable Object
  loses them; correctness comes from the version poll at each renewal and on
  cold start.
* **Witness outage during a lease.** A value the workload verified against a
  fresh attestation within the current lease may stay in memory and remain in
  use until that lease ends, at most 1 hour, even if the witness becomes
  unreachable. New fetches and renewals still fail closed, and `lease_revoked`
  drops plaintext immediately. This exception applies only to workloads,
  whose environments are already server-readable; people, machines and CI keep
  the 10-minute rule.
* A workload granted a writing role on specific variables writes signed
  version records with compare-and-swap on the previous version.
* Ending custody revokes leases, records a signed entry, starts a new epoch
  for every granted environment and lists values to rotate at their source.

## Values, sensitivity and versions

* A variable has a name (`^[A-Z_][A-Z0-9_]{0,127}$`), a type (`secret` or
  `variable`), a sensitivity flag, optional expiry and rotation interval, and
  signed versions.
* **Variables** and **secrets** are encrypted under the EDK, or sealed to the
  intake key when written by a `writer`. Secrets need a confirmation to reveal,
  and each reveal and copy is audited.
* **Sensitive** secrets are sealed to the ESK. `writer` and `editor` can set
  them; only `admin` holds the ESK, because admins approve machines. Admin
  reveals are audited by first-party clients only.
* **Marking a variable sensitive** re-seals its retained versions under the ESK
  in the same client operation, deletes the EDK and intake ciphertexts, and
  starts a new epoch so the old history wraps stop covering it. Readers may
  already hold earlier plaintext, so the UI suggests rotating at the source.
  Clearing the flag re-encrypts under the EDK.
* The newest 20 versions or 90 days are retained, whichever is more. Restoring
  writes a new signed version. Deletion writes a signed tombstone and purges
  ciphertext after 30 days.

## RBAC

| Role | Names | Decrypt normal | Decrypt sensitive | Set values | Manage |
| - | - | - | - | - | - |
| `viewer` | Yes | No | No | No | No |
| `writer` | Yes | No | No | Yes | No |
| `reader` | Yes | Yes | No | No | No |
| `editor` | Yes | Yes | No | Yes | No |
| `admin` | Yes | Yes | Yes | Yes | Members, grants, rotation |

`writer` holds no EDK. It seals sensitive values to the ESK public key and
normal values to the epoch's intake public key, both authenticated through the
epoch descriptor. The intake private key is wrapped with the EDK to every
principal that decrypts normal values, so readers decrypt intake ciphertext
directly and the writer cannot read it back. A workspace permission
`manage_secrets_vault` allows creating projects and environments. Server checks
decide who fetches which ciphertext; cryptography decides who decrypts.

## Membership and epochs

* **Add:** an invite binds the member's keys; an admin signs the member entry
  and wraps the current epoch keys at the granted level.
* **Remove, downgrade, revoke or disable PIN:** the admin's client performs the
  change together with the next epoch: new EDK, intake and ESK keys, wraps to
  every remaining principal at its level, history wraps, and a signed epoch
  descriptor. The witness appends the change and the descriptor atomically;
  from then on it rejects records under the old epoch. The API stops serving
  old-epoch wraps to the removed principal and revokes dependent machine leases
  and CI deliveries.
* **Failure handling.** If the witness rejects the change, nothing applies. If
  it accepts and the database write fails, clients fail closed on that
  environment until the API republishes from the witness copy; the admin's
  client retains the new wraps until the API confirms storage.
* **Re-encryption** of retained versions into the new epoch runs on authorised
  clients in bounded batches with a per-variable idempotent marker, and resumes
  after interruption. Until it finishes, old versions stay readable through
  history wraps at each principal's level.
* **Rotation list:** the removal shows every value the principal could decrypt
  so admins can rotate them at their source.
* **Unlock method loss:** deleting a passkey or recovery wrap stops its future
  use but cannot revoke copies. If a method may be compromised, the user
  rotates the identity: new keys, a signed key-log entry, re-wraps, and a new
  epoch on every environment the old identity could read. An owner rotation
  also follows the owner-set rule.

## Audit

`private.vault_audit_events` records actor kind (`user`, `machine`, `ci`,
`workload`, `sync`), actor ID, event, resource IDs and names, a truncated IP
prefix (/24 or /48), user-agent family, grant or lease ID and result. It never
records values, ciphertext, wraps, PINs, OPRF material or tokens. Workspace
admins can read it; events are kept for 400 days.

Audit is **server-trusted**: the operator could rewrite or drop events. The
per-workspace hash chain detects accidental damage, and its head is included
in each witness checkpoint, so rewriting history before a checkpoint is
detectable. Reveal and copy events come from first-party clients; a modified
client can skip them.

## Sync targets

Sync decrypts, so it runs only in a principal that already decrypts: an
unlocked browser, `ttr secrets sync` with a machine grant, or a CI job. The
server never syncs on its own.

| Target | Direction | Notes |
| - | - | - |
| Cloudflare Worker secrets | Push | Per Worker and environment |
| GitHub environment secrets | Push | Sealed box to the repository public key, as GitHub requires |
| Vercel | Import and archive | Vercel `sensitive` values cannot be read back; they are listed by name for re-entry |

Idempotency uses the signed version record ID: a target is up to date when its
recorded version ID matches. No value digest is stored or logged. Provider
tokens are sensitive vault values. A run is bounded (at most 500 writes, 3
retries with backoff), records a terminal state and stops on a durable cancel
flag.

## CLI

| Command | Behaviour |
| - | - |
| `ttr secrets login` | Starts the agent and requests a machine grant |
| `ttr secrets unlock` | Renews or widens the lease through a new approval |
| `ttr secrets list [--env]` | Names and metadata |
| `ttr secrets get NAME [--env]` | Prints one value to stdout; refuses a TTY for secrets without `--reveal` |
| `ttr secrets set NAME [--env] [--sensitive]` | Reads the value from stdin only |
| `ttr secrets run [--env] -- <cmd>` | Spawns `cmd` with the environment injected; writes nothing to disk |
| `ttr secrets pull --stdout [--format]` | Prints only |
| `ttr secrets sync <target>` | Runs a configured sync |
| `ttr secrets logout` | Revokes the lease and stops the agent |

No command accepts a value on argv. Debug output is redacted by value match.
Same-user processes can read a process environment on most systems; that is
the accepted boundary for `run`.

## Web delivery hardening

* The vault UI is served from `vault.tuturuuu.com` with a nonce-based CSP, no
  third-party scripts, Trusted Types, `frame-ancestors 'none'` and
  `Cross-Origin-Opener-Policy: same-origin`.
* It uses a host-only child session (`__Host-` cookie) from the satellite
  handoff and same-origin vault APIs. No long-lived bearer token is readable by
  page script, per [Shared session](https://docs.tuturuuu.com/platform/architecture/shared-session.md).
* Plaintext lives only in component memory, never in TanStack Query caches,
  Web Storage, IndexedDB or logs. Unlocked state ends on tab close, 15 minutes
  of inactivity, or lock. The keyring head cache in `sessionStorage` holds no
  key material.

## Storage and runtime

Ciphertext, wraps, records, the key log, keyrings and audit live in Postgres in
the `private` schema, reached only through server routes and
`packages/internal-api`; the witness is the commit point and Postgres is the
store. No Supabase-only features are used, so the tables move to Hyperdrive
with the platform. The API lives under
`apps/web/src/app/api/v1/workspaces/[wsId]/vault/**`.

New backend work runs on Cloudflare: the witness, the share service, reminder
scheduling (a Cron Trigger Worker sending expiry and rotation reminders 14, 3
and 0 days ahead from plaintext metadata) and workload leases. Each of these
metered Workers bounds operations per request and per minute, retries at most
3 times with backoff, keys work idempotently, and has a durable stop flag with
a restart test, before it is admitted. Plaintext re-encryption always runs on
authorised clients.

## Package boundaries

* `packages/vault-crypto`: formats, context binding, wraps, signatures, key
  log and manifest verification, pairing, recovery encoding. Its portable
  entrypoint imports no Next.js, React, Cloudflare or request globals.
* `packages/internal-api/src/vault/*`: data access and authorisation.
* `packages/sdk/src/cli/secrets/*`: CLI commands and the agent.
* `apps/vault-share`, `apps/vault-witness`: Cloudflare Workers.

## Dependencies on the central session

Reused from the central provider-agnostic session model:

1. The `ttr+stepup` proof for the share service (`aud: stepup:vault-share`),
   verified offline with `iss`, `env`, `typ`, `aud` and `act` pinned and
   `paramsHash` from `@tuturuuu/session/stepup`, consumed through `StepUpConsumePort`,
   and the `sid` checked for liveness separately. MFA unlock stays off until it
   ships.
2. The `cli` device session (`dev`, `sid`, approval with `stepUpGrantId`) that
   machine grants bind to.
3. The host-only child session for `vault.tuturuuu.com` (design gate G9) and
   the trusted-ingress proof for subdomain hosts (design gate G4), both before
   the vault origin reads first-party identity. Slice 3a is admitted only with
   links to the accepted evidence for both gates.
4. The step-up confirmation page and one-time code redemption, with `act`
   value `vault.pin-eval` registered for `ttr+stepup`; no other vault act exists.

Login passkeys and their credential list are not used for vault unlock.

## Threat model and delivery

The threat model and the delivery slices live in
[Secrets vault threat model and delivery](https://docs.tuturuuu.com/platform/architecture/secrets-vault-delivery.md).


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