Compare commits
2 Commits
5d04e18482
...
v4.14.0
| Author | SHA1 | Date | |
|---|---|---|---|
| b82a803e0c | |||
| bcae7b346e |
@@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
title: "Register venter ikke lenger på en server som ikke svarer"
|
||||||
|
date: 2026-10-15
|
||||||
|
author: "Claude"
|
||||||
|
---
|
||||||
|
|
||||||
|
Prism ble stående med et tomt vindu i flere minutter 2026-10-15 mens zyon var nede.
|
||||||
|
En av grunnene lå her: `Shade.initialize()` ventet på `transport.register()` uten
|
||||||
|
tidsgrense. Når pakkene droppes i stedet for å avvises, betyr det ca. 2 minutter før kjernen
|
||||||
|
gir opp TCP-handshaken. Og feilmeldingen lovet «Will retry on next replenish», men
|
||||||
|
replenish registrerer aldri. En identitet som startet mens serveren var nede, forble
|
||||||
|
uregistrert til neste restart.
|
||||||
|
|
||||||
|
## Endret
|
||||||
|
|
||||||
|
- **`ShadeFetchTransport`**: alle forespørsler går gjennom én `request()` med tidsgrense (`requestTimeoutMs`, standard 15 000, `DEFAULT_REQUEST_TIMEOUT_MS` eksporteres) og en valgfri `fetch`-override. Når tidsgrensen nås, kommer en `NetworkError` med «No response from <host> within N ms».
|
||||||
|
- **`ShadeConfig`**: `registration: 'await' | 'background'`, `requestTimeoutMs`, `fetch`. Standard er `'await'`, så eksisterende brukere får fortsatt «registrert når `createShade` er ferdig», bare med tidsgrense. `'background'` er for apper der det å åpne identiteten skal være helt lokalt (Prisms unlock-port).
|
||||||
|
- **Ekte retry**: en register som feiler, prøves på nytt med backoff 5/15/30/60 s til den lykkes. Retryen avbrytes av `shutdown()`, `rotate()` og `importBackup()`, så en gammel identitet aldri publiseres etter rotasjon.
|
||||||
|
- De tre stedene som bygde `ShadeFetchTransport` bruker nå samme `makeTransport()`, så tidsgrense og fetch følger med ved rotasjon og restore.
|
||||||
|
|
||||||
|
## Verifisert
|
||||||
|
|
||||||
|
`tests/registration.test.ts` (5 nye) mot en fetch som aldri svarer: `'background'`
|
||||||
|
blir ferdig uten å vente, `'await'` gir opp ved tidsgrensen, en feilet register blir
|
||||||
|
prøvd på nytt etter 5 s, og `shutdown` stopper retryene. To nye transporttester for
|
||||||
|
tidsgrensen og fetch-overriden. Hele suiten: 1206 grønne, typecheck ren på alle 26 pakker.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Ikke publisert ennå. Registryet bor på `gt.zyon.no`, som var nede da dette ble skrevet.
|
||||||
|
> Neste steg er 4.13.2, og deretter at Prism bumper og setter `registration: 'background'` og `fetch: serverLink.fetch`.
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
---
|
---
|
||||||
project: "Shade"
|
project: "Shade"
|
||||||
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
|
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
|
||||||
updated: 2026-08-14
|
updated: 2026-10-15
|
||||||
focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. De tre gjenstående G0-P0-ene er publiserings- og CI-saker. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret."
|
focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. De tre gjenstående G0-P0-ene er publiserings- og CI-saker. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret."
|
||||||
blockers:
|
blockers:
|
||||||
- "P0: @shade/observer@4.11.1 tomt på registry (outDir=dist-build, publish shipper dist/)"
|
- "P0: @shade/observer@4.11.1 tomt på registry (outDir=dist-build, publish shipper dist/)"
|
||||||
@@ -17,6 +17,9 @@ blockers:
|
|||||||
|
|
||||||
## Nå
|
## Nå
|
||||||
Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-artifact 2026-07-10, se log.md).
|
Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-artifact 2026-07-10, se log.md).
|
||||||
|
- [ ] **Publiser 4.13.2** (register med tidsgrense + ekte retry + `registration: 'background'`,
|
||||||
|
gjort 2026-10-15, se `logs/2026-10-15-register-venter-ikke-lenger-pa-en-server-som-ikke-svarer.md`).
|
||||||
|
Venter på at `gt.zyon.no` er oppe. UNCOMMITTED.
|
||||||
- [ ] **G0 — Stopp blødningen (P0):** ~~tilfeldig nonce per skriving i
|
- [ ] **G0 — Stopp blødningen (P0):** ~~tilfeldig nonce per skriving i
|
||||||
storage-encrypted~~ (gjort 2026-08-13 — 9 nye tester, ingen migrering nødvendig,
|
storage-encrypted~~ (gjort 2026-08-13 — 9 nye tester, ingen migrering nødvendig,
|
||||||
Android var aldri rammet; se `logs/2026-08-13-gcm-nonce-reuse-fikset.md`.
|
Android var aldri rammet; se `logs/2026-08-13-gcm-nonce-reuse-fikset.md`.
|
||||||
|
|||||||
60
CHANGELOG.md
60
CHANGELOG.md
@@ -5,6 +5,66 @@ All notable changes to Shade are documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [4.14.0] — 2026-10-16 — Vault v2: smaller, cheaper pushes, big files, retention
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- **`@shade/vault`: compressed and multi-part entries.** A file is deflated
|
||||||
|
(raw, kept only if it saves ≥ 5 %, skipped for known compressed formats)
|
||||||
|
and split into 4 MiB parts. `VaultEntry` gains optional `enc` and `parts`;
|
||||||
|
`size` stays the plaintext length. Files over the relay's 8 MiB object limit
|
||||||
|
can now be backed up at all.
|
||||||
|
- **Manifest v2**: `"SVM2"` + deflate-raw(JSON). Push writes v2; readers
|
||||||
|
accept v1 and v2 and refuse anything else.
|
||||||
|
- **`VaultIndex`** — `push(files, at, message?, { index })` returns an `index`
|
||||||
|
to persist. With a fresh one, an unchanged file is recognised by plaintext
|
||||||
|
SHA-256 with no download, no seal and no upload (renames and copies too).
|
||||||
|
- **A push that changes nothing commits nothing** (`unchanged: true`), unless a
|
||||||
|
`message` asks for a version.
|
||||||
|
- **Lazy reads**: `VaultClient.manifest(seq?)` and `readEntry(entry)`; `pull`
|
||||||
|
is built on them. Exported helpers: `openEntryBytes`, `entryObjectHashes`,
|
||||||
|
`packEntry`, `sealEntry`, `encodeManifest`/`decodeManifest`, `vaultIndexFrom`.
|
||||||
|
- **Retention**: signed `POST /v1/vault/:id/prune` `{ keep }`,
|
||||||
|
`VaultClient.prune(keep)` → `{ removedVersions, removedObjects, freedBytes }`.
|
||||||
|
The relay records each commit's referenced hashes and collects objects no
|
||||||
|
remaining version uses. Versions from before this pin their objects until
|
||||||
|
they are pruned themselves. `VaultRoutesOptions.pruneGraceMs` (default 1 h)
|
||||||
|
protects uploads whose commit is still in flight.
|
||||||
|
- `VaultStore.prune` and an optional `refs` argument on `appendLog`;
|
||||||
|
`SqliteVaultStore` migrates its schema in place on open.
|
||||||
|
- `test-vectors/vault-v2.json` for the Kotlin port; `@shade/vault/testing`
|
||||||
|
(fixed-nonce sealing, vectors only).
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- Push without an index reads only the head manifest and downloads a previous
|
||||||
|
file only when its path and size match — it used to download every file of
|
||||||
|
the head. Freshly sealed objects are no longer have-checked (their names are
|
||||||
|
new by construction). A reused entry takes the file's current `mode`.
|
||||||
|
- `VaultTransport` has a required `prune` method; custom transports must add it.
|
||||||
|
|
||||||
|
## [4.13.2] — 2026-10-15 — No prekey-server call can hang an identity open
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **`@shade/transport`: every prekey-server request has a deadline**
|
||||||
|
(`requestTimeoutMs`, default 15 000; `DEFAULT_REQUEST_TIMEOUT_MS` exported).
|
||||||
|
A server that drops packets instead of refusing them held each call until
|
||||||
|
the kernel gave up on the TCP handshake — about two minutes on Linux.
|
||||||
|
Expiry throws a `NetworkError` naming the host.
|
||||||
|
- **`@shade/sdk`: a failed initial registration is actually retried** — with
|
||||||
|
backoff (5/15/30/60 s) until it succeeds, the identity rotates or is
|
||||||
|
restored, or `shutdown()` runs. The old log line promised a retry "on next
|
||||||
|
replenish", but replenish never registers: an identity that came up while
|
||||||
|
the server was unreachable stayed unregistered until the next restart.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
- `ShadeConfig.registration: 'await' | 'background'` (default `'await'`, now
|
||||||
|
bounded by the timeout). `'background'` opens the identity without waiting
|
||||||
|
on the network — for apps whose unlock must be purely local.
|
||||||
|
- `ShadeConfig.requestTimeoutMs` and `ShadeConfig.fetch` (also on
|
||||||
|
`ShadeFetchTransport`): observe reachability, or stub the network in tests.
|
||||||
|
|
||||||
|
Found by Prism: with the relay unreachable, unlock — and with it the first
|
||||||
|
terminal — waited minutes on a register call.
|
||||||
|
|
||||||
## [4.13.1] — 2026-10-06 — Inbox keeps per-recipient order across retries
|
## [4.13.1] — 2026-10-06 — Inbox keeps per-recipient order across retries
|
||||||
|
|
||||||
### Fixed
|
### Fixed
|
||||||
|
|||||||
102
docs/vault.md
102
docs/vault.md
@@ -50,21 +50,84 @@ const crypto = new SubtleCryptoProvider();
|
|||||||
const keys = await deriveVaultKeys(masterKey, 'scaffold');
|
const keys = await deriveVaultKeys(masterKey, 'scaffold');
|
||||||
const client = new VaultClient(crypto, keys, new HttpVaultTransport('https://vault.example'));
|
const client = new VaultClient(crypto, keys, new HttpVaultTransport('https://vault.example'));
|
||||||
|
|
||||||
// Back up. Unchanged files are not re-uploaded.
|
// Back up. Unchanged files are not re-uploaded. Persist `res.index` and pass
|
||||||
const res = await client.push(files, Date.now(), 'nightly');
|
// it to the next push: an unchanged file is then recognised locally, with no
|
||||||
// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204 }
|
// download at all.
|
||||||
|
const res = await client.push(files, Date.now(), undefined, { index: savedIndex });
|
||||||
|
// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204, unchanged: false, index }
|
||||||
|
|
||||||
// Restore — the newest, or any earlier version.
|
// Restore — the newest, or any earlier version.
|
||||||
const { manifest, files: restored } = await client.pull();
|
const { manifest, files: restored } = await client.pull();
|
||||||
const old = await client.pull(2);
|
const old = await client.pull(2);
|
||||||
|
|
||||||
// History.
|
// Lazy: list a version, then fetch only what is opened.
|
||||||
|
const m = await client.manifest();
|
||||||
|
const bytes = await client.readEntry(m.entries[0]);
|
||||||
|
|
||||||
|
// History, and retention.
|
||||||
const log = await client.history();
|
const log = await client.history();
|
||||||
|
await client.prune([log.head - 1, log.head]); // → { removedVersions, removedObjects, freedBytes }
|
||||||
```
|
```
|
||||||
|
|
||||||
`push` takes `at` rather than reading the clock, so a queued backup records
|
`push` takes `at` rather than reading the clock, so a queued backup records
|
||||||
when it was *taken* rather than when it finally reached the relay.
|
when it was *taken* rather than when it finally reached the relay.
|
||||||
|
|
||||||
|
**A push that changes nothing commits nothing.** Same paths, same modes, every
|
||||||
|
file reused, no `message`: the result is `{ unchanged: true, seq: head }` and
|
||||||
|
the log does not grow. Pushes run on every workspace change; a version per
|
||||||
|
trigger would fill the log with empty commits. Pass a `message` to force one.
|
||||||
|
|
||||||
|
**The index** (`VaultIndex`, plain JSON) maps each path to its plaintext
|
||||||
|
SHA-256 and the entry it was stored as. It is trusted only when its `vaultId`
|
||||||
|
matches and its `seq` is still the relay's head; otherwise the push reads the
|
||||||
|
head manifest and downloads only same-path, same-size candidates to compare. It
|
||||||
|
holds plaintext hashes, so keep it with the files, never on the relay. After a
|
||||||
|
restore, `vaultIndexFrom(vaultId, manifest, files)` builds one, so the first
|
||||||
|
push from a fresh device is free too.
|
||||||
|
|
||||||
|
## Format (v2) — the cross-language contract
|
||||||
|
|
||||||
|
Every object is `nonce(12) || AES-256-GCM(contentKey, plaintext, aad)`, named
|
||||||
|
by the lowercase hex SHA-256 of those bytes, with
|
||||||
|
`aad = utf8("shade-vault-object-v1|" + vaultId)`.
|
||||||
|
|
||||||
|
**Entries.** A file's plaintext becomes its *stored* bytes, then *parts*:
|
||||||
|
|
||||||
|
1. Unless the plaintext is empty or starts with a known compressed signature —
|
||||||
|
PNG `89 50 4E 47`, JPEG `FF D8 FF`, WebP `"RIFF"` + `"WEBP"` at offset 8,
|
||||||
|
MP4 family `"ftyp"` at offset 4, GIF `"GIF8"`, gzip `1F 8B`, zip `"PK"` —
|
||||||
|
deflate it (raw RFC 1951, zlib default level). Keep the result, and set
|
||||||
|
`enc: "deflate-raw"`, only if `compressed * 20 <= plain * 19` (≤ 95 %, in
|
||||||
|
integers so no port rounds differently).
|
||||||
|
2. Split the stored bytes into slices of at most 4 MiB (4 194 304). An empty
|
||||||
|
file is one empty slice.
|
||||||
|
3. Seal each slice as its own object. One slice: `hash` names it and there is
|
||||||
|
no `parts`. Several: `parts` lists their hashes in order and
|
||||||
|
`hash = parts[0]`.
|
||||||
|
|
||||||
|
`size` is always the **plaintext** length. A reader fetches
|
||||||
|
`parts ?? [hash]`, verifies and opens each, concatenates, inflates if `enc`,
|
||||||
|
and checks the result against `size`. An unknown `enc` is refused.
|
||||||
|
|
||||||
|
**Manifests.** v2 plaintext is ASCII `"SVM2"` followed by deflate-raw of the
|
||||||
|
UTF-8 JSON; v1 is the bare JSON. A reader inflates when the magic is present,
|
||||||
|
parses, and accepts `version` 1 or 2 only — refusing beats guessing, since
|
||||||
|
silently dropping a field it cannot represent would lose data on its next
|
||||||
|
commit. JSON key order is not part of the contract. A v1-only reader fails on a
|
||||||
|
v2 manifest at JSON parse, loudly, rather than misreading it.
|
||||||
|
|
||||||
|
**Commits** list every part of every entry in the signed `hashes`. The relay
|
||||||
|
checks they exist and records them as what the version references; a part
|
||||||
|
left out may be collected by the next prune.
|
||||||
|
|
||||||
|
**Signed bodies** are canonicalised as JSON of every field except
|
||||||
|
`signature`, top-level keys sorted, nested values as-is; the signature is
|
||||||
|
Ed25519 over those bytes with the vault's signing seed, base64 on the wire.
|
||||||
|
|
||||||
|
Vectors for all of the above: `test-vectors/vault-v2.json` (regenerate with
|
||||||
|
`bun run scripts/generate-vectors.ts vault-v2.json`). Compressed bytes are
|
||||||
|
pinned (`stored`) for writer parity; a reader needs only `wire`.
|
||||||
|
|
||||||
## Server
|
## Server
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@@ -83,6 +146,7 @@ Routes:
|
|||||||
| `GET /v1/vault/:id/object/:hash` | raw ciphertext |
|
| `GET /v1/vault/:id/object/:hash` | raw ciphertext |
|
||||||
| `PUT /v1/vault/:id/object/:hash` | signed; verifies hash matches bytes |
|
| `PUT /v1/vault/:id/object/:hash` | signed; verifies hash matches bytes |
|
||||||
| `POST /v1/vault/:id/commit` | signed; refuses a stale `seq` or a missing object |
|
| `POST /v1/vault/:id/commit` | signed; refuses a stale `seq` or a missing object |
|
||||||
|
| `POST /v1/vault/:id/prune` | signed `{ keep: number[] }`; must keep the head |
|
||||||
|
|
||||||
Auth is TOFU-Ed25519, as for blobs: the first signed write pins a pubkey, and
|
Auth is TOFU-Ed25519, as for blobs: the first signed write pins a pubkey, and
|
||||||
every later write must be signed by it. The pubkey travels **inside** the
|
every later write must be signed by it. The pubkey travels **inside** the
|
||||||
@@ -106,6 +170,31 @@ mounted, with a warning that says why.
|
|||||||
### Limits
|
### Limits
|
||||||
|
|
||||||
Per object 8 MiB, per vault 512 MiB, both overridable via `VaultRoutesOptions`.
|
Per object 8 MiB, per vault 512 MiB, both overridable via `VaultRoutesOptions`.
|
||||||
|
Files larger than an object are split into 4 MiB parts by the client, so the
|
||||||
|
per-object limit no longer caps file size.
|
||||||
|
|
||||||
|
### Retention
|
||||||
|
|
||||||
|
`prune` deletes every log entry not in `keep` and then every object no
|
||||||
|
remaining entry references. The client chooses the policy — only it can read
|
||||||
|
the manifests — and the relay executes it:
|
||||||
|
|
||||||
|
- `keep` must include the current head, or the request fails with
|
||||||
|
`SEQ_CONFLICT` (and the head). That is also what a keep-list computed before
|
||||||
|
another device's commit, or a replayed prune, runs into.
|
||||||
|
- Prune never pins an owner: on a vault with no owner it is a 404.
|
||||||
|
- An entry newer than the head the route checked is never removed, even if a
|
||||||
|
commit lands mid-request.
|
||||||
|
- An object no version has ever referenced (an upload whose commit is still
|
||||||
|
in flight) survives for `pruneGraceMs`, default one hour.
|
||||||
|
- **Versions committed before ref tracking** have no recorded hash list. Every
|
||||||
|
object present when such a version was written (for SQLite: when the
|
||||||
|
database was migrated) is pinned and never collected while any untracked
|
||||||
|
version remains. Once the last one is pruned, nothing has an unknown
|
||||||
|
reference set, and the pins are released.
|
||||||
|
|
||||||
|
`SqliteVaultStore` migrates in place on open: `refs_known` on the log,
|
||||||
|
`pinned` on objects, a `shade_vault_refs` table. No manual step.
|
||||||
|
|
||||||
## What the relay learns
|
## What the relay learns
|
||||||
|
|
||||||
@@ -121,6 +210,5 @@ share, which is exactly what a blind store must not do.
|
|||||||
## Status
|
## Status
|
||||||
|
|
||||||
Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and
|
Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and
|
||||||
tested (16 unit + 7 store tests, plus an end-to-end suite against a real
|
tested, v2 format and prune included, with cross-language vectors. Not yet: a
|
||||||
workspace of 491 files). Not yet: a Postgres store, rate limiting on the vault
|
Postgres store, rate limiting on the vault routes, and the Kotlin port of v2.
|
||||||
routes, and garbage collection of objects no manifest references any more.
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/cli",
|
"name": "@shade/cli",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/cli.ts",
|
"main": "src/cli.ts",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/core",
|
"name": "@shade/core",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/crypto-web",
|
"name": "@shade/crypto-web",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/dashboard",
|
"name": "@shade/dashboard",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/files",
|
"name": "@shade/files",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/inbox-server",
|
"name": "@shade/inbox-server",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/inbox",
|
"name": "@shade/inbox",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/key-transparency",
|
"name": "@shade/key-transparency",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/keychain",
|
"name": "@shade/keychain",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/observability",
|
"name": "@shade/observability",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/observer",
|
"name": "@shade/observer",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/proto",
|
"name": "@shade/proto",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/recovery",
|
"name": "@shade/recovery",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/sdk",
|
"name": "@shade/sdk",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { StorageProvider } from '@shade/core';
|
import type { StorageProvider } from '@shade/core';
|
||||||
import { ConfigurationError } from '@shade/core';
|
import { ConfigurationError } from '@shade/core';
|
||||||
import type { ObservabilityHook } from '@shade/observability';
|
import type { ObservabilityHook } from '@shade/observability';
|
||||||
|
import { DEFAULT_REQUEST_TIMEOUT_MS } from '@shade/transport';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shade SDK configuration.
|
* Shade SDK configuration.
|
||||||
@@ -84,6 +85,29 @@ export interface ShadeConfig {
|
|||||||
* Default: KT verification disabled. Set this to enable.
|
* Default: KT verification disabled. Set this to enable.
|
||||||
*/
|
*/
|
||||||
keyTransparency?: ShadeKTConfig;
|
keyTransparency?: ShadeKTConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What `initialize()` does about registering with the prekey server.
|
||||||
|
*
|
||||||
|
* - `'await'` (default): wait for it — at most `requestTimeoutMs` — so a
|
||||||
|
* peer can fetch this identity's bundle the moment `createShade`
|
||||||
|
* resolves.
|
||||||
|
* - `'background'`: don't wait. For apps where opening the identity must
|
||||||
|
* not depend on the network, e.g. a local unlock gate.
|
||||||
|
*
|
||||||
|
* Either way a registration that fails is retried in the background with
|
||||||
|
* backoff until it succeeds or `shutdown()` runs.
|
||||||
|
*/
|
||||||
|
registration?: 'await' | 'background';
|
||||||
|
|
||||||
|
/** Every prekey-server request gives up after this many ms. Default 15 000. */
|
||||||
|
requestTimeoutMs?: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch for every prekey-server request — to observe the server's
|
||||||
|
* reachability, or to stub the network in tests. Default: global fetch.
|
||||||
|
*/
|
||||||
|
fetch?: typeof fetch;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Public configuration shape for `Shade.keyTransparency`. */
|
/** Public configuration shape for `Shade.keyTransparency`. */
|
||||||
@@ -117,6 +141,9 @@ export interface ResolvedConfig {
|
|||||||
};
|
};
|
||||||
observability?: ObservabilityHook;
|
observability?: ObservabilityHook;
|
||||||
keyTransparency?: ResolvedKTConfig;
|
keyTransparency?: ResolvedKTConfig;
|
||||||
|
registration: 'await' | 'background';
|
||||||
|
requestTimeoutMs: number;
|
||||||
|
fetch?: typeof fetch;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ResolvedKTConfig {
|
export interface ResolvedKTConfig {
|
||||||
@@ -146,8 +173,20 @@ export function resolveConfig(input: ShadeConfig): ResolvedConfig {
|
|||||||
address: input.address,
|
address: input.address,
|
||||||
autoReplenish,
|
autoReplenish,
|
||||||
autoRotate: input.autoRotate ?? false,
|
autoRotate: input.autoRotate ?? false,
|
||||||
|
registration: input.registration ?? 'await',
|
||||||
|
requestTimeoutMs: input.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (resolved.registration !== 'await' && resolved.registration !== 'background') {
|
||||||
|
throw new ConfigurationError(`registration must be 'await' or 'background'`);
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(resolved.requestTimeoutMs) || resolved.requestTimeoutMs <= 0) {
|
||||||
|
throw new ConfigurationError('requestTimeoutMs must be a positive number');
|
||||||
|
}
|
||||||
|
if (input.fetch !== undefined) {
|
||||||
|
resolved.fetch = input.fetch;
|
||||||
|
}
|
||||||
|
|
||||||
if (input.observer) {
|
if (input.observer) {
|
||||||
if (!input.observer.token || input.observer.token.length < 16) {
|
if (!input.observer.token || input.observer.token.length < 16) {
|
||||||
throw new ConfigurationError('observer.token must be at least 16 characters');
|
throw new ConfigurationError('observer.token must be at least 16 characters');
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ export interface ShadeUploadOptions extends TransferOptions {
|
|||||||
generateThumbnail?: boolean | ThumbnailGenerationOptions;
|
generateThumbnail?: boolean | ThumbnailGenerationOptions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Delays between retries of the initial registration; the last repeats. */
|
||||||
|
const REGISTRATION_RETRY_MS: readonly number[] = [5_000, 15_000, 30_000, 60_000];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The high-level Shade API.
|
* The high-level Shade API.
|
||||||
*
|
*
|
||||||
@@ -157,6 +160,9 @@ export class Shade {
|
|||||||
private manager!: ShadeSessionManager;
|
private manager!: ShadeSessionManager;
|
||||||
private transport!: ShadeFetchTransport;
|
private transport!: ShadeFetchTransport;
|
||||||
private _background: BackgroundTasks | null = null;
|
private _background: BackgroundTasks | null = null;
|
||||||
|
/** Pending retry of the initial registration; see [retryRegistration]. */
|
||||||
|
private registrationRetry: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private shutDown = false;
|
||||||
private address!: string;
|
private address!: string;
|
||||||
private initialized = false;
|
private initialized = false;
|
||||||
|
|
||||||
@@ -279,28 +285,23 @@ export class Shade {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
this.transport = new ShadeFetchTransport({
|
this.transport = this.makeTransport(identity.signingPrivateKey, ktOpts);
|
||||||
baseUrl: this.config.prekeyServer,
|
|
||||||
crypto: this.crypto,
|
|
||||||
signingPrivateKey: identity.signingPrivateKey,
|
|
||||||
...(ktOpts ? { keyTransparency: ktOpts } : {}),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Step 5: Initial prekeys + register
|
// Step 5: Initial prekeys + register
|
||||||
const otpks = await this.manager.generateOneTimePreKeys(20);
|
const otpks = await this.manager.generateOneTimePreKeys(20);
|
||||||
const bundle = await this.manager.createPreKeyBundle();
|
const bundle = await this.manager.createPreKeyBundle();
|
||||||
|
const publicIdentity = this.manager.getPublicIdentity();
|
||||||
|
const register = () =>
|
||||||
|
this.transport.register(this.address, publicIdentity, bundle.signedPreKey, otpks);
|
||||||
|
|
||||||
|
if (this.config.registration === 'background') {
|
||||||
|
this.retryRegistration(register, 0, 0);
|
||||||
|
} else {
|
||||||
try {
|
try {
|
||||||
await this.transport.register(
|
await register();
|
||||||
this.address,
|
|
||||||
this.manager.getPublicIdentity(),
|
|
||||||
bundle.signedPreKey,
|
|
||||||
otpks,
|
|
||||||
);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn(
|
this.retryRegistration(register, 1, undefined, err as Error);
|
||||||
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${(err as Error).message}. Will retry on next replenish.`,
|
}
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 6: Background tasks
|
// Step 6: Background tasks
|
||||||
@@ -742,6 +743,10 @@ export class Shade {
|
|||||||
async rotate(): Promise<void> {
|
async rotate(): Promise<void> {
|
||||||
if (!this.initialized) throw new Error('Not initialized');
|
if (!this.initialized) throw new Error('Not initialized');
|
||||||
|
|
||||||
|
// The initial registration's retry would publish the identity we are
|
||||||
|
// about to replace; this rotation registers the new one itself.
|
||||||
|
this.cancelRegistrationRetry();
|
||||||
|
|
||||||
// Rotate locally first
|
// Rotate locally first
|
||||||
const newBundle = await this.manager.rotateIdentity();
|
const newBundle = await this.manager.rotateIdentity();
|
||||||
|
|
||||||
@@ -749,11 +754,7 @@ export class Shade {
|
|||||||
// signed operations (replenish, delete, register) work
|
// signed operations (replenish, delete, register) work
|
||||||
const identity = await this.storage.getIdentityKeyPair();
|
const identity = await this.storage.getIdentityKeyPair();
|
||||||
if (!identity) throw new Error('Identity missing after rotate');
|
if (!identity) throw new Error('Identity missing after rotate');
|
||||||
this.transport = new ShadeFetchTransport({
|
this.transport = this.makeTransport(identity.signingPrivateKey);
|
||||||
baseUrl: this.config.prekeyServer,
|
|
||||||
crypto: this.crypto,
|
|
||||||
signingPrivateKey: identity.signingPrivateKey,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Re-upload the new bundle
|
// Re-upload the new bundle
|
||||||
await this.transport.register(
|
await this.transport.register(
|
||||||
@@ -822,17 +823,79 @@ export class Shade {
|
|||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
await this.manager.initialize();
|
await this.manager.initialize();
|
||||||
this.transport = new ShadeFetchTransport({
|
// Same reason as in rotate(): the pending retry is for the old identity.
|
||||||
|
this.cancelRegistrationRetry();
|
||||||
|
this.transport = this.makeTransport(restored.signingPrivateKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private makeTransport(
|
||||||
|
signingPrivateKey: Uint8Array,
|
||||||
|
keyTransparency?: KTVerifierOptions,
|
||||||
|
): ShadeFetchTransport {
|
||||||
|
return new ShadeFetchTransport({
|
||||||
baseUrl: this.config.prekeyServer,
|
baseUrl: this.config.prekeyServer,
|
||||||
crypto: this.crypto,
|
crypto: this.crypto,
|
||||||
signingPrivateKey: restored.signingPrivateKey,
|
signingPrivateKey,
|
||||||
|
requestTimeoutMs: this.config.requestTimeoutMs,
|
||||||
|
...(this.config.fetch ? { fetch: this.config.fetch } : {}),
|
||||||
|
...(keyTransparency ? { keyTransparency } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register with the prekey server, retrying with backoff until it works,
|
||||||
|
* the identity changes, or the instance shuts down.
|
||||||
|
*
|
||||||
|
* This used to be one attempt whose failure promised "will retry on next
|
||||||
|
* replenish" — but replenish never registers, so an identity that came
|
||||||
|
* up while the server was unreachable stayed unregistered until the next
|
||||||
|
* restart.
|
||||||
|
*
|
||||||
|
* `attempt` 0 is the first try (no delay unless `delayMs` says so); each
|
||||||
|
* failure moves one step along [REGISTRATION_RETRY_MS].
|
||||||
|
*/
|
||||||
|
private retryRegistration(
|
||||||
|
register: () => Promise<void>,
|
||||||
|
attempt: number,
|
||||||
|
delayMs?: number,
|
||||||
|
lastError?: Error,
|
||||||
|
): void {
|
||||||
|
if (this.shutDown) return;
|
||||||
|
const steps = REGISTRATION_RETRY_MS;
|
||||||
|
const delay = delayMs ?? steps[Math.min(Math.max(attempt - 1, 0), steps.length - 1)] ?? 60_000;
|
||||||
|
if (lastError) {
|
||||||
|
console.warn(
|
||||||
|
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${lastError.message}. Retrying in ${Math.round(delay / 1000)} s.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.registrationRetry = setTimeout(() => {
|
||||||
|
this.registrationRetry = null;
|
||||||
|
if (this.shutDown) return;
|
||||||
|
register().then(
|
||||||
|
() => {
|
||||||
|
if (attempt > 0) {
|
||||||
|
console.warn(`[Shade] Registered with prekey server at ${this.config.prekeyServer}.`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(err: Error) => this.retryRegistration(register, attempt + 1, undefined, err),
|
||||||
|
);
|
||||||
|
}, delay);
|
||||||
|
(this.registrationRetry as unknown as { unref?: () => void }).unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelRegistrationRetry(): void {
|
||||||
|
if (this.registrationRetry !== null) {
|
||||||
|
clearTimeout(this.registrationRetry);
|
||||||
|
this.registrationRetry = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clean shutdown: stop timers, close storage if it supports it */
|
/** Clean shutdown: stop timers, close storage if it supports it */
|
||||||
async shutdown(): Promise<void> {
|
async shutdown(): Promise<void> {
|
||||||
this._background?.stop();
|
this._background?.stop();
|
||||||
|
this.cancelRegistrationRetry();
|
||||||
|
this.shutDown = true;
|
||||||
if (this.transferEngine !== null) this.transferEngine.destroy();
|
if (this.transferEngine !== null) this.transferEngine.destroy();
|
||||||
if (this.controlChannel !== null) this.controlChannel.destroy();
|
if (this.controlChannel !== null) this.controlChannel.destroy();
|
||||||
if (this.webrtcRuntime !== null) {
|
if (this.webrtcRuntime !== null) {
|
||||||
|
|||||||
111
packages/shade-sdk/tests/registration.test.ts
Normal file
111
packages/shade-sdk/tests/registration.test.ts
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { describe, test, expect } from 'bun:test';
|
||||||
|
import { createShade } from '../src/index.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opening an identity used to wait on the prekey server with no deadline:
|
||||||
|
* with the server unreachable (packets dropped, not refused) `createShade`
|
||||||
|
* hung until the kernel gave up on the TCP handshake, about two minutes —
|
||||||
|
* and the failed registration was never retried, despite the log saying
|
||||||
|
* it would be.
|
||||||
|
*/
|
||||||
|
describe('registration with an unreachable prekey server', () => {
|
||||||
|
/** Never answers; honours abort like the real fetch. Counts calls. */
|
||||||
|
function blackHole() {
|
||||||
|
const urls: string[] = [];
|
||||||
|
const fetch = ((url: string, init?: RequestInit) => {
|
||||||
|
urls.push(url);
|
||||||
|
return new Promise<Response>((_resolve, reject) => {
|
||||||
|
init?.signal?.addEventListener('abort', () => reject(init.signal!.reason));
|
||||||
|
});
|
||||||
|
}) as unknown as typeof globalThis.fetch;
|
||||||
|
return { fetch, urls };
|
||||||
|
}
|
||||||
|
|
||||||
|
test("'background' opens the identity without waiting on the server", async () => {
|
||||||
|
const net = blackHole();
|
||||||
|
const started = Date.now();
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://prekey.invalid',
|
||||||
|
address: 'alice',
|
||||||
|
autoReplenish: false,
|
||||||
|
registration: 'background',
|
||||||
|
requestTimeoutMs: 60_000,
|
||||||
|
fetch: net.fetch,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
expect(Date.now() - started).toBeLessThan(5_000);
|
||||||
|
expect(shade.myAddress).toBe('alice');
|
||||||
|
await new Promise((r) => setTimeout(r, 20));
|
||||||
|
expect(net.urls).toEqual(['https://prekey.invalid/v1/keys/register']);
|
||||||
|
} finally {
|
||||||
|
await shade.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("'await' gives up at the request deadline instead of hanging", async () => {
|
||||||
|
const net = blackHole();
|
||||||
|
const started = Date.now();
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://prekey.invalid',
|
||||||
|
address: 'bob',
|
||||||
|
autoReplenish: false,
|
||||||
|
requestTimeoutMs: 100,
|
||||||
|
fetch: net.fetch,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
expect(Date.now() - started).toBeLessThan(5_000);
|
||||||
|
expect(net.urls).toHaveLength(1);
|
||||||
|
} finally {
|
||||||
|
await shade.shutdown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a failed registration is retried until the server answers', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const fetch = (async () => {
|
||||||
|
calls += 1;
|
||||||
|
if (calls === 1) throw new TypeError('Unable to connect');
|
||||||
|
return new Response('{}', { status: 200 });
|
||||||
|
}) as unknown as typeof globalThis.fetch;
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://prekey.invalid',
|
||||||
|
address: 'carol',
|
||||||
|
autoReplenish: false,
|
||||||
|
fetch,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
// First retry is due 5 s after the failure.
|
||||||
|
await new Promise((r) => setTimeout(r, 5_300));
|
||||||
|
expect(calls).toBe(2);
|
||||||
|
} finally {
|
||||||
|
await shade.shutdown();
|
||||||
|
}
|
||||||
|
}, 10_000);
|
||||||
|
|
||||||
|
test('shutdown stops the retries', async () => {
|
||||||
|
let calls = 0;
|
||||||
|
const fetch = (async () => {
|
||||||
|
calls += 1;
|
||||||
|
throw new TypeError('Unable to connect');
|
||||||
|
}) as unknown as typeof globalThis.fetch;
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://prekey.invalid',
|
||||||
|
address: 'dave',
|
||||||
|
autoReplenish: false,
|
||||||
|
fetch,
|
||||||
|
});
|
||||||
|
await shade.shutdown();
|
||||||
|
await new Promise((r) => setTimeout(r, 5_300));
|
||||||
|
expect(calls).toBe(1);
|
||||||
|
}, 10_000);
|
||||||
|
|
||||||
|
test('nonsense settings are refused up front', async () => {
|
||||||
|
await expect(
|
||||||
|
createShade({ prekeyServer: 'https://x.invalid', requestTimeoutMs: 0 }),
|
||||||
|
).rejects.toThrow('requestTimeoutMs');
|
||||||
|
await expect(
|
||||||
|
createShade({ prekeyServer: 'https://x.invalid', registration: 'later' as never }),
|
||||||
|
).rejects.toThrow('registration');
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/server",
|
"name": "@shade/server",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-encrypted",
|
"name": "@shade/storage-encrypted",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-indexeddb",
|
"name": "@shade/storage-indexeddb",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-postgres",
|
"name": "@shade/storage-postgres",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-sqlite",
|
"name": "@shade/storage-sqlite",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { Database } from 'bun:sqlite';
|
import { Database } from 'bun:sqlite';
|
||||||
import type { VaultLogEntry, VaultStore } from '@shade/vault';
|
import type { VaultLogEntry, VaultPrunePlan, VaultPruneResult, VaultStore } from '@shade/vault';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SQLite-backed VaultStore for the V4.13 encrypted file store.
|
* SQLite-backed VaultStore for the V4.13 encrypted file store.
|
||||||
@@ -9,6 +9,13 @@ import type { VaultLogEntry, VaultStore } from '@shade/vault';
|
|||||||
* never decrypts anything — it enforces auth, verifies that an object's bytes
|
* never decrypts anything — it enforces auth, verifies that an object's bytes
|
||||||
* hash to its name, and refuses a commit whose objects are not all present.
|
* hash to its name, and refuses a commit whose objects are not all present.
|
||||||
*
|
*
|
||||||
|
* A fourth table, `shade_vault_refs`, records which objects each version
|
||||||
|
* references (the commit's signed hashes plus its manifest). The relay cannot
|
||||||
|
* read manifests, so this is what prune computes garbage from. Versions from
|
||||||
|
* before it existed have `refs_known = 0`, and every object that was in the
|
||||||
|
* database when the columns were added is `pinned` — see `VaultPrunePlan` for
|
||||||
|
* why that is the safe reading and how the pins are eventually released.
|
||||||
|
*
|
||||||
* Objects are stored as BLOBs rather than base64 text. A workspace backup is
|
* Objects are stored as BLOBs rather than base64 text. A workspace backup is
|
||||||
* a few hundred files where the blob primitive holds one small profile, so the
|
* a few hundred files where the blob primitive holds one small profile, so the
|
||||||
* 33% base64 overhead stops being a rounding error.
|
* 33% base64 overhead stops being a rounding error.
|
||||||
@@ -31,6 +38,8 @@ export class SqliteVaultStore implements VaultStore {
|
|||||||
log: ReturnType<Database['prepare']>;
|
log: ReturnType<Database['prepare']>;
|
||||||
logLimit: ReturnType<Database['prepare']>;
|
logLimit: ReturnType<Database['prepare']>;
|
||||||
appendLog: ReturnType<Database['prepare']>;
|
appendLog: ReturnType<Database['prepare']>;
|
||||||
|
appendRef: ReturnType<Database['prepare']>;
|
||||||
|
pinAll: ReturnType<Database['prepare']>;
|
||||||
usage: ReturnType<Database['prepare']>;
|
usage: ReturnType<Database['prepare']>;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -56,6 +65,7 @@ export class SqliteVaultStore implements VaultStore {
|
|||||||
bytes BLOB NOT NULL,
|
bytes BLOB NOT NULL,
|
||||||
size INTEGER NOT NULL,
|
size INTEGER NOT NULL,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
|
pinned INTEGER NOT NULL DEFAULT 0,
|
||||||
PRIMARY KEY (vault_id, hash)
|
PRIMARY KEY (vault_id, hash)
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -65,9 +75,38 @@ export class SqliteVaultStore implements VaultStore {
|
|||||||
manifest TEXT NOT NULL,
|
manifest TEXT NOT NULL,
|
||||||
at INTEGER NOT NULL,
|
at INTEGER NOT NULL,
|
||||||
bytes INTEGER NOT NULL,
|
bytes INTEGER NOT NULL,
|
||||||
|
refs_known INTEGER NOT NULL DEFAULT 1,
|
||||||
PRIMARY KEY (vault_id, seq)
|
PRIMARY KEY (vault_id, seq)
|
||||||
);
|
);
|
||||||
|
|
||||||
|
CREATE TABLE IF NOT EXISTS shade_vault_refs (
|
||||||
|
vault_id TEXT NOT NULL,
|
||||||
|
seq INTEGER NOT NULL,
|
||||||
|
hash TEXT NOT NULL,
|
||||||
|
PRIMARY KEY (vault_id, seq, hash)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS shade_vault_refs_by_hash ON shade_vault_refs (vault_id, hash);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
|
// Databases from before ref tracking. The defaults here are the whole
|
||||||
|
// migration: every existing log row becomes untracked (refs_known = 0),
|
||||||
|
// and every existing object pinned (pinned = 1), because any of them may
|
||||||
|
// be referenced by one of those rows. New rows always set both columns
|
||||||
|
// explicitly, so these defaults only ever apply to the old ones.
|
||||||
|
const has = (table: string, column: string): boolean =>
|
||||||
|
(this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some(
|
||||||
|
(c) => c.name === column,
|
||||||
|
);
|
||||||
|
this.db.transaction(() => {
|
||||||
|
if (!has('shade_vault_log', 'refs_known')) {
|
||||||
|
this.db.exec(
|
||||||
|
'ALTER TABLE shade_vault_log ADD COLUMN refs_known INTEGER NOT NULL DEFAULT 0',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!has('shade_vault_objects', 'pinned')) {
|
||||||
|
this.db.exec('ALTER TABLE shade_vault_objects ADD COLUMN pinned INTEGER NOT NULL DEFAULT 1');
|
||||||
|
}
|
||||||
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
private prepareStatements() {
|
private prepareStatements() {
|
||||||
@@ -82,7 +121,7 @@ export class SqliteVaultStore implements VaultStore {
|
|||||||
// An object's name IS its content hash, so a repeat upload is the same
|
// An object's name IS its content hash, so a repeat upload is the same
|
||||||
// bytes by definition — ignoring it is correct, not lossy.
|
// bytes by definition — ignoring it is correct, not lossy.
|
||||||
putObject: this.db.prepare(
|
putObject: this.db.prepare(
|
||||||
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at) VALUES (?, ?, ?, ?, ?)',
|
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at, pinned) VALUES (?, ?, ?, ?, ?, 0)',
|
||||||
),
|
),
|
||||||
getObject: this.db.prepare(
|
getObject: this.db.prepare(
|
||||||
'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||||
@@ -95,8 +134,12 @@ export class SqliteVaultStore implements VaultStore {
|
|||||||
'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC',
|
'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC',
|
||||||
),
|
),
|
||||||
appendLog: this.db.prepare(
|
appendLog: this.db.prepare(
|
||||||
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes) VALUES (?, ?, ?, ?, ?)',
|
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes, refs_known) VALUES (?, ?, ?, ?, ?, ?)',
|
||||||
),
|
),
|
||||||
|
appendRef: this.db.prepare(
|
||||||
|
'INSERT OR IGNORE INTO shade_vault_refs (vault_id, seq, hash) VALUES (?, ?, ?)',
|
||||||
|
),
|
||||||
|
pinAll: this.db.prepare('UPDATE shade_vault_objects SET pinned = 1 WHERE vault_id = ?'),
|
||||||
usage: this.db.prepare(
|
usage: this.db.prepare(
|
||||||
'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?',
|
'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?',
|
||||||
),
|
),
|
||||||
@@ -139,8 +182,100 @@ export class SqliteVaultStore implements VaultStore {
|
|||||||
return rows;
|
return rows;
|
||||||
}
|
}
|
||||||
|
|
||||||
async appendLog(vaultId: string, entry: VaultLogEntry): Promise<void> {
|
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||||
this.stmts.appendLog.run(vaultId, entry.seq, entry.manifest, entry.at, entry.bytes);
|
this.db.transaction(() => {
|
||||||
|
this.stmts.appendLog.run(
|
||||||
|
vaultId,
|
||||||
|
entry.seq,
|
||||||
|
entry.manifest,
|
||||||
|
entry.at,
|
||||||
|
entry.bytes,
|
||||||
|
refs ? 1 : 0,
|
||||||
|
);
|
||||||
|
if (refs) {
|
||||||
|
for (const h of refs) this.stmts.appendRef.run(vaultId, entry.seq, h);
|
||||||
|
} else {
|
||||||
|
// Untracked: it can reference anything stored so far, so pin all of it.
|
||||||
|
this.stmts.pinAll.run(vaultId);
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One transaction, so a commit cannot interleave between deciding what is
|
||||||
|
* garbage and deleting it. bun:sqlite is synchronous, and a write
|
||||||
|
* transaction holds the database lock for its whole duration.
|
||||||
|
*/
|
||||||
|
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
|
||||||
|
return this.db.transaction((): VaultPruneResult => {
|
||||||
|
const keep = new Set(plan.keep);
|
||||||
|
const rows = this.db
|
||||||
|
.prepare('SELECT seq, refs_known FROM shade_vault_log WHERE vault_id = ?')
|
||||||
|
.all(vaultId) as Array<{ seq: number; refs_known: number }>;
|
||||||
|
const removed = rows.filter((r) => r.seq <= plan.upTo && !keep.has(r.seq)).map((r) => r.seq);
|
||||||
|
const untrackedRemains = rows.some(
|
||||||
|
(r) => r.refs_known === 0 && !(r.seq <= plan.upTo && !keep.has(r.seq)),
|
||||||
|
);
|
||||||
|
|
||||||
|
// The removed seqs go into a temp table so every query below can say
|
||||||
|
// "the log as it will be" without string-building an IN list.
|
||||||
|
this.db.exec(
|
||||||
|
'CREATE TEMP TABLE IF NOT EXISTS shade_vault_prune_removed (seq INTEGER PRIMARY KEY)',
|
||||||
|
);
|
||||||
|
this.db.exec('DELETE FROM shade_vault_prune_removed');
|
||||||
|
const addRemoved = this.db.prepare('INSERT INTO shade_vault_prune_removed (seq) VALUES (?)');
|
||||||
|
for (const seq of removed) addRemoved.run(seq);
|
||||||
|
|
||||||
|
if (!untrackedRemains) {
|
||||||
|
// No version with an unknown reference set is left, so nothing can
|
||||||
|
// depend on a pin any more.
|
||||||
|
this.db.prepare('UPDATE shade_vault_objects SET pinned = 0 WHERE vault_id = ?').run(vaultId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Garbage: not pinned, not used by a remaining version, and — if no
|
||||||
|
// version ever used it — older than the grace for in-flight uploads.
|
||||||
|
const garbage = this.db
|
||||||
|
.prepare(
|
||||||
|
`SELECT o.hash AS hash, o.size AS size FROM shade_vault_objects o
|
||||||
|
WHERE o.vault_id = ?1
|
||||||
|
AND o.pinned = 0
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM shade_vault_refs r
|
||||||
|
WHERE r.vault_id = ?1 AND r.hash = o.hash
|
||||||
|
AND r.seq NOT IN (SELECT seq FROM shade_vault_prune_removed))
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1 FROM shade_vault_log l
|
||||||
|
WHERE l.vault_id = ?1 AND l.manifest = o.hash
|
||||||
|
AND l.seq NOT IN (SELECT seq FROM shade_vault_prune_removed))
|
||||||
|
AND (
|
||||||
|
o.created_at <= ?2
|
||||||
|
OR EXISTS (SELECT 1 FROM shade_vault_refs r WHERE r.vault_id = ?1 AND r.hash = o.hash)
|
||||||
|
OR EXISTS (SELECT 1 FROM shade_vault_log l WHERE l.vault_id = ?1 AND l.manifest = o.hash))`,
|
||||||
|
)
|
||||||
|
.all(vaultId, plan.protectSince) as Array<{ hash: string; size: number }>;
|
||||||
|
|
||||||
|
const delObject = this.db.prepare(
|
||||||
|
'DELETE FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||||
|
);
|
||||||
|
let freedBytes = 0;
|
||||||
|
for (const g of garbage) {
|
||||||
|
delObject.run(vaultId, g.hash);
|
||||||
|
freedBytes += g.size;
|
||||||
|
}
|
||||||
|
this.db
|
||||||
|
.prepare(
|
||||||
|
'DELETE FROM shade_vault_refs WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)',
|
||||||
|
)
|
||||||
|
.run(vaultId);
|
||||||
|
this.db
|
||||||
|
.prepare(
|
||||||
|
'DELETE FROM shade_vault_log WHERE vault_id = ? AND seq IN (SELECT seq FROM shade_vault_prune_removed)',
|
||||||
|
)
|
||||||
|
.run(vaultId);
|
||||||
|
this.db.exec('DELETE FROM shade_vault_prune_removed');
|
||||||
|
|
||||||
|
return { removedVersions: removed.length, removedObjects: garbage.length, freedBytes };
|
||||||
|
})();
|
||||||
}
|
}
|
||||||
|
|
||||||
async usage(vaultId: string): Promise<number> {
|
async usage(vaultId: string): Promise<number> {
|
||||||
|
|||||||
@@ -118,3 +118,134 @@ describe('semantics', () => {
|
|||||||
store.close();
|
store.close();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('prune', () => {
|
||||||
|
const h = (c: string) => c.repeat(64);
|
||||||
|
|
||||||
|
test('removes unkept versions and only the objects nothing else uses', async () => {
|
||||||
|
const store = new SqliteVaultStore(scratch('prune'));
|
||||||
|
await store.putObject(VAULT, h('1'), new Uint8Array(10)); // manifest 1
|
||||||
|
await store.putObject(VAULT, h('2'), new Uint8Array(20)); // manifest 2
|
||||||
|
await store.putObject(VAULT, h('a'), new Uint8Array(30)); // shared file
|
||||||
|
await store.putObject(VAULT, h('b'), new Uint8Array(40)); // only in v1
|
||||||
|
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1'), h('a'), h('b')]);
|
||||||
|
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2'), h('a')]);
|
||||||
|
|
||||||
|
const res = await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||||
|
expect(res).toEqual({ removedVersions: 1, removedObjects: 2, freedBytes: 50 });
|
||||||
|
expect(await store.hasObject(VAULT, h('a'))).toBe(true);
|
||||||
|
expect(await store.hasObject(VAULT, h('b'))).toBe(false);
|
||||||
|
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2]);
|
||||||
|
store.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a fresh, never-committed upload survives; a stale one does not', async () => {
|
||||||
|
const store = new SqliteVaultStore(scratch('grace'));
|
||||||
|
await store.putObject(VAULT, h('1'), new Uint8Array(1));
|
||||||
|
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }, [h('1')]);
|
||||||
|
await store.putObject(VAULT, h('c'), new Uint8Array(5));
|
||||||
|
|
||||||
|
const kept = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() - 60_000 });
|
||||||
|
expect(kept.removedObjects).toBe(0);
|
||||||
|
const gone = await store.prune(VAULT, { keep: [1], upTo: 1, protectSince: Date.now() + 1 });
|
||||||
|
expect(gone.removedObjects).toBe(1);
|
||||||
|
expect(await store.hasObject(VAULT, h('c'))).toBe(false);
|
||||||
|
store.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('never removes an entry above upTo, even when it is not in keep', async () => {
|
||||||
|
const store = new SqliteVaultStore(scratch('upto'));
|
||||||
|
for (let seq = 1; seq <= 3; seq++) {
|
||||||
|
await store.appendLog(VAULT, { seq, manifest: `${seq}`.repeat(64), at: seq, bytes: 0 }, []);
|
||||||
|
}
|
||||||
|
await store.prune(VAULT, { keep: [2], upTo: 2, protectSince: 0 });
|
||||||
|
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([2, 3]);
|
||||||
|
store.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('untracked entries pin what existed when they were appended, until they are gone', async () => {
|
||||||
|
const store = new SqliteVaultStore(scratch('pin'));
|
||||||
|
await store.putObject(VAULT, h('1'), new Uint8Array(1));
|
||||||
|
await store.putObject(VAULT, h('b'), new Uint8Array(1));
|
||||||
|
await store.appendLog(VAULT, { seq: 1, manifest: h('1'), at: 1, bytes: 0 }); // no refs
|
||||||
|
await store.putObject(VAULT, h('2'), new Uint8Array(1));
|
||||||
|
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]);
|
||||||
|
await store.putObject(VAULT, h('3'), new Uint8Array(1));
|
||||||
|
await store.appendLog(VAULT, { seq: 3, manifest: h('3'), at: 3, bytes: 0 }, [h('3')]);
|
||||||
|
|
||||||
|
const first = await store.prune(VAULT, { keep: [1, 3], upTo: 3, protectSince: Date.now() });
|
||||||
|
expect(first.removedObjects).toBe(1); // only manifest 2
|
||||||
|
expect(await store.hasObject(VAULT, h('b'))).toBe(true);
|
||||||
|
|
||||||
|
const second = await store.prune(VAULT, { keep: [3], upTo: 3, protectSince: Date.now() });
|
||||||
|
expect(second.removedObjects).toBe(2); // manifest 1 and b, unpinned
|
||||||
|
expect(await store.hasObject(VAULT, h('3'))).toBe(true);
|
||||||
|
store.close();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('a database from before ref tracking migrates with everything pinned', async () => {
|
||||||
|
// The exact pre-v2 schema, with a version and its objects in it.
|
||||||
|
const path = scratch('migrate');
|
||||||
|
const { Database } = await import('bun:sqlite');
|
||||||
|
const old = new Database(path, { create: true });
|
||||||
|
old.exec(`
|
||||||
|
CREATE TABLE shade_vault_objects (vault_id TEXT NOT NULL, hash TEXT NOT NULL, bytes BLOB NOT NULL,
|
||||||
|
size INTEGER NOT NULL, created_at INTEGER NOT NULL, PRIMARY KEY (vault_id, hash));
|
||||||
|
CREATE TABLE shade_vault_log (vault_id TEXT NOT NULL, seq INTEGER NOT NULL, manifest TEXT NOT NULL,
|
||||||
|
at INTEGER NOT NULL, bytes INTEGER NOT NULL, PRIMARY KEY (vault_id, seq));
|
||||||
|
`);
|
||||||
|
old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('1'), new Uint8Array(1), 1, 0);
|
||||||
|
old.prepare('INSERT INTO shade_vault_objects VALUES (?, ?, ?, ?, ?)').run(VAULT, h('a'), new Uint8Array(1), 1, 0);
|
||||||
|
old.prepare('INSERT INTO shade_vault_log VALUES (?, ?, ?, ?, ?)').run(VAULT, 1, h('1'), 1, 2);
|
||||||
|
old.close();
|
||||||
|
|
||||||
|
const store = new SqliteVaultStore(path);
|
||||||
|
// A tracked version on top, then drop nothing but nothing referenced by it:
|
||||||
|
// the old file object must survive because version 1 may use it.
|
||||||
|
await store.putObject(VAULT, h('2'), new Uint8Array(1));
|
||||||
|
await store.appendLog(VAULT, { seq: 2, manifest: h('2'), at: 2, bytes: 0 }, [h('2')]);
|
||||||
|
const res = await store.prune(VAULT, { keep: [1, 2], upTo: 2, protectSince: Date.now() });
|
||||||
|
expect(res.removedObjects).toBe(0);
|
||||||
|
expect(await store.hasObject(VAULT, h('a'))).toBe(true);
|
||||||
|
store.close();
|
||||||
|
|
||||||
|
// Reopening runs the migration check again and must be a no-op.
|
||||||
|
const again = new SqliteVaultStore(path);
|
||||||
|
expect((await again.log(VAULT)).map((e) => e.seq)).toEqual([1, 2]);
|
||||||
|
const final = await again.prune(VAULT, { keep: [2], upTo: 2, protectSince: Date.now() });
|
||||||
|
expect(final).toMatchObject({ removedVersions: 1, removedObjects: 2 });
|
||||||
|
again.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('through the real routes and client', () => {
|
||||||
|
test('v2 push, index reuse, multi-part and prune all work on SQLite', async () => {
|
||||||
|
const { SubtleCryptoProvider } = await import('@shade/crypto-web');
|
||||||
|
const { createVaultRoutes } = await import('@shade/vault/server');
|
||||||
|
const { HttpVaultTransport, VaultClient, deriveVaultKeys } = await import('@shade/vault');
|
||||||
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
const store = new SqliteVaultStore(scratch('e2e'));
|
||||||
|
const routes = createVaultRoutes(store, crypto, { pruneGraceMs: 0 });
|
||||||
|
const transport = new HttpVaultTransport('http://v', (i, init) => routes.fetch(new Request(i, init)));
|
||||||
|
const keys = await deriveVaultKeys(new Uint8Array(32).fill(5), 'scaffold');
|
||||||
|
const client = new VaultClient(crypto, keys, transport, { chunkSize: 512 });
|
||||||
|
|
||||||
|
const big = new Uint8Array(2000);
|
||||||
|
globalThis.crypto.getRandomValues(big);
|
||||||
|
const text = new TextEncoder().encode('linje\n'.repeat(500));
|
||||||
|
const first = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 1);
|
||||||
|
const same = await client.push([{ path: 'big.bin', bytes: big }, { path: 't.md', bytes: text }], 2, undefined, {
|
||||||
|
index: first.index,
|
||||||
|
});
|
||||||
|
expect(same.unchanged).toBe(true);
|
||||||
|
await client.push([{ path: 't.md', bytes: text }], 3, undefined, { index: same.index });
|
||||||
|
|
||||||
|
const pruned = await client.prune([2]);
|
||||||
|
expect(pruned.removedVersions).toBe(1);
|
||||||
|
expect(pruned.removedObjects).toBe(5); // big.bin's 4 parts + manifest 1
|
||||||
|
const { files } = await client.pull();
|
||||||
|
expect(files.get('t.md')).toEqual(text);
|
||||||
|
expect(files.has('big.bin')).toBe(false);
|
||||||
|
store.close();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/streams",
|
"name": "@shade/streams",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transfer",
|
"name": "@shade/transfer",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transport-bridge",
|
"name": "@shade/transport-bridge",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transport-webrtc",
|
"name": "@shade/transport-webrtc",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transport",
|
"name": "@shade/transport",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ import {
|
|||||||
KTVerificationError,
|
KTVerificationError,
|
||||||
} from '@shade/key-transparency';
|
} from '@shade/key-transparency';
|
||||||
|
|
||||||
|
/** How long any prekey-server request may go unanswered. */
|
||||||
|
export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HTTP transport client for the Shade Prekey Server.
|
* HTTP transport client for the Shade Prekey Server.
|
||||||
*
|
*
|
||||||
@@ -67,15 +70,31 @@ export class ShadeFetchTransport {
|
|||||||
private readonly crypto: CryptoProvider;
|
private readonly crypto: CryptoProvider;
|
||||||
private readonly signingPrivateKey?: Uint8Array;
|
private readonly signingPrivateKey?: Uint8Array;
|
||||||
private readonly kt?: KTVerifierOptions;
|
private readonly kt?: KTVerifierOptions;
|
||||||
|
private readonly fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
|
||||||
|
private readonly requestTimeoutMs: number;
|
||||||
|
|
||||||
constructor(options: {
|
constructor(options: {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
crypto: CryptoProvider;
|
crypto: CryptoProvider;
|
||||||
signingPrivateKey?: Uint8Array;
|
signingPrivateKey?: Uint8Array;
|
||||||
keyTransparency?: KTVerifierOptions;
|
keyTransparency?: KTVerifierOptions;
|
||||||
|
/**
|
||||||
|
* Fetch for every request. Lets an app observe its server's
|
||||||
|
* reachability, or tests stub the network. Default: global fetch.
|
||||||
|
*/
|
||||||
|
fetch?: typeof fetch;
|
||||||
|
/**
|
||||||
|
* A request with no response by then fails with a `NetworkError`.
|
||||||
|
* Default 15 000. Without it an unreachable server (packets dropped,
|
||||||
|
* not refused) held each call until the kernel gave up on the TCP
|
||||||
|
* handshake — about two minutes on Linux.
|
||||||
|
*/
|
||||||
|
requestTimeoutMs?: number;
|
||||||
}) {
|
}) {
|
||||||
this.baseUrl = options.baseUrl;
|
this.baseUrl = options.baseUrl;
|
||||||
this.crypto = options.crypto;
|
this.crypto = options.crypto;
|
||||||
|
this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
|
||||||
|
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||||
if (options.signingPrivateKey !== undefined) {
|
if (options.signingPrivateKey !== undefined) {
|
||||||
this.signingPrivateKey = options.signingPrivateKey;
|
this.signingPrivateKey = options.signingPrivateKey;
|
||||||
}
|
}
|
||||||
@@ -84,6 +103,22 @@ export class ShadeFetchTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every request goes through here, so every request has a deadline. */
|
||||||
|
private async request(url: string, init: RequestInit = {}): Promise<Response> {
|
||||||
|
const timeout = AbortSignal.timeout(this.requestTimeoutMs);
|
||||||
|
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
||||||
|
try {
|
||||||
|
return await this.fetchImpl(url, { ...init, signal });
|
||||||
|
} catch (err) {
|
||||||
|
if (timeout.aborted && !init.signal?.aborted) {
|
||||||
|
throw new NetworkError(
|
||||||
|
`No response from ${new URL(url).host} within ${this.requestTimeoutMs} ms`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private headers(): Record<string, string> {
|
private headers(): Record<string, string> {
|
||||||
return { 'Content-Type': 'application/json' };
|
return { 'Content-Type': 'application/json' };
|
||||||
}
|
}
|
||||||
@@ -133,7 +168,7 @@ export class ShadeFetchTransport {
|
|||||||
|
|
||||||
const signed = await this.sign(body);
|
const signed = await this.sign(body);
|
||||||
|
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/register`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/register`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
body: JSON.stringify(signed),
|
body: JSON.stringify(signed),
|
||||||
@@ -159,7 +194,7 @@ export class ShadeFetchTransport {
|
|||||||
* direct access to the proof side-channel.
|
* direct access to the proof side-channel.
|
||||||
*/
|
*/
|
||||||
async fetchBundleVerified(address: string): Promise<FetchBundleResult> {
|
async fetchBundleVerified(address: string): Promise<FetchBundleResult> {
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -283,7 +318,7 @@ export class ShadeFetchTransport {
|
|||||||
};
|
};
|
||||||
const signed = await this.sign(body);
|
const signed = await this.sign(body);
|
||||||
|
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/replenish`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/replenish`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
body: JSON.stringify(signed),
|
body: JSON.stringify(signed),
|
||||||
@@ -295,7 +330,7 @@ export class ShadeFetchTransport {
|
|||||||
|
|
||||||
/** Get remaining one-time prekey count (anonymous) */
|
/** Get remaining one-time prekey count (anonymous) */
|
||||||
async getKeyCount(address: string): Promise<number> {
|
async getKeyCount(address: string): Promise<number> {
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
|
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
|
||||||
@@ -306,7 +341,7 @@ export class ShadeFetchTransport {
|
|||||||
/** Delete all keys for this identity (signed) */
|
/** Delete all keys for this identity (signed) */
|
||||||
async unregister(address: string): Promise<void> {
|
async unregister(address: string): Promise<void> {
|
||||||
const signed = await this.sign({ address });
|
const signed = await this.sign({ address });
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
body: JSON.stringify(signed),
|
body: JSON.stringify(signed),
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
export { ShadeFetchTransport } from './fetch-transport.js';
|
export { ShadeFetchTransport, DEFAULT_REQUEST_TIMEOUT_MS } from './fetch-transport.js';
|
||||||
export type { FetchBundleResult, KTVerifierOptions } from './fetch-transport.js';
|
export type { FetchBundleResult, KTVerifierOptions } from './fetch-transport.js';
|
||||||
export { ShadeWebSocket } from './ws-adapter.js';
|
export { ShadeWebSocket } from './ws-adapter.js';
|
||||||
|
|||||||
@@ -82,3 +82,44 @@ describe('ShadeFetchTransport', () => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A server that drops packets instead of refusing them used to hold every
|
||||||
|
* call until the kernel gave up on the TCP handshake — two minutes on
|
||||||
|
* Linux. Every request now has a deadline.
|
||||||
|
*/
|
||||||
|
describe('ShadeFetchTransport request deadline', () => {
|
||||||
|
/** A fetch that never answers, but honours abort like the real one. */
|
||||||
|
const blackHole = ((_url: unknown, init?: RequestInit) =>
|
||||||
|
new Promise<Response>((_resolve, reject) => {
|
||||||
|
init?.signal?.addEventListener('abort', () => reject(init.signal!.reason));
|
||||||
|
})) as unknown as typeof fetch;
|
||||||
|
|
||||||
|
test('a request nobody answers fails with a NetworkError at the deadline', async () => {
|
||||||
|
const transport = new ShadeFetchTransport({
|
||||||
|
baseUrl: 'https://prekey.invalid',
|
||||||
|
crypto,
|
||||||
|
fetch: blackHole,
|
||||||
|
requestTimeoutMs: 50,
|
||||||
|
});
|
||||||
|
const started = Date.now();
|
||||||
|
const err = await transport.getKeyCount('bob').catch((e) => e);
|
||||||
|
expect(err.name).toBe('NetworkError');
|
||||||
|
expect(err.message).toContain('No response from prekey.invalid within 50 ms');
|
||||||
|
expect(Date.now() - started).toBeLessThan(2_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('every request goes through the supplied fetch', async () => {
|
||||||
|
const urls: string[] = [];
|
||||||
|
const transport = new ShadeFetchTransport({
|
||||||
|
baseUrl: 'https://prekey.invalid',
|
||||||
|
crypto,
|
||||||
|
fetch: (async (url: string) => {
|
||||||
|
urls.push(url);
|
||||||
|
return new Response(JSON.stringify({ count: 7 }), { status: 200 });
|
||||||
|
}) as unknown as typeof fetch,
|
||||||
|
});
|
||||||
|
expect(await transport.getKeyCount('bob')).toBe(7);
|
||||||
|
expect(urls).toEqual(['https://prekey.invalid/v1/keys/count/bob']);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,13 +1,14 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/vault",
|
"name": "@shade/vault",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"description": "Server-side encrypted file store for Shade — content-addressed objects with an append-only manifest log",
|
"description": "Server-side encrypted file store for Shade — content-addressed objects with an append-only manifest log",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
"exports": {
|
"exports": {
|
||||||
".": "./src/index.ts",
|
".": "./src/index.ts",
|
||||||
"./server": "./src/server.ts"
|
"./server": "./src/server.ts",
|
||||||
|
"./testing": "./src/testing.ts"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
|
|||||||
@@ -2,10 +2,12 @@
|
|||||||
* The client half: turn a set of files into an encrypted, versioned vault,
|
* 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.
|
* 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
|
* A workspace changes a few lines at a time, so a push has to cost what
|
||||||
* at a time, so asking "do you already have these hashes?" and uploading only
|
* changed, not what exists. Everything unchanged keeps the entry — and so the
|
||||||
* the misses turns a full backup into a handful of small writes. Everything
|
* objects — it had in the previous version, and costs nothing. Recognising
|
||||||
* unchanged keeps its hash from the previous commit and costs nothing.
|
* "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';
|
import type { CryptoProvider } from '@shade/core';
|
||||||
@@ -19,8 +21,24 @@ import {
|
|||||||
deriveVaultId,
|
deriveVaultId,
|
||||||
deriveVaultSigningSeed,
|
deriveVaultSigningSeed,
|
||||||
} from '@shade/storage-encrypted';
|
} from '@shade/storage-encrypted';
|
||||||
import { openManifest, openObject, sealManifest, sealObject, toHex } from './crypto.js';
|
import { sha256 } from '@noble/hashes/sha2.js';
|
||||||
import type { VaultEntry, VaultLog, VaultManifest } from './types.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. */
|
/** A file as the app sees it, before encryption. */
|
||||||
export interface VaultFile {
|
export interface VaultFile {
|
||||||
@@ -61,15 +79,37 @@ export interface VaultTransport {
|
|||||||
get(vaultId: string, hash: string): Promise<Uint8Array>;
|
get(vaultId: string, hash: string): Promise<Uint8Array>;
|
||||||
log(vaultId: string, limit?: number): Promise<VaultLog>;
|
log(vaultId: string, limit?: number): Promise<VaultLog>;
|
||||||
commit(vaultId: string, body: unknown): Promise<{ seq: number }>;
|
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 {
|
export interface PushResult {
|
||||||
|
/** The version now at the head — the new one, or the old one if `unchanged`. */
|
||||||
seq: number;
|
seq: number;
|
||||||
/** Objects actually sent — the rest were already on the relay. */
|
/** Data objects sent (the manifest is not counted). */
|
||||||
uploaded: number;
|
uploaded: number;
|
||||||
/** Objects skipped because the relay had them. */
|
/** Files whose previous entry was reused without sealing anything. */
|
||||||
reused: number;
|
reused: number;
|
||||||
bytesUploaded: 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 {
|
export class VaultClient {
|
||||||
@@ -77,6 +117,7 @@ export class VaultClient {
|
|||||||
private readonly crypto: CryptoProvider,
|
private readonly crypto: CryptoProvider,
|
||||||
private readonly keys: VaultKeys,
|
private readonly keys: VaultKeys,
|
||||||
private readonly transport: VaultTransport,
|
private readonly transport: VaultTransport,
|
||||||
|
private readonly options: VaultClientOptions = {},
|
||||||
) {}
|
) {}
|
||||||
|
|
||||||
get vaultId(): string {
|
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
|
* `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
|
* commit reproducible in tests, and so a queued backup records when it was
|
||||||
* *taken* rather than when it finally reached the relay.
|
* *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> {
|
async push(
|
||||||
const { head } = await this.transport.log(this.keys.vaultId, 1);
|
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 entries: VaultEntry[] = [];
|
||||||
|
const indexEntries: Record<string, VaultIndexEntry> = {};
|
||||||
let uploaded = 0;
|
let uploaded = 0;
|
||||||
let reused = 0;
|
let reused = 0;
|
||||||
let bytesUploaded = 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) {
|
for (const file of files) {
|
||||||
const prior = byPath.get(file.path);
|
const digest = toHex(sha256(file.bytes));
|
||||||
const priorBytes = priorPlain.get(file.path);
|
let prior = byHash.get(digest);
|
||||||
if (prior && priorBytes && sameBytes(priorBytes, file.bytes)) {
|
if (!prior) {
|
||||||
entries.push({ ...prior, size: file.bytes.length });
|
const candidate = byPath.get(file.path);
|
||||||
reused++;
|
if (candidate && candidate.size === file.bytes.length) {
|
||||||
continue;
|
const old = await this.readEntry(candidate).catch(() => null);
|
||||||
|
if (old && sameBytes(old, file.bytes)) prior = candidate;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const sealed = await sealObject(
|
let entry: VaultEntry;
|
||||||
|
if (prior) {
|
||||||
|
entry = { ...prior, path: file.path, size: file.bytes.length };
|
||||||
|
reused++;
|
||||||
|
} else {
|
||||||
|
const sealed = await sealEntry(
|
||||||
this.crypto,
|
this.crypto,
|
||||||
this.keys.contentKey,
|
this.keys.contentKey,
|
||||||
this.keys.vaultId,
|
this.keys.vaultId,
|
||||||
file.bytes,
|
file.bytes,
|
||||||
|
this.options.chunkSize === undefined ? {} : { chunkSize: this.options.chunkSize },
|
||||||
);
|
);
|
||||||
if (!(await this.transport.has(this.keys.vaultId, sealed.hash))) {
|
// 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(
|
await this.transport.put(
|
||||||
this.keys.vaultId,
|
this.keys.vaultId,
|
||||||
sealed.hash,
|
obj.hash,
|
||||||
await this.sign({ data: toBase64(sealed.bytes) }),
|
await this.sign({ data: toBase64(obj.bytes) }),
|
||||||
);
|
);
|
||||||
uploaded++;
|
uploaded++;
|
||||||
bytesUploaded += sealed.bytes.length;
|
bytesUploaded += obj.bytes.length;
|
||||||
} else {
|
|
||||||
reused++;
|
|
||||||
}
|
}
|
||||||
const entry: VaultEntry = { path: file.path, hash: sealed.hash, size: file.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);
|
||||||
|
}
|
||||||
|
// 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;
|
if (file.mode !== undefined) entry.mode = file.mode;
|
||||||
|
|
||||||
entries.push(entry);
|
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;
|
if (message !== undefined) manifest.message = message;
|
||||||
|
|
||||||
const sealedManifest = await sealManifest(
|
const sealedManifest = await sealManifest(
|
||||||
@@ -166,58 +275,142 @@ export class VaultClient {
|
|||||||
await this.sign({ data: toBase64(sealedManifest.bytes) }),
|
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(
|
const { seq } = await this.transport.commit(
|
||||||
this.keys.vaultId,
|
this.keys.vaultId,
|
||||||
await this.sign({
|
await this.sign({
|
||||||
manifest: sealedManifest.hash,
|
manifest: sealedManifest.hash,
|
||||||
seq: manifest.seq,
|
seq: manifest.seq,
|
||||||
at,
|
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
|
* The cheap way to answer "what is in the backup?" — a file browser lists a
|
||||||
* files rather than a handle: a caller that has to make a second round of
|
* thousand-file workspace with one download, then `readEntry`s what the
|
||||||
* decisions to get their data back does not have a backup.
|
* user actually opens.
|
||||||
*/
|
*/
|
||||||
async pull(seq?: number): Promise<{ manifest: VaultManifest; files: Map<string, Uint8Array> }> {
|
async manifest(seq?: number): Promise<VaultManifest> {
|
||||||
const log = await this.transport.log(this.keys.vaultId);
|
// 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 wanted = seq ?? log.head;
|
||||||
const row = log.entries.find((e) => e.seq === wanted);
|
const row = log.entries.find((e) => e.seq === wanted);
|
||||||
if (!row) throw new Error(`vault has no version ${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 };
|
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. */
|
/** Version history, newest last. */
|
||||||
async history(limit?: number): Promise<VaultLog> {
|
async history(limit?: number): Promise<VaultLog> {
|
||||||
return this.transport.log(this.keys.vaultId, limit);
|
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 {
|
function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
|
||||||
if (a.length !== b.length) return false;
|
if (a.length !== b.length) return false;
|
||||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) 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 { sha256 } from '@noble/hashes/sha2.js';
|
||||||
import type { CryptoProvider } from '@shade/core';
|
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 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. */
|
/** Lowercase hex SHA-256 — the name of an object. */
|
||||||
export function objectHash(sealed: Uint8Array): string {
|
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
|
* being sealed, so it cannot be known before sealing, and the relay's own
|
||||||
* hash check already covers substitution.
|
* 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}`);
|
return new TextEncoder().encode(`shade-vault-object-v1|${vaultId}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,7 +80,7 @@ export async function sealObject(
|
|||||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(
|
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(
|
||||||
contentKey,
|
contentKey,
|
||||||
plaintext,
|
plaintext,
|
||||||
objectAad(vaultId),
|
vaultObjectAad(vaultId),
|
||||||
);
|
);
|
||||||
const bytes = new Uint8Array(NONCE_LEN + ciphertext.length);
|
const bytes = new Uint8Array(NONCE_LEN + ciphertext.length);
|
||||||
bytes.set(nonce, 0);
|
bytes.set(nonce, 0);
|
||||||
@@ -77,7 +102,7 @@ export async function openObject(
|
|||||||
expectedHash: string,
|
expectedHash: string,
|
||||||
bytes: Uint8Array,
|
bytes: Uint8Array,
|
||||||
): Promise<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');
|
throw new Error('vault object too short to be a sealed object');
|
||||||
}
|
}
|
||||||
const actual = objectHash(bytes);
|
const actual = objectHash(bytes);
|
||||||
@@ -88,19 +113,301 @@ export async function openObject(
|
|||||||
contentKey,
|
contentKey,
|
||||||
bytes.subarray(NONCE_LEN),
|
bytes.subarray(NONCE_LEN),
|
||||||
bytes.subarray(0, 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(
|
export async function sealManifest(
|
||||||
crypto: CryptoProvider,
|
crypto: CryptoProvider,
|
||||||
contentKey: Uint8Array,
|
contentKey: Uint8Array,
|
||||||
vaultId: string,
|
vaultId: string,
|
||||||
manifest: VaultManifest,
|
manifest: VaultManifest,
|
||||||
): Promise<SealedObject> {
|
): Promise<SealedObject> {
|
||||||
const json = new TextEncoder().encode(JSON.stringify(manifest));
|
return sealObject(crypto, contentKey, vaultId, await encodeManifest(manifest));
|
||||||
return sealObject(crypto, contentKey, vaultId, json);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function openManifest(
|
export async function openManifest(
|
||||||
@@ -110,15 +417,18 @@ export async function openManifest(
|
|||||||
expectedHash: string,
|
expectedHash: string,
|
||||||
bytes: Uint8Array,
|
bytes: Uint8Array,
|
||||||
): Promise<VaultManifest> {
|
): Promise<VaultManifest> {
|
||||||
const plain = await openObject(crypto, contentKey, vaultId, expectedHash, bytes);
|
return decodeManifest(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
|
function concatBytes(chunks: Uint8Array[], total: number): Uint8Array {
|
||||||
// cannot represent, and silently dropping it would lose data on the next
|
if (chunks.length === 1 && chunks[0]!.length === total) return chunks[0]!;
|
||||||
// commit made from this client.
|
const out = new Uint8Array(total);
|
||||||
throw new Error(`unsupported vault manifest version: ${parsed.version}`);
|
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. */
|
/** Lowercase hex of arbitrary bytes — used for vaultId and pubkeys on the wire. */
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
import { fromBase64 } from '@shade/core';
|
import { fromBase64 } from '@shade/core';
|
||||||
import type { VaultTransport } from './client.js';
|
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>;
|
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');
|
if (!res.ok) return this.fail(res, 'commit');
|
||||||
return (await res.json()) as { seq: number };
|
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 };
|
export { fromBase64 };
|
||||||
|
|||||||
@@ -2,5 +2,5 @@ export * from './types.js';
|
|||||||
export * from './crypto.js';
|
export * from './crypto.js';
|
||||||
export * from './client.js';
|
export * from './client.js';
|
||||||
export { MemoryVaultStore } from './store.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';
|
export { HttpVaultTransport } from './http-transport.js';
|
||||||
|
|||||||
@@ -6,6 +6,8 @@
|
|||||||
* HEAD /v1/vault/:vaultId/object/:hash → 200 | 404 (have-check)
|
* HEAD /v1/vault/:vaultId/object/:hash → 200 | 404 (have-check)
|
||||||
* PUT /v1/vault/:vaultId/object/:hash → { stored } (signed)
|
* PUT /v1/vault/:vaultId/object/:hash → { stored } (signed)
|
||||||
* POST /v1/vault/:vaultId/commit → { seq } (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
|
* 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
|
* signed write pins a pubkey for the vault, and every later write must be
|
||||||
@@ -30,10 +32,19 @@ export interface VaultRoutesOptions {
|
|||||||
maxObjectBytes?: number;
|
maxObjectBytes?: number;
|
||||||
/** Whole-vault ceiling. Defaults to 512 MiB. */
|
/** Whole-vault ceiling. Defaults to 512 MiB. */
|
||||||
maxVaultBytes?: number;
|
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_OBJECT = 8 * 1024 * 1024;
|
||||||
const DEFAULT_MAX_VAULT = 512 * 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) {
|
function fail(code: string, message: string, status: ContentfulStatusCode) {
|
||||||
return { body: { error: { code, message } }, status };
|
return { body: { error: { code, message } }, status };
|
||||||
@@ -47,6 +58,7 @@ export function createVaultRoutes(
|
|||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
const maxObject = options.maxObjectBytes ?? DEFAULT_MAX_OBJECT;
|
const maxObject = options.maxObjectBytes ?? DEFAULT_MAX_OBJECT;
|
||||||
const maxVault = options.maxVaultBytes ?? DEFAULT_MAX_VAULT;
|
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
|
* 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);
|
return c.json({ ...f.body, missing: missing.slice(0, 20) }, f.status);
|
||||||
}
|
}
|
||||||
|
|
||||||
await store.appendLog(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,
|
seq: body.seq,
|
||||||
manifest: body.manifest,
|
manifest: body.manifest,
|
||||||
at: typeof body.at === 'number' ? body.at : Date.now(),
|
at: typeof body.at === 'number' ? body.at : Date.now(),
|
||||||
bytes: await store.usage(vaultId),
|
bytes: await store.usage(vaultId),
|
||||||
});
|
},
|
||||||
|
refs,
|
||||||
|
);
|
||||||
|
|
||||||
return c.json({ seq: body.seq, head: body.seq });
|
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;
|
return app;
|
||||||
}
|
}
|
||||||
|
|
||||||
export type { VaultStore } from './store.js';
|
export type { VaultStore, VaultPrunePlan } from './store.js';
|
||||||
export { MemoryVaultStore } from './store.js';
|
export { MemoryVaultStore } from './store.js';
|
||||||
export type { VaultManifest };
|
export type { VaultManifest };
|
||||||
|
|||||||
@@ -6,7 +6,42 @@
|
|||||||
* what makes a SQLite, Postgres or object-store implementation equivalent.
|
* 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 {
|
export interface VaultStore {
|
||||||
/** Ed25519 pubkey pinned on first write (TOFU), or null for a fresh vault. */
|
/** 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>;
|
head(vaultId: string): Promise<number>;
|
||||||
/** Newest last. `limit` counts back from the head. */
|
/** Newest last. `limit` counts back from the head. */
|
||||||
log(vaultId: string, limit?: number): Promise<VaultLogEntry[]>;
|
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. */
|
/** Total stored bytes, for quota decisions. */
|
||||||
usage(vaultId: string): Promise<number>;
|
usage(vaultId: string): Promise<number>;
|
||||||
@@ -36,6 +83,12 @@ export class MemoryVaultStore implements VaultStore {
|
|||||||
private owners = new Map<string, Uint8Array>();
|
private owners = new Map<string, Uint8Array>();
|
||||||
private objects = new Map<string, Map<string, Uint8Array>>();
|
private objects = new Map<string, Map<string, Uint8Array>>();
|
||||||
private logs = new Map<string, VaultLogEntry[]>();
|
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> {
|
async getOwner(vaultId: string): Promise<Uint8Array | null> {
|
||||||
return this.owners.get(vaultId) ?? 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> {
|
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> {
|
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));
|
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) ?? [];
|
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);
|
l.push(entry);
|
||||||
this.logs.set(vaultId, l);
|
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> {
|
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.
|
* 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 {
|
export interface VaultEntry {
|
||||||
/** Path within the collection, as the app understands it. */
|
/** Path within the collection, as the app understands it. */
|
||||||
path: string;
|
path: string;
|
||||||
/** Lowercase hex SHA-256 of the ciphertext object. */
|
/** Lowercase hex SHA-256 of the (first) ciphertext object. */
|
||||||
hash: string;
|
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;
|
size: number;
|
||||||
/** Optional app-defined mode/metadata, opaque to the vault. */
|
/** Optional app-defined mode/metadata, opaque to the vault. */
|
||||||
mode?: string;
|
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. */
|
/** The full contents of a collection at one point in time. */
|
||||||
export interface VaultManifest {
|
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. */
|
/** Monotonic, assigned by the client and checked by the relay. */
|
||||||
seq: number;
|
seq: number;
|
||||||
/** Epoch millis when the commit was made. */
|
/** Epoch millis when the commit was made. */
|
||||||
@@ -64,6 +92,48 @@ export interface VaultLog {
|
|||||||
head: number;
|
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.
|
* Error codes clients branch on.
|
||||||
*
|
*
|
||||||
|
|||||||
662
packages/shade-vault/tests/vault-v2.test.ts
Normal file
662
packages/shade-vault/tests/vault-v2.test.ts
Normal 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]);
|
||||||
|
});
|
||||||
|
});
|
||||||
100
packages/shade-vault/tests/vectors.test.ts
Normal file
100
packages/shade-vault/tests/vectors.test.ts
Normal 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);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/widgets",
|
"name": "@shade/widgets",
|
||||||
"version": "4.13.1",
|
"version": "4.14.0",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -9,7 +9,9 @@
|
|||||||
* Bump `VECTOR_FILE_VERSION` whenever the vector schema (NOT just values)
|
* Bump `VECTOR_FILE_VERSION` whenever the vector schema (NOT just values)
|
||||||
* changes, so downstream consumers can fail loudly on mismatch.
|
* 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 { writeFileSync } from 'fs';
|
||||||
import { join } from 'path';
|
import { join } from 'path';
|
||||||
@@ -38,6 +40,18 @@ import {
|
|||||||
buildApprovalRequest,
|
buildApprovalRequest,
|
||||||
type ApprovalRequestFrame,
|
type ApprovalRequestFrame,
|
||||||
} from '../packages/shade-sdk/src/index.js';
|
} 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;
|
const VECTOR_FILE_VERSION = 2;
|
||||||
|
|
||||||
@@ -821,6 +835,146 @@ async function generateApprovalVectors(): Promise<Vector[]> {
|
|||||||
return [...payloads, e2e];
|
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() {
|
async function main() {
|
||||||
console.log('Generating cross-platform test vectors…');
|
console.log('Generating cross-platform test vectors…');
|
||||||
|
|
||||||
@@ -837,9 +991,12 @@ async function main() {
|
|||||||
['storage-hkdf.json', { vectors: await generateStorageEncryptionSubset() }],
|
['storage-hkdf.json', { vectors: await generateStorageEncryptionSubset() }],
|
||||||
['blob.json', { vectors: await generateBlobVectors() }],
|
['blob.json', { vectors: await generateBlobVectors() }],
|
||||||
['approval.json', { vectors: await generateApprovalVectors() }],
|
['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) {
|
for (const [name, data] of files) {
|
||||||
|
if (only.size > 0 && !only.has(name)) continue;
|
||||||
const path = join(OUT_DIR, name);
|
const path = join(OUT_DIR, name);
|
||||||
const versioned = { version: VECTOR_FILE_VERSION, ...data };
|
const versioned = { version: VECTOR_FILE_VERSION, ...data };
|
||||||
writeFileSync(path, JSON.stringify(versioned, null, 2) + '\n');
|
writeFileSync(path, JSON.stringify(versioned, null, 2) + '\n');
|
||||||
|
|||||||
227
test-vectors/vault-v2.json
Normal file
227
test-vectors/vault-v2.json
Normal file
@@ -0,0 +1,227 @@
|
|||||||
|
{
|
||||||
|
"version": 2,
|
||||||
|
"vectors": [
|
||||||
|
{
|
||||||
|
"description": "vault-v2 keys: vaultId/contentKey/signingSeed = HKDF branches of masterKey for app; publicKey = Ed25519(signingSeed)",
|
||||||
|
"masterKey": "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20",
|
||||||
|
"app": "scaffold",
|
||||||
|
"vaultId": "9360b12394a010ecfa677dfc38941a00c43ebb22e79a681f76d928285de52dc2",
|
||||||
|
"contentKey": "a5990e3c71b6c11902b0f05afe65d2a1476222026a5ff5a897a670af92629d8e",
|
||||||
|
"signingSeed": "718e842f89c926369c0d2cc9f05b5f40f8bafe30599747b1d1de67fb5ffbca4b",
|
||||||
|
"publicKey": "60666a9e492ce5808d5ce3e2c409d5d374bc540f5546ac54da78acd186959117",
|
||||||
|
"objectAad": "73686164652d7661756c742d6f626a6563742d76317c39333630623132333934613031306563666136373764666333383934316130306334336562623232653739613638316637366439323832383564653532646332",
|
||||||
|
"objectAadUtf8": "shade-vault-object-v1|9360b12394a010ecfa677dfc38941a00c43ebb22e79a681f76d928285de52dc2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 entry: small text, compressed, one part",
|
||||||
|
"chunkSize": 4194304,
|
||||||
|
"plaintext": "2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a2320506c616e0a0a2323204ec3a50a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f650a2d205b205d206e6f6520616e6e65740a",
|
||||||
|
"stored": "535608c849cce3e2525656f03bbc944b57215a2156212f3f153f4b21312f2fb5844b79686a0600",
|
||||||
|
"enc": "deflate-raw",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"nonce": "101112131415161718191a1b",
|
||||||
|
"plaintext": "535608c849cce3e2525656f03bbc944b57215a2156212f3f153f4b21312f2fb5844b79686a0600",
|
||||||
|
"wire": "101112131415161718191a1b3df181a4021d0d030b94331430d5e4a11b55bbf4164312f6280db7db72629e5183b7bd473ac4d8c7b6ed2edc7b18a6e6c11c5c340906e4",
|
||||||
|
"hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"entry": {
|
||||||
|
"path": ".scaffold/plan.md",
|
||||||
|
"hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480",
|
||||||
|
"enc": "deflate-raw",
|
||||||
|
"size": 244
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 entry: multi-part (chunkSize 32), compressed — concatenate parts, then inflate",
|
||||||
|
"chunkSize": 32,
|
||||||
|
"plaintext": "6c696e6a6520303a20300a6c696e6a6520313a203931390a6c696e6a6520323a203833380a6c696e6a6520333a203735370a6c696e6a6520343a203637360a6c696e6a6520353a203539350a6c696e6a6520363a203531340a6c696e6a6520373a203433330a6c696e6a6520383a203335320a6c696e6a6520393a203237310a6c696e6a652031303a203139300a6c696e6a652031313a203130390a6c696e6a652031323a2032380a6c696e6a652031333a203934370a6c696e6a652031343a203836360a6c696e6a652031353a203738350a6c696e6a652031363a203730340a6c696e6a652031373a203632330a6c696e6a652031383a203534320a6c696e6a652031393a203436310a6c696e6a652032303a203338300a6c696e6a652032313a203239390a6c696e6a652032323a203231380a6c696e6a652032333a203133370a6c696e6a652032343a2035360a6c696e6a652032353a203937350a6c696e6a652032363a203839340a6c696e6a652032373a203831330a6c696e6a652032383a203733320a6c696e6a652032393a203635310a6c696e6a652033303a203537300a6c696e6a652033313a203438390a6c696e6a652033323a203430380a6c696e6a652033333a203332370a6c696e6a652033343a203234360a6c696e6a652033353a203136350a6c696e6a652033363a2038340a6c696e6a652033373a20330a6c696e6a652033383a203932320a6c696e6a652033393a203834310a",
|
||||||
|
"stored": "3dd1316e84310884d17e4f314730600ccc7d52245ae5fe65f4479eedfc49483ce1f7f7efcf1716b15eefffa7116373c3898ebe114465ddd8c4a97323899cbc7188b47da3881d71a38948bf31849769e9226c3e04236cc9604eb80c16c46c216c137da4b024aac5b043d492c38a382e8835915b121b621f517c11d1a2b8113e9f733c1493c583b090c53791a2781253a2f8217a44f122da44f1262a44f1214e8a128bc812258cd82d4a38b1d7e76b8208172536e15b9648c28e2cf158448922048926c6058979c6ecf507",
|
||||||
|
"enc": "deflate-raw",
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"nonce": "202122232425262728292a2b",
|
||||||
|
"plaintext": "3dd1316e84310884d17e4f314730600ccc7d52245ae5fe65f4479eedfc49483c",
|
||||||
|
"wire": "202122232425262728292a2b0e79d38efa3cc03de999a559f68f49e2dc720f2b54641279bf38c56fbb5657b7006f03b9ac641e01a39c9c300b6727bc",
|
||||||
|
"hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nonce": "2122232425262728292a2b2c",
|
||||||
|
"plaintext": "e1f7f7efcf1716b15eefffa7116373c3898ebe114465ddd8c4a97323899cbc71",
|
||||||
|
"wire": "2122232425262728292a2b2c8e0fc4531fc8900f2cf5e44a0ca9d99ae969c571754f1fcb8ea3682976ab70a4da805b0ebbec3b183a6187688b283599",
|
||||||
|
"hash": "dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nonce": "22232425262728292a2b2c2d",
|
||||||
|
"plaintext": "88b47da3881d71a38948bf31849769e9226c3e04236cc9604eb80c16c46c216c",
|
||||||
|
"wire": "22232425262728292a2b2c2dca0d1c8465b46b1edc12987c6288d4df1327df36c40d998240b918dd99e4a1633179bc85a965eb2fc2923c6623b11a64",
|
||||||
|
"hash": "1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nonce": "232425262728292a2b2c2d2e",
|
||||||
|
"plaintext": "137da4b024aac5b043d492c38a382e8835915b121b621f517c11d1a2b8113e9f",
|
||||||
|
"wire": "232425262728292a2b2c2d2eb6ad5e0146a9cd45e063c0d6a0706a8ef94ae7dc57222ec73a49de99cabe4b47ad115ba42b0d88d520b3ec4cfe6ce107",
|
||||||
|
"hash": "1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nonce": "2425262728292a2b2c2d2e2f",
|
||||||
|
"plaintext": "733c1493c583b090c53791a2781253a2f8217a44f122da44f1262a44f1214e8a",
|
||||||
|
"wire": "2425262728292a2b2c2d2e2fd929c8f629fc833859bc2f6516434460e22fe68efb36823c7fcd67744d90253c7d9d8276663308a283256c0553bbc893",
|
||||||
|
"hash": "5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nonce": "25262728292a2b2c2d2e2f30",
|
||||||
|
"plaintext": "128bc812258cd82d4a38b1d7e76b8208172536e15b9648c28e2cf15844892204",
|
||||||
|
"wire": "25262728292a2b2c2d2e2f300feb2c185b6c0d9c9b7c53c8b4667e470524922fb75bf5a86849b848fa6d6c616f3909067dda152d8f7c2a0078de3ed6",
|
||||||
|
"hash": "46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"nonce": "262728292a2b2c2d2e2f3031",
|
||||||
|
"plaintext": "8926c6058979c6ecf507",
|
||||||
|
"wire": "262728292a2b2c2d2e2f3031dd501f12336af9813a6b845aa252e8bb446f9eff169d0db9d476",
|
||||||
|
"hash": "2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"entry": {
|
||||||
|
"path": "logs/2026-10-16.md",
|
||||||
|
"hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||||
|
"parts": [
|
||||||
|
"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||||
|
"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1",
|
||||||
|
"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5",
|
||||||
|
"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f",
|
||||||
|
"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49",
|
||||||
|
"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2",
|
||||||
|
"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc"
|
||||||
|
],
|
||||||
|
"enc": "deflate-raw",
|
||||||
|
"size": 543,
|
||||||
|
"mode": "644"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 entry: PNG magic, never compressed, one part",
|
||||||
|
"chunkSize": 4194304,
|
||||||
|
"plaintext": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||||
|
"stored": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||||
|
"enc": null,
|
||||||
|
"parts": [
|
||||||
|
{
|
||||||
|
"nonce": "303132333435363738393a3b",
|
||||||
|
"plaintext": "89504e470d0a1a0a00000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||||
|
"wire": "303132333435363738393a3b69d66e5792c16a018c81a00c8d7739372b72143758d5f60c7fceb1e92a465ca1c10c59e9fd22d991085376961813de4939087ff23a9d4fae2bb4ad92b4c7c559",
|
||||||
|
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"entry": {
|
||||||
|
"path": "bilde.png",
|
||||||
|
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4",
|
||||||
|
"size": 48
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 manifest v2: plaintext = \"SVM2\" || deflate-raw(json utf-8)",
|
||||||
|
"manifest": {
|
||||||
|
"version": 2,
|
||||||
|
"seq": 7,
|
||||||
|
"at": 1786600000000,
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"path": ".scaffold/plan.md",
|
||||||
|
"hash": "19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480",
|
||||||
|
"enc": "deflate-raw",
|
||||||
|
"size": 244
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "logs/2026-10-16.md",
|
||||||
|
"hash": "cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||||
|
"parts": [
|
||||||
|
"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||||
|
"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1",
|
||||||
|
"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5",
|
||||||
|
"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f",
|
||||||
|
"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49",
|
||||||
|
"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2",
|
||||||
|
"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc"
|
||||||
|
],
|
||||||
|
"enc": "deflate-raw",
|
||||||
|
"size": 543,
|
||||||
|
"mode": "644"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"path": "bilde.png",
|
||||||
|
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4",
|
||||||
|
"size": 48
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"message": "nattlig backup"
|
||||||
|
},
|
||||||
|
"json": "{\"version\":2,\"seq\":7,\"at\":1786600000000,\"entries\":[{\"path\":\".scaffold/plan.md\",\"hash\":\"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480\",\"enc\":\"deflate-raw\",\"size\":244},{\"path\":\"logs/2026-10-16.md\",\"hash\":\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"parts\":[\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1\",\"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5\",\"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f\",\"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49\",\"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2\",\"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc\"],\"enc\":\"deflate-raw\",\"size\":543,\"mode\":\"644\"},{\"path\":\"bilde.png\",\"hash\":\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\",\"size\":48}],\"message\":\"nattlig backup\"}",
|
||||||
|
"plaintext": "53564d32ad92cd6e9c370c455fa5d0fab32352fcd3bc4a910529918ed1f1d8f54c1b2081dfbd98a208d24d57e596c03d87e0fddefeccf7ebf3eba59df068d7fcbd9df4687e6b275013e9ffccd1f2727b7fce6b3bfdfabdbdf9ed4b3bb5c7ebf2aad7f3fef476f6cbe3cb6e47fbe2d7fb0a66d816d1822dc45c34c5d49982d3472a53af8201c33cf62017cb95c68952be90acb73b70b553db5967bfe5c3bb7f6d47bb3e7fcb7642a28fe387c5f9f5e9fa093bca03f407907f69ac6db84d80688e4dda7deedad17973540da0350b77586007436002556558bc486d588c76b4377fbfddaffe3fb2f682ccd127e20677ddaa7d2e30c2353a04745a590488e89d0698576950cd4813c4e9d08e069dba745c9041192a02d30b69a5878c987b77d3696cd5318741afa93178b393488dcdf788d0316ace39dc99977816605896d7185606911a883a2c7b0c0799ddc80b78833960b5a3f1fd6d3c915957b9baa86827f472c6c88e0b31d7ee49606b244c9ce522e8bc8c57d06c4723a91dba74632a156ee8bd17e554079e515c62659c7b880fe9246b80902cd8035db0b01d0d636d5da004cc8b7ce41cbb262429b0e592a0aa9e61511c140812ab00ff761d9ab5dae7ff6a19d338dacbebce766a42d47eaa5c3c9f773ebe5d9e7e2a3c2095850c0b125c6b9bb1a6c20a0e57c41424ef53d7761563914ca1b1d4595d76d20f2cd9c7e7a3bde4f5ea4f77f4c56fb7f3f3d32fe1ebb73fdedac75f",
|
||||||
|
"nonce": "c0c0c0c0c0c0c0c0c0c0c0c0",
|
||||||
|
"wire": "c0c0c0c0c0c0c0c0c0c0c0c01190980ff0edf6049a9dd9120f8c01a273076cddd38f51af94f999837a8d78f3197a2a1ce77cde7fe2b3b455a7ae03810e2dd77e8bed66bcf7ccc2939a86639bb84872395229dea7dbef6c454a5444e080685320990a600753dbbaa6992e654d4827c8b3186c98b66a1f48766a6d41d1caeadbcfd3c82023b6171ab2a89b87acb7de83069a47280aba9bf01a784cfdab45983a96015890a00db4a70cd1fea7ecefc2ce813a193d941f0f93d2654c6fb0eb8d9d1e5327af17e03828aa1e33fbb0963d647d794c9e758bbfbfda7f6d799563d4532494abe21eae51e69da7b9721f54c6b08f3977138869268ec0005fdf8e2dfe69f715e34a403788d9ea35b8a1da9c62e5aeac7b88564d787d8f2ecb9e8c9d1316722651c245ceeca875ac91dcc920e26158b40ab594d0ae006f7c9df76559f377ef1373ed3bdb3dafd7bf9b263e9ac6a0563f4ea31478567a4ec548d8bd7dcc8206f9a2703d2a535ddf93935f2fd47b0937d760cb694434989262cead89b35bce9f3d69a09dcb0e8ac4ea1046e13ff06306cd644e9d53aa5c99847aed0847f5804c9ba09e661fad5641116846f102af64e1d170af6f54a149c757830e7ac5c415510de66874a7fd488d01b58e779ef002afb7ae07049fe6b57b957e35ac70d9d6904c5a1f55c0ffe55da94ec6b88731e5b7a361242303e48906991f863c9c6d4f783899d0ba97168fcf9e96aa26c922ec66b0d7e61b2e56f7f52143d964bc40ec9222f3d91892bcaed3d3137e0ddb6c68b223",
|
||||||
|
"hash": "cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 manifest v1: plaintext = json utf-8 (back-compat, still readable)",
|
||||||
|
"manifest": {
|
||||||
|
"version": 1,
|
||||||
|
"seq": 1,
|
||||||
|
"at": 1786500000000,
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"path": "notes.yaml",
|
||||||
|
"hash": "1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4",
|
||||||
|
"size": 48
|
||||||
|
}
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"json": "{\"version\":1,\"seq\":1,\"at\":1786500000000,\"entries\":[{\"path\":\"notes.yaml\",\"hash\":\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\",\"size\":48}]}",
|
||||||
|
"plaintext": "7b2276657273696f6e223a312c22736571223a312c226174223a313738363530303030303030302c22656e7472696573223a5b7b2270617468223a226e6f7465732e79616d6c222c2268617368223a2231313234663862363338623436326363643838353765373163623562613732326536323461303937636461373638353636656536343363376135376136646534222c2273697a65223a34387d5d7d",
|
||||||
|
"nonce": "d0d0d0d0d0d0d0d0d0d0d0d0",
|
||||||
|
"wire": "d0d0d0d0d0d0d0d0d0d0d0d0eaa53cdb2e8e93a47c29a2ea9d62c2d3beb5304d6c2250d6edbe3db0219d612e8203060d698f80c3d527dab75c10856f061f55aac3c8dcf44d454b09038791d993576c4099bfb0db8e98d9d1d583858b61a63667bd3fcac71b6c60ecd62213e3775cbb519da048a55c73d064ea0be5518952e92d5d508c0fe0be4c12d60125ab19f908e13687f2322b647f347297d037e0b3b6e6d2b32fb2723ca9cc39b7227869596194bce9568fbde4004d53a8",
|
||||||
|
"hash": "d450e5f430700dc7d33adf75904f92069c5e4075276dbbdca7b484603c783475"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 signed commit: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)",
|
||||||
|
"body": {
|
||||||
|
"manifest": "cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609",
|
||||||
|
"seq": 7,
|
||||||
|
"at": 1786600000000,
|
||||||
|
"hashes": [
|
||||||
|
"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480",
|
||||||
|
"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3",
|
||||||
|
"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1",
|
||||||
|
"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5",
|
||||||
|
"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f",
|
||||||
|
"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49",
|
||||||
|
"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2",
|
||||||
|
"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc",
|
||||||
|
"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4"
|
||||||
|
],
|
||||||
|
"publicKey": "YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc="
|
||||||
|
},
|
||||||
|
"signedAt": 1786600000123,
|
||||||
|
"canonical": "{\"at\":1786600000000,\"hashes\":[\"19b8d667f1d6455f49687a54b5ea3e7540ff13138abd34a68ece85e26fac2480\",\"cd82d8614493d470a9dfdb05d5bff314c9f2db8b20182154177751c5c47838b3\",\"dc1ee30922d1aa7d7709c1842c301b104cef41222a04318aff7b4f9be86229a1\",\"1040602c1eb4eb76619af24ceab63b9dd0879858f02e3810f97b35d5a466f3d5\",\"1b733f9993aa55c6aef12b8efaf338f81be7b22738e0b3a169084af15d18a12f\",\"5abd3592557cfa7a6767042afa52be02c22ecd0e418c3e1929fa662a5c85cb49\",\"46fdb7c7d2e74f2d1000f4e97a159bf5f68f85ed36a36046c31646c1d32a62f2\",\"2bcd7c174155c4a3e93df91e47158ec6b4ff0eb8bf5b4b216bcf126767037efc\",\"1124f8b638b462ccd8857e71cb5ba722e624a097cda768566ee643c7a57a6de4\"],\"manifest\":\"cc6c2374920cb357e44ec3b907177b8f10bde789df9e7a707d483be7dce68609\",\"publicKey\":\"YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=\",\"seq\":7,\"signedAt\":1786600000123}",
|
||||||
|
"canonicalHex": "7b226174223a313738363630303030303030302c22686173686573223a5b2231396238643636376631643634353566343936383761353462356561336537353430666631333133386162643334613638656365383565323666616332343830222c2263643832643836313434393364343730613964666462303564356266663331346339663264623862323031383231353431373737353163356334373833386233222c2264633165653330393232643161613764373730396331383432633330316231303463656634313232326130343331386166663762346639626538363232396131222c2231303430363032633165623465623736363139616632346365616236336239646430383739383538663032653338313066393762333564356134363666336435222c2231623733336639393933616135356336616566313262386566616633333866383162653762323237333865306233613136393038346166313564313861313266222c2235616264333539323535376366613761363736373034326166613532626530326332326563643065343138633365313932396661363632613563383563623439222c2234366664623763376432653734663264313030306634653937613135396266356636386638356564333661333630343663333136343663316433326136326632222c2232626364376331373431353563346133653933646639316534373135386563366234666630656238626635623462323136626366313236373637303337656663222c2231313234663862363338623436326363643838353765373163623562613732326536323461303937636461373638353636656536343363376135376136646534225d2c226d616e6966657374223a2263633663323337343932306362333537653434656333623930373137376238663130626465373839646639653761373037643438336265376463653638363039222c227075626c69634b6579223a2259475a716e6b6b733559434e584f506978416e56303353385641395652717855326e6973305961566b52633d222c22736571223a372c227369676e65644174223a313738363630303030303132337d",
|
||||||
|
"signature": "495f601cfbe2574b483a1710e4e40ec252a21f27a0454f7220537d3d9b19230ae38402d9119ae4df9f2506c01472370ed30d26bd22ccac1e2ce4fa6028c5790b",
|
||||||
|
"signatureBase64": "SV9gHPviV0tIOhcQ5OQOwlKiHyegRU9yIFN9PZsZIwrjhALZEZrk358lBsAUcjcO0w0mvSLMrB4s5PpgKMV5Cw=="
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "vault-v2 signed prune: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)",
|
||||||
|
"body": {
|
||||||
|
"keep": [
|
||||||
|
5,
|
||||||
|
7
|
||||||
|
],
|
||||||
|
"publicKey": "YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc="
|
||||||
|
},
|
||||||
|
"signedAt": 1786600000123,
|
||||||
|
"canonical": "{\"keep\":[5,7],\"publicKey\":\"YGZqnkks5YCNXOPixAnV03S8VA9VRqxU2nis0YaVkRc=\",\"signedAt\":1786600000123}",
|
||||||
|
"canonicalHex": "7b226b656570223a5b352c375d2c227075626c69634b6579223a2259475a716e6b6b733559434e584f506978416e56303353385641395652717855326e6973305961566b52633d222c227369676e65644174223a313738363630303030303132337d",
|
||||||
|
"signature": "928c803849691673610b9cb98062f75e81bdbac9b192880ffcd70d57abe0bb3b1878183b1827601a9b43dd4d8e615f9790a97ecfe2da35beacf5200129a73f0e",
|
||||||
|
"signatureBase64": "koyAOElpFnNhC5y5gGL3XoG9usmxkogP/NcNV6vguzsYeBg7GCdgGptD3U2OYV+XkKl+z+LaNb6s9SABKac/Dg=="
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user