feat(vault): v2 — compressed entries, chunked objects, index pushes, lazy reads, prune (4.14.0)
Some checks failed
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled

Entries are deflate-raw compressed when it pays, split into 4 MiB sealed
parts, and manifests are compressed (SVM2). A push with a local index
reuses unchanged files without downloading anything, and a push with no
changes commits nothing. Readers fetch one manifest and only the entries
they need. The relay records what each version references and can prune
old versions signed by the owner. Cross-language vectors in
test-vectors/vault-v2.json.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-16 01:38:45 +02:00
parent bcae7b346e
commit b82a803e0c
42 changed files with 2549 additions and 143 deletions

View File

@@ -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<keyof typeof this.counts>) 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<VaultLog> {
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<VaultPruneResult> {
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<Response> },
path: string,
seed: Uint8Array,
publicKey: Uint8Array,
body: Record<string, unknown>,
) {
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]);
});
});

View File

@@ -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);
}
});
});