feat(vault): v2 — compressed entries, chunked objects, index pushes, lazy reads, prune (4.14.0)
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:
@@ -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<Uint8Array>;
|
||||
log(vaultId: string, limit?: number): Promise<VaultLog>;
|
||||
commit(vaultId: string, body: unknown): Promise<{ seq: number }>;
|
||||
prune(vaultId: string, body: unknown): Promise<VaultPruneResult>;
|
||||
}
|
||||
|
||||
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<PushResult> {
|
||||
const { head } = await this.transport.log(this.keys.vaultId, 1);
|
||||
async push(
|
||||
files: VaultFile[],
|
||||
at: number,
|
||||
message?: string,
|
||||
opts: PushOptions = {},
|
||||
): Promise<PushResult> {
|
||||
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<string, VaultEntry>();
|
||||
let byPath = new Map<string, VaultEntry>();
|
||||
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<string, VaultIndexEntry> = {};
|
||||
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<string, Uint8Array>();
|
||||
|
||||
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<string, Uint8Array> }> {
|
||||
const log = await this.transport.log(this.keys.vaultId);
|
||||
async manifest(seq?: number): Promise<VaultManifest> {
|
||||
// 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<string, Uint8Array>();
|
||||
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<Uint8Array> {
|
||||
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<string, Uint8Array> }> {
|
||||
const manifest = await this.manifest(seq);
|
||||
const files = new Map<string, Uint8Array>();
|
||||
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<VaultPruneResult> {
|
||||
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<VaultManifest> {
|
||||
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<VaultLog> {
|
||||
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<string, Uint8Array>,
|
||||
): VaultIndex {
|
||||
const entries: Record<string, VaultIndexEntry> = {};
|
||||
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;
|
||||
|
||||
@@ -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<Uint8Array> {
|
||||
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<Uint8Array> {
|
||||
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<ArrayBuffer>)
|
||||
.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<Uint8Array> {
|
||||
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<Uint8Array> {
|
||||
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<PackedEntry> {
|
||||
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<VaultEntry, 'hash' | 'parts'>): 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<Uint8Array> {
|
||||
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<Uint8Array> {
|
||||
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<VaultManifest> {
|
||||
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<SealedObject> {
|
||||
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<VaultManifest> {
|
||||
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. */
|
||||
|
||||
@@ -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<Response>;
|
||||
|
||||
@@ -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<VaultPruneResult> {
|
||||
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 };
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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<string, unknown> | 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 };
|
||||
|
||||
@@ -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<number>;
|
||||
/** Newest last. `limit` counts back from the head. */
|
||||
log(vaultId: string, limit?: number): Promise<VaultLogEntry[]>;
|
||||
appendLog(vaultId: string, entry: VaultLogEntry): Promise<void>;
|
||||
/**
|
||||
* 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<void>;
|
||||
|
||||
/**
|
||||
* 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<VaultPruneResult>;
|
||||
|
||||
/** Total stored bytes, for quota decisions. */
|
||||
usage(vaultId: string): Promise<number>;
|
||||
@@ -36,6 +83,12 @@ export class MemoryVaultStore implements VaultStore {
|
||||
private owners = new Map<string, Uint8Array>();
|
||||
private objects = new Map<string, Map<string, Uint8Array>>();
|
||||
private logs = new Map<string, VaultLogEntry[]>();
|
||||
/** Per vault: seq → referenced hashes, or null for an untracked entry. */
|
||||
private refs = new Map<string, Map<number, Set<string> | null>>();
|
||||
/** Per vault: objects an untracked entry may reference. */
|
||||
private pinned = new Map<string, Set<string>>();
|
||||
/** Per vault: when each object was first stored, for the prune grace. */
|
||||
private storedAt = new Map<string, Map<string, number>>();
|
||||
|
||||
async getOwner(vaultId: string): Promise<Uint8Array | null> {
|
||||
return this.owners.get(vaultId) ?? null;
|
||||
@@ -59,7 +112,15 @@ export class MemoryVaultStore implements VaultStore {
|
||||
}
|
||||
|
||||
async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void> {
|
||||
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<Uint8Array | null> {
|
||||
@@ -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<void> {
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||
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<string>();
|
||||
for (const h of this.bucket(vaultId).keys()) pins.add(h);
|
||||
this.pinned.set(vaultId, pins);
|
||||
}
|
||||
}
|
||||
|
||||
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
|
||||
// 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<number, Set<string> | null>();
|
||||
const bucket = this.bucket(vaultId);
|
||||
const times = this.storedAt.get(vaultId) ?? new Map<string, number>();
|
||||
|
||||
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<string>();
|
||||
for (const e of log) {
|
||||
everReferenced.add(e.manifest);
|
||||
for (const h of byseq.get(e.seq) ?? []) everReferenced.add(h);
|
||||
}
|
||||
|
||||
const inUse = new Set<string>();
|
||||
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<string>();
|
||||
|
||||
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<number> {
|
||||
|
||||
77
packages/shade-vault/src/testing.ts
Normal file
77
packages/shade-vault/src/testing.ts
Normal file
@@ -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<SealedObject> {
|
||||
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 };
|
||||
}
|
||||
@@ -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<string, VaultIndexEntry>;
|
||||
}
|
||||
|
||||
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.
|
||||
*
|
||||
|
||||
Reference in New Issue
Block a user