diff --git a/CHANGELOG.md b/CHANGELOG.md index 8bf671b..fd6d49a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,42 @@ All notable changes to Shade are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [4.14.0] — 2026-10-16 — Vault v2: smaller, cheaper pushes, big files, retention + +### Added +- **`@shade/vault`: compressed and multi-part entries.** A file is deflated + (raw, kept only if it saves ≥ 5 %, skipped for known compressed formats) + and split into 4 MiB parts. `VaultEntry` gains optional `enc` and `parts`; + `size` stays the plaintext length. Files over the relay's 8 MiB object limit + can now be backed up at all. +- **Manifest v2**: `"SVM2"` + deflate-raw(JSON). Push writes v2; readers + accept v1 and v2 and refuse anything else. +- **`VaultIndex`** — `push(files, at, message?, { index })` returns an `index` + to persist. With a fresh one, an unchanged file is recognised by plaintext + SHA-256 with no download, no seal and no upload (renames and copies too). +- **A push that changes nothing commits nothing** (`unchanged: true`), unless a + `message` asks for a version. +- **Lazy reads**: `VaultClient.manifest(seq?)` and `readEntry(entry)`; `pull` + is built on them. Exported helpers: `openEntryBytes`, `entryObjectHashes`, + `packEntry`, `sealEntry`, `encodeManifest`/`decodeManifest`, `vaultIndexFrom`. +- **Retention**: signed `POST /v1/vault/:id/prune` `{ keep }`, + `VaultClient.prune(keep)` → `{ removedVersions, removedObjects, freedBytes }`. + The relay records each commit's referenced hashes and collects objects no + remaining version uses. Versions from before this pin their objects until + they are pruned themselves. `VaultRoutesOptions.pruneGraceMs` (default 1 h) + protects uploads whose commit is still in flight. +- `VaultStore.prune` and an optional `refs` argument on `appendLog`; + `SqliteVaultStore` migrates its schema in place on open. +- `test-vectors/vault-v2.json` for the Kotlin port; `@shade/vault/testing` + (fixed-nonce sealing, vectors only). + +### Changed +- Push without an index reads only the head manifest and downloads a previous + file only when its path and size match — it used to download every file of + the head. Freshly sealed objects are no longer have-checked (their names are + new by construction). A reused entry takes the file's current `mode`. +- `VaultTransport` has a required `prune` method; custom transports must add it. + ## [4.13.2] — 2026-10-15 — No prekey-server call can hang an identity open ### Fixed diff --git a/docs/vault.md b/docs/vault.md index 1d8ff13..2e636fb 100644 --- a/docs/vault.md +++ b/docs/vault.md @@ -50,21 +50,84 @@ 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. -const res = await client.push(files, Date.now(), 'nightly'); -// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204 } +// 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); -// History. +// 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 @@ -83,6 +146,7 @@ Routes: | `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 @@ -106,6 +170,31 @@ 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 @@ -121,6 +210,5 @@ share, which is exactly what a blind store must not do. ## Status Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and -tested (16 unit + 7 store tests, plus an end-to-end suite against a real -workspace of 491 files). Not yet: a Postgres store, rate limiting on the vault -routes, and garbage collection of objects no manifest references any more. +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. diff --git a/packages/shade-cli/package.json b/packages/shade-cli/package.json index c798fce..1984287 100644 --- a/packages/shade-cli/package.json +++ b/packages/shade-cli/package.json @@ -1,6 +1,6 @@ { "name": "@shade/cli", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/cli.ts", "bin": { diff --git a/packages/shade-core/package.json b/packages/shade-core/package.json index 49a20c4..20b00a1 100644 --- a/packages/shade-core/package.json +++ b/packages/shade-core/package.json @@ -1,6 +1,6 @@ { "name": "@shade/core", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-crypto-web/package.json b/packages/shade-crypto-web/package.json index 3f0d4a3..1944179 100644 --- a/packages/shade-crypto-web/package.json +++ b/packages/shade-crypto-web/package.json @@ -1,6 +1,6 @@ { "name": "@shade/crypto-web", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-dashboard/package.json b/packages/shade-dashboard/package.json index 4022307..245bdd9 100644 --- a/packages/shade-dashboard/package.json +++ b/packages/shade-dashboard/package.json @@ -1,6 +1,6 @@ { "name": "@shade/dashboard", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "scripts": { "dev": "vite", diff --git a/packages/shade-files/package.json b/packages/shade-files/package.json index 4814e70..c713c39 100644 --- a/packages/shade-files/package.json +++ b/packages/shade-files/package.json @@ -1,6 +1,6 @@ { "name": "@shade/files", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-inbox-server/package.json b/packages/shade-inbox-server/package.json index 0dbd807..afcd814 100644 --- a/packages/shade-inbox-server/package.json +++ b/packages/shade-inbox-server/package.json @@ -1,6 +1,6 @@ { "name": "@shade/inbox-server", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-inbox/package.json b/packages/shade-inbox/package.json index 26caff3..42bae60 100644 --- a/packages/shade-inbox/package.json +++ b/packages/shade-inbox/package.json @@ -1,6 +1,6 @@ { "name": "@shade/inbox", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-key-transparency/package.json b/packages/shade-key-transparency/package.json index 3b257f9..6a37f97 100644 --- a/packages/shade-key-transparency/package.json +++ b/packages/shade-key-transparency/package.json @@ -1,6 +1,6 @@ { "name": "@shade/key-transparency", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-keychain/package.json b/packages/shade-keychain/package.json index 165ef43..858f42b 100644 --- a/packages/shade-keychain/package.json +++ b/packages/shade-keychain/package.json @@ -1,6 +1,6 @@ { "name": "@shade/keychain", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-observability/package.json b/packages/shade-observability/package.json index ef03669..043640c 100644 --- a/packages/shade-observability/package.json +++ b/packages/shade-observability/package.json @@ -1,6 +1,6 @@ { "name": "@shade/observability", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-observer/package.json b/packages/shade-observer/package.json index 2b87514..7e8a045 100644 --- a/packages/shade-observer/package.json +++ b/packages/shade-observer/package.json @@ -1,6 +1,6 @@ { "name": "@shade/observer", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-proto/package.json b/packages/shade-proto/package.json index 659e79e..fffc7a3 100644 --- a/packages/shade-proto/package.json +++ b/packages/shade-proto/package.json @@ -1,6 +1,6 @@ { "name": "@shade/proto", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-recovery/package.json b/packages/shade-recovery/package.json index 5b542f4..70210ee 100644 --- a/packages/shade-recovery/package.json +++ b/packages/shade-recovery/package.json @@ -1,6 +1,6 @@ { "name": "@shade/recovery", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-sdk/package.json b/packages/shade-sdk/package.json index d69c1a7..04493df 100644 --- a/packages/shade-sdk/package.json +++ b/packages/shade-sdk/package.json @@ -1,6 +1,6 @@ { "name": "@shade/sdk", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-server/package.json b/packages/shade-server/package.json index e12c2f1..53cc2f5 100644 --- a/packages/shade-server/package.json +++ b/packages/shade-server/package.json @@ -1,6 +1,6 @@ { "name": "@shade/server", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-storage-encrypted/package.json b/packages/shade-storage-encrypted/package.json index 72b4b7b..c2bb853 100644 --- a/packages/shade-storage-encrypted/package.json +++ b/packages/shade-storage-encrypted/package.json @@ -1,6 +1,6 @@ { "name": "@shade/storage-encrypted", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-storage-indexeddb/package.json b/packages/shade-storage-indexeddb/package.json index 7014ead..bd40e82 100644 --- a/packages/shade-storage-indexeddb/package.json +++ b/packages/shade-storage-indexeddb/package.json @@ -1,6 +1,6 @@ { "name": "@shade/storage-indexeddb", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-storage-postgres/package.json b/packages/shade-storage-postgres/package.json index f78abf2..9834ec2 100644 --- a/packages/shade-storage-postgres/package.json +++ b/packages/shade-storage-postgres/package.json @@ -1,6 +1,6 @@ { "name": "@shade/storage-postgres", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-storage-sqlite/package.json b/packages/shade-storage-sqlite/package.json index cfabab5..3a9a42b 100644 --- a/packages/shade-storage-sqlite/package.json +++ b/packages/shade-storage-sqlite/package.json @@ -1,6 +1,6 @@ { "name": "@shade/storage-sqlite", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-storage-sqlite/src/sqlite-vault-store.ts b/packages/shade-storage-sqlite/src/sqlite-vault-store.ts index 154bb8b..fdfc652 100644 --- a/packages/shade-storage-sqlite/src/sqlite-vault-store.ts +++ b/packages/shade-storage-sqlite/src/sqlite-vault-store.ts @@ -1,5 +1,5 @@ import { Database } from 'bun:sqlite'; -import type { VaultLogEntry, VaultStore } from '@shade/vault'; +import type { VaultLogEntry, VaultPrunePlan, VaultPruneResult, VaultStore } from '@shade/vault'; /** * SQLite-backed VaultStore for the V4.13 encrypted file store. @@ -9,6 +9,13 @@ import type { VaultLogEntry, VaultStore } from '@shade/vault'; * never decrypts anything — it enforces auth, verifies that an object's bytes * hash to its name, and refuses a commit whose objects are not all present. * + * A fourth table, `shade_vault_refs`, records which objects each version + * references (the commit's signed hashes plus its manifest). The relay cannot + * read manifests, so this is what prune computes garbage from. Versions from + * before it existed have `refs_known = 0`, and every object that was in the + * database when the columns were added is `pinned` — see `VaultPrunePlan` for + * why that is the safe reading and how the pins are eventually released. + * * Objects are stored as BLOBs rather than base64 text. A workspace backup is * a few hundred files where the blob primitive holds one small profile, so the * 33% base64 overhead stops being a rounding error. @@ -31,6 +38,8 @@ export class SqliteVaultStore implements VaultStore { log: ReturnType; logLimit: ReturnType; appendLog: ReturnType; + appendRef: ReturnType; + pinAll: ReturnType; usage: ReturnType; }; @@ -56,18 +65,48 @@ export class SqliteVaultStore implements VaultStore { bytes BLOB NOT NULL, size INTEGER NOT NULL, created_at INTEGER NOT NULL, + pinned INTEGER NOT NULL DEFAULT 0, PRIMARY KEY (vault_id, hash) ); CREATE TABLE IF NOT EXISTS shade_vault_log ( - vault_id TEXT NOT NULL, - seq INTEGER NOT NULL, - manifest TEXT NOT NULL, - at INTEGER NOT NULL, - bytes INTEGER NOT NULL, + vault_id TEXT NOT NULL, + seq INTEGER NOT NULL, + manifest TEXT NOT NULL, + at INTEGER NOT NULL, + bytes INTEGER NOT NULL, + refs_known INTEGER NOT NULL DEFAULT 1, PRIMARY KEY (vault_id, seq) ); + + CREATE TABLE IF NOT EXISTS shade_vault_refs ( + vault_id TEXT NOT NULL, + seq INTEGER NOT NULL, + hash TEXT NOT NULL, + PRIMARY KEY (vault_id, seq, hash) + ); + CREATE INDEX IF NOT EXISTS shade_vault_refs_by_hash ON shade_vault_refs (vault_id, hash); `); + + // Databases from before ref tracking. The defaults here are the whole + // migration: every existing log row becomes untracked (refs_known = 0), + // and every existing object pinned (pinned = 1), because any of them may + // be referenced by one of those rows. New rows always set both columns + // explicitly, so these defaults only ever apply to the old ones. + const has = (table: string, column: string): boolean => + (this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some( + (c) => c.name === column, + ); + this.db.transaction(() => { + if (!has('shade_vault_log', 'refs_known')) { + this.db.exec( + 'ALTER TABLE shade_vault_log ADD COLUMN refs_known INTEGER NOT NULL DEFAULT 0', + ); + } + if (!has('shade_vault_objects', 'pinned')) { + this.db.exec('ALTER TABLE shade_vault_objects ADD COLUMN pinned INTEGER NOT NULL DEFAULT 1'); + } + })(); } private prepareStatements() { @@ -82,7 +121,7 @@ export class SqliteVaultStore implements VaultStore { // An object's name IS its content hash, so a repeat upload is the same // bytes by definition — ignoring it is correct, not lossy. putObject: this.db.prepare( - 'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at) VALUES (?, ?, ?, ?, ?)', + 'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at, pinned) VALUES (?, ?, ?, ?, ?, 0)', ), getObject: this.db.prepare( 'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?', @@ -95,8 +134,12 @@ export class SqliteVaultStore implements VaultStore { 'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC', ), appendLog: this.db.prepare( - 'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes) VALUES (?, ?, ?, ?, ?)', + 'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes, refs_known) VALUES (?, ?, ?, ?, ?, ?)', ), + appendRef: this.db.prepare( + 'INSERT OR IGNORE INTO shade_vault_refs (vault_id, seq, hash) VALUES (?, ?, ?)', + ), + pinAll: this.db.prepare('UPDATE shade_vault_objects SET pinned = 1 WHERE vault_id = ?'), usage: this.db.prepare( 'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?', ), @@ -139,8 +182,100 @@ export class SqliteVaultStore implements VaultStore { return rows; } - async appendLog(vaultId: string, entry: VaultLogEntry): Promise { - this.stmts.appendLog.run(vaultId, entry.seq, entry.manifest, entry.at, entry.bytes); + async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise { + this.db.transaction(() => { + this.stmts.appendLog.run( + vaultId, + entry.seq, + entry.manifest, + entry.at, + entry.bytes, + refs ? 1 : 0, + ); + if (refs) { + for (const h of refs) this.stmts.appendRef.run(vaultId, entry.seq, h); + } else { + // Untracked: it can reference anything stored so far, so pin all of it. + this.stmts.pinAll.run(vaultId); + } + })(); + } + + /** + * One transaction, so a commit cannot interleave between deciding what is + * garbage and deleting it. bun:sqlite is synchronous, and a write + * transaction holds the database lock for its whole duration. + */ + async prune(vaultId: string, plan: VaultPrunePlan): Promise { + return this.db.transaction((): VaultPruneResult => { + const keep = new Set(plan.keep); + const rows = this.db + .prepare('SELECT seq, refs_known FROM shade_vault_log WHERE vault_id = ?') + .all(vaultId) as Array<{ seq: number; refs_known: number }>; + const removed = rows.filter((r) => r.seq <= plan.upTo && !keep.has(r.seq)).map((r) => r.seq); + const untrackedRemains = rows.some( + (r) => r.refs_known === 0 && !(r.seq <= plan.upTo && !keep.has(r.seq)), + ); + + // The removed seqs go into a temp table so every query below can say + // "the log as it will be" without string-building an IN list. + this.db.exec( + 'CREATE TEMP TABLE IF NOT EXISTS shade_vault_prune_removed (seq INTEGER PRIMARY KEY)', + ); + this.db.exec('DELETE FROM shade_vault_prune_removed'); + const addRemoved = this.db.prepare('INSERT INTO shade_vault_prune_removed (seq) VALUES (?)'); + for (const seq of removed) addRemoved.run(seq); + + if (!untrackedRemains) { + // No version with an unknown reference set is left, so nothing can + // depend on a pin any more. + this.db.prepare('UPDATE shade_vault_objects SET pinned = 0 WHERE vault_id = ?').run(vaultId); + } + + // Garbage: not pinned, not used by a remaining version, and — if no + // version ever used it — older than the grace for in-flight uploads. + const garbage = this.db + .prepare( + `SELECT o.hash AS hash, o.size AS size FROM shade_vault_objects o + WHERE o.vault_id = ?1 + AND o.pinned = 0 + AND NOT EXISTS ( + SELECT 1 FROM shade_vault_refs r + WHERE r.vault_id = ?1 AND r.hash = o.hash + AND r.seq NOT IN (SELECT seq FROM shade_vault_prune_removed)) + AND NOT EXISTS ( + SELECT 1 FROM shade_vault_log l + WHERE l.vault_id = ?1 AND l.manifest = o.hash + AND l.seq NOT IN (SELECT seq FROM shade_vault_prune_removed)) + AND ( + o.created_at <= ?2 + OR EXISTS (SELECT 1 FROM shade_vault_refs r WHERE r.vault_id = ?1 AND r.hash = o.hash) + OR EXISTS (SELECT 1 FROM shade_vault_log l WHERE l.vault_id = ?1 AND l.manifest = o.hash))`, + ) + .all(vaultId, plan.protectSince) as Array<{ hash: string; size: number }>; + + const delObject = this.db.prepare( + 'DELETE FROM shade_vault_objects WHERE vault_id = ? AND hash = ?', + ); + let freedBytes = 0; + for (const g of garbage) { + delObject.run(vaultId, g.hash); + freedBytes += g.size; + } + this.db + .prepare( + 'DELETE FROM shade_vault_refs WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)', + ) + .run(vaultId); + this.db + .prepare( + 'DELETE FROM shade_vault_log WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)', + ) + .run(vaultId); + this.db.exec('DELETE FROM shade_vault_prune_removed'); + + return { removedVersions: removed.length, removedObjects: garbage.length, freedBytes }; + })(); } async usage(vaultId: string): Promise { diff --git a/packages/shade-storage-sqlite/tests/sqlite-vault-store.test.ts b/packages/shade-storage-sqlite/tests/sqlite-vault-store.test.ts index 851df00..e196fd5 100644 --- a/packages/shade-storage-sqlite/tests/sqlite-vault-store.test.ts +++ b/packages/shade-storage-sqlite/tests/sqlite-vault-store.test.ts @@ -118,3 +118,134 @@ describe('semantics', () => { store.close(); }); }); + +describe('prune', () => { + const h = (c: string) => c.repeat(64); + + test('removes unkept versions and only the objects nothing else uses', async () => { + const store = new SqliteVaultStore(scratch('prune')); + await store.putObject(VAULT, h('1'), new Uint8Array(10)); // manifest 1 + await store.putObject(VAULT, h('2'), new Uint8Array(20)); // manifest 2 + await store.putObject(VAULT, h('a'), new Uint8Array(30)); // shared file + await store.putObject(VAULT, h('b'), new Uint8Array(40)); // only in v1 + await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1'), h('a'), h('b')]); + await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2'), h('a')]); + + const res = await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() }); + expect(res).toEqual({ removedVersions: 1, removedObjects: 2, freedBytes: 50 }); + expect(await store.hasObject(VAULT, h('a'))).toBe(true); + expect(await store.hasObject(VAULT, h('b'))).toBe(false); + expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2]); + store.close(); + }); + + test('a fresh, never-committed upload survives; a stale one does not', async () => { + const store = new SqliteVaultStore(scratch('grace')); + await store.putObject(VAULT, h('1'), new Uint8Array(1)); + await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1')]); + await store.putObject(VAULT, h('c'), new Uint8Array(5)); + + const kept = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() - 60_000 }); + expect(kept.removedObjects).toBe(0); + const gone = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() + 1 }); + expect(gone.removedObjects).toBe(1); + expect(await store.hasObject(VAULT, h('c'))).toBe(false); + store.close(); + }); + + test('never removes an entry above upTo, even when it is not in keep', async () => { + const store = new SqliteVaultStore(scratch('upto')); + for (let seq = 1; seq <= 3; seq++) { + await store.appendLog(VAULT, { seq, manifest: `${seq}`.repeat(64), at: seq, bytes: 0 }, []); + } + await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: 0 }); + expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2, 3]); + store.close(); + }); + + test('untracked entries pin what existed when they were appended, until they are gone', async () => { + const store = new SqliteVaultStore(scratch('pin')); + await store.putObject(VAULT, h('1'), new Uint8Array(1)); + await store.putObject(VAULT, h('b'), new Uint8Array(1)); + await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }); // no refs + await store.putObject(VAULT, h('2'), new Uint8Array(1)); + await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]); + await store.putObject(VAULT, h('3'), new Uint8Array(1)); + await store.appendLog(VAULT, { seq: 3, manifest: h('3'), at: 3, bytes: 0 }, [h('3')]); + + const first = await store.prune(VAULT, { keep: [1, 3], upTo: 3, protectSince: Date.now() }); + expect(first.removedObjects).toBe(1); // only manifest 2 + expect(await store.hasObject(VAULT, h('b'))).toBe(true); + + const second = await store.prune(VAULT, { keep: [3], upTo: 3, protectSince: Date.now() }); + expect(second.removedObjects).toBe(2); // manifest 1 and b, unpinned + expect(await store.hasObject(VAULT, h('3'))).toBe(true); + store.close(); + }); + + test('a database from before ref tracking migrates with everything pinned', async () => { + // The exact pre-v2 schema, with a version and its objects in it. + const path = scratch('migrate'); + const { Database } = await import('bun:sqlite'); + const old = new Database(path, { create: true }); + old.exec(` + CREATE TABLE shade_vault_objects (vault_id TEXT NOT NULL, hash TEXT NOT NULL, bytes BLOB NOT NULL, + size INTEGER NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (vault_id, hash)); + CREATE TABLE shade_vault_log (vault_id TEXT NOT NULL, seq INTEGER NOT NULL, manifest TEXT NOT NULL, + at INTEGER NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY (vault_id, seq)); + `); + old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('1'), new Uint8Array(1), 1, 0); + old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('a'), new Uint8Array(1), 1, 0); + old.prepare('INSERT INTO shade_vault_log VALUES (?, ?, ?, ?, ?)').run(VAULT, 1, h('1'), 1, 2); + old.close(); + + const store = new SqliteVaultStore(path); + // A tracked version on top, then drop nothing but nothing referenced by it: + // the old file object must survive because version 1 may use it. + await store.putObject(VAULT, h('2'), new Uint8Array(1)); + await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]); + const res = await store.prune(VAULT, { keep: [1, 2], upTo: 2, protectSince: Date.now() }); + expect(res.removedObjects).toBe(0); + expect(await store.hasObject(VAULT, h('a'))).toBe(true); + store.close(); + + // Reopening runs the migration check again and must be a no-op. + const again = new SqliteVaultStore(path); + expect((await again.log(VAULT)).map((e) => e.seq)).toEqual([1, 2]); + const final = await again.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() }); + expect(final).toMatchObject({ removedVersions: 1, removedObjects: 2 }); + again.close(); + }); +}); + +describe('through the real routes and client', () => { + test('v2 push, index reuse, multi-part and prune all work on SQLite', async () => { + const { SubtleCryptoProvider } = await import('@shade/crypto-web'); + const { createVaultRoutes } = await import('@shade/vault/server'); + const { HttpVaultTransport, VaultClient, deriveVaultKeys } = await import('@shade/vault'); + const crypto = new SubtleCryptoProvider(); + const store = new SqliteVaultStore(scratch('e2e')); + const routes = createVaultRoutes(store, crypto, { pruneGraceMs: 0 }); + const transport = new HttpVaultTransport('http://v', (i, init) => routes.fetch(new Request(i, init))); + const keys = await deriveVaultKeys(new Uint8Array(32).fill(5), 'scaffold'); + const client = new VaultClient(crypto, keys, transport, { chunkSize: 512 }); + + const big = new Uint8Array(2000); + globalThis.crypto.getRandomValues(big); + const text = new TextEncoder().encode('linje\n'.repeat(500)); + const first = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 1); + const same = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 2, undefined, { + index: first.index, + }); + expect(same.unchanged).toBe(true); + await client.push([{ path: 't.md', bytes: text }], 3, undefined, { index: same.index }); + + const pruned = await client.prune([2]); + expect(pruned.removedVersions).toBe(1); + expect(pruned.removedObjects).toBe(5); // big.bin's 4 parts + manifest 1 + const { files } = await client.pull(); + expect(files.get('t.md')).toEqual(text); + expect(files.has('big.bin')).toBe(false); + store.close(); + }); +}); diff --git a/packages/shade-streams/package.json b/packages/shade-streams/package.json index e188215..44a1eeb 100644 --- a/packages/shade-streams/package.json +++ b/packages/shade-streams/package.json @@ -1,6 +1,6 @@ { "name": "@shade/streams", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-transfer/package.json b/packages/shade-transfer/package.json index 33a886a..9eeb15e 100644 --- a/packages/shade-transfer/package.json +++ b/packages/shade-transfer/package.json @@ -1,6 +1,6 @@ { "name": "@shade/transfer", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-transport-bridge/package.json b/packages/shade-transport-bridge/package.json index ecd810b..4cdc38b 100644 --- a/packages/shade-transport-bridge/package.json +++ b/packages/shade-transport-bridge/package.json @@ -1,6 +1,6 @@ { "name": "@shade/transport-bridge", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-transport-webrtc/package.json b/packages/shade-transport-webrtc/package.json index f854b1a..cc8fdbc 100644 --- a/packages/shade-transport-webrtc/package.json +++ b/packages/shade-transport-webrtc/package.json @@ -1,6 +1,6 @@ { "name": "@shade/transport-webrtc", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-transport/package.json b/packages/shade-transport/package.json index 3481254..03e4ff3 100644 --- a/packages/shade-transport/package.json +++ b/packages/shade-transport/package.json @@ -1,6 +1,6 @@ { "name": "@shade/transport", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/packages/shade-vault/package.json b/packages/shade-vault/package.json index 463d1b6..5bfe855 100644 --- a/packages/shade-vault/package.json +++ b/packages/shade-vault/package.json @@ -1,13 +1,14 @@ { "name": "@shade/vault", - "version": "4.13.2", + "version": "4.14.0", "description": "Server-side encrypted file store for Shade — content-addressed objects with an append-only manifest log", "type": "module", "main": "src/index.ts", "types": "src/index.ts", "exports": { ".": "./src/index.ts", - "./server": "./src/server.ts" + "./server": "./src/server.ts", + "./testing": "./src/testing.ts" }, "dependencies": { "@noble/hashes": "^2.0.1", diff --git a/packages/shade-vault/src/client.ts b/packages/shade-vault/src/client.ts index 56e67f4..b02d26b 100644 --- a/packages/shade-vault/src/client.ts +++ b/packages/shade-vault/src/client.ts @@ -2,10 +2,12 @@ * The client half: turn a set of files into an encrypted, versioned vault, * and turn it back again on a machine that has nothing but the credentials. * - * The push is deliberately have-check-first. A workspace changes a few lines - * at a time, so asking "do you already have these hashes?" and uploading only - * the misses turns a full backup into a handful of small writes. Everything - * unchanged keeps its hash from the previous commit and costs nothing. + * A workspace changes a few lines at a time, so a push has to cost what + * changed, not what exists. Everything unchanged keeps the entry — and so the + * objects — it had in the previous version, and costs nothing. Recognising + * "unchanged" is the expensive part: with a `VaultIndex` from the previous + * push it is a local hash comparison; without one, the previous manifest is + * read and only same-path, same-size candidates are downloaded to compare. */ import type { CryptoProvider } from '@shade/core'; @@ -19,8 +21,24 @@ import { deriveVaultId, deriveVaultSigningSeed, } from '@shade/storage-encrypted'; -import { openManifest, openObject, sealManifest, sealObject, toHex } from './crypto.js'; -import type { VaultEntry, VaultLog, VaultManifest } from './types.js'; +import { sha256 } from '@noble/hashes/sha2.js'; +import { + entryObjectHashes, + openEntryBytes, + openManifest, + sealEntry, + sealManifest, + toHex, +} from './crypto.js'; +import type { + VaultEntry, + VaultIndex, + VaultIndexEntry, + VaultLog, + VaultLogEntry, + VaultManifest, + VaultPruneResult, +} from './types.js'; /** A file as the app sees it, before encryption. */ export interface VaultFile { @@ -61,15 +79,37 @@ export interface VaultTransport { get(vaultId: string, hash: string): Promise; log(vaultId: string, limit?: number): Promise; commit(vaultId: string, body: unknown): Promise<{ seq: number }>; + prune(vaultId: string, body: unknown): Promise; +} + +export interface PushOptions { + /** + * The index the previous push returned. Trusted only when it belongs to + * this vault and its `seq` is still the relay's head; otherwise ignored. + */ + index?: VaultIndex; } export interface PushResult { + /** The version now at the head — the new one, or the old one if `unchanged`. */ seq: number; - /** Objects actually sent — the rest were already on the relay. */ + /** Data objects sent (the manifest is not counted). */ uploaded: number; - /** Objects skipped because the relay had them. */ + /** Files whose previous entry was reused without sealing anything. */ reused: number; bytesUploaded: number; + /** Nothing differed from the head, so no version was committed. */ + unchanged: boolean; + /** Describes the head after this push; persist it and pass it to the next one. */ + index: VaultIndex; +} + +export interface VaultClientOptions { + /** + * Override the 4 MiB part size. Internal — tests and vectors only. A real + * writer must use the default so every implementation splits identically. + */ + chunkSize?: number; } export class VaultClient { @@ -77,6 +117,7 @@ export class VaultClient { private readonly crypto: CryptoProvider, private readonly keys: VaultKeys, private readonly transport: VaultTransport, + private readonly options: VaultClientOptions = {}, ) {} get vaultId(): string { @@ -104,54 +145,122 @@ export class VaultClient { * `at` is passed in rather than read from the clock so a caller can make a * commit reproducible in tests, and so a queued backup records when it was * *taken* rather than when it finally reached the relay. + * + * When nothing differs from the head — same paths, same modes, every file + * reused — and no `message` asks for a version anyway, nothing is + * committed. Pushes run on every workspace change, and a version per + * trigger that changed nothing would grow the log for nothing. */ - async push(files: VaultFile[], at: number, message?: string): Promise { - const { head } = await this.transport.log(this.keys.vaultId, 1); + async push( + files: VaultFile[], + at: number, + message?: string, + opts: PushOptions = {}, + ): Promise { + const { head, entries: tail } = await this.transport.log(this.keys.vaultId, 1); + const headRow = tail.find((e) => e.seq === head); + + const fresh = (prior: VaultIndex | undefined): prior is VaultIndex => + prior !== undefined && prior.vaultId === this.keys.vaultId && prior.seq === head; + + // Reuse beats re-sealing: sealing is nondeterministic (fresh nonce), so + // re-sealing an untouched file would produce a new hash and a pointless + // upload every single time. + // + // With a fresh index, reuse is decided locally by plaintext hash — also + // across paths, so a renamed or copied file costs nothing either. Without + // one, read only the head manifest, and download a previous file only + // when its path and size both match (a different size cannot be the same + // content). That is the old behaviour's correctness at a fraction of its + // cost: it used to download every file of the head on every push. + let headEntries: VaultEntry[] | null = null; + const byHash = new Map(); + let byPath = new Map(); + if (fresh(opts.index)) { + headEntries = Object.values(opts.index.entries).map((e) => e.entry); + for (const e of Object.values(opts.index.entries)) byHash.set(e.sha256, e.entry); + } else if (headRow) { + // A head this client cannot read (a newer format, a corrupt manifest) + // must not block a backup; it only costs the reuse. + const manifest = await this.openRow(headRow).catch(() => null); + if (manifest) { + headEntries = manifest.entries; + byPath = new Map(manifest.entries.map((e) => [e.path, e])); + } + } const entries: VaultEntry[] = []; + const indexEntries: Record = {}; let uploaded = 0; let reused = 0; let bytesUploaded = 0; - // Reuse the previous manifest's hashes for unchanged content: sealing is - // nondeterministic (fresh nonce), so re-sealing an untouched file would - // produce a new hash and a pointless upload every single time. - const previous = head > 0 ? await this.pull().catch(() => null) : null; - const byPath = new Map(previous?.manifest.entries.map((e) => [e.path, e]) ?? []); - const priorPlain = previous?.files ?? new Map(); - for (const file of files) { - const prior = byPath.get(file.path); - const priorBytes = priorPlain.get(file.path); - if (prior && priorBytes && sameBytes(priorBytes, file.bytes)) { - entries.push({ ...prior, size: file.bytes.length }); - reused++; - continue; + const digest = toHex(sha256(file.bytes)); + let prior = byHash.get(digest); + if (!prior) { + const candidate = byPath.get(file.path); + if (candidate && candidate.size === file.bytes.length) { + const old = await this.readEntry(candidate).catch(() => null); + if (old && sameBytes(old, file.bytes)) prior = candidate; + } } - const sealed = await sealObject( - this.crypto, - this.keys.contentKey, - this.keys.vaultId, - file.bytes, - ); - if (!(await this.transport.has(this.keys.vaultId, sealed.hash))) { - await this.transport.put( - this.keys.vaultId, - sealed.hash, - await this.sign({ data: toBase64(sealed.bytes) }), - ); - uploaded++; - bytesUploaded += sealed.bytes.length; - } else { + let entry: VaultEntry; + if (prior) { + entry = { ...prior, path: file.path, size: file.bytes.length }; reused++; + } else { + const sealed = await sealEntry( + this.crypto, + this.keys.contentKey, + this.keys.vaultId, + file.bytes, + this.options.chunkSize === undefined ? {} : { chunkSize: this.options.chunkSize }, + ); + // No have-check first: every object here was just sealed under a + // fresh nonce, so its name is new by construction, and asking would + // only add a round trip per part. + for (const obj of sealed.objects) { + await this.transport.put( + this.keys.vaultId, + obj.hash, + await this.sign({ data: toBase64(obj.bytes) }), + ); + uploaded++; + bytesUploaded += obj.bytes.length; + } + entry = { path: file.path, ...sealed.locator, size: file.bytes.length }; + // A second copy later in this same push reuses what was just sealed. + byHash.set(digest, entry); } - const entry: VaultEntry = { path: file.path, hash: sealed.hash, size: file.bytes.length }; + // The mode is metadata of this push, not of the content: a reused entry + // takes the new one, and loses the old one if the file has none now. + delete entry.mode; if (file.mode !== undefined) entry.mode = file.mode; + entries.push(entry); + indexEntries[file.path] = { sha256: digest, entry }; } - const manifest: VaultManifest = { version: 1, seq: head + 1, at, entries }; + if ( + message === undefined && + headRow && + headEntries && + uploaded === 0 && + sameEntries(headEntries, entries) + ) { + return { + seq: head, + uploaded: 0, + reused, + bytesUploaded: 0, + unchanged: true, + index: { vaultId: this.keys.vaultId, seq: head, entries: indexEntries }, + }; + } + + const manifest: VaultManifest = { version: 2, seq: head + 1, at, entries }; if (message !== undefined) manifest.message = message; const sealedManifest = await sealManifest( @@ -166,58 +275,142 @@ export class VaultClient { await this.sign({ data: toBase64(sealedManifest.bytes) }), ); + // Every part, not just each entry's `hash`: the relay checks these exist + // before publishing the version, and records them as what it references — + // a part missing here would be fair game for the next prune. + const hashes = [...new Set(entries.flatMap((e) => entryObjectHashes(e)))]; const { seq } = await this.transport.commit( this.keys.vaultId, await this.sign({ manifest: sealedManifest.hash, seq: manifest.seq, at, - hashes: entries.map((e) => e.hash), + hashes, }), ); - return { seq, uploaded, reused, bytesUploaded }; + return { + seq, + uploaded, + reused, + bytesUploaded, + unchanged: false, + index: { vaultId: this.keys.vaultId, seq, entries: indexEntries }, + }; } /** - * Fetch a version and decrypt it. Defaults to the newest. + * Fetch and open just a version's manifest. Defaults to the newest. * - * Restoring is the whole point of the exercise, so this returns the plain - * files rather than a handle: a caller that has to make a second round of - * decisions to get their data back does not have a backup. + * The cheap way to answer "what is in the backup?" — a file browser lists a + * thousand-file workspace with one download, then `readEntry`s what the + * user actually opens. */ - async pull(seq?: number): Promise<{ manifest: VaultManifest; files: Map }> { - const log = await this.transport.log(this.keys.vaultId); + async manifest(seq?: number): Promise { + // The head needs only the newest row; an older version needs the log to + // find its row, since `limit` counts back from the head. + const log = await this.transport.log(this.keys.vaultId, seq === undefined ? 1 : undefined); const wanted = seq ?? log.head; const row = log.entries.find((e) => e.seq === wanted); if (!row) throw new Error(`vault has no version ${wanted}`); + return this.openRow(row); + } - const manifestBytes = await this.transport.get(this.keys.vaultId, row.manifest); - const manifest = await openManifest( - this.crypto, - this.keys.contentKey, - this.keys.vaultId, - row.manifest, - manifestBytes, - ); - - const files = new Map(); - for (const entry of manifest.entries) { - const bytes = await this.transport.get(this.keys.vaultId, entry.hash); - files.set( - entry.path, - await openObject(this.crypto, this.keys.contentKey, this.keys.vaultId, entry.hash, bytes), - ); + /** Fetch, verify, decrypt and reassemble one file of a manifest. */ + async readEntry(entry: VaultEntry): Promise { + const objects: Uint8Array[] = []; + for (const hash of entryObjectHashes(entry)) { + objects.push(await this.transport.get(this.keys.vaultId, hash)); } + return openEntryBytes(this.crypto, this.keys.contentKey, this.keys.vaultId, entry, objects); + } + + /** + * Fetch a version and decrypt all of it. Defaults to the newest. + * + * Restoring is the whole point of the exercise, so this returns the plain + * files rather than a handle: a caller that has to make a second round of + * decisions to get their data back does not have a backup. Callers that do + * want to choose use `manifest` + `readEntry`, which this is built from. + */ + async pull(seq?: number): Promise<{ manifest: VaultManifest; files: Map }> { + const manifest = await this.manifest(seq); + const files = new Map(); + for (const entry of manifest.entries) files.set(entry.path, await this.readEntry(entry)); return { manifest, files }; } + /** + * Drop every version not in `keep`, and let the relay delete the objects + * only those versions used. `keep` must include the current head; the + * relay refuses with SEQ_CONFLICT otherwise, which is also what a + * keep-list computed before another device's commit runs into. + */ + async prune(keep: number[]): Promise { + const res = await this.transport.prune(this.keys.vaultId, await this.sign({ keep })); + return { + removedVersions: res.removedVersions, + removedObjects: res.removedObjects, + freedBytes: res.freedBytes, + }; + } + + private async openRow(row: VaultLogEntry): Promise { + const bytes = await this.transport.get(this.keys.vaultId, row.manifest); + return openManifest(this.crypto, this.keys.contentKey, this.keys.vaultId, row.manifest, bytes); + } + /** Version history, newest last. */ async history(limit?: number): Promise { return this.transport.log(this.keys.vaultId, limit); } } +/** + * Build the index for a version you already hold in plaintext — after a + * restore, say, so the first push from a fresh device needs no download. + */ +export function vaultIndexFrom( + vaultId: string, + manifest: VaultManifest, + files: Map, +): VaultIndex { + const entries: Record = {}; + for (const entry of manifest.entries) { + const bytes = files.get(entry.path); + if (bytes) entries[entry.path] = { sha256: toHex(sha256(bytes)), entry }; + } + return { vaultId, seq: manifest.seq, entries }; +} + +/** + * Would committing `next` publish the same collection as `head`? + * + * Compared as a set by path, field by field, rather than by JSON: order of + * files is not meaningful, and a reader's view of an entry is exactly these + * fields. + */ +function sameEntries(head: VaultEntry[], next: VaultEntry[]): boolean { + if (head.length !== next.length) return false; + const byPath = new Map(head.map((e) => [e.path, e])); + if (byPath.size !== head.length) return false; + for (const e of next) { + const h = byPath.get(e.path); + if ( + !h || + h.hash !== e.hash || + h.size !== e.size || + h.mode !== e.mode || + h.enc !== e.enc || + (h.parts ?? []).join(',') !== (e.parts ?? []).join(',') + ) { + return false; + } + byPath.delete(e.path); + } + return byPath.size === 0; +} + function sameBytes(a: Uint8Array, b: Uint8Array): boolean { if (a.length !== b.length) return false; for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false; diff --git a/packages/shade-vault/src/crypto.ts b/packages/shade-vault/src/crypto.ts index aca5385..08dd35f 100644 --- a/packages/shade-vault/src/crypto.ts +++ b/packages/shade-vault/src/crypto.ts @@ -16,9 +16,34 @@ import { sha256 } from '@noble/hashes/sha2.js'; import type { CryptoProvider } from '@shade/core'; -import type { VaultManifest } from './types.js'; +import type { VaultEntry, VaultEntryEncoding, VaultManifest } from './types.js'; const NONCE_LEN = 12; +const TAG_LEN = 16; + +/** + * Largest stored (post-compression) slice sealed as one object: 4 MiB. + * + * The relay's per-object ceiling defaults to 8 MiB, and a file used to be + * exactly one object — so a 9 MB PDF simply could not be backed up. Splitting + * at 4 MiB leaves headroom under that ceiling for the nonce and tag, keeps a + * single upload short enough to retry cheaply on a phone, and is part of the + * wire contract: a Kotlin writer must split at the same boundary, or the two + * would produce manifests the other cannot reproduce in a vector test. + */ +export const VAULT_CHUNK_SIZE = 4 * 1024 * 1024; + +/** + * Ceiling on an inflated manifest, as a defence against a decompression bomb. + * + * Every manifest is sealed under our own key, so a bomb could only come from + * a device that already holds that key — but an accident (a corrupted write, + * a buggy port) should fail with a message, not by exhausting memory. + */ +const MAX_MANIFEST_BYTES = 256 * 1024 * 1024; + +/** ASCII "SVM2" — the prefix that marks a compressed v2 manifest. */ +const MANIFEST_V2_MAGIC = new Uint8Array([0x53, 0x56, 0x4d, 0x32]); /** Lowercase hex SHA-256 — the name of an object. */ export function objectHash(sealed: Uint8Array): string { @@ -36,7 +61,7 @@ export function objectHash(sealed: Uint8Array): string { * being sealed, so it cannot be known before sealing, and the relay's own * hash check already covers substitution. */ -function objectAad(vaultId: string): Uint8Array { +export function vaultObjectAad(vaultId: string): Uint8Array { return new TextEncoder().encode(`shade-vault-object-v1|${vaultId}`); } @@ -55,7 +80,7 @@ export async function sealObject( const { ciphertext, nonce } = await crypto.aesGcmEncrypt( contentKey, plaintext, - objectAad(vaultId), + vaultObjectAad(vaultId), ); const bytes = new Uint8Array(NONCE_LEN + ciphertext.length); bytes.set(nonce, 0); @@ -77,7 +102,7 @@ export async function openObject( expectedHash: string, bytes: Uint8Array, ): Promise { - if (bytes.length < NONCE_LEN + 16) { + if (bytes.length < NONCE_LEN + TAG_LEN) { throw new Error('vault object too short to be a sealed object'); } const actual = objectHash(bytes); @@ -88,19 +113,301 @@ export async function openObject( contentKey, bytes.subarray(NONCE_LEN), bytes.subarray(0, NONCE_LEN), - objectAad(vaultId), + vaultObjectAad(vaultId), ); } -/** A manifest is stored as an ordinary object; this is the JSON step around it. */ +// ─── Compression ───────────────────────────────────────────── + +/** + * Run bytes through a (De)CompressionStream, refusing to produce more than + * `limit` bytes. + * + * The streams API rather than `node:zlib`: it is the one deflate that exists + * in browsers, Bun, Node and Deno alike, so the same client can run in a web + * app without a polyfill. It offers no level knob — it compresses at zlib's + * default, which is byte-identical to `deflateRawSync` without options and to + * `java.util.zip.Deflater(DEFAULT_COMPRESSION, nowrap = true)` on the JVM. The + * difference to level 9 on text is a percent or two; portability wins. + */ +async function pump( + bytes: Uint8Array, + stream: CompressionStream | DecompressionStream, + limit: number, +): Promise { + const writer = stream.writable.getWriter(); + // Not awaited before reading: a stream applies backpressure, so waiting for + // the write to drain before anyone reads would deadlock on large inputs. + // Its failure surfaces through the reader below, so swallowing it here only + // prevents an unhandled-rejection warning. + const written = writer + .write(bytes as unknown as Uint8Array) + .then(() => writer.close()) + .catch(() => {}); + const reader = stream.readable.getReader(); + const chunks: Uint8Array[] = []; + let total = 0; + for (;;) { + const { value, done } = await reader.read(); + if (done) break; + total += value.length; + if (total > limit) { + await reader.cancel().catch(() => {}); + throw new Error(`vault inflate exceeded ${limit} bytes`); + } + chunks.push(value); + } + await written; + return concatBytes(chunks, total); +} + +/** Raw DEFLATE (RFC 1951) — no zlib or gzip header, which a port would have to strip. */ +export async function deflateRaw(bytes: Uint8Array): Promise { + return pump(bytes, new CompressionStream('deflate-raw'), Number.MAX_SAFE_INTEGER); +} + +/** Inverse of `deflateRaw`, refusing output longer than `limit`. */ +export async function inflateRaw(bytes: Uint8Array, limit: number): Promise { + try { + return await pump(bytes, new DecompressionStream('deflate-raw'), limit); + } catch (e) { + // The streams API rejects corrupt input with an empty message in some + // runtimes, which would surface as "Error: " with nothing to go on. + const why = (e as Error)?.message || 'corrupt deflate stream'; + throw new Error(`vault inflate failed: ${why}`); + } +} + +/** + * Does this file start with the signature of a format that is already + * compressed? + * + * Purely a CPU saving: the ≤95 % rule below would reject a JPEG anyway, but + * only after deflating every byte of it. The list is part of the contract so + * that a port makes the same choices and produces the same `enc` on the same + * input — PNG, JPEG, WebP ("RIFF"…"WEBP"), MP4/MOV/HEIC ("ftyp" at offset 4), + * GIF, gzip and zip ("PK", which also covers docx/xlsx/jar/apk). + */ +export function looksCompressed(b: Uint8Array): boolean { + const at = (offset: number, sig: number[]): boolean => + b.length >= offset + sig.length && sig.every((v, i) => b[offset + i] === v); + return ( + at(0, [0x89, 0x50, 0x4e, 0x47]) || // PNG + at(0, [0xff, 0xd8, 0xff]) || // JPEG + (at(0, [0x52, 0x49, 0x46, 0x46]) && at(8, [0x57, 0x45, 0x42, 0x50])) || // RIFF....WEBP + at(4, [0x66, 0x74, 0x79, 0x70]) || // ....ftyp (MP4 family) + at(0, [0x47, 0x49, 0x46, 0x38]) || // GIF8 + at(0, [0x1f, 0x8b]) || // gzip + at(0, [0x50, 0x4b]) // PK (zip) + ); +} + +// ─── Entries ───────────────────────────────────────────────── + +/** A file's bytes as they will be stored, before sealing. */ +export interface PackedEntry { + /** Set only when the stored bytes are deflate-raw of the plaintext. */ + enc?: VaultEntryEncoding; + /** The stored bytes: the plaintext, or its deflate-raw. */ + stored: Uint8Array; + /** `stored`, split into slices of at most the chunk size. Never empty. */ + chunks: Uint8Array[]; +} + +export interface PackOptions { + /** + * Override the slice size. Internal: exists so tests and cross-language + * vectors can exercise multi-part entries without megabytes of fixture. + * Production writers must use `VAULT_CHUNK_SIZE`. + */ + chunkSize?: number; +} + +/** + * Turn a file's plaintext into the slices that get sealed — deterministic, + * and the half of the format a port has to reproduce byte for byte. + * + * Compression is kept only when it saves at least 5 %, written as the integer + * test `compressed * 20 <= plain * 19` so no implementation can disagree with + * another over floating-point rounding at the boundary. Below that, the + * reader's inflate pass costs more than the bytes it saves. + * + * Compression runs over the whole file and THEN the result is split, not per + * chunk: a reader concatenates the opened parts and inflates once. That keeps + * the dictionary spanning the whole file, and means `parts` are opaque slices + * with no framing of their own. + */ +export async function packEntry(plaintext: Uint8Array, opts: PackOptions = {}): Promise { + const chunkSize = opts.chunkSize ?? VAULT_CHUNK_SIZE; + if (!Number.isInteger(chunkSize) || chunkSize < 1) { + throw new Error(`vault chunk size must be a positive integer, got ${chunkSize}`); + } + + let stored = plaintext; + let enc: VaultEntryEncoding | undefined; + if (plaintext.length > 0 && !looksCompressed(plaintext)) { + const deflated = await deflateRaw(plaintext); + if (deflated.length * 20 <= plaintext.length * 19) { + stored = deflated; + enc = 'deflate-raw'; + } + } + + // An empty file is still one (empty) object, exactly as in v1: an entry + // always names something the relay holds, so a reader never special-cases. + const chunks: Uint8Array[] = []; + for (let i = 0; i < stored.length || chunks.length === 0; i += chunkSize) { + chunks.push(stored.subarray(i, i + chunkSize)); + } + return enc ? { enc, stored, chunks } : { stored, chunks }; +} + +/** The manifest fields that locate a file's ciphertext. */ +export interface EntryLocator { + hash: string; + parts?: string[]; + enc?: VaultEntryEncoding; +} + +/** Shape an entry's locator from its sealed parts (one part → no `parts`). */ +export function entryLocator(packed: PackedEntry, sealed: SealedObject[]): EntryLocator { + const locator: EntryLocator = { hash: sealed[0]!.hash }; + if (sealed.length > 1) locator.parts = sealed.map((o) => o.hash); + if (packed.enc) locator.enc = packed.enc; + return locator; +} + +/** Pack and seal one file: the locator for its manifest entry, and the objects to upload. */ +export async function sealEntry( + crypto: CryptoProvider, + contentKey: Uint8Array, + vaultId: string, + plaintext: Uint8Array, + opts: PackOptions = {}, +): Promise<{ locator: EntryLocator; objects: SealedObject[] }> { + const packed = await packEntry(plaintext, opts); + const objects: SealedObject[] = []; + for (const chunk of packed.chunks) { + objects.push(await sealObject(crypto, contentKey, vaultId, chunk)); + } + return { locator: entryLocator(packed, objects), objects }; +} + +/** + * Every object an entry needs, in read order. + * + * This is also what a commit's signed `hashes` must list. The relay cannot + * read manifests, so `hashes` is the only way it learns what a version + * references — for the missing-object check, and since prune, for deciding + * what is still in use. A part left out of it may be garbage-collected. + */ +export function entryObjectHashes(entry: Pick): string[] { + return entry.parts && entry.parts.length > 0 ? entry.parts : [entry.hash]; +} + +/** + * Reassemble a file from its fetched objects, in `entryObjectHashes` order: + * verify and open each part, concatenate, inflate if `enc`, check the size. + * + * Order is guarded by the manifest: `parts` sits inside the sealed manifest, + * and each fetched object must hash to the name in its slot. The size check + * covers the rest — every part authenticates on its own, so an entry whose + * part list lost or gained an element would otherwise open cleanly into a + * truncated or padded file. + */ +export async function openEntryBytes( + crypto: CryptoProvider, + contentKey: Uint8Array, + vaultId: string, + entry: VaultEntry, + objects: Uint8Array[], +): Promise { + const hashes = entryObjectHashes(entry); + if (entry.parts && entry.parts.length > 0 && entry.parts[0] !== entry.hash) { + throw new Error(`vault entry ${entry.path}: hash must equal parts[0]`); + } + if (objects.length !== hashes.length) { + throw new Error( + `vault entry ${entry.path}: expected ${hashes.length} object(s), got ${objects.length}`, + ); + } + + const opened: Uint8Array[] = []; + let storedLen = 0; + for (let i = 0; i < hashes.length; i++) { + const plain = await openObject(crypto, contentKey, vaultId, hashes[i]!, objects[i]!); + opened.push(plain); + storedLen += plain.length; + } + const stored = concatBytes(opened, storedLen); + + let plaintext: Uint8Array; + if (entry.enc === undefined) { + plaintext = stored; + } else if (entry.enc === 'deflate-raw') { + plaintext = await inflateRaw(stored, entry.size); + } else { + // Same reasoning as an unknown manifest version: guessing would hand back + // bytes that look like the file and are not. + throw new Error(`vault entry ${entry.path}: unsupported encoding ${String(entry.enc)}`); + } + + if (plaintext.length !== entry.size) { + throw new Error( + `vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.length}`, + ); + } + return plaintext; +} + +// ─── Manifests ─────────────────────────────────────────────── + +/** + * A manifest's plaintext before sealing. + * + * v1 is bare UTF-8 JSON. v2 is "SVM2" followed by deflate-raw of that JSON: + * a workspace manifest is hundreds of near-identical path/hash lines, which + * compress roughly 2:1 even though the hashes are random, and a new manifest + * object is written on every single push. The magic, rather than sniffing for + * `{`, makes the format self-describing — and a v1-only reader fails on it + * loudly at JSON.parse instead of misreading it. + * + * The version field decides the container, so the same function writes the + * v1 vectors that keep old manifests readable. + */ +export async function encodeManifest(manifest: VaultManifest): Promise { + const json = new TextEncoder().encode(JSON.stringify(manifest)); + if (manifest.version === 1) return json; + const deflated = await deflateRaw(json); + return concatBytes([MANIFEST_V2_MAGIC, deflated], MANIFEST_V2_MAGIC.length + deflated.length); +} + +/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */ +export async function decodeManifest(plain: Uint8Array): Promise { + const isV2 = + plain.length >= MANIFEST_V2_MAGIC.length && + MANIFEST_V2_MAGIC.every((v, i) => plain[i] === v); + const json = isV2 + ? await inflateRaw(plain.subarray(MANIFEST_V2_MAGIC.length), MAX_MANIFEST_BYTES) + : plain; + const parsed = JSON.parse(new TextDecoder().decode(json)) as VaultManifest; + if (parsed.version !== 1 && parsed.version !== 2) { + // Refusing beats guessing: a future manifest may mean a file the reader + // cannot represent, and silently dropping it would lose data on the next + // commit made from this client. + throw new Error(`unsupported vault manifest version: ${String(parsed.version)}`); + } + return parsed; +} + +/** A manifest is stored as an ordinary object; this is the encoding step around it. */ export async function sealManifest( crypto: CryptoProvider, contentKey: Uint8Array, vaultId: string, manifest: VaultManifest, ): Promise { - const json = new TextEncoder().encode(JSON.stringify(manifest)); - return sealObject(crypto, contentKey, vaultId, json); + return sealObject(crypto, contentKey, vaultId, await encodeManifest(manifest)); } export async function openManifest( @@ -110,15 +417,18 @@ export async function openManifest( expectedHash: string, bytes: Uint8Array, ): Promise { - const plain = await openObject(crypto, contentKey, vaultId, expectedHash, bytes); - const parsed = JSON.parse(new TextDecoder().decode(plain)) as VaultManifest; - if (parsed.version !== 1) { - // Refusing beats guessing: a future manifest may mean a file the reader - // cannot represent, and silently dropping it would lose data on the next - // commit made from this client. - throw new Error(`unsupported vault manifest version: ${parsed.version}`); + return decodeManifest(await openObject(crypto, contentKey, vaultId, expectedHash, bytes)); +} + +function concatBytes(chunks: Uint8Array[], total: number): Uint8Array { + if (chunks.length === 1 && chunks[0]!.length === total) return chunks[0]!; + const out = new Uint8Array(total); + let offset = 0; + for (const c of chunks) { + out.set(c, offset); + offset += c.length; } - return parsed; + return out; } /** Lowercase hex of arbitrary bytes — used for vaultId and pubkeys on the wire. */ diff --git a/packages/shade-vault/src/http-transport.ts b/packages/shade-vault/src/http-transport.ts index 00bfa6c..28bf5db 100644 --- a/packages/shade-vault/src/http-transport.ts +++ b/packages/shade-vault/src/http-transport.ts @@ -9,7 +9,7 @@ import { fromBase64 } from '@shade/core'; import type { VaultTransport } from './client.js'; -import type { VaultLog } from './types.js'; +import type { VaultLog, VaultPruneResult } from './types.js'; type FetchLike = (input: string, init?: RequestInit) => Promise; @@ -75,6 +75,16 @@ export class HttpVaultTransport implements VaultTransport { if (!res.ok) return this.fail(res, 'commit'); return (await res.json()) as { seq: number }; } + + async prune(vaultId: string, body: unknown): Promise { + const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/prune`), { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); + if (!res.ok) return this.fail(res, 'prune'); + return (await res.json()) as VaultPruneResult; + } } export { fromBase64 }; diff --git a/packages/shade-vault/src/index.ts b/packages/shade-vault/src/index.ts index 31df631..955b32b 100644 --- a/packages/shade-vault/src/index.ts +++ b/packages/shade-vault/src/index.ts @@ -2,5 +2,5 @@ export * from './types.js'; export * from './crypto.js'; export * from './client.js'; export { MemoryVaultStore } from './store.js'; -export type { VaultStore } from './store.js'; +export type { VaultStore, VaultPrunePlan } from './store.js'; export { HttpVaultTransport } from './http-transport.js'; diff --git a/packages/shade-vault/src/server.ts b/packages/shade-vault/src/server.ts index b4e0432..857224e 100644 --- a/packages/shade-vault/src/server.ts +++ b/packages/shade-vault/src/server.ts @@ -6,6 +6,8 @@ * HEAD /v1/vault/:vaultId/object/:hash → 200 | 404 (have-check) * PUT /v1/vault/:vaultId/object/:hash → { stored } (signed) * POST /v1/vault/:vaultId/commit → { seq } (signed) + * POST /v1/vault/:vaultId/prune → { removedVersions, removedObjects, + * freedBytes, head } (signed) * * Auth is the same TOFU-Ed25519 scheme the blob primitive uses: the first * signed write pins a pubkey for the vault, and every later write must be @@ -30,10 +32,19 @@ export interface VaultRoutesOptions { maxObjectBytes?: number; /** Whole-vault ceiling. Defaults to 512 MiB. */ maxVaultBytes?: number; + /** + * How long an uploaded-but-never-committed object survives a prune. + * Defaults to one hour — long enough for a slow phone to finish a large + * push between its first upload and its commit. + */ + pruneGraceMs?: number; } const DEFAULT_MAX_OBJECT = 8 * 1024 * 1024; const DEFAULT_MAX_VAULT = 512 * 1024 * 1024; +const DEFAULT_PRUNE_GRACE = 60 * 60 * 1000; +/** A keep-list longer than this is not a retention policy, it is a mistake. */ +const MAX_KEEP = 100_000; function fail(code: string, message: string, status: ContentfulStatusCode) { return { body: { error: { code, message } }, status }; @@ -47,6 +58,7 @@ export function createVaultRoutes( const app = new Hono(); const maxObject = options.maxObjectBytes ?? DEFAULT_MAX_OBJECT; const maxVault = options.maxVaultBytes ?? DEFAULT_MAX_VAULT; + const pruneGrace = options.pruneGraceMs ?? DEFAULT_PRUNE_GRACE; /** * Check a signed request against the vault's pinned key, pinning it on the @@ -208,19 +220,89 @@ export function createVaultRoutes( return c.json({ ...f.body, missing: missing.slice(0, 20) }, f.status); } - await store.appendLog(vaultId, { - seq: body.seq, - manifest: body.manifest, - at: typeof body.at === 'number' ? body.at : Date.now(), - bytes: await store.usage(vaultId), - }); + // The signed `hashes` plus the manifest are everything this version + // references. Recording them is what lets prune collect garbage later + // without ever reading a manifest — so a client that leaves a part out of + // `hashes` is telling the relay that part may be deleted. + const refs = [...new Set([body.manifest, ...hashes])]; + await store.appendLog( + vaultId, + { + seq: body.seq, + manifest: body.manifest, + at: typeof body.at === 'number' ? body.at : Date.now(), + bytes: await store.usage(vaultId), + }, + refs, + ); return c.json({ seq: body.seq, head: body.seq }); }); + /** + * Retention: drop versions and the objects only they used. + * + * Without this the log is append-only in the literal sense, and a vault + * pushed on every edit grows until it hits the quota and stops accepting + * backups — the failure arriving exactly when the user is relying on it. + * The client decides the policy (keep the last N, one per day, …) because + * only it can read the manifests; the relay just executes a keep-list. + */ + app.post('/v1/vault/:vaultId/prune', async (c) => { + const vaultId = c.req.param('vaultId'); + if (!ID_REGEX.test(vaultId)) { + const f = fail('BAD_REQUEST', 'vaultId must be 64 lowercase hex chars', 400); + return c.json(f.body, f.status); + } + + const body = (await c.req.json().catch(() => null)) as Record | null; + const keep = body?.keep; + if ( + !body || + !Array.isArray(keep) || + keep.length > MAX_KEEP || + !keep.every((s) => Number.isSafeInteger(s) && (s as number) >= 0) + ) { + const f = fail('BAD_REQUEST', 'expected { keep: number[], signedAt, signature }', 400); + return c.json(f.body, f.status); + } + + // Deliberately not `authorize`'s TOFU path: a prune must never be the + // write that pins an owner. On a vault nobody has written to there is + // nothing to prune, and accepting it would hand the vault to whoever + // asked first. + if (!(await store.getOwner(vaultId))) { + const f = fail('NOT_FOUND', 'no such vault', 404); + return c.json(f.body, f.status); + } + const auth = await authorize(vaultId, body); + if (!auth.ok) { + const f = fail(auth.code, auth.message, auth.status); + return c.json(f.body, f.status); + } + + const head = await store.head(vaultId); + if (!(keep as number[]).includes(head)) { + // Pruning the head would leave the vault restoring to something other + // than what was last backed up. It is also what a keep-list computed + // before another device's commit looks like — so this is a conflict the + // client resolves by re-reading, not a malformed request. A replayed + // prune hits the same wall as soon as anything has been committed. + const f = fail('SEQ_CONFLICT', `keep must include the current head ${head}`, 409); + return c.json({ ...f.body, head }, f.status); + } + + const result = await store.prune(vaultId, { + keep: keep as number[], + upTo: head, + protectSince: Date.now() - pruneGrace, + }); + return c.json({ ...result, head }); + }); + return app; } -export type { VaultStore } from './store.js'; +export type { VaultStore, VaultPrunePlan } from './store.js'; export { MemoryVaultStore } from './store.js'; export type { VaultManifest }; diff --git a/packages/shade-vault/src/store.ts b/packages/shade-vault/src/store.ts index ed36f87..254e212 100644 --- a/packages/shade-vault/src/store.ts +++ b/packages/shade-vault/src/store.ts @@ -6,7 +6,42 @@ * what makes a SQLite, Postgres or object-store implementation equivalent. */ -import type { VaultLogEntry } from './types.js'; +import type { VaultLogEntry, VaultPruneResult } from './types.js'; + +/** + * What the relay is asked to forget, already checked by the route. + * + * The relay cannot read a manifest, so it cannot know on its own which + * objects a version uses. It knows because every commit since prune existed + * hands the store its `refs` — the signed `hashes` plus the manifest object — + * and that list is what garbage collection is computed from. + * + * **Versions committed before ref tracking have no list.** Their objects are + * "pinned": every object present when such an entry was appended (or, for a + * SQLite database, when it was migrated) is treated as referenced for as long + * as any untracked entry remains in the log. Pinning is coarse — it protects + * objects the old entry may not use — but it is the only safe reading of "we + * do not know", and it is self-limiting: once the last untracked version has + * been pruned, no unknown reference set is left, the pins are dropped and + * those objects are collected like any other. + */ +export interface VaultPrunePlan { + /** Sequence numbers to keep. The route has checked that the head is among them. */ + keep: readonly number[]; + /** + * Only entries with `seq <= upTo` may be removed — the head the route saw. + * A commit that lands between that check and the prune is newer, and must + * survive even though it is not in `keep`. + */ + upTo: number; + /** + * Epoch millis. An object no version has ever referenced, stored after + * this, is left alone: it is most likely an upload whose commit is still + * on its way, and deleting it would fail that push with MISSING_OBJECTS. + * Objects that a removed version referenced get no such grace. + */ + protectSince: number; +} export interface VaultStore { /** Ed25519 pubkey pinned on first write (TOFU), or null for a fresh vault. */ @@ -21,7 +56,19 @@ export interface VaultStore { head(vaultId: string): Promise; /** Newest last. `limit` counts back from the head. */ log(vaultId: string, limit?: number): Promise; - appendLog(vaultId: string, entry: VaultLogEntry): Promise; + /** + * Append a version. `refs` is every object hash it references, manifest + * included; the routes always pass it. Omitting it records the entry as + * untracked, with the pinning described on `VaultPrunePlan` — that is how + * entries from before ref tracking behave, and how tests simulate them. + */ + appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise; + + /** + * Remove log entries and garbage-collect the objects nothing left uses. + * Must be atomic with respect to other writes to the same vault. + */ + prune(vaultId: string, plan: VaultPrunePlan): Promise; /** Total stored bytes, for quota decisions. */ usage(vaultId: string): Promise; @@ -36,6 +83,12 @@ export class MemoryVaultStore implements VaultStore { private owners = new Map(); private objects = new Map>(); private logs = new Map(); + /** Per vault: seq → referenced hashes, or null for an untracked entry. */ + private refs = new Map | null>>(); + /** Per vault: objects an untracked entry may reference. */ + private pinned = new Map>(); + /** Per vault: when each object was first stored, for the prune grace. */ + private storedAt = new Map>(); async getOwner(vaultId: string): Promise { return this.owners.get(vaultId) ?? null; @@ -59,7 +112,15 @@ export class MemoryVaultStore implements VaultStore { } async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise { - this.bucket(vaultId).set(hash, bytes); + const bucket = this.bucket(vaultId); + if (bucket.has(hash)) return; + bucket.set(hash, bytes); + let times = this.storedAt.get(vaultId); + if (!times) { + times = new Map(); + this.storedAt.set(vaultId, times); + } + times.set(hash, Date.now()); } async getObject(vaultId: string, hash: string): Promise { @@ -76,10 +137,76 @@ export class MemoryVaultStore implements VaultStore { return limit === undefined ? [...l] : l.slice(Math.max(0, l.length - limit)); } - async appendLog(vaultId: string, entry: VaultLogEntry): Promise { + async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise { const l = this.logs.get(vaultId) ?? []; + if (l.some((e) => e.seq === entry.seq)) { + // Mirrors the SQLite primary key: two rows with one seq would make + // history ambiguous, and prune would not know which refs to drop. + throw new Error(`vault ${vaultId} already has seq ${entry.seq}`); + } l.push(entry); this.logs.set(vaultId, l); + + let byseq = this.refs.get(vaultId); + if (!byseq) { + byseq = new Map(); + this.refs.set(vaultId, byseq); + } + if (refs) { + byseq.set(entry.seq, new Set(refs)); + } else { + // An untracked entry can only reference what was here when it was + // committed — so pin exactly that. + byseq.set(entry.seq, null); + const pins = this.pinned.get(vaultId) ?? new Set(); + for (const h of this.bucket(vaultId).keys()) pins.add(h); + this.pinned.set(vaultId, pins); + } + } + + async prune(vaultId: string, plan: VaultPrunePlan): Promise { + // No await anywhere below: the whole prune runs in one turn of the event + // loop, which is what makes it atomic against a concurrent commit. + const keep = new Set(plan.keep); + const log = this.logs.get(vaultId) ?? []; + const byseq = this.refs.get(vaultId) ?? new Map | null>(); + const bucket = this.bucket(vaultId); + const times = this.storedAt.get(vaultId) ?? new Map(); + + const removed = log.filter((e) => e.seq <= plan.upTo && !keep.has(e.seq)); + const remaining = log.filter((e) => !(e.seq <= plan.upTo && !keep.has(e.seq))); + + const everReferenced = new Set(); + for (const e of log) { + everReferenced.add(e.manifest); + for (const h of byseq.get(e.seq) ?? []) everReferenced.add(h); + } + + const inUse = new Set(); + let untrackedRemains = false; + for (const e of remaining) { + inUse.add(e.manifest); + const r = byseq.get(e.seq); + if (r === undefined || r === null) untrackedRemains = true; + else for (const h of r) inUse.add(h); + } + if (!untrackedRemains) this.pinned.delete(vaultId); + const pins = this.pinned.get(vaultId) ?? new Set(); + + let removedObjects = 0; + let freedBytes = 0; + for (const [hash, bytes] of [...bucket]) { + if (inUse.has(hash) || pins.has(hash)) continue; + if (!everReferenced.has(hash) && (times.get(hash) ?? 0) > plan.protectSince) continue; + bucket.delete(hash); + times.delete(hash); + removedObjects++; + freedBytes += bytes.length; + } + + for (const e of removed) byseq.delete(e.seq); + this.logs.set(vaultId, remaining); + return { removedVersions: removed.length, removedObjects, freedBytes }; } async usage(vaultId: string): Promise { diff --git a/packages/shade-vault/src/testing.ts b/packages/shade-vault/src/testing.ts new file mode 100644 index 0000000..86c183e --- /dev/null +++ b/packages/shade-vault/src/testing.ts @@ -0,0 +1,77 @@ +/** + * Deterministic sealing, for cross-language test vectors only. + * + * Production sealing takes its nonce from the `CryptoProvider`, which is the + * point: a nonce reused under one content key breaks AES-GCM outright. A + * vector, though, has to pin every byte so a Kotlin port can reproduce the + * same wire bytes — so this takes the nonce from the caller. + * + * Lives behind its own export (`@shade/vault/testing`) and is not re-exported + * from the package root, so it cannot be picked up by accident from an + * autocomplete list next to `sealObject`. + */ + +import { + entryLocator, + objectHash, + packEntry, + vaultObjectAad, + type EntryLocator, + type PackOptions, + type PackedEntry, + type SealedObject, +} from './crypto.js'; + +const NONCE_LEN = 12; + +/** `sealObject` with a caller-chosen nonce. Never use outside vectors and tests. */ +export async function sealObjectWithNonce( + contentKey: Uint8Array, + vaultId: string, + plaintext: Uint8Array, + nonce: Uint8Array, +): Promise { + if (nonce.length !== NONCE_LEN) throw new Error(`nonce must be ${NONCE_LEN} bytes`); + const subtle = globalThis.crypto.subtle; + const key = await subtle.importKey( + 'raw', + contentKey as unknown as ArrayBuffer, + 'AES-GCM', + false, + ['encrypt'], + ); + const ct = new Uint8Array( + await subtle.encrypt( + { + name: 'AES-GCM', + iv: nonce as unknown as ArrayBuffer, + additionalData: vaultObjectAad(vaultId) as unknown as ArrayBuffer, + }, + key, + plaintext as unknown as ArrayBuffer, + ), + ); + const bytes = new Uint8Array(NONCE_LEN + ct.length); + bytes.set(nonce, 0); + bytes.set(ct, NONCE_LEN); + return { hash: objectHash(bytes), bytes }; +} + +/** + * `sealEntry` with one caller-chosen nonce per part — the same `packEntry` + * the real writer uses, so a vector pins the production format, not a copy. + */ +export async function sealEntryWithNonces( + contentKey: Uint8Array, + vaultId: string, + plaintext: Uint8Array, + nonceFor: (partIndex: number) => Uint8Array, + opts: PackOptions = {}, +): Promise<{ packed: PackedEntry; locator: EntryLocator; objects: SealedObject[] }> { + const packed = await packEntry(plaintext, opts); + const objects: SealedObject[] = []; + for (let i = 0; i < packed.chunks.length; i++) { + objects.push(await sealObjectWithNonce(contentKey, vaultId, packed.chunks[i]!, nonceFor(i))); + } + return { packed, locator: entryLocator(packed, objects), objects }; +} diff --git a/packages/shade-vault/src/types.ts b/packages/shade-vault/src/types.ts index cf5c924..9e77efe 100644 --- a/packages/shade-vault/src/types.ts +++ b/packages/shade-vault/src/types.ts @@ -22,22 +22,50 @@ * of that, which is the versioning half of the requirement. */ -/** One file in a manifest. `hash` names the ciphertext object. */ +/** + * How an entry's stored bytes relate to its plaintext. Absent means stored + * as-is; `deflate-raw` means RFC 1951 raw DEFLATE (no zlib/gzip header). + */ +export type VaultEntryEncoding = 'deflate-raw'; + +/** + * One file in a manifest. `hash` names the ciphertext object. + * + * v2 adds two optional fields, and an entry without them is exactly a v1 + * entry — so a v2 reader needs no separate path for old manifests: + * + * - `enc`: the stored bytes are compressed. Set only when that saved at least + * 5 %, so a reader can never assume it. + * - `parts`: the stored bytes were split into several objects (files larger + * than one 4 MiB chunk). Listed in order; `hash` is then `parts[0]`, which + * keeps "`hash` names an object the relay holds" true for every entry. + */ export interface VaultEntry { /** Path within the collection, as the app understands it. */ path: string; - /** Lowercase hex SHA-256 of the ciphertext object. */ + /** Lowercase hex SHA-256 of the (first) ciphertext object. */ hash: string; - /** Plaintext byte length, for progress reporting and sanity checks. */ + /** + * PLAINTEXT byte length — before compression, whatever `enc` says. Readers + * check the reassembled file against it. + */ size: number; /** Optional app-defined mode/metadata, opaque to the vault. */ mode?: string; + /** Present only when the stored bytes are compressed. */ + enc?: VaultEntryEncoding; + /** Present only when there is more than one object; `parts[0] === hash`. */ + parts?: string[]; } /** The full contents of a collection at one point in time. */ export interface VaultManifest { - /** Schema version — a client that does not know it must refuse, not guess. */ - version: 1; + /** + * Schema version — a client that does not know it must refuse, not guess. + * 1: bare JSON. 2: "SVM2" + deflate-raw(JSON), entries may carry `enc` and + * `parts`. Writers emit 2; readers accept both. + */ + version: 1 | 2; /** Monotonic, assigned by the client and checked by the relay. */ seq: number; /** Epoch millis when the commit was made. */ @@ -64,6 +92,48 @@ export interface VaultLog { head: number; } +/** + * What the client remembers about its own last push, so the next one can skip + * re-reading the relay. + * + * Without it, deciding "is this file unchanged?" means downloading and + * decrypting the previous version of it — on a push that runs after every + * edit, that is the whole workspace pulled down to upload three lines. With + * it, an unchanged file is recognised by its plaintext SHA-256 and reuses the + * entry (and objects) it already has, with no network at all. + * + * Only trusted when `vaultId` matches and `seq` is still the relay's head: + * after another device commits, the entries no longer describe the head, and + * the push falls back to reading it. Plain JSON on purpose — callers persist + * it to disk next to the files it describes. + * + * It holds plaintext hashes of the user's files, so store it where the files + * themselves live, never on the relay. + */ +export interface VaultIndex { + vaultId: string; + /** The version these entries describe. */ + seq: number; + /** Keyed by path. */ + entries: Record; +} + +export interface VaultIndexEntry { + /** Lowercase hex SHA-256 of the file's plaintext. */ + sha256: string; + entry: VaultEntry; +} + +/** What `POST /v1/vault/:id/prune` returns. */ +export interface VaultPruneResult { + /** Log entries removed. */ + removedVersions: number; + /** Objects deleted because no remaining version references them. */ + removedObjects: number; + /** Bytes those objects occupied. */ + freedBytes: number; +} + /** * Error codes clients branch on. * diff --git a/packages/shade-vault/tests/vault-v2.test.ts b/packages/shade-vault/tests/vault-v2.test.ts new file mode 100644 index 0000000..5741d62 --- /dev/null +++ b/packages/shade-vault/tests/vault-v2.test.ts @@ -0,0 +1,662 @@ +/** + * Vault v2: compression, multi-part entries, the compressed manifest, the + * local index, lazy reads and prune. + * + * Same rule as vault.test.ts: the client talks to the REAL route handlers. + * The counting transport only wraps the HTTP one, so "this push downloaded + * nothing" is measured on the actual wire calls, not on a mock's opinion. + */ +import { describe, test, expect } from 'bun:test'; +import { SubtleCryptoProvider } from '@shade/crypto-web'; +import { signPayload } from '@shade/server'; +import { toBase64 } from '@shade/core'; +import { createVaultRoutes, type VaultRoutesOptions } from '../src/server.js'; +import { MemoryVaultStore } from '../src/store.js'; +import type { VaultStore } from '../src/store.js'; +import { HttpVaultTransport } from '../src/http-transport.js'; +import { VaultClient, deriveVaultKeys, vaultIndexFrom } from '../src/client.js'; +import type { VaultKeys, VaultTransport } from '../src/client.js'; +import { + VAULT_CHUNK_SIZE, + decodeManifest, + entryObjectHashes, + openEntryBytes, + openObject, + packEntry, + sealManifest, + sealObject, +} from '../src/crypto.js'; +import type { VaultLog, VaultManifest, VaultPruneResult } from '../src/types.js'; + +const crypto = new SubtleCryptoProvider(); +const AT = 1_786_600_000_000; + +function enc(s: string): Uint8Array { + return new TextEncoder().encode(s); +} +function dec(b: Uint8Array): string { + return new TextDecoder().decode(b); +} +function random(n: number): Uint8Array { + const out = new Uint8Array(n); + // getRandomValues caps at 64 KiB per call. + for (let i = 0; i < n; i += 65_536) globalThis.crypto.getRandomValues(out.subarray(i, i + 65_536)); + return out; +} + +/** Wraps the real HTTP transport and counts every call by kind. */ +class CountingTransport implements VaultTransport { + counts = { has: 0, put: 0, get: 0, log: 0, commit: 0, prune: 0 }; + constructor(private readonly inner: VaultTransport) {} + reset() { + for (const k of Object.keys(this.counts) as Array) this.counts[k] = 0; + } + has(v: string, h: string) { + this.counts.has++; + return this.inner.has(v, h); + } + put(v: string, h: string, b: unknown) { + this.counts.put++; + return this.inner.put(v, h, b); + } + get(v: string, h: string) { + this.counts.get++; + return this.inner.get(v, h); + } + log(v: string, l?: number): Promise { + this.counts.log++; + return this.inner.log(v, l); + } + commit(v: string, b: unknown) { + this.counts.commit++; + return this.inner.commit(v, b); + } + prune(v: string, b: unknown): Promise { + this.counts.prune++; + return this.inner.prune(v, b); + } +} + +async function harness( + opts: { + store?: VaultStore; + master?: Uint8Array; + chunkSize?: number; + routes?: VaultRoutesOptions; + } = {}, +) { + const store = opts.store ?? new MemoryVaultStore(); + const routes = createVaultRoutes(store, crypto, opts.routes ?? {}); + const fetchImpl = (input: string, init?: RequestInit) => routes.fetch(new Request(input, init)); + const transport = new CountingTransport(new HttpVaultTransport('http://vault.test', fetchImpl)); + const keys = await deriveVaultKeys(opts.master ?? new Uint8Array(32).fill(7), 'scaffold'); + const client = new VaultClient( + crypto, + keys, + transport, + opts.chunkSize === undefined ? {} : { chunkSize: opts.chunkSize }, + ); + /** A second device: same credentials, its own transport and no index. */ + const device = () => + new VaultClient(crypto, keys, new HttpVaultTransport('http://vault.test', fetchImpl)); + return { store, routes, transport, keys, client, device }; +} + +/** + * Write a version exactly as a pre-v2 relay and client did: a bare-JSON v1 + * manifest, one object per file, and a log row with no recorded refs. + */ +async function legacyPush( + store: VaultStore, + keys: VaultKeys, + seq: number, + files: Array<{ path: string; bytes: Uint8Array }>, +): Promise<{ manifest: string; objects: string[] }> { + if (!(await store.getOwner(keys.vaultId))) await store.setOwner(keys.vaultId, keys.publicKey); + const entries = []; + const objects: string[] = []; + for (const f of files) { + const o = await sealObject(crypto, keys.contentKey, keys.vaultId, f.bytes); + await store.putObject(keys.vaultId, o.hash, o.bytes); + objects.push(o.hash); + entries.push({ path: f.path, hash: o.hash, size: f.bytes.length }); + } + const manifest: VaultManifest = { version: 1, seq, at: AT, entries }; + const m = await sealManifest(crypto, keys.contentKey, keys.vaultId, manifest); + await store.putObject(keys.vaultId, m.hash, m.bytes); + await store.appendLog(keys.vaultId, { + seq, + manifest: m.hash, + at: AT, + bytes: await store.usage(keys.vaultId), + }); + return { manifest: m.hash, objects }; +} + +async function signedPost( + routes: { fetch: (r: Request) => Response | Promise }, + path: string, + seed: Uint8Array, + publicKey: Uint8Array, + body: Record, +) { + const signed = await signPayload(crypto, seed, { ...body, publicKey: toBase64(publicKey) }); + return routes.fetch( + new Request(`http://v${path}`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(signed), + }), + ); +} + +describe('entry packing', () => { + test('compressible text is stored deflated, and size stays the plaintext length', async () => { + const text = enc('## Nå\n- [ ] noe å gjøre\n'.repeat(200)); + const packed = await packEntry(text); + expect(packed.enc).toBe('deflate-raw'); + expect(packed.stored.length).toBeLessThan(text.length / 10); + expect(packed.chunks.length).toBe(1); + + const { client } = await harness(); + await client.push([{ path: 'plan.md', bytes: text }], AT); + const manifest = await client.manifest(); + expect(manifest.entries[0]!.enc).toBe('deflate-raw'); + expect(manifest.entries[0]!.size).toBe(text.length); + expect(dec(await client.readEntry(manifest.entries[0]!))).toBe(dec(text)); + }); + + test('incompressible bytes are stored as-is', async () => { + const packed = await packEntry(random(10_000)); + expect(packed.enc).toBeUndefined(); + }); + + test('known compressed formats are not even tried', async () => { + // Highly compressible body, but a PNG/zip/MP4 signature in front: the + // magic wins, which is what saves the CPU on a photo library. + const body = new Uint8Array(5000); + const png = new Uint8Array([0x89, 0x50, 0x4e, 0x47, ...body]); + const zip = new Uint8Array([0x50, 0x4b, 0x03, 0x04, ...body]); + const mp4 = new Uint8Array([0, 0, 0, 0x20, 0x66, 0x74, 0x79, 0x70, ...body]); + const webp = new Uint8Array([...enc('RIFF'), 0, 0, 0, 0, ...enc('WEBP'), ...body]); + for (const b of [png, zip, mp4, webp]) expect((await packEntry(b)).enc).toBeUndefined(); + expect((await packEntry(new Uint8Array([0x00, ...body]))).enc).toBe('deflate-raw'); + }); + + test('an empty file is one empty object, as in v1', async () => { + const packed = await packEntry(new Uint8Array(0)); + expect(packed.enc).toBeUndefined(); + expect(packed.chunks.length).toBe(1); + expect(packed.chunks[0]!.length).toBe(0); + + const { client } = await harness(); + await client.push([{ path: 'tom.txt', bytes: new Uint8Array(0) }], AT); + expect((await client.pull()).files.get('tom.txt')!.length).toBe(0); + }); +}); + +describe('multi-part entries', () => { + test('a file larger than the chunk size is split, and every part is committed', async () => { + const { client, store, keys } = await harness({ chunkSize: 1024 }); + const big = random(5000); // incompressible → 5 parts of ≤ 1024 + const res = await client.push([{ path: 'stor.bin', bytes: big }], AT); + expect(res.uploaded).toBe(5); + + const entry = (await client.manifest()).entries[0]!; + expect(entry.parts!.length).toBe(5); + expect(entry.hash).toBe(entry.parts![0]!); + expect(entry.size).toBe(5000); + expect(await client.readEntry(entry)).toEqual(big); + + // Every part was recorded as referenced: a prune with nothing to drop + // must not collect any of them. + const pruned = await client.prune([1]); + expect(pruned.removedObjects).toBe(0); + for (const h of entry.parts!) expect(await store.hasObject(keys.vaultId, h)).toBe(true); + }); + + test('compression runs before splitting, and parts reassemble before inflating', async () => { + const { client } = await harness({ chunkSize: 64 }); + const text = enc(Array.from({ length: 300 }, (_, i) => `linje ${i * 7919}\n`).join('')); + await client.push([{ path: 'logg.md', bytes: text }], AT); + const entry = (await client.manifest()).entries[0]!; + expect(entry.enc).toBe('deflate-raw'); + expect(entry.parts!.length).toBeGreaterThan(1); + expect(dec(await client.readEntry(entry))).toBe(dec(text)); + }); + + test('a dropped part, a part under the wrong name, or a bad hash field is refused', async () => { + const { client, keys, transport } = await harness({ chunkSize: 1024 }); + await client.push([{ path: 'x.bin', bytes: random(3000) }], AT); + const entry = (await client.manifest()).entries[0]!; + const objects = await Promise.all( + entryObjectHashes(entry).map((h) => transport.get(keys.vaultId, h)), + ); + + // Each remaining part authenticates on its own; only the size check + // notices the file is short. + const truncated = { ...entry, parts: entry.parts!.slice(0, 2) }; + await expect( + openEntryBytes(crypto, keys.contentKey, keys.vaultId, truncated, objects.slice(0, 2)), + ).rejects.toThrow(/size mismatch/); + + // Bytes handed back out of order fail on their names. + await expect( + openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, [ + objects[0]!, + objects[2]!, + objects[1]!, + ]), + ).rejects.toThrow(/hash mismatch/); + + const misnamed = { ...entry, hash: entry.parts![1]! }; + await expect( + openEntryBytes(crypto, keys.contentKey, keys.vaultId, misnamed, objects), + ).rejects.toThrow(/parts\[0\]/); + }); + + test('a file over the real 4 MiB chunk fits under the relay object ceiling', async () => { + // The point of parts: before v2, one file was one object, and anything + // over 8 MiB could not be backed up at all. + const { client } = await harness(); + const big = random(9 * 1024 * 1024); + const res = await client.push([{ path: 'video.mov', bytes: big }], AT); + expect(res.uploaded).toBe(3); + const entry = (await client.manifest()).entries[0]!; + expect(entry.parts!.length).toBe(Math.ceil(big.length / VAULT_CHUNK_SIZE)); + expect(await client.readEntry(entry)).toEqual(big); + }); +}); + +describe('manifest v2', () => { + test('push writes a compressed v2 manifest', async () => { + const { client, store, keys } = await harness(); + await client.push([{ path: 'a.md', bytes: enc('A') }], AT, 'første'); + const row = (await store.log(keys.vaultId))[0]!; + const plain = await openObject( + crypto, + keys.contentKey, + keys.vaultId, + row.manifest, + (await store.getObject(keys.vaultId, row.manifest))!, + ); + expect(dec(plain.subarray(0, 4))).toBe('SVM2'); + const manifest = await decodeManifest(plain); + expect(manifest.version).toBe(2); + expect(manifest.message).toBe('første'); + }); + + test('a v1 vault written by the old client is still readable, and pushable on top', async () => { + const { client, store, keys } = await harness(); + await legacyPush(store, keys, 1, [ + { path: 'gammel.md', bytes: enc('fra v1') }, + { path: 'annen.md', bytes: enc('også v1') }, + ]); + const { manifest, files } = await client.pull(); + expect(manifest.version).toBe(1); + expect(dec(files.get('gammel.md')!)).toBe('fra v1'); + + // A v2 push reuses the v1 entries it can prove unchanged. + const res = await client.push( + [ + { path: 'gammel.md', bytes: enc('fra v1') }, + { path: 'annen.md', bytes: enc('endret') }, + ], + AT + 1, + ); + expect(res.seq).toBe(2); + expect(res.reused).toBe(1); + expect(res.uploaded).toBe(1); + expect(dec((await client.pull(1)).files.get('annen.md')!)).toBe('også v1'); + }); + + test('an unknown manifest version is refused', async () => { + await expect(decodeManifest(enc(JSON.stringify({ version: 3, entries: [] })))).rejects.toThrow( + /unsupported vault manifest version: 3/, + ); + }); +}); + +describe('the local index', () => { + const files = () => [ + { path: 'plan.md', bytes: enc('# Plan\n') }, + { path: 'stor.md', bytes: enc('x'.repeat(50_000)) }, + { path: 'run.sh', bytes: enc('#!/bin/sh\n'), mode: '755' }, + ]; + + test('an unchanged push with a fresh index touches nothing: no seal, no download, no commit', async () => { + const { client, transport } = await harness(); + const first = await client.push(files(), AT); + expect(first.unchanged).toBe(false); + + // Through JSON, as a caller persisting it to disk would. + const index = JSON.parse(JSON.stringify(first.index)); + transport.reset(); + const second = await client.push(files(), AT + 1, undefined, { index }); + expect(second).toMatchObject({ seq: 1, uploaded: 0, reused: 3, bytesUploaded: 0, unchanged: true }); + expect(transport.counts.put).toBe(0); + expect(transport.counts.get).toBe(0); + expect(transport.counts.has).toBe(0); + expect(transport.counts.commit).toBe(0); + expect(second.index).toEqual(first.index); + expect((await client.history()).head).toBe(1); + }); + + test('a changed file uploads only itself, still without downloading', async () => { + const { client, transport } = await harness(); + const { index } = await client.push(files(), AT); + transport.reset(); + const changed = files(); + changed[0] = { path: 'plan.md', bytes: enc('# Plan v2\n') }; + const res = await client.push(changed, AT + 1, undefined, { index }); + expect(res).toMatchObject({ seq: 2, uploaded: 1, reused: 2, unchanged: false }); + expect(transport.counts.get).toBe(0); + expect(transport.counts.put).toBe(2); // the file + the manifest + expect(transport.counts.commit).toBe(1); + expect(dec((await client.pull()).files.get('plan.md')!)).toBe('# Plan v2\n'); + expect(res.index.seq).toBe(2); + }); + + test('a renamed file reuses its objects', async () => { + const { client, store, keys } = await harness(); + const { index } = await client.push(files(), AT); + const before = await store.usage(keys.vaultId); + const renamed = files().map((f) => (f.path === 'stor.md' ? { ...f, path: 'arkiv/stor.md' } : f)); + const res = await client.push(renamed, AT + 1, undefined, { index }); + expect(res.uploaded).toBe(0); + expect(res.unchanged).toBe(false); // the path set changed + expect((await client.pull()).files.get('arkiv/stor.md')!.length).toBe(50_000); + // Only a new manifest was stored. + expect((await store.usage(keys.vaultId)) - before).toBeLessThan(2000); + }); + + test('a mode change alone is a new version', async () => { + const { client } = await harness(); + const { index } = await client.push(files(), AT); + const chmod = files().map((f) => (f.path === 'run.sh' ? { ...f, mode: '644' } : f)); + const res = await client.push(chmod, AT + 1, undefined, { index }); + expect(res).toMatchObject({ seq: 2, uploaded: 0, unchanged: false }); + expect((await client.manifest()).entries.find((e) => e.path === 'run.sh')!.mode).toBe('644'); + }); + + test('a deleted file is a new version', async () => { + const { client } = await harness(); + const { index } = await client.push(files(), AT); + const res = await client.push(files().slice(0, 2), AT + 1, undefined, { index }); + expect(res).toMatchObject({ seq: 2, unchanged: false }); + }); + + test('a message forces a version even when nothing changed', async () => { + const { client, transport } = await harness(); + const { index } = await client.push(files(), AT); + transport.reset(); + const res = await client.push(files(), AT + 1, 'nattlig backup', { index }); + expect(res).toMatchObject({ seq: 2, uploaded: 0, unchanged: false }); + expect(transport.counts.commit).toBe(1); + }); + + test('an unchanged push without an index commits nothing either, reading only what it must', async () => { + const { client, transport } = await harness(); + await client.push(files(), AT); + transport.reset(); + const res = await client.push(files(), AT + 1); + expect(res).toMatchObject({ seq: 1, uploaded: 0, reused: 3, unchanged: true }); + expect(transport.counts.commit).toBe(0); + expect(transport.counts.put).toBe(0); + // The manifest, plus one download per same-path same-size candidate. + expect(transport.counts.get).toBe(1 + 3); + }); + + test('without an index, a file whose size changed is not downloaded to compare', async () => { + const { client, transport } = await harness(); + await client.push(files(), AT); + transport.reset(); + const changed = files(); + changed[1] = { path: 'stor.md', bytes: enc('y'.repeat(60_000)) }; + await client.push(changed, AT + 1); + expect(transport.counts.get).toBe(1 + 2); // manifest + the two same-size files + }); + + test('a stale index (another device committed) falls back and stays correct', async () => { + const { client, device } = await harness(); + const { index } = await client.push(files(), AT); + await device().push([{ path: 'plan.md', bytes: enc('fra telefonen') }], AT + 1); + + const res = await client.push(files(), AT + 2, undefined, { index }); + // Reverts the phone's edit and restores the other files: a real change. + expect(res).toMatchObject({ seq: 3, unchanged: false }); + const { files: back } = await client.pull(); + expect(dec(back.get('plan.md')!)).toBe('# Plan\n'); + expect(back.get('stor.md')!.length).toBe(50_000); + expect(res.index.seq).toBe(3); + }); + + test('an index for a different vault is ignored', async () => { + const { client, transport } = await harness(); + const { index } = await client.push(files(), AT); + transport.reset(); + const foreign = { ...index, vaultId: 'f'.repeat(64) }; + const res = await client.push(files(), AT + 1, undefined, { index: foreign }); + expect(res.unchanged).toBe(true); + expect(transport.counts.get).toBeGreaterThan(0); // had to read the head instead + }); + + test('vaultIndexFrom after a restore makes the first push from a fresh device free', async () => { + const { client, device, keys } = await harness(); + await client.push(files(), AT); + const phone = device(); + const { manifest, files: restored } = await phone.pull(); + const index = vaultIndexFrom(keys.vaultId, manifest, restored); + const res = await phone.push(files(), AT + 1, undefined, { index }); + expect(res).toMatchObject({ unchanged: true, uploaded: 0 }); + }); + + test('two copies of one file in a single push share their objects', async () => { + const { client } = await harness(); + const same = enc('identisk innhold '.repeat(100)); + const res = await client.push( + [ + { path: 'a.md', bytes: same }, + { path: 'kopi/a.md', bytes: same }, + ], + AT, + ); + expect(res.uploaded).toBe(1); + const { files: back } = await client.pull(); + expect(dec(back.get('kopi/a.md')!)).toBe(dec(same)); + }); +}); + +describe('lazy reads', () => { + test('manifest() fetches only the manifest; readEntry only the file asked for', async () => { + const { client, transport } = await harness({ chunkSize: 1024 }); + await client.push( + [ + { path: 'a.bin', bytes: random(3000) }, + { path: 'b.md', bytes: enc('B') }, + ], + AT, + ); + transport.reset(); + const manifest = await client.manifest(); + expect(transport.counts.get).toBe(1); + expect(manifest.entries.map((e) => e.path)).toEqual(['a.bin', 'b.md']); + + transport.reset(); + await client.readEntry(manifest.entries[1]!); + expect(transport.counts.get).toBe(1); + await client.readEntry(manifest.entries[0]!); + expect(transport.counts.get).toBe(1 + 3); + }); + + test('manifest(seq) reads an older version', async () => { + const { client } = await harness(); + await client.push([{ path: 'p', bytes: enc('1') }], AT); + await client.push([{ path: 'p', bytes: enc('2') }], AT + 1); + expect((await client.manifest(1)).seq).toBe(1); + await expect(client.manifest(7)).rejects.toThrow(/no version 7/); + }); +}); + +describe('prune', () => { + async function threeVersions(store?: VaultStore) { + const h = await harness({ ...(store ? { store } : {}), routes: { pruneGraceMs: 0 } }); + const stable = { path: 'stabil.md', bytes: enc('rører seg aldri '.repeat(500)) }; + await h.client.push([stable, { path: 'plan.md', bytes: random(3000) }], AT); + await h.client.push([stable, { path: 'plan.md', bytes: random(3000) }], AT + 1); + await h.client.push([stable, { path: 'plan.md', bytes: random(3000) }], AT + 2); + return h; + } + + test('keeps what remaining versions use and frees the rest', async () => { + const { client, store, keys } = await threeVersions(); + const before = await store.usage(keys.vaultId); + + const res = await client.prune([3]); + // Versions 1 and 2: each had its own plan.md and manifest. + expect(res.removedVersions).toBe(2); + expect(res.removedObjects).toBe(4); + expect(res.freedBytes).toBe(before - (await store.usage(keys.vaultId))); + expect(res.freedBytes).toBeGreaterThan(6000); + + const log = await client.history(); + expect(log.entries.map((e) => e.seq)).toEqual([3]); + expect(log.head).toBe(3); + // The stable file, first uploaded in version 1, survives: version 3 uses it. + const { files } = await client.pull(); + expect(dec(files.get('stabil.md')!)).toBe('rører seg aldri '.repeat(500)); + await expect(client.pull(1)).rejects.toThrow(/no version 1/); + + // And the vault keeps working after a prune. + const next = await client.push([{ path: 'ny.md', bytes: enc('etter') }], AT + 3); + expect(next.seq).toBe(4); + }); + + test('keeping an older version keeps its objects', async () => { + const { client } = await threeVersions(); + const res = await client.prune([1, 3]); + expect(res.removedVersions).toBe(1); + expect(res.removedObjects).toBe(2); + expect((await client.pull(1)).files.get('plan.md')!.length).toBe(3000); + }); + + test('is refused when the keep-list leaves out the head', async () => { + const { client, store, keys } = await threeVersions(); + await expect(client.prune([1, 2])).rejects.toThrow(/409.*SEQ_CONFLICT/); + expect((await store.log(keys.vaultId)).length).toBe(3); + }); + + test('is refused with a bad signature, or signed by another key', async () => { + const { routes, keys, store } = await threeVersions(); + const attacker = await deriveVaultKeys(new Uint8Array(32).fill(9), 'scaffold'); + const res = await signedPost( + routes, + `/v1/vault/${keys.vaultId}/prune`, + attacker.signingSeed, + attacker.publicKey, + { keep: [3] }, + ); + expect(res.status).toBe(401); + + // Correct key, tampered body after signing. + const signed = await signPayload(crypto, keys.signingSeed, { + keep: [3], + publicKey: toBase64(keys.publicKey), + }); + const tampered = await routes.fetch( + new Request(`http://v/v1/vault/${keys.vaultId}/prune`, { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ ...signed, keep: [1, 3] }), + }), + ); + expect(tampered.status).toBe(401); + expect((await store.log(keys.vaultId)).length).toBe(3); + }); + + test('cannot be the write that pins an owner', async () => { + const store = new MemoryVaultStore(); + const routes = createVaultRoutes(store, crypto); + const keys = await deriveVaultKeys(new Uint8Array(32).fill(3), 'scaffold'); + const res = await signedPost( + routes, + `/v1/vault/${keys.vaultId}/prune`, + keys.signingSeed, + keys.publicKey, + { keep: [0] }, + ); + expect(res.status).toBe(404); + expect(await store.getOwner(keys.vaultId)).toBeNull(); + }); + + test('rejects a malformed keep-list', async () => { + const { routes, keys } = await threeVersions(); + for (const keep of [undefined, 'alle', [3, -1], [3, 1.5]]) { + const res = await signedPost( + routes, + `/v1/vault/${keys.vaultId}/prune`, + keys.signingSeed, + keys.publicKey, + keep === undefined ? {} : { keep }, + ); + expect(res.status).toBe(400); + } + }); + + test('legacy versions without a recorded hash list keep their objects', async () => { + const { client, store, keys } = await harness({ routes: { pruneGraceMs: 0 } }); + const legacy = await legacyPush(store, keys, 1, [{ path: 'gammel.md', bytes: enc('v1-data') }]); + await client.push([{ path: 'ny.md', bytes: random(2000) }], AT + 1); + await client.push([{ path: 'ny.md', bytes: random(2000) }], AT + 2); + + // Drop version 2 but keep the legacy one: its objects are pinned, since + // the relay has no idea which objects it uses. + const res = await client.prune([1, 3]); + expect(res.removedVersions).toBe(1); + expect(res.removedObjects).toBe(2); // version 2's file and manifest only + for (const h of [legacy.manifest, ...legacy.objects]) { + expect(await store.hasObject(keys.vaultId, h)).toBe(true); + } + expect(dec((await client.pull(1)).files.get('gammel.md')!)).toBe('v1-data'); + + // Once the legacy version itself is pruned, no unknown reference set is + // left and its objects are ordinary garbage. + const second = await client.prune([3]); + expect(second.removedVersions).toBe(1); + for (const h of [legacy.manifest, ...legacy.objects]) { + expect(await store.hasObject(keys.vaultId, h)).toBe(false); + } + expect((await client.pull()).files.get('ny.md')!.length).toBe(2000); + }); + + test('an upload whose commit has not arrived yet survives the grace period', async () => { + const { client, keys, store } = await threeVersions(); // grace 0 here… + const orphan = await sealObject(crypto, keys.contentKey, keys.vaultId, enc('på vei')); + await store.putObject(keys.vaultId, orphan.hash, orphan.bytes); + + // …so under a real grace, a fresh orphan is left alone. + const routes = createVaultRoutes(store, crypto, { pruneGraceMs: 60_000 }); + const res = await signedPost( + routes, + `/v1/vault/${keys.vaultId}/prune`, + keys.signingSeed, + keys.publicKey, + { keep: [3] }, + ); + expect(res.status).toBe(200); + expect(await store.hasObject(keys.vaultId, orphan.hash)).toBe(true); + // While objects only an old version used are freed at once. + expect((await res.json()).removedObjects).toBe(4); + + // With no grace, the orphan is collected. + await client.prune([3]); + expect(await store.hasObject(keys.vaultId, orphan.hash)).toBe(false); + }); + + test('the store never removes an entry newer than the head the route checked', async () => { + const { store, keys } = await threeVersions(); + const res = await store.prune(keys.vaultId, { keep: [2], upTo: 2, protectSince: Date.now() }); + expect(res.removedVersions).toBe(1); + expect((await store.log(keys.vaultId)).map((e) => e.seq)).toEqual([2, 3]); + }); +}); diff --git a/packages/shade-vault/tests/vectors.test.ts b/packages/shade-vault/tests/vectors.test.ts new file mode 100644 index 0000000..a8f4bf7 --- /dev/null +++ b/packages/shade-vault/tests/vectors.test.ts @@ -0,0 +1,100 @@ +/** + * The vault-v2 cross-language vectors, checked against this implementation. + * + * The Kotlin port is written against `test-vectors/vault-v2.json`; this test + * is what stops the file and the TypeScript code from drifting apart, so a + * port that matches the vectors also matches the client that wrote them. + * Regenerate with `bun run scripts/generate-vectors.ts vault-v2.json`. + */ +import { describe, test, expect } from 'bun:test'; +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { SubtleCryptoProvider } from '@shade/crypto-web'; +import { canonicalizePayload } from '@shade/server'; +import { deriveVaultKeys } from '../src/client.js'; +import { + decodeManifest, + encodeManifest, + openEntryBytes, + openManifest, + packEntry, + toHex, + vaultObjectAad, +} from '../src/crypto.js'; +import { sealEntryWithNonces, sealObjectWithNonce } from '../src/testing.js'; +import type { VaultEntry } from '../src/types.js'; + +const crypto = new SubtleCryptoProvider(); +const file = JSON.parse( + readFileSync(join(import.meta.dir, '..', '..', '..', 'test-vectors', 'vault-v2.json'), 'utf-8'), +) as { version: number; vectors: any[] }; + +function fromHex(s: string): Uint8Array { + const out = new Uint8Array(s.length / 2); + for (let i = 0; i < out.length; i++) out[i] = parseInt(s.slice(i * 2, i * 2 + 2), 16); + return out; +} +const byPrefix = (p: string) => file.vectors.filter((v) => v.description.startsWith(p)); + +describe('vault-v2 vectors', async () => { + const k = byPrefix('vault-v2 keys')[0]; + const keys = await deriveVaultKeys(fromHex(k.masterKey), k.app); + + test('the file is schema version 2 and has every kind', () => { + expect(file.version).toBe(2); + expect(byPrefix('vault-v2 entry').length).toBe(3); + expect(byPrefix('vault-v2 manifest').length).toBe(2); + expect(byPrefix('vault-v2 signed').length).toBe(2); + }); + + test('key derivation and AAD', () => { + expect(keys.vaultId).toBe(k.vaultId); + expect(toHex(keys.contentKey)).toBe(k.contentKey); + expect(toHex(keys.signingSeed)).toBe(k.signingSeed); + expect(toHex(keys.publicKey)).toBe(k.publicKey); + expect(toHex(vaultObjectAad(keys.vaultId))).toBe(k.objectAad); + }); + + test('entries: readers reassemble, writers reproduce every byte', async () => { + for (const v of byPrefix('vault-v2 entry')) { + const entry = v.entry as VaultEntry; + const wires = v.parts.map((p: any) => fromHex(p.wire)); + const plain = await openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, wires); + expect(toHex(plain)).toBe(v.plaintext); + + const packed = await packEntry(plain, { chunkSize: v.chunkSize }); + expect(toHex(packed.stored)).toBe(v.stored); + expect(packed.enc ?? null).toBe(v.enc); + + const resealed = await sealEntryWithNonces( + keys.contentKey, + keys.vaultId, + plain, + (i) => fromHex(v.parts[i].nonce), + { chunkSize: v.chunkSize }, + ); + expect(resealed.objects.map((o) => toHex(o.bytes))).toEqual(v.parts.map((p: any) => p.wire)); + expect({ path: entry.path, ...resealed.locator, size: plain.length, ...(entry.mode ? { mode: entry.mode } : {}) }).toEqual(entry); + } + }); + + test('manifests: v2 and v1 both open; encoding reproduces the plaintext', async () => { + for (const v of byPrefix('vault-v2 manifest')) { + const opened = await openManifest(crypto, keys.contentKey, keys.vaultId, v.hash, fromHex(v.wire)); + expect(opened).toEqual(v.manifest); + expect(await decodeManifest(fromHex(v.plaintext))).toEqual(v.manifest); + expect(toHex(await encodeManifest(v.manifest))).toBe(v.plaintext); + const sealed = await sealObjectWithNonce(keys.contentKey, keys.vaultId, fromHex(v.plaintext), fromHex(v.nonce)); + expect(sealed.hash).toBe(v.hash); + } + }); + + test('signed bodies: canonical bytes and a deterministic Ed25519 signature', async () => { + for (const v of byPrefix('vault-v2 signed')) { + const canonical = canonicalizePayload({ ...v.body, signedAt: v.signedAt, signature: '' }); + expect(toHex(canonical)).toBe(v.canonicalHex); + expect(toHex(await crypto.sign(keys.signingSeed, canonical))).toBe(v.signature); + expect(await crypto.verify(keys.publicKey, canonical, fromHex(v.signature))).toBe(true); + } + }); +}); diff --git a/packages/shade-widgets/package.json b/packages/shade-widgets/package.json index 5f88b61..150fcc3 100644 --- a/packages/shade-widgets/package.json +++ b/packages/shade-widgets/package.json @@ -1,6 +1,6 @@ { "name": "@shade/widgets", - "version": "4.13.2", + "version": "4.14.0", "type": "module", "main": "src/index.ts", "types": "src/index.ts", diff --git a/scripts/generate-vectors.ts b/scripts/generate-vectors.ts index 93207cc..8722f94 100644 --- a/scripts/generate-vectors.ts +++ b/scripts/generate-vectors.ts @@ -9,7 +9,9 @@ * Bump `VECTOR_FILE_VERSION` whenever the vector schema (NOT just values) * changes, so downstream consumers can fail loudly on mismatch. * - * Usage: bun run scripts/generate-vectors.ts + * Usage: bun run scripts/generate-vectors.ts [file.json …] + * With file names, only those are regenerated — so adding a vector file + * does not churn the others. */ import { writeFileSync } from 'fs'; import { join } from 'path'; @@ -38,6 +40,18 @@ import { buildApprovalRequest, type ApprovalRequestFrame, } from '../packages/shade-sdk/src/index.js'; +import { deriveVaultKeys } from '../packages/shade-vault/src/client.js'; +import { + encodeManifest, + entryObjectHashes, + vaultObjectAad, +} from '../packages/shade-vault/src/crypto.js'; +import { + sealEntryWithNonces, + sealObjectWithNonce, +} from '../packages/shade-vault/src/testing.js'; +import type { VaultEntry, VaultManifest } from '../packages/shade-vault/src/types.js'; +import { canonicalizePayload } from '../packages/shade-server/src/auth.js'; const VECTOR_FILE_VERSION = 2; @@ -821,6 +835,146 @@ async function generateApprovalVectors(): Promise { return [...payloads, e2e]; } +async function generateVaultV2Vectors(): Promise { + // One vault, derived from a pinned master, used by every vector below — + // so a port checks its key derivation once and then the formats on top. + const masterKey = new Uint8Array(32).map((_, i) => i + 1); + const app = 'scaffold'; + const keys = await deriveVaultKeys(masterKey, app); + const te = new TextEncoder(); + + const vectors: Vector[] = [ + { + description: + 'vault-v2 keys: vaultId/contentKey/signingSeed = HKDF branches of masterKey for app; publicKey = Ed25519(signingSeed)', + masterKey: hex(masterKey), + app, + vaultId: keys.vaultId, + contentKey: hex(keys.contentKey), + signingSeed: hex(keys.signingSeed), + publicKey: hex(keys.publicKey), + objectAad: hex(vaultObjectAad(keys.vaultId)), + objectAadUtf8: `shade-vault-object-v1|${keys.vaultId}`, + }, + ]; + + // Entries. `stored` is pinned so a writer can be checked byte for byte + // (zlib default level, raw deflate); a reader must only need `wire`. + const pngLike = new Uint8Array(48); + pngLike.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); + const entryCases: Array<{ name: string; path: string; plaintext: Uint8Array; chunkSize?: number; mode?: string }> = [ + { + name: 'small text, compressed, one part', + path: '.scaffold/plan.md', + plaintext: te.encode('# Plan\n\n## Nå\n- [ ] noe\n- [ ] noe\n- [ ] noe\n- [ ] noe annet\n'.repeat(4)), + }, + { + name: 'multi-part (chunkSize 32), compressed — concatenate parts, then inflate', + path: 'logs/2026-10-16.md', + plaintext: te.encode( + Array.from({ length: 40 }, (_, i) => `linje ${i}: ${(i * 7919) % 1000}\n`).join(''), + ), + chunkSize: 32, + mode: '644', + }, + { + name: 'PNG magic, never compressed, one part', + path: 'bilde.png', + plaintext: pngLike, + }, + ]; + + const committedHashes: string[] = []; + const manifestEntries: VaultEntry[] = []; + for (const [n, c] of entryCases.entries()) { + const sealed = await sealEntryWithNonces( + keys.contentKey, + keys.vaultId, + c.plaintext, + (part) => new Uint8Array(12).map((_, i) => (n + 1) * 0x10 + part + i), + c.chunkSize === undefined ? {} : { chunkSize: c.chunkSize }, + ); + const entry: VaultEntry = { path: c.path, ...sealed.locator, size: c.plaintext.length }; + if (c.mode !== undefined) entry.mode = c.mode; + manifestEntries.push(entry); + committedHashes.push(...entryObjectHashes(entry)); + vectors.push({ + description: `vault-v2 entry: ${c.name}`, + chunkSize: c.chunkSize ?? 4 * 1024 * 1024, + plaintext: hex(c.plaintext), + stored: hex(sealed.packed.stored), + enc: sealed.packed.enc ?? null, + parts: sealed.objects.map((o, i) => ({ + nonce: hex(o.bytes.subarray(0, 12)), + plaintext: hex(sealed.packed.chunks[i]!), + wire: hex(o.bytes), + hash: o.hash, + })), + entry, + }); + } + + // Manifests: v2 (what push writes) and v1 (what old vaults hold). + const v2: VaultManifest = { version: 2, seq: 7, at: 1_786_600_000_000, entries: manifestEntries, message: 'nattlig backup' }; + const v1: VaultManifest = { + version: 1, + seq: 1, + at: 1_786_500_000_000, + entries: [{ path: 'notes.yaml', hash: manifestEntries[2]!.hash, size: 48 }], + }; + let manifestHash = ''; + for (const [m, nonceByte] of [[v2, 0xc0], [v1, 0xd0]] as const) { + const plain = await encodeManifest(m); + const sealed = await sealObjectWithNonce(keys.contentKey, keys.vaultId, plain, new Uint8Array(12).fill(nonceByte)); + if (m.version === 2) manifestHash = sealed.hash; + vectors.push({ + description: + m.version === 2 + ? 'vault-v2 manifest v2: plaintext = "SVM2" || deflate-raw(json utf-8)' + : 'vault-v2 manifest v1: plaintext = json utf-8 (back-compat, still readable)', + manifest: m, + json: JSON.stringify(m), + plaintext: hex(plain), + nonce: hex(sealed.bytes.subarray(0, 12)), + wire: hex(sealed.bytes), + hash: sealed.hash, + }); + } + + // Signed request bodies. Canonical form: every field except `signature`, + // top-level keys sorted, JSON.stringify — the same function the relay + // verifies with. Nested arrays keep their order. + const signed: Array<[string, Record]> = [ + [ + 'commit', + { + manifest: manifestHash, + seq: 7, + at: 1_786_600_000_000, + hashes: [...new Set(committedHashes)], + publicKey: Buffer.from(keys.publicKey).toString('base64'), + }, + ], + ['prune', { keep: [5, 7], publicKey: Buffer.from(keys.publicKey).toString('base64') }], + ]; + for (const [what, body] of signed) { + const signedAt = 1_786_600_000_123; + const canonical = canonicalizePayload({ ...body, signedAt, signature: '' }); + const sig = await crypto.sign(keys.signingSeed, canonical); + vectors.push({ + description: `vault-v2 signed ${what}: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)`, + body, + signedAt, + canonical: new TextDecoder().decode(canonical), + canonicalHex: hex(canonical), + signature: hex(sig), + signatureBase64: Buffer.from(sig).toString('base64'), + }); + } + + return vectors; +} + async function main() { console.log('Generating cross-platform test vectors…'); @@ -837,9 +991,12 @@ async function main() { ['storage-hkdf.json', { vectors: await generateStorageEncryptionSubset() }], ['blob.json', { vectors: await generateBlobVectors() }], ['approval.json', { vectors: await generateApprovalVectors() }], + ['vault-v2.json', { vectors: await generateVaultV2Vectors() }], ]; + const only = new Set(process.argv.slice(2)); for (const [name, data] of files) { + if (only.size > 0 && !only.has(name)) continue; const path = join(OUT_DIR, name); const versioned = { version: VECTOR_FILE_VERSION, ...data }; writeFileSync(path, JSON.stringify(versioned, null, 2) + '\n'); diff --git a/test-vectors/vault-v2.json b/test-vectors/vault-v2.json new file mode 100644 index 0000000..8a54013 --- /dev/null +++ b/test-vectors/vault-v2.json @@ -0,0 +1,227 @@ +{ + "version": 2, + "vectors": [ + { + "description": "vault-v2 keys: vaultId/contentKey/signingSeed = HKDF branches of masterKey for app; publicKey = Ed25519(signingSeed)", + "masterKey": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20", + "app": "scaffold", + "vaultId": "9360b12394a010ecfa677dfc38941a00c43ebb22e79a681f76d928285de52dc2", + "contentKey": "a5990e3c71b6c11902b0f05afe65d2a1476222026a5ff5a897a670af92629d8e", + "signingSeed": "718e842f89c926369c0d2cc9f05b5f40f8bafe30599747b1d1de67fb5ffbca4b", + "publicKey": "60666a9e492ce5808d5ce3e2c409d5d374bc540f5546ac54da78acd186959117", + "objectAad": "73686164652d7661756c742d6f626a6563742d76317c39333630623132333934613031306563666136373764666333383934316130306334336562623232653739613638316637366439323832383564653532646332", + "objectAadUtf8": "shade-vault-object-v1|9360b12394a010ecfa677dfc38941a00c43ebb22e79a681f76d928285de52dc2" + }, + { + "description": "vault-v2 entry: small text, compressed, one part", + "chunkSize": 4194304, + "plaintext": "2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a", + "stored": "535608c849cce3e2525656f03bbc944b57215a2156212f3f153f4b21312f2fb5844b79686a0600", + "enc": "deflate-raw", + "parts": [ + { + "nonce": "101112131415161718191a1b", + "plaintext": "535608c849cce3e2525656f03bbc944b57215a2156212f3f153f4b21312f2fb5844b79686a0600", + "wire": "101112131415161718191a1b3df181a4021d0d030b94331430d5e4a11b55bbf4164312f6280db7db72629e5183b7bd473ac4d8c7b6ed2edc7b18a6e6c11c5c340906e4", + "hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480" + } + ], + "entry": { + "path": ".scaffold/plan.md", + "hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480", + "enc": "deflate-raw", + "size": 244 + } + }, + { + "description": "vault-v2 entry: multi-part (chunkSize 32), compressed — concatenate parts, then inflate", + "chunkSize": 32, + "plaintext": "6c696e6a6520303a20300a6c696e6a6520313a203931390a6c696e6a6520323a203833380a6c696e6a6520333a203735370a6c696e6a6520343a203637360a6c696e6a6520353a203539350a6c696e6a6520363a203531340a6c696e6a6520373a203433330a6c696e6a6520383a203335320a6c696e6a6520393a203237310a6c696e6a652031303a203139300a6c696e6a652031313a203130390a6c696e6a652031323a2032380a6c696e6a652031333a203934370a6c696e6a652031343a203836360a6c696e6a652031353a203738350a6c696e6a652031363a203730340a6c696e6a652031373a203632330a6c696e6a652031383a203534320a6c696e6a652031393a203436310a6c696e6a652032303a203338300a6c696e6a652032313a203239390a6c696e6a652032323a203231380a6c696e6a652032333a203133370a6c696e6a652032343a2035360a6c696e6a652032353a203937350a6c696e6a652032363a203839340a6c696e6a652032373a203831330a6c696e6a652032383a203733320a6c696e6a652032393a203635310a6c696e6a652033303a203537300a6c696e6a652033313a203438390a6c696e6a652033323a203430380a6c696e6a652033333a203332370a6c696e6a652033343a203234360a6c696e6a652033353a203136350a6c696e6a652033363a2038340a6c696e6a652033373a20330a6c696e6a652033383a203932320a6c696e6a652033393a203834310a", + "stored": "3dd1316e84310884d17e4f314730600ccc7d52245ae5fe65f4479eedfc49483ce1f7f7efcf1716b15eefffa7116373c3898ebe114465ddd8c4a97323899cbc7188b47da3881d71a38948bf31849769e9226c3e04236cc9604eb80c16c46c216c137da4b024aac5b043d492c38a382e8835915b121b621f517c11d1a2b8113e9f733c1493c583b090c53791a2781253a2f8217a44f122da44f1262a44f1214e8a128bc812258cd82d4a38b1d7e76b8208172536e15b9648c28e2cf158448922048926c6058979c6ecf507", + "enc": "deflate-raw", + "parts": [ + { + "nonce": "202122232425262728292a2b", + "plaintext": "3dd1316e84310884d17e4f314730600ccc7d52245ae5fe65f4479eedfc49483c", + "wire": "202122232425262728292a2b0e79d38efa3cc03de999a559f68f49e2dc720f2b54641279bf38c56fbb5657b7006f03b9ac641e01a39c9c300b6727bc", + "hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3" + }, + { + "nonce": "2122232425262728292a2b2c", + "plaintext": "e1f7f7efcf1716b15eefffa7116373c3898ebe114465ddd8c4a97323899cbc71", + "wire": "2122232425262728292a2b2c8e0fc4531fc8900f2cf5e44a0ca9d99ae969c571754f1fcb8ea3682976ab70a4da805b0ebbec3b183a6187688b283599", + "hash": "dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1" + }, + { + "nonce": "22232425262728292a2b2c2d", + "plaintext": "88b47da3881d71a38948bf31849769e9226c3e04236cc9604eb80c16c46c216c", + "wire": "22232425262728292a2b2c2dca0d1c8465b46b1edc12987c6288d4df1327df36c40d998240b918dd99e4a1633179bc85a965eb2fc2923c6623b11a64", + "hash": "1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5" + }, + { + "nonce": "232425262728292a2b2c2d2e", + "plaintext": "137da4b024aac5b043d492c38a382e8835915b121b621f517c11d1a2b8113e9f", + "wire": "232425262728292a2b2c2d2eb6ad5e0146a9cd45e063c0d6a0706a8ef94ae7dc57222ec73a49de99cabe4b47ad115ba42b0d88d520b3ec4cfe6ce107", + "hash": "1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f" + }, + { + "nonce": "2425262728292a2b2c2d2e2f", + "plaintext": "733c1493c583b090c53791a2781253a2f8217a44f122da44f1262a44f1214e8a", + "wire": "2425262728292a2b2c2d2e2fd929c8f629fc833859bc2f6516434460e22fe68efb36823c7fcd67744d90253c7d9d8276663308a283256c0553bbc893", + "hash": "5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49" + }, + { + "nonce": "25262728292a2b2c2d2e2f30", + "plaintext": "128bc812258cd82d4a38b1d7e76b8208172536e15b9648c28e2cf15844892204", + "wire": "25262728292a2b2c2d2e2f300feb2c185b6c0d9c9b7c53c8b4667e470524922fb75bf5a86849b848fa6d6c616f3909067dda152d8f7c2a0078de3ed6", + "hash": "46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2" + }, + { + "nonce": "262728292a2b2c2d2e2f3031", + "plaintext": "8926c6058979c6ecf507", + "wire": "262728292a2b2c2d2e2f3031dd501f12336af9813a6b845aa252e8bb446f9eff169d0db9d476", + "hash": "2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc" + } + ], + "entry": { + "path": "logs/2026-10-16.md", + "hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3", + "parts": [ + "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3", + "dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1", + "1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5", + "1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f", + "5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49", + "46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2", + "2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc" + ], + "enc": "deflate-raw", + "size": 543, + "mode": "644" + } + }, + { + "description": "vault-v2 entry: PNG magic, never compressed, one part", + "chunkSize": 4194304, + "plaintext": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000", + "stored": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000", + "enc": null, + "parts": [ + { + "nonce": "303132333435363738393a3b", + "plaintext": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000", + "wire": "303132333435363738393a3b69d66e5792c16a018c81a00c8d7739372b72143758d5f60c7fceb1e92a465ca1c10c59e9fd22d991085376961813de4939087ff23a9d4fae2bb4ad92b4c7c559", + "hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4" + } + ], + "entry": { + "path": "bilde.png", + "hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4", + "size": 48 + } + }, + { + "description": "vault-v2 manifest v2: plaintext = \"SVM2\" || deflate-raw(json utf-8)", + "manifest": { + "version": 2, + "seq": 7, + "at": 1786600000000, + "entries": [ + { + "path": ".scaffold/plan.md", + "hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480", + "enc": "deflate-raw", + "size": 244 + }, + { + "path": "logs/2026-10-16.md", + "hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3", + "parts": [ + "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3", + "dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1", + "1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5", + "1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f", + "5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49", + "46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2", + "2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc" + ], + "enc": "deflate-raw", + "size": 543, + "mode": "644" + }, + { + "path": "bilde.png", + "hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4", + "size": 48 + } + ], + "message": "nattlig backup" + }, + "json": "{\"version\":2,\"seq\":7,\"at\":1786600000000,\"entries\":[{\"path\":\".scaffold/plan.md\",\"hash\":\"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480\",\"enc\":\"deflate-raw\",\"size\":244},{\"path\":\"logs/2026-10-16.md\",\"hash\":\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"parts\":[\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1\",\"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5\",\"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f\",\"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49\",\"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2\",\"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc\"],\"enc\":\"deflate-raw\",\"size\":543,\"mode\":\"644\"},{\"path\":\"bilde.png\",\"hash\":\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\",\"size\":48}],\"message\":\"nattlig backup\"}", + "plaintext": "53564d32ad92cd6e9c370c455fa5d0fab32352fcd3bc4a910529918ed1f1d8f54c1b2081dfbd98a208d24d57e596c03d87e0fddefeccf7ebf3eba59df068d7fcbd9df4687e6b275013e9ffccd1f2727b7fce6b3bfdfabdbdf9ed4b3bb5c7ebf2aad7f3fef476f6cbe3cb6e47fbe2d7fb0a66d816d1822dc45c34c5d49982d3472a53af8201c33cf62017cb95c68952be90acb73b70b553db5967bfe5c3bb7f6d47bb3e7fcb7642a28fe387c5f9f5e9fa093bca03f407907f69ac6db84d80688e4dda7deedad17973540da0350b77586007436002556558bc486d588c76b4377fbfddaffe3fb2f682ccd127e20677ddaa7d2e30c2353a04745a590488e89d0698576950cd4813c4e9d08e069dba745c9041192a02d30b69a5878c987b77d3696cd5318741afa93178b393488dcdf788d0316ace39dc99977816605896d7185606911a883a2c7b0c0799ddc80b78833960b5a3f1fd6d3c915957b9baa86827f472c6c88e0b31d7ee49606b244c9ce522e8bc8c57d06c4723a91dba74632a156ee8bd17e554079e515c62659c7b880fe9246b80902cd8035db0b01d0d636d5da004cc8b7ce41cbb262429b0e592a0aa9e61511c140812ab00ff761d9ab5dae7ff6a19d338dacbebce766a42d47eaa5c3c9f773ebe5d9e7e2a3c2095850c0b125c6b9bb1a6c20a0e57c41424ef53d7761563914ca1b1d4595d76d20f2cd9c7e7a3bde4f5ea4f77f4c56fb7f3f3d32fe1ebb73fdedac75f", + "nonce": "c0c0c0c0c0c0c0c0c0c0c0c0", + "wire": "c0c0c0c0c0c0c0c0c0c0c0c01190980ff0edf6049a9dd9120f8c01a273076cddd38f51af94f999837a8d78f3197a2a1ce77cde7fe2b3b455a7ae03810e2dd77e8bed66bcf7ccc2939a86639bb84872395229dea7dbef6c454a5444e080685320990a600753dbbaa6992e654d4827c8b3186c98b66a1f48766a6d41d1caeadbcfd3c82023b6171ab2a89b87acb7de83069a47280aba9bf01a784cfdab45983a96015890a00db4a70cd1fea7ecefc2ce813a193d941f0f93d2654c6fb0eb8d9d1e5327af17e03828aa1e33fbb0963d647d794c9e758bbfbfda7f6d799563d4532494abe21eae51e69da7b9721f54c6b08f3977138869268ec0005fdf8e2dfe69f715e34a403788d9ea35b8a1da9c62e5aeac7b88564d787d8f2ecb9e8c9d1316722651c245ceeca875ac91dcc920e26158b40ab594d0ae006f7c9df76559f377ef1373ed3bdb3dafd7bf9b263e9ac6a0563f4ea31478567a4ec548d8bd7dcc8206f9a2703d2a535ddf93935f2fd47b0937d760cb694434989262cead89b35bce9f3d69a09dcb0e8ac4ea1046e13ff06306cd644e9d53aa5c99847aed0847f5804c9ba09e661fad5641116846f102af64e1d170af6f54a149c757830e7ac5c415510de66874a7fd488d01b58e779ef002afb7ae07049fe6b57b957e35ac70d9d6904c5a1f55c0ffe55da94ec6b88731e5b7a361242303e48906991f863c9c6d4f783899d0ba97168fcf9e96aa26c922ec66b0d7e61b2e56f7f52143d964bc40ec9222f3d91892bcaed3d3137e0ddb6c68b223", + "hash": "cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609" + }, + { + "description": "vault-v2 manifest v1: plaintext = json utf-8 (back-compat, still readable)", + "manifest": { + "version": 1, + "seq": 1, + "at": 1786500000000, + "entries": [ + { + "path": "notes.yaml", + "hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4", + "size": 48 + } + ] + }, + "json": "{\"version\":1,\"seq\":1,\"at\":1786500000000,\"entries\":[{\"path\":\"notes.yaml\",\"hash\":\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\",\"size\":48}]}", + "plaintext": "7b2276657273696f6e223a312c22736571223a312c226174223a313738363530303030303030302c22656e7472696573223a5b7b2270617468223a226e6f7465732e79616d6c222c2268617368223a2231313234663862363338623436326363643838353765373163623562613732326536323461303937636461373638353636656536343363376135376136646534222c2273697a65223a34387d5d7d", + "nonce": "d0d0d0d0d0d0d0d0d0d0d0d0", + "wire": "d0d0d0d0d0d0d0d0d0d0d0d0eaa53cdb2e8e93a47c29a2ea9d62c2d3beb5304d6c2250d6edbe3db0219d612e8203060d698f80c3d527dab75c10856f061f55aac3c8dcf44d454b09038791d993576c4099bfb0db8e98d9d1d583858b61a63667bd3fcac71b6c60ecd62213e3775cbb519da048a55c73d064ea0be5518952e92d5d508c0fe0be4c12d60125ab19f908e13687f2322b647f347297d037e0b3b6e6d2b32fb2723ca9cc39b7227869596194bce9568fbde4004d53a8", + "hash": "d450e5f430700dc7d33adf75904f92069c5e4075276dbbdca7b484603c783475" + }, + { + "description": "vault-v2 signed commit: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)", + "body": { + "manifest": "cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609", + "seq": 7, + "at": 1786600000000, + "hashes": [ + "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480", + "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3", + "dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1", + "1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5", + "1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f", + "5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49", + "46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2", + "2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc", + "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4" + ], + "publicKey": "YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=" + }, + "signedAt": 1786600000123, + "canonical": "{\"at\":1786600000000,\"hashes\":[\"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480\",\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1\",\"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5\",\"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f\",\"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49\",\"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2\",\"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc\",\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\"],\"manifest\":\"cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609\",\"publicKey\":\"YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=\",\"seq\":7,\"signedAt\":1786600000123}", + "canonicalHex": "7b226174223a313738363630303030303030302c22686173686573223a5b2231396238643636376631643634353566343936383761353462356561336537353430666631333133386162643334613638656365383565323666616332343830222c2263643832643836313434393364343730613964666462303564356266663331346339663264623862323031383231353431373737353163356334373833386233222c2264633165653330393232643161613764373730396331383432633330316231303463656634313232326130343331386166663762346639626538363232396131222c2231303430363032633165623465623736363139616632346365616236336239646430383739383538663032653338313066393762333564356134363666336435222c2231623733336639393933616135356336616566313262386566616633333866383162653762323237333865306233613136393038346166313564313861313266222c2235616264333539323535376366613761363736373034326166613532626530326332326563643065343138633365313932396661363632613563383563623439222c2234366664623763376432653734663264313030306634653937613135396266356636386638356564333661333630343663333136343663316433326136326632222c2232626364376331373431353563346133653933646639316534373135386563366234666630656238626635623462323136626366313236373637303337656663222c2231313234663862363338623436326363643838353765373163623562613732326536323461303937636461373638353636656536343363376135376136646534225d2c226d616e6966657374223a2263633663323337343932306362333537653434656333623930373137376238663130626465373839646639653761373037643438336265376463653638363039222c227075626c69634b6579223a2259475a716e6b6b733559434e584f506978416e56303353385641395652717855326e6973305961566b52633d222c22736571223a372c227369676e65644174223a313738363630303030303132337d", + "signature": "495f601cfbe2574b483a1710e4e40ec252a21f27a0454f7220537d3d9b19230ae38402d9119ae4df9f2506c01472370ed30d26bd22ccac1e2ce4fa6028c5790b", + "signatureBase64": "SV9gHPviV0tIOhcQ5OQOwlKiHyegRU9yIFN9PZsZIwrjhALZEZrk358lBsAUcjcO0w0mvSLMrB4s5PpgKMV5Cw==" + }, + { + "description": "vault-v2 signed prune: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)", + "body": { + "keep": [ + 5, + 7 + ], + "publicKey": "YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=" + }, + "signedAt": 1786600000123, + "canonical": "{\"keep\":[5,7],\"publicKey\":\"YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=\",\"signedAt\":1786600000123}", + "canonicalHex": "7b226b656570223a5b352c375d2c227075626c69634b6579223a2259475a716e6b6b733559434e584f506978416e56303353385641395652717855326e6973305961566b52633d222c227369676e65644174223a313738363630303030303132337d", + "signature": "928c803849691673610b9cb98062f75e81bdbac9b192880ffcd70d57abe0bb3b1878183b1827601a9b43dd4d8e615f9790a97ecfe2da35beacf5200129a73f0e", + "signatureBase64": "koyAOElpFnNhC5y5gGL3XoG9usmxkogP/NcNV6vguzsYeBg7GCdgGptD3U2OYV+XkKl+z+LaNb6s9SABKac/Dg==" + } + ] +}