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

@@ -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<Vector[]> {
return [...payloads, e2e];
}
async function generateVaultV2Vectors(): Promise<Vector[]> {
// 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<string, unknown>]> = [
[
'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');