# `@shade/vault` — server-side encrypted file store V4.13. Where the blob primitive (V4.9) holds one small blob per account, a vault holds a whole **collection** — a workspace, a mailbox, a drive folder — as content-addressed objects plus an append-only log of manifests. It is the piece Shade was missing to let an app offer backup, or to let a client read data while the peer that owns it is switched off. ## The model **Objects are content-addressed.** An object's name is the SHA-256 of its *ciphertext*, so the relay can store, dedupe and verify without a key: it recomputes the hash on upload and rejects anything mislabelled. **A manifest names the collection.** Paths live inside the encrypted manifest, never in object names — the relay must not learn that a user has a file called `Projects/Divorce/plan.md`. The manifest is itself stored as an object. **The log is append-only.** Each commit adds a row pointing at a manifest. History, rollback and "what changed last Tuesday" all fall out of that. ## Keys Three deterministic derivations off the account master key, in their own HKDF branch: ``` vaultId = HKDF(masterKey, "shade-vault-id-v1:") contentKey = HKDF(masterKey, "shade-vault-content-v1:") sigSeed = HKDF(masterKey, "shade-vault-sig-v1:") ``` Separate from `shade-blob-*-v1` on purpose: a vault key reads every file, a profile-blob key reads a host list. Sharing a derivation would turn one compromise into the other. Because the derivation is deterministic, **recovery is credentials**. A fresh device that can derive the profile master can derive these, and the relay hands over ciphertext it has never been able to read. The flip side is that recovery strength is password strength — see G1's argon2id item. ## Client ```ts import { SubtleCryptoProvider } from '@shade/crypto-web'; import { VaultClient, HttpVaultTransport, deriveVaultKeys } from '@shade/vault'; const crypto = new SubtleCryptoProvider(); const keys = await deriveVaultKeys(masterKey, 'scaffold'); const client = new VaultClient(crypto, keys, new HttpVaultTransport('https://vault.example')); // Back up. Unchanged files are not re-uploaded. Persist `res.index` and pass // it to the next push: an unchanged file is then recognised locally, with no // download at all. const res = await client.push(files, Date.now(), undefined, { index: savedIndex }); // → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204, unchanged: false, index } // Restore — the newest, or any earlier version. const { manifest, files: restored } = await client.pull(); const old = await client.pull(2); // Lazy: list a version, then fetch only what is opened. const m = await client.manifest(); const bytes = await client.readEntry(m.entries[0]); // History, and retention. const log = await client.history(); await client.prune([log.head - 1, log.head]); // → { removedVersions, removedObjects, freedBytes } ``` `push` takes `at` rather than reading the clock, so a queued backup records when it was *taken* rather than when it finally reached the relay. **A push that changes nothing commits nothing.** Same paths, same modes, every file reused, no `message`: the result is `{ unchanged: true, seq: head }` and the log does not grow. Pushes run on every workspace change; a version per trigger would fill the log with empty commits. Pass a `message` to force one. **The index** (`VaultIndex`, plain JSON) maps each path to its plaintext SHA-256 and the entry it was stored as. It is trusted only when its `vaultId` matches and its `seq` is still the relay's head; otherwise the push reads the head manifest and downloads only same-path, same-size candidates to compare. It holds plaintext hashes, so keep it with the files, never on the relay. After a restore, `vaultIndexFrom(vaultId, manifest, files)` builds one, so the first push from a fresh device is free too. ## Format (v2) — the cross-language contract Every object is `nonce(12) || AES-256-GCM(contentKey, plaintext, aad)`, named by the lowercase hex SHA-256 of those bytes, with `aad = utf8("shade-vault-object-v1|" + vaultId)`. **Entries.** A file's plaintext becomes its *stored* bytes, then *parts*: 1. Unless the plaintext is empty or starts with a known compressed signature — PNG `89 50 4E 47`, JPEG `FF D8 FF`, WebP `"RIFF"` + `"WEBP"` at offset 8, MP4 family `"ftyp"` at offset 4, GIF `"GIF8"`, gzip `1F 8B`, zip `"PK"` — deflate it (raw RFC 1951, zlib default level). Keep the result, and set `enc: "deflate-raw"`, only if `compressed * 20 <= plain * 19` (≤ 95 %, in integers so no port rounds differently). 2. Split the stored bytes into slices of at most 4 MiB (4 194 304). An empty file is one empty slice. 3. Seal each slice as its own object. One slice: `hash` names it and there is no `parts`. Several: `parts` lists their hashes in order and `hash = parts[0]`. `size` is always the **plaintext** length. A reader fetches `parts ?? [hash]`, verifies and opens each, concatenates, inflates if `enc`, and checks the result against `size`. An unknown `enc` is refused. **Manifests.** v2 plaintext is ASCII `"SVM2"` followed by deflate-raw of the UTF-8 JSON; v1 is the bare JSON. A reader inflates when the magic is present, parses, and accepts `version` 1 or 2 only — refusing beats guessing, since silently dropping a field it cannot represent would lose data on its next commit. JSON key order is not part of the contract. A v1-only reader fails on a v2 manifest at JSON parse, loudly, rather than misreading it. **Commits** list every part of every entry in the signed `hashes`. The relay checks they exist and records them as what the version references; a part left out may be collected by the next prune. **Signed bodies** are canonicalised as JSON of every field except `signature`, top-level keys sorted, nested values as-is; the signature is Ed25519 over those bytes with the vault's signing seed, base64 on the wire. Vectors for all of the above: `test-vectors/vault-v2.json` (regenerate with `bun run scripts/generate-vectors.ts vault-v2.json`). Compressed bytes are pinned (`stored`) for writer parity; a reader needs only `wire`. ## Server ```ts import { createVaultRoutes } from '@shade/vault/server'; import { SqliteVaultStore } from '@shade/storage-sqlite'; app.route('/', createVaultRoutes(new SqliteVaultStore('/data/shade-vault.db'), crypto)); ``` Routes: | | | |---|---| | `GET /v1/vault/:id/log` | `{ entries, head }` | | `HEAD /v1/vault/:id/object/:hash` | 200 / 404 — the have-check | | `GET /v1/vault/:id/object/:hash` | raw ciphertext | | `PUT /v1/vault/:id/object/:hash` | signed; verifies hash matches bytes | | `POST /v1/vault/:id/commit` | signed; refuses a stale `seq` or a missing object | | `POST /v1/vault/:id/prune` | signed `{ keep: number[] }`; must keep the head | Auth is TOFU-Ed25519, as for blobs: the first signed write pins a pubkey, and every later write must be signed by it. The pubkey travels **inside** the signed payload — appended afterwards it would not be covered by the signature, and could be swapped in transit on the pinning write. ### Configuration ``` SHADE_VAULT_DB_PATH=/data/shade-vault.db # required — no in-memory fallback SHADE_DISABLE_VAULT=1 # optional: off entirely ``` **There is deliberately no in-memory fallback.** The blob store has one, and on 2026-08-12 a routine redeploy destroyed every profile because the path was never set in compose: the fallback worked perfectly right up until the container was recreated, and nothing ever failed loudly. A vault that forgets is worse than no vault, so an unset path means the routes are simply not mounted, with a warning that says why. ### Limits Per object 8 MiB, per vault 512 MiB, both overridable via `VaultRoutesOptions`. Files larger than an object are split into 4 MiB parts by the client, so the per-object limit no longer caps file size. ### Retention `prune` deletes every log entry not in `keep` and then every object no remaining entry references. The client chooses the policy — only it can read the manifests — and the relay executes it: - `keep` must include the current head, or the request fails with `SEQ_CONFLICT` (and the head). That is also what a keep-list computed before another device's commit, or a replayed prune, runs into. - Prune never pins an owner: on a vault with no owner it is a 404. - An entry newer than the head the route checked is never removed, even if a commit lands mid-request. - An object no version has ever referenced (an upload whose commit is still in flight) survives for `pruneGraceMs`, default one hour. - **Versions committed before ref tracking** have no recorded hash list. Every object present when such a version was written (for SQLite: when the database was migrated) is pinned and never collected while any untracked version remains. Once the last one is pruned, nothing has an unknown reference set, and the pins are released. `SqliteVaultStore` migrates in place on open: `refs_known` on the log, `pinned` on objects, a `shade_vault_refs` table. No manual step. ## What the relay learns Object sizes, how many objects there are, when commits happen, and that some opaque 64-hex id is active. Not contents, not paths, not filenames, and not which user a vaultId belongs to — the id is itself derived from a secret. Deduplication is **within** a version chain, not across independent seals: sealing uses a fresh nonce, so identical plaintext yields different names. Convergent encryption would dedupe globally but leak which files two users share, which is exactly what a blind store must not do. ## Status Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and tested, v2 format and prune included, with cross-language vectors. Not yet: a Postgres store, rate limiting on the vault routes, and the Kotlin port of v2.