Compare commits
16 Commits
b44acf867b
...
v4.14.1
| Author | SHA1 | Date | |
|---|---|---|---|
| a1c370359e | |||
| b82a803e0c | |||
| bcae7b346e | |||
| 5d04e18482 | |||
| f6e4ac8aeb | |||
| baddf5f56e | |||
| 53ce776c02 | |||
| 3c69995097 | |||
| 9789b6fc16 | |||
| 40286a8542 | |||
| cc6b1d53d7 | |||
| d8f6da55ef | |||
| 3da977207c | |||
| 84d3166ca1 | |||
| 012d7f5289 | |||
| 96c20cb4b2 |
@@ -28,6 +28,13 @@ jobs:
|
||||
- name: Install dependencies
|
||||
run: ~/.bun/bin/bun install --frozen-lockfile
|
||||
|
||||
# Before the tests, not after: a type error is cheaper to read than the
|
||||
# runtime failure it eventually causes. The compiler is pinned in
|
||||
# devDependencies, so this gate goes red when the repo changes — not
|
||||
# when TypeScript ships a release.
|
||||
- name: Typecheck
|
||||
run: ~/.bun/bin/bun run typecheck
|
||||
|
||||
- name: Run tests
|
||||
env:
|
||||
SHADE_TEST_PG_URL: postgres://postgres:test@localhost:5432/postgres
|
||||
|
||||
3
.gitignore
vendored
3
.gitignore
vendored
@@ -5,3 +5,6 @@ dist/
|
||||
**/.tmp-*.db
|
||||
**/.tmp-*.db-shm
|
||||
**/.tmp-*.db-wal
|
||||
|
||||
# Byggeartefakt fra @shade/observer (outDir-avviket i G0)
|
||||
dist-build/
|
||||
|
||||
@@ -1,5 +1,16 @@
|
||||
# Logg — Shade
|
||||
|
||||
## 2026-07-10 — Holistisk helsesjekk + gated plan mot V5.0
|
||||
Fem parallelle analysepass (arkitektur, test/CI, kryptosikkerhet, Android-paritet, docs/DX), topp-funn kildeverifisert. Kjernen er reell og moden (1159 tester grønne, vektorer byte-pinnet, KT/recovery ekte implementasjoner) — men «GA-frosset og revisjonsklar» stemte ikke. Fire P0-blockere identifisert og lagt inn som blockers i plan.md + kort i tasks.yaml:
|
||||
1. **AES-GCM nonce-gjenbruk** i at-rest storage (`storage-encrypted/src/crypto/kdf.ts:116`) — deterministisk nonce uten meldingsteller, `saveSession` re-krypterer hver ratchet-op → GCM forbidden attack mot §4. Reachable bekreftet; fiks er liten (tilfeldig nonce, wire lagrer den allerede i prefiks).
|
||||
2. **@shade/observer@4.11.1 tomt på registry** — `outDir=dist-build` men publish shipper `dist/`; `dist-build/` er det untrackede git-avviket.
|
||||
3. **Typecheck-gaten rød** — TS upinnet → `bunx tsc` henter 7.0.2 (fjernet `baseUrl`, brukt i consumer-strict); gaten kjøres aldri i CI.
|
||||
4. **@shade/cli bin dingler** etter publish (bin ikke omskrevet til dist/).
|
||||
|
||||
P1: safety-number matcher aldri peerens eget (`session.ts:241`, MITM-forsvar ikke-funksjonelt); backup-KDF HKDF ikke argon2id (finnes allerede i repoet); hono <4.12.18; begge flaggskip-eksempler røde (accept-race `shade-transfer/engine.ts:1140`). Paritet: ShadeStream (v4.11) uvoktet selv på TS-siden, Kotlin stopper på v4.10.
|
||||
|
||||
Låst prinsipp: **V5.0-implementasjon er gated på G0–G4 grønne.** V5.0.md er idéskisse — modnes parallelt (wire-typer reconciled mot 0x31–0x33, Insertable Streams-mekanisme, ratchet-params). Full rapport: helsesjekk-artifact (claude.ai/code).
|
||||
|
||||
## 2026-07-09 — Adoptert Scaffold plan-kontrakt
|
||||
Migrerte `docs/ROADMAP.md` og `android/shade-android/ROADMAP-ANDROID.md` til `.scaffold/`: nåbildet destillert inn i `plan.md`, originalene arkivert under `.scaffold/archive/` med opprinnelig mappestruktur. Versjonsdesigndokumentene (`docs/V5.0.md`, `docs/archive/V*.md`) er bevisst latt stå — de er spesifikasjoner, ikke planfiler.
|
||||
|
||||
|
||||
41
.scaffold/logs/2026-08-13-gcm-nonce-reuse-fikset.md
Normal file
41
.scaffold/logs/2026-08-13-gcm-nonce-reuse-fikset.md
Normal file
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: "G0: AES-GCM nonce-gjenbruk fjernet fra at-rest-lagringen"
|
||||
date: 2026-08-13
|
||||
author: Claude
|
||||
---
|
||||
|
||||
Den første av de fire P0-ene fra helsesjekken 10. juli er borte. `row-codec` forsegler nå med tilfeldig nonce i stedet for en avledet.
|
||||
|
||||
## Hva som var galt
|
||||
|
||||
`deriveNonce()` laget nonce som en ren funksjon av `(fieldKey, table, pk)` — altså av radens identitet. Doc-kommentaren argumenterte for at det var trygt fordi «hver `(key, plaintext)`-kombinasjon opptrer høyst én gang», men det er nøyaktig omvendt av hva AES-GCM krever: det farlige er å gjenbruke `(key, nonce)` på tvers av *ulike* plaintekster. `saveSession` re-forsegler sesjonsraden ved hvert ratchet-steg, så paret gjentok seg per konstruksjon. Konsekvensen er ikke bare XOR av plaintekstene, men lekkasje av GHASH-subnøkkelen — «the forbidden attack» — som gir tag-forfalskning under den nøkkelen. Det gjaldt alle muterbare rader: sesjoner, config, prekey-state og trust.
|
||||
|
||||
## Fiksen
|
||||
|
||||
Fire kallesteder, som kartlagt: `sealString` og `sealBytes` (`row-codec.ts:67`/`:96`) tar nå `randomNonce()` fra `aead.ts`, og `openString`/`openBytes` (`:83`/`:112`) slutter å sende `expectedNonce`.
|
||||
|
||||
Tilfeldig ble valgt framfor en teller fordi codec-en er delt mellom SQLite og Postgres og ikke har noen varig per-rad skrivteller å støtte seg på. 96 bit holder collision-sannsynligheten neglisjerbar langt forbi et realistisk antall re-lagringer.
|
||||
|
||||
`deriveNonce` er beholdt og markert `@deprecated` framfor slettet — den er del av den publiserte flaten via både `index.ts` og `crypto.ts`. Ingen kaller den lenger inne i pakken, og et søk gjennom `packages/`, `android/` og `examples/` fant ingen andre konsumenter. `expectedNonce`-parameteren i `aeadOpen` er beholdt på samme vilkår, med dokumentasjon om hvorfor den ikke skal brukes: den ga ingen tuklingsdeteksjon som AEAD-taggen og `(table, column, pk)`-AAD-en ikke allerede gir.
|
||||
|
||||
`randomNonce` er eksportert fra `index.ts` og `crypto.ts`, så konsumenter som forsegler selv har den trygge kilden for hånden.
|
||||
|
||||
## Ingen migrering trengs
|
||||
|
||||
`aeadOpen` har alltid lest nonce fra blob-prefikset; `expectedNonce` var kun en valgfri ekstrasjekk. Eksisterende blobber åpnes derfor uendret etter fiksen. Todoen om en migreringssti er erstattet av en test som beviser det.
|
||||
|
||||
## Android var aldri rammet
|
||||
|
||||
Kryssplattform-vektoren «Storage HKDF: rowNonce» tester HKDF-funksjonen, ikke at forseglingen bruker den, så den består uendret — `deriveNonce` er fortsatt der med samme oppførsel. Og `KeystoreStorage` henter nonce fra `cipher.iv`, altså Android Keystores egen tilfeldige IV, som ikke lar seg overstyre. TS-siden er nå på linje med Kotlin, ikke omvendt.
|
||||
|
||||
## Verifisering
|
||||
|
||||
Ny `tests/nonce-reuse.test.ts` med ni tester i tre grupper: nonce-unikhet (inkludert 200 re-lagringer med 200 distinkte nonces), bakoverkompatibilitet (blob forseglet med den gamle avledningen åpnes, og nye og gamle blobber leses under samme nøkkel), og at tuklingsdeteksjonen overlevde — flippet nonce-byte og flyttet rad avvises fortsatt.
|
||||
|
||||
Testene ble bevist å ha verdi ved å reversere fiksen midlertidig: nøyaktig de tre som beskriver feilen falt, mens bakoverkompatibilitets- og tuklingstestene sto uendret.
|
||||
|
||||
87 tester grønne i `@shade/storage-encrypted`, typecheck ren, og de to avhengige pakkene kjørt: `@shade/cli` 15/15 og `@shade/sdk` 104/104. En enkelt sdk-feil i første kjøring var en flaky gjennomstrømningsmåling — tre påfølgende kjøringer er grønne.
|
||||
|
||||
## Ikke publisert
|
||||
|
||||
Fiksen ligger i kildetreet. Prism er pinnet på `@shade/storage-encrypted@4.12.0` og får den først ved en release, som er riktig rekkefølge: `prism-daemon` skal ikke restartes nå.
|
||||
41
.scaffold/logs/2026-08-14-shade-vault.md
Normal file
41
.scaffold/logs/2026-08-14-shade-vault.md
Normal file
@@ -0,0 +1,41 @@
|
||||
---
|
||||
title: "@shade/vault — server-side kryptert fillager (V4.13)"
|
||||
date: 2026-08-14
|
||||
author: Claude
|
||||
---
|
||||
|
||||
Shade kunne flytte filer mellom peers (`@shade/files`) og lagre én liten profil-blob per konto (`/v1/blob/<slotId>`), men hadde ingen alltid-på lagring av krypterte filer. Uten den kan ingen Shade-app tilby backup, og ingen klient kan lese data mens peeren som eier dem er avslått. `@shade/vault` fyller det hullet.
|
||||
|
||||
## Modellen
|
||||
|
||||
Tre ideer, og formen følger av dem.
|
||||
|
||||
**Objekter er innholdsadresserte.** Et objekts navn er SHA-256 av *ciphertexten*, så relayen kan lagre, deduplisere og verifisere uten å forstå noe. Den regner om hashen ved opplasting og avviser et objekt som ikke er det det utgir seg for — uten å eie en nøkkel.
|
||||
|
||||
**Et manifest navngir samlingen.** Stier bor i manifestet, ikke i objektnavn: relayen skal ikke lære at brukeren har en fil som heter `Projects/Skilsmisse/plan.md`. Manifestet er selv kryptert og lagret som et objekt.
|
||||
|
||||
**Loggen er append-only.** Hver commit legger til en rad som peker på et manifest. Historikk, rollback og «hva endret seg sist tirsdag» faller ut av det — versjoneringshalvdelen av bestillingen.
|
||||
|
||||
## Valg verdt å begrunne
|
||||
|
||||
*Egen HKDF-gren* (`shade-vault-{id,content,sig}-v1`) ved siden av `shade-blob-*-v1`. En vault-nøkkel leser hver eneste fil; en profil-blob-nøkkel leser en vertsliste. Delt derivasjon ville gjort ett kompromiss om til det andre.
|
||||
|
||||
*Ingen konvergent kryptering.* Identisk klartekst gir ulike objektnavn fordi nonce er fersk. Dedupliseringen skjer derfor innenfor en versjonskjede — en uendret fil beholder hashen sin fordi klienten gjenbruker objektet den allerede lastet opp — ikke på tvers av uavhengige forseglinger. Konvergent kryptering ville lekket hvilke filer to brukere deler, som er nøyaktig det en blind butikk ikke skal.
|
||||
|
||||
*Commit verifiserer at objektene finnes.* Ellers ville loggen kunne publisere en versjon som ikke lar seg gjenopprette, og det er verdt en ekstra rundtur å utelukke.
|
||||
|
||||
*Pubkeyen er inne i signaturen.* Første forsøk la den på utenfor, som både brøt `verifyPayload` (den kanonikaliserer alle felt) og — hvis skjemaet hadde ignorert det — ville latt hvem som helst bytte identitet i transit på den TOFU-pinnende førsteskrivingen. Fanget av testene.
|
||||
|
||||
## Verifisering
|
||||
|
||||
16 tester, alle mot de ekte rutehåndtererne gjennom Honos `fetch` — ikke mot en mock-transport, som ville vært enig med klienten per konstruksjon og ikke bevist noe om wire-kontrakten.
|
||||
|
||||
Dekket: rundtur bit-for-bit; gjenoppretting på en fersk klient som bare har kontonøkkelen; feil master-nøkkel når ikke fram; tre versjoner med rollback til hver enkelt; en 50 KB uendret fil lastes ikke opp på nytt (`bytesUploaded` under 1 KB på andre push); slettet fil borte i ny versjon, intakt i gammel; lagrede objekter inneholder verken innhold eller sti; feilnavngitt objekt avvist; `SEQ_CONFLICT` ved commit fra utdatert head; `MISSING_OBJECTS` ved manglende referanse; fremmed nøkkel avvist mot en pinnet vault; usignert skriving avvist; og at vault-grenen er forskjellig fra blob-grenen.
|
||||
|
||||
Typecheck ren. `@shade/storage-encrypted` fortsatt 87/87 etter endringene i `kdf.ts`.
|
||||
|
||||
## Gjenstår
|
||||
|
||||
Ruting i `shade-server/src/standalone.ts` ved siden av `createBlobRoutes`, en varig `VaultStore` (SQLite/Postgres — bare `MemoryVaultStore` finnes), `docs/vault.md`, og deploy. Ingenting av det er gjort: deploy og publisering er utenfor mandatet for en uovervåket økt.
|
||||
|
||||
Arbeidet ligger ukommittert i arbeidstreet, sammen med de eksisterende endringene fra juli.
|
||||
25
.scaffold/logs/2026-08-14-typecheck-gaten.md
Normal file
25
.scaffold/logs/2026-08-14-typecheck-gaten.md
Normal file
@@ -0,0 +1,25 @@
|
||||
---
|
||||
title: "G0: typecheck-gaten pinnet og lagt i CI"
|
||||
date: 2026-08-14
|
||||
author: Claude
|
||||
---
|
||||
|
||||
Tredje av de fire P0-ene fra helsesjekken 10. juli.
|
||||
|
||||
## Hva som faktisk var galt
|
||||
|
||||
Helsesjekken beskrev gaten som rød fordi TS 7.0.2 hadde fjernet `baseUrl`, som `consumer-strict` brukte. Det stemmer ikke lenger: `baseUrl` finnes ikke noe sted i repoet, og `bun run typecheck` er grønn for alle 26 pakker — inkludert den nye `shade-vault`.
|
||||
|
||||
Den ekte feilen står likevel, og er den viktigere av de to: `scripts/typecheck-all.ts` kjørte `bunx tsc`, som henter nyeste utgivelse ved hver kjøring. Gaten kunne altså gå rød — eller stille slutte å fange ting — fordi TypeScript hadde sluppet en versjon, ikke fordi repoet endret seg. Det er en gate som ikke måler det den utgir seg for å måle.
|
||||
|
||||
## Fiksen
|
||||
|
||||
`typescript` er pinnet til `7.0.2` i rotens `devDependencies`, og `typecheck-all.ts` kjører `node_modules/.bin/tsc` i stedet for `bunx`. Et `Typecheck`-steg er lagt inn i `.gitea/workflows/test.yml`, plassert før testene: en typefeil er billigere å lese enn kjøretidsfeilen den til slutt forårsaker.
|
||||
|
||||
## Verifisering
|
||||
|
||||
`bun run typecheck` med den pinnede kompilatoren: alle 26 pakker grønne, inkludert consumer-strict-røyktesten (`lib: DOM`, `exactOptionalPropertyTypes`, `paths → workspace`).
|
||||
|
||||
## Gjenstår i G0
|
||||
|
||||
De to siste P0-ene — `@shade/observer` tomt på registry og `@shade/cli` sin dinglende `bin` — krever begge publisering til npm. Det er en utadvendt handling, og ble ikke gjort i en uovervåket økt.
|
||||
@@ -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,9 +1,11 @@
|
||||
---
|
||||
project: "Shade"
|
||||
phase: "Post-4.x GA — V5.0 (Voice & Video) i idéfase"
|
||||
updated: 2026-07-09
|
||||
focus: "4.x-kjernen er GA-frosset og revisjonsklar; neste løft er V5.0 sanntid oppå den låste stacken"
|
||||
blockers: []
|
||||
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
|
||||
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."
|
||||
blockers:
|
||||
- "P0: @shade/observer@4.11.1 tomt på registry (outDir=dist-build, publish shipper dist/)"
|
||||
- "P0: @shade/cli bin dingler etter publish (bin ikke omskrevet til dist/)"
|
||||
---
|
||||
|
||||
# Plan — Shade
|
||||
@@ -11,17 +13,52 @@ blockers: []
|
||||
## Mål
|
||||
- E2EE-bibliotek som implementerer Signal-protokollen (X3DH + Double Ratchet) for TypeScript/Bun — drop-in for frontend, backend og mobil, med forward secrecy og post-compromise recovery.
|
||||
- Byte-for-byte kryssplattform-paritet: Kotlin/Android-porten verifiseres kontinuerlig mot TS-referansen via delte test-vektorer i `test-vectors/`.
|
||||
- GA-frosset, revisjonsklar 4.0-kjerne som fundament; nye kapabiliteter (sanntid i V5.0) bygges oppå uten å røre kjernekrypto-revisjonen.
|
||||
- Reelt revisjonsklar 4.x-kjerne som fundament (G0–G4 grønne); sanntid (V5.0) bygges oppå den låste stacken uten å røre kjernekrypto-revisjonen.
|
||||
|
||||
## Nå
|
||||
- [ ] V5.0 fra `Idea` til `Design`: designnotatet `docs/V5.0.md` (SFrame-style frame encryption, `@shade/voice` / `@shade/video` / `@shade/broadcast`) må modnes og godkjennes
|
||||
- [ ] Ende-til-ende interop-test TS-server ↔ Kotlin-klient over ekte socket (anbefalt før «production»-label på Android)
|
||||
- [ ] Instrumenterte tester for `KeystoreStorage` (krever Android-emulator/enhet — utsatt i v4.9/v4.10-porten)
|
||||
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
|
||||
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`.
|
||||
**Ikke publisert** — Prism er pinnet på 4.12.0); observer `outDir→dist` +
|
||||
republiser 4.11.2 + gitignore `dist-build/`; ~~pin `typescript` + typecheck i CI~~
|
||||
(gjort 2026-08-14 — pinnet 7.0.2, `typecheck-all.ts` bruker lokal binær i
|
||||
stedet for `bunx` latest, steg lagt i `test.yml`; `baseUrl` var allerede
|
||||
borte og alle 26 pakker er grønne); fiks `bin`-omskriving + tarball-verifisering i publish.
|
||||
Port: typecheck grønn i CI, nonce-negativtest grønn, `bun pm pack` inneholder
|
||||
main-fil for alle pakker.
|
||||
- [ ] **G1 — Revisjonsklar kjerne (P1):** peer-signeringsnøkkel per sesjon → symmetrisk safety-number; argon2id i backup-KDF (TS+Kotlin); hono ≥4.12.18; håndhevende §4 at-rest-tuklingstest; bestill ekstern krypto-review + pentest. Port: `alice.verify(bob, bob.getIdentityFingerprint())`===true, `bun audit` ren.
|
||||
- [ ] **G2 — CI som mur:** biome + coverage-terskel + soak:smoke i CI; fjern/synk `.github/workflows`; publish kjører `prepublish:check`; bryt server↔inbox-server-syklus; rydd sdk/cli/files-deps; `dashboard: private`; pin bun. Port: PR blokkeres ved brudd, alle 8 examples grønne i CI.
|
||||
|
||||
## Neste
|
||||
- V5.0-implementasjon: `@shade/voice` (1:1 voice) → `@shade/video` → `@shade/broadcast` (1:N med relay-helper)
|
||||
- «Production»-label på Android når interop-testen er grønn
|
||||
- **V4.13 — `@shade/vault`: server-side kryptert fillager.** Klient, ruter,
|
||||
`MemoryVaultStore`, `SqliteVaultStore`, ruting i `standalone.ts` og
|
||||
`docs/vault.md` er levert natt til 2026-08-14 (auto-mode); 16 + 7 tester
|
||||
grønne, og kjeden er kjørt mot en ekte HTTP-server med et ekte workspace:
|
||||
491 filer bit-identiske etter gjenoppretting, andre push sendte 0 KB.
|
||||
Gjenstår: Postgres-store, rate limiting på vault-rutene, GC av objekter
|
||||
ingen manifest lenger refererer — og deploy. Bestilt 2026-08-13 av
|
||||
Scaffold-backupen, men er en generell mangel: Shade kan flytte filer mellom peers
|
||||
(`@shade/files`) og lagre én liten profil-blob per konto (`/v1/blob/<slotId>`, V4.9),
|
||||
men har ingen **alltid-på lagring av krypterte filer på relayen**. Hver konsument
|
||||
docs/files.md nevner (Dispatch, Mail, Drive-style apps) trenger det samme, så det
|
||||
hører i Shade og ikke i den enkelte appen.
|
||||
- *Form:* innholdsadressert lager — klienten krypterer og navngir etter hash av
|
||||
ciphertext, serveren ser aldri klartekst og trenger ingen forståelse av innholdet.
|
||||
- *Historikk:* append-only oplog per samling gir versjonering og rollback gratis;
|
||||
det er «mini github»-halvdelen av Scaffold-bestillingen.
|
||||
- *Nøkler:* egen HKDF-gren ved siden av `shade-blob-*-v1`, så et vault-kompromiss
|
||||
ikke rører profil-slotten. Recovery er kontocredentials, som blob-primitivet —
|
||||
med det forbeholdet at gjenopprettingsstyrken da er passordstyrken (se G1s
|
||||
argon2id-punkt, som løfter nettopp den).
|
||||
- *Gated på G0:* lageret bygger på at-rest-stacken, og skal ikke reise seg på en
|
||||
kjent GCM forbidden attack.
|
||||
- **G3 — Paritetslås:** ShadeStream-vektorer (3-DH, wire 0x31–0x33) konsumert av begge sider; Kotlin-port av v4.11; utvid cross-vectors path-filter; `PARITY-VERSION`-sjekk; symmetriser alle 14 vektorfiler; Robolectric-tester for KeystoreStorage; E2E socket-interop TS↔Kotlin. Port: begge sider verifiserer alle vektorer, minor-bump uten Android-ack ⇒ rød CI. Vilkår for «production»-label på Android.
|
||||
- **G4 — Docs = sannhet:** README/MIGRATION/CHANGELOG/CONTRIBUTING → 4.11.x; fiks brutte lenker + riktig remote; legg indexeddb/ShadeStream/broadcast i README+SHADE-BY-SCENARIO; Postgres at-rest quick-start + salt-livssyklus; per-pakke README for de 6 viktigste.
|
||||
|
||||
## Senere
|
||||
- Re-pinne backup-vektoren når begge porter bytter til argon2id som passord-KDF (HKDF-placeholder flagget i threat-model; `deriveMasterKeyArgon2id` finnes allerede i Kotlin)
|
||||
- Versjonsdesigndokumentene bor fortsatt i `docs/V5.0.md` og `docs/archive/V*.md` — de er spesifikasjoner, ikke planfiler
|
||||
- **G5 — V5.0 (Voice/Video):** implementasjon gated på G0–G4 grønne. `docs/V5.0.md` er i dag idéskisse (135 linjer) — modnes parallelt: wire-type-allokering reconciled mot 0x31–0x33 (nå tatt av ShadeStream), browser-SFrame-mekanisme (RTCRtpScriptTransform/Insertable Streams), ratchet-parametre, API-flate, milepæler, intern konsistens (60fps/1080p vs 30fps-test). Godkjennes i diskusjon (Stian + Fable) før koding.
|
||||
- Versjonsdesigndokumentene bor fortsatt i `docs/V5.0.md` og `docs/archive/V*.md` — de er spesifikasjoner, ikke planfiler.
|
||||
|
||||
@@ -14,4 +14,315 @@
|
||||
# created: 2026-07-09
|
||||
# updated: 2026-07-09
|
||||
# completed_at: null
|
||||
tasks: []
|
||||
tasks:
|
||||
# ─────────────── G0 — Stopp blødningen (P0-blockere) ───────────────
|
||||
- id: g0-gcm-nonce-reuse
|
||||
title: "Fjern AES-GCM nonce-gjenbruk i at-rest storage"
|
||||
description: >
|
||||
deriveNonce() lager deterministisk nonce fra (fieldKey, tabell, pk) uten
|
||||
meldingsteller. saveSession re-krypterer sesjonsraden ved hvert ratchet-steg,
|
||||
så to DB-snapshots deler (key, nonce) over ulik plaintext = GCM forbidden
|
||||
attack. Systemisk: gjelder alle muterbare rader (config, prekey-state, trust).
|
||||
status: done
|
||||
column: done
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: >
|
||||
Kallesteder kartlagt 2026-08-13: kun row-codec.ts:67 og :96 lager nonce,
|
||||
og :83/:112 tvinger den ved lesing. deriveNonce() er eksportert fra både
|
||||
index.ts og crypto.ts, så den beholdes (deprecated) framfor å brekke
|
||||
konsumenter. VERIFISERT: aeadOpen leser alltid nonce fra blob-prefiks
|
||||
(aead.ts:72) og expectedNonce er kun en valgfri ekstrasjekk — eksisterende
|
||||
blobber åpnes derfor uendret, og ingen migreringssti trengs.
|
||||
acceptance: "Tilfeldig nonce per skriving; aeadOpen leser nonce fra prefiks (dropp expectedNonce-tvang). Negativ test: to session-snapshots ved ulik message-count deler ikke (key, nonce). Test som åpner en blob forseglet med gammel deterministisk nonce. Alle eksisterende tester grønne."
|
||||
todos:
|
||||
- text: "row-codec.ts:67/96 → tilfeldig 12-byte nonce, lagret i blob-prefiks"
|
||||
done: true
|
||||
- text: "Dropp expectedNonce-argumentet i row-codec.ts:83/112"
|
||||
done: true
|
||||
- text: "Negativ regresjonstest for nonce-unikhet på tvers av re-saves"
|
||||
done: true
|
||||
- text: "Bakoverkompatibilitetstest: blob med gammel deterministisk nonce åpnes"
|
||||
done: true
|
||||
- text: "Marker deriveNonce deprecated (fortsatt eksportert fra index/crypto)"
|
||||
done: true
|
||||
- text: "IKKE PUBLISERT — Prism er pinnet på 4.12.0 og får fiksen først ved release"
|
||||
done: false
|
||||
created: 2026-07-10
|
||||
updated: 2026-08-13
|
||||
completed_at: 2026-08-13
|
||||
|
||||
- id: g0-observer-publish
|
||||
title: "Fiks @shade/observer publiserings-artefakt (tomt på registry)"
|
||||
description: >
|
||||
outDir=dist-build avviker fra alle andre pakker (dist). Publish kjører
|
||||
rm -rf dist og shipper files:[dist] → tarballen mangler JS, main peker på
|
||||
manglende fil. dist-build/ er det untrackede avviket i git status.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: "packages/shade-observer/tsconfig.json (outDir), scripts/publish-all.ts:109/186-227, dashboard copy-to-observer.ts-konflikten"
|
||||
acceptance: "outDir=dist; dashboard-SPA-konflikt løst eksplisitt; 4.11.2 republisert med verifisert tarball; dist-build/ i .gitignore."
|
||||
todos:
|
||||
- text: "tsconfig outDir → dist"
|
||||
done: false
|
||||
- text: "Løs dashboard-SPA vs publish-eierskap til dist/"
|
||||
done: false
|
||||
- text: "gitignore dist-build/ + fjern restene"
|
||||
done: false
|
||||
- text: "Republiser observer 4.11.2"
|
||||
done: false
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: g0-typecheck-gate
|
||||
title: "Pin TypeScript, fiks baseUrl, kjør typecheck i CI"
|
||||
description: >
|
||||
TS ikke pinnet noe sted → bunx tsc henter 7.0.2 som fjernet baseUrl (brukt i
|
||||
consumer-strict). typecheck exit 1 nå → prepublish:check rød. Gaten kjøres
|
||||
heller aldri i CI.
|
||||
status: done
|
||||
column: done
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: "tests/consumer-strict/tsconfig.json:17 (baseUrl), scripts/typecheck-all.ts (bruker upinnet bunx tsc), .gitea/workflows/test.yml"
|
||||
acceptance: "typescript pinnet som devDependency og brukt av typecheck-all.ts; baseUrl fjernet; bun run typecheck grønn og kjøres i .gitea/workflows/test.yml."
|
||||
todos:
|
||||
- text: "Pin typescript i root devDependencies"
|
||||
done: true
|
||||
- text: "typecheck-all.ts bruker lokal tsc, ikke bunx latest"
|
||||
done: true
|
||||
- text: "Fjern baseUrl fra consumer-strict tsconfig (var allerede borte)"
|
||||
done: true
|
||||
- text: "Legg typecheck-steg i test.yml"
|
||||
done: true
|
||||
created: 2026-07-10
|
||||
updated: 2026-08-14
|
||||
completed_at: 2026-08-14
|
||||
|
||||
- id: g0-cli-bin-tarball-verify
|
||||
title: "Fiks cli bin-omskriving + tarball-verifisering i publish"
|
||||
description: >
|
||||
bin.shade=src/cli.ts omskrives ikke til dist/ (rewriteEntryPointsForDist
|
||||
dekker kun main/types/exports). npm i -g @shade/cli gir brutt binær. Samme
|
||||
rot som observer: publish mangler integritetssjekk.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: "scripts/publish-all.ts:186-196 (rewriteEntryPointsForDist), packages/shade-cli/package.json (bin)"
|
||||
acceptance: "bin omskrives til dist/; publish asserterer at bun pm pack inneholder main-filen for hver pakke; npm i -g @shade/cli kjørbar."
|
||||
todos:
|
||||
- text: "Utvid rewriteEntryPointsForDist til pkgJson.bin"
|
||||
done: false
|
||||
- text: "Legg tarball-innhold-assert (bun pm pack) i publish-flyten"
|
||||
done: false
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
# ─────────────── G1 — Revisjonsklar kjerne (P1-sikkerhet) ───────────────
|
||||
- id: g1-symmetric-safety-number
|
||||
title: "Symmetrisk safety-number (lagre peer-signeringsnøkkel per sesjon)"
|
||||
description: >
|
||||
getRemoteFingerprint sender remoteIdentityKey (DH) som begge argumenter →
|
||||
H(dh‖dh) ≠ peerens egen H(sig‖dh). OOB-verifisering kan aldri matche →
|
||||
primær MITM-forsvar ikke-funksjonelt.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: "packages/shade-core/src/session.ts:238-245, SDK verify()/markPeerVerified()/isPeerVerified() shade.ts:590/649/659"
|
||||
acceptance: "Peer-signeringsnøkkel lagres per sesjon; kanonisk symmetrisk safety-number; kryssparts-test alice.verify(bob, bob.getIdentityFingerprint())===true uten MITM."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: g1-argon2id-backup
|
||||
title: "Koble argon2id inn i backup-KDF (TS + Kotlin)"
|
||||
description: >
|
||||
Backup-passord-KDF er HKDF → offline brute-force i HKDF-hastighet.
|
||||
argon2idAsync fra @noble/hashes er allerede dependency og brukes i
|
||||
storage-encrypted. Kotlin har deriveMasterKeyArgon2id via Bouncy Castle.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: "packages/shade-sdk/src/backup.ts:112-119, android/.../backup/BackupKdf.kt:27-36, referanse: storage-encrypted/src/crypto/kdf.ts:73-91"
|
||||
acceptance: "Backup-KDF = argon2id på begge plattformer; backup-vektor re-pinnet; cross-platform-vektortest grønn."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: g1-hono-upgrade-audit
|
||||
title: "Oppgrader hono ≥4.12.18 + bun audit-gate"
|
||||
description: >
|
||||
hono <4.12.18 har bodyLimit-bypass (svekker §7 64 KiB body-cap), path
|
||||
traversal i serve-static, IP-restriction-bypass. Dev/test: happy-dom
|
||||
(critical VM-escape), vite, postcss.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: "hono i shade-server/inbox-server/transfer/observer/transport-bridge; bun.lock pinner nåværende"
|
||||
acceptance: "hono ≥4.12.18 overalt; bun audit uten runtime-high/critical; §7 DoS-cap re-evaluert."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: g1-at-rest-tamper-test
|
||||
title: "Håndhevende §4 at-rest-tuklingstest + bestill ekstern review"
|
||||
description: >
|
||||
SECURITY.md-cellen «§4 at-rest session DB» er «none yet» → ikke håndhevet.
|
||||
Ekstern krypto-review + pentest står «Pending V4.0» og må ikke skli forbi V5.0.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: high
|
||||
assignee: any
|
||||
context: "SECURITY.md:18 (celler uten testlenke ikke håndhevet), THREAT-MODEL §4"
|
||||
acceptance: "Negativ test som beviser at at-rest-tukling fanges (AAD/tag); SECURITY.md-celle lenket. Ekstern review + pentest bestilt."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
# ─────────────── G2/G3-hoder (nedbrytes når G0/G1 nærmer seg) ───────────────
|
||||
- id: g2-ci-wall
|
||||
title: "G2: CI som mur — lint/format/coverage/soak + rydd .github + arkitektur"
|
||||
description: >
|
||||
biome (lint+format), coverage-terskel (gulv=dagens), soak:smoke i CI;
|
||||
fjern/synk stale .github/workflows (7 pakker→npmjs); publish kjører
|
||||
prepublish:check; bryt server↔inbox-server-syklus; rydd sdk/cli/files ubrukte
|
||||
deps; dashboard private; pin bun i workflows; kjør alle 8 examples (fiks
|
||||
accept-race i shade-transfer/engine.ts:1140).
|
||||
status: todo
|
||||
column: todo
|
||||
priority: medium
|
||||
assignee: claude
|
||||
context: "Se helsesjekk-artifact 2026-07-10 (P2-arkitektur + CI-hull)"
|
||||
acceptance: "PR blokkeres ved brudd på typecheck·lint·format·test·coverage; alle 8 examples grønne i CI; ingen udeklarert/ubrukt hard dep."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: g3-parity-lock
|
||||
title: "G3: Paritetslås — ShadeStream-vektorer + Kotlin v4.11 + interop"
|
||||
description: >
|
||||
ShadeStream (v4.11) har null vektorer selv på TS-siden. Kotlin stopper på
|
||||
v4.10. Lag vektorer (3-DH deriveStreamRootKey, wire 0x31-0x33, frame
|
||||
seal/open) konsumert av begge; port ShadeStream til Kotlin; utvid
|
||||
cross-vectors path-filter; PARITY-VERSION-sjekk; symmetriser alle 14
|
||||
vektorfiler; Robolectric-tester for KeystoreStorage; E2E socket-interop.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: medium
|
||||
assignee: claude
|
||||
context: "packages/shade-core/src/stream.ts, scripts/generate-vectors.ts, .gitea/workflows/cross-vectors.yml, android/shade-android-keystore (0 tester)"
|
||||
acceptance: "Begge sider verifiserer alle 14 vektorer + ShadeStream; minor-bump uten Android-ack ⇒ rød CI; E2E TS-server↔Kotlin-klient over socket grønn."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: g4-docs-truth
|
||||
title: "G4: Docs = sannhet — oppdater til 4.11.x, fiks lenker/remote/eksempler"
|
||||
description: >
|
||||
README/MIGRATION/CHANGELOG/CONTRIBUTING frosset på 4.0. Riktig remote er
|
||||
Gitea (ikke GitHub). Legg indexeddb/ShadeStream/broadcast i README+
|
||||
SHADE-BY-SCENARIO; Postgres at-rest quick-start + salt-livssyklus; per-pakke
|
||||
README for sdk/core/files/streams/storage-encrypted/transport.
|
||||
status: todo
|
||||
column: todo
|
||||
priority: medium
|
||||
assignee: claude
|
||||
context: "README.md, MIGRATION.md, CHANGELOG.md, CONTRIBUTING.md, docs/SHADE-BY-SCENARIO.md"
|
||||
acceptance: "Én sannhetskilde for versjon; ingen brutte doc-lenker (CI link-check); hvert ECOSYSTEM-scenario har kjørende CI-testet eksempel-sti."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
# ─────────────── Åpne beslutninger (Stian avgjør i plandiskusjon) ───────────────
|
||||
- id: decision-g3-vs-g4-order
|
||||
title: "BESLUTNING: rekkefølge G3 (paritetslås) vs G4 (docs)"
|
||||
description: >
|
||||
Foreslått G3 før G4 fordi «production»-label på Android henger på paritet.
|
||||
Men hvis Prism/Vyvern trenger docs-sannhet raskere, kan de bytte plass.
|
||||
status: blocked
|
||||
column: blocked
|
||||
priority: medium
|
||||
assignee: human
|
||||
acceptance: "Rekkefølge bestemt; plan.md Neste-seksjon speiler valget."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: decision-external-review-timing
|
||||
title: "BESLUTNING: bestille ekstern krypto-review/pentest nå eller etter G0+G1"
|
||||
description: >
|
||||
Parallelt nå (raskere kalender) vs etter G0+G1-fiksene (revisor ser korrekt
|
||||
kjerne — nonce-fiks + symmetrisk safety-number inne). Fable heller mot fikse først.
|
||||
status: blocked
|
||||
column: blocked
|
||||
priority: medium
|
||||
assignee: human
|
||||
context: "Kobles til g1-at-rest-tamper-test; SECURITY.md-celler «Pending V4.0»"
|
||||
acceptance: "Tidspunkt bestemt; g1-at-rest-tamper-test oppdatert deretter."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
- id: decision-argon2id-migration
|
||||
title: "BESLUTNING: argon2id backup-migreringsstrategi"
|
||||
description: >
|
||||
Re-pinning av backup-vektor betyr at eksisterende 4.x-backups må migreres.
|
||||
Big-bang i 4.12 vs dobbelt-lesende overgangsvindu (les HKDF-legacy, skriv argon2id).
|
||||
status: blocked
|
||||
column: blocked
|
||||
priority: medium
|
||||
assignee: human
|
||||
context: "Kobles til g1-argon2id-backup"
|
||||
acceptance: "Migreringsstrategi valgt; g1-argon2id-backup-kortet får todos deretter."
|
||||
created: 2026-07-10
|
||||
updated: 2026-07-10
|
||||
completed_at: null
|
||||
|
||||
# ─────────────── V4.13 — @shade/vault (server-side kryptert fillager) ───────────────
|
||||
- id: vault-package
|
||||
title: "@shade/vault — innholdsadressert kryptert fillager på relayen"
|
||||
description: >
|
||||
Shade kan flytte filer mellom peers (@shade/files) og lagre én liten
|
||||
profil-blob per konto (/v1/blob/<slotId>), men har ingen alltid-på lagring
|
||||
av krypterte filer. Uten den kan ingen Shade-app tilby backup, og ingen
|
||||
klient kan lese data når peeren er avslått. Klienten krypterer og navngir
|
||||
etter hash av ciphertext; serveren ser aldri klartekst.
|
||||
status: doing
|
||||
column: doing
|
||||
priority: high
|
||||
assignee: claude
|
||||
context: >
|
||||
Bestilt av Scaffold-backupen 2026-08-13, men generell: docs/files.md peker
|
||||
selv på Dispatch/Mail/Drive-style apps som konsumenter. Egen HKDF-gren ved
|
||||
siden av shade-blob-*-v1 i storage-encrypted/src/crypto/kdf.ts, så et
|
||||
vault-kompromiss ikke rører profil-slotten. Rutes i shade-server/src/
|
||||
standalone.ts ved siden av createBlobRoutes.
|
||||
acceptance: >
|
||||
Klient kan pushe/hente en samling krypterte objekter mot relayen uten at
|
||||
serveren kan lese noe; oplog gir versjonsliste og henting av tidligere
|
||||
versjon; ny enhet med kontocredentials rekonstruerer hele samlingen.
|
||||
SHADE_VAULT_DB_PATH dokumentert med samme advarsel som SHADE_BLOB_DB_PATH.
|
||||
todos:
|
||||
- text: "HKDF-gren for vault-nøkler (slot, innhold, signatur)"
|
||||
done: true
|
||||
- text: "Innholdsadressert put/get med CAS-semantikk"
|
||||
done: true
|
||||
- text: "Append-only oplog per samling — versjonsliste og rollback"
|
||||
done: true
|
||||
- text: "Serverruter + persistenskonfigurasjon i standalone.ts"
|
||||
done: true
|
||||
- text: "docs/vault.md + README-rad i statustabellen"
|
||||
done: false
|
||||
- text: "IKKE DEPLOYET — krever SHADE_VAULT_DB_PATH i compose + Dokploy-runde"
|
||||
done: false
|
||||
created: 2026-08-13
|
||||
updated: 2026-08-14
|
||||
completed_at: null
|
||||
|
||||
86
CHANGELOG.md
86
CHANGELOG.md
@@ -5,6 +5,92 @@ All notable changes to Shade are documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [4.14.1] — 2026-10-16 — Vault: `edit` for vaults two devices write
|
||||
|
||||
- `VaultClient.edit(change, at)` changes a few files against the head that
|
||||
was actually read and commits `head + 1`; on `SEQ_CONFLICT` it re-reads and
|
||||
calls `change` again. `push` publishes a whole collection and would drop a
|
||||
file another device appended in between — right for a backup with one
|
||||
writer, wrong for a queue a phone appends to while a PC drains it.
|
||||
|
||||
## [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
|
||||
|
||||
### Fixed
|
||||
- **`@shade/inbox`: a failed PUT no longer lets the next message overtake it.**
|
||||
`flushOnce` drained each recipient's bucket sequentially but carried on
|
||||
past a failure, so entry N+1 was delivered in the same round and N only on
|
||||
the retry — the recipient saw them reversed. For sender-key broadcasts that
|
||||
is data loss, not cosmetics: a receiver that has advanced past iteration N
|
||||
cannot open it. The bucket now stops at the first failure (head-of-line,
|
||||
per recipient only; other recipients still drain in parallel). An entry
|
||||
dropped at `maxAttempts` gives up its place. Found by Prism, where it
|
||||
showed up as frozen terminal output on phones.
|
||||
|
||||
### Docs
|
||||
- `senderKeyDecrypt` no longer claims a skipped-key cache it never had.
|
||||
Out-of-order group messages still throw "Stale iteration"; senders must
|
||||
deliver in iteration order (which the inbox fix above now guarantees).
|
||||
|
||||
## [4.11.2] — 2026-07-10 — Files pull-mode startup hotfix
|
||||
|
||||
**`@shade/files`**
|
||||
|
||||
123
bun.lock
123
bun.lock
@@ -13,11 +13,12 @@
|
||||
"devDependencies": {
|
||||
"bun-types": "^1.3.11",
|
||||
"fast-check": "^3.22.0",
|
||||
"typescript": "7.0.2",
|
||||
},
|
||||
},
|
||||
"packages/shade-cli": {
|
||||
"name": "@shade/cli",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"bin": {
|
||||
"shade": "src/cli.ts",
|
||||
},
|
||||
@@ -36,7 +37,7 @@
|
||||
},
|
||||
"packages/shade-core": {
|
||||
"name": "@shade/core",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/observability": "workspace:*",
|
||||
},
|
||||
@@ -49,7 +50,7 @@
|
||||
},
|
||||
"packages/shade-crypto-web": {
|
||||
"name": "@shade/crypto-web",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1",
|
||||
"@noble/hashes": "^2.0.1",
|
||||
@@ -59,7 +60,7 @@
|
||||
},
|
||||
"packages/shade-dashboard": {
|
||||
"name": "@shade/dashboard",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/widgets": "workspace:*",
|
||||
"react": "^19.0.0",
|
||||
@@ -74,7 +75,7 @@
|
||||
},
|
||||
"packages/shade-files": {
|
||||
"name": "@shade/files",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -101,7 +102,7 @@
|
||||
},
|
||||
"packages/shade-inbox": {
|
||||
"name": "@shade/inbox",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/proto": "workspace:*",
|
||||
@@ -114,7 +115,7 @@
|
||||
},
|
||||
"packages/shade-inbox-server": {
|
||||
"name": "@shade/inbox-server",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
@@ -132,7 +133,7 @@
|
||||
},
|
||||
"packages/shade-key-transparency": {
|
||||
"name": "@shade/key-transparency",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -144,11 +145,11 @@
|
||||
},
|
||||
"packages/shade-keychain": {
|
||||
"name": "@shade/keychain",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
},
|
||||
"packages/shade-observability": {
|
||||
"name": "@shade/observability",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
},
|
||||
@@ -166,7 +167,7 @@
|
||||
},
|
||||
"packages/shade-observer": {
|
||||
"name": "@shade/observer",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
@@ -178,14 +179,14 @@
|
||||
},
|
||||
"packages/shade-proto": {
|
||||
"name": "@shade/proto",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
},
|
||||
},
|
||||
"packages/shade-recovery": {
|
||||
"name": "@shade/recovery",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -198,7 +199,7 @@
|
||||
},
|
||||
"packages/shade-sdk": {
|
||||
"name": "@shade/sdk",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -228,12 +229,14 @@
|
||||
},
|
||||
"packages/shade-server": {
|
||||
"name": "@shade/server",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/key-transparency": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
"@shade/storage-sqlite": "workspace:*",
|
||||
"@shade/vault": "workspace:*",
|
||||
"hono": "^4.12.12",
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -248,7 +251,7 @@
|
||||
},
|
||||
"packages/shade-storage-encrypted": {
|
||||
"name": "@shade/storage-encrypted",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -270,7 +273,7 @@
|
||||
},
|
||||
"packages/shade-storage-indexeddb": {
|
||||
"name": "@shade/storage-indexeddb",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"idb": "^8.0.3",
|
||||
@@ -282,7 +285,7 @@
|
||||
},
|
||||
"packages/shade-storage-postgres": {
|
||||
"name": "@shade/storage-postgres",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
@@ -297,17 +300,20 @@
|
||||
},
|
||||
"packages/shade-storage-sqlite": {
|
||||
"name": "@shade/storage-sqlite",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@shade/vault": "workspace:*",
|
||||
},
|
||||
},
|
||||
"packages/shade-streams": {
|
||||
"name": "@shade/streams",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
@@ -319,7 +325,7 @@
|
||||
},
|
||||
"packages/shade-transfer": {
|
||||
"name": "@shade/transfer",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -336,7 +342,7 @@
|
||||
},
|
||||
"packages/shade-transport": {
|
||||
"name": "@shade/transport",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
@@ -347,7 +353,7 @@
|
||||
},
|
||||
"packages/shade-transport-bridge": {
|
||||
"name": "@shade/transport-bridge",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
@@ -369,16 +375,29 @@
|
||||
},
|
||||
"packages/shade-transport-webrtc": {
|
||||
"name": "@shade/transport-webrtc",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/streams": "workspace:*",
|
||||
"@shade/transfer": "workspace:*",
|
||||
},
|
||||
},
|
||||
"packages/shade-vault": {
|
||||
"name": "@shade/vault",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
"@shade/storage-encrypted": "workspace:*",
|
||||
"hono": "^4.12.18",
|
||||
},
|
||||
},
|
||||
"packages/shade-widgets": {
|
||||
"name": "@shade/widgets",
|
||||
"version": "4.8.5",
|
||||
"version": "4.13.0",
|
||||
"dependencies": {
|
||||
"@shade/recovery": "workspace:*",
|
||||
"@shade/sdk": "workspace:*",
|
||||
@@ -603,6 +622,8 @@
|
||||
|
||||
"@shade/transport-webrtc": ["@shade/transport-webrtc@workspace:packages/shade-transport-webrtc"],
|
||||
|
||||
"@shade/vault": ["@shade/vault@workspace:packages/shade-vault"],
|
||||
|
||||
"@shade/widgets": ["@shade/widgets@workspace:packages/shade-widgets"],
|
||||
|
||||
"@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
|
||||
@@ -621,6 +642,46 @@
|
||||
|
||||
"@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
|
||||
|
||||
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
|
||||
|
||||
"@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
|
||||
|
||||
"@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
|
||||
|
||||
"@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
|
||||
|
||||
"@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
|
||||
|
||||
"@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
|
||||
|
||||
"@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
|
||||
|
||||
"@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
|
||||
|
||||
"@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
|
||||
|
||||
"@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
|
||||
|
||||
"@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
|
||||
|
||||
"@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
|
||||
|
||||
"@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
|
||||
|
||||
"@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
|
||||
|
||||
"@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
|
||||
|
||||
"@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
|
||||
|
||||
"@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
|
||||
|
||||
"@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
|
||||
|
||||
"@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
|
||||
|
||||
"@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
|
||||
|
||||
"@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="],
|
||||
|
||||
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.17", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-HdrkN8eVG2CXxeifv/VdJ4A4RSra1DTW8dc/hdxzhGHN8QePs6gKaWM9pHPcpCoxYZJuOZ8drHmbdpLHjCYjLA=="],
|
||||
@@ -703,6 +764,8 @@
|
||||
|
||||
"tinyglobby": ["tinyglobby@0.2.16", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
|
||||
|
||||
"typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
|
||||
|
||||
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
|
||||
|
||||
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
|
||||
@@ -716,5 +779,15 @@
|
||||
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
|
||||
|
||||
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
||||
|
||||
"@shade/inbox-server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/observer/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/transport-bridge/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
|
||||
"@shade/vault/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
|
||||
}
|
||||
}
|
||||
|
||||
214
docs/vault.md
Normal file
214
docs/vault.md
Normal file
@@ -0,0 +1,214 @@
|
||||
# `@shade/vault` — server-side encrypted file store
|
||||
|
||||
V4.13. Where the blob primitive (V4.9) holds one small blob per account, a
|
||||
vault holds a whole **collection** — a workspace, a mailbox, a drive folder —
|
||||
as content-addressed objects plus an append-only log of manifests.
|
||||
|
||||
It is the piece Shade was missing to let an app offer backup, or to let a
|
||||
client read data while the peer that owns it is switched off.
|
||||
|
||||
## The model
|
||||
|
||||
**Objects are content-addressed.** An object's name is the SHA-256 of its
|
||||
*ciphertext*, so the relay can store, dedupe and verify without a key: it
|
||||
recomputes the hash on upload and rejects anything mislabelled.
|
||||
|
||||
**A manifest names the collection.** Paths live inside the encrypted manifest,
|
||||
never in object names — the relay must not learn that a user has a file called
|
||||
`Projects/Divorce/plan.md`. The manifest is itself stored as an object.
|
||||
|
||||
**The log is append-only.** Each commit adds a row pointing at a manifest.
|
||||
History, rollback and "what changed last Tuesday" all fall out of that.
|
||||
|
||||
## Keys
|
||||
|
||||
Three deterministic derivations off the account master key, in their own HKDF
|
||||
branch:
|
||||
|
||||
```
|
||||
vaultId = HKDF(masterKey, "shade-vault-id-v1:<app>")
|
||||
contentKey = HKDF(masterKey, "shade-vault-content-v1:<app>")
|
||||
sigSeed = HKDF(masterKey, "shade-vault-sig-v1:<app>")
|
||||
```
|
||||
|
||||
Separate from `shade-blob-*-v1` on purpose: a vault key reads every file, a
|
||||
profile-blob key reads a host list. Sharing a derivation would turn one
|
||||
compromise into the other.
|
||||
|
||||
Because the derivation is deterministic, **recovery is credentials**. A fresh
|
||||
device that can derive the profile master can derive these, and the relay hands
|
||||
over ciphertext it has never been able to read. The flip side is that recovery
|
||||
strength is password strength — see G1's argon2id item.
|
||||
|
||||
## Client
|
||||
|
||||
```ts
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import { VaultClient, HttpVaultTransport, deriveVaultKeys } from '@shade/vault';
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const keys = await deriveVaultKeys(masterKey, 'scaffold');
|
||||
const client = new VaultClient(crypto, keys, new HttpVaultTransport('https://vault.example'));
|
||||
|
||||
// Back up. Unchanged files are not re-uploaded. Persist `res.index` and pass
|
||||
// it to the next push: an unchanged file is then recognised locally, with no
|
||||
// download at all.
|
||||
const res = await client.push(files, Date.now(), undefined, { index: savedIndex });
|
||||
// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204, unchanged: false, index }
|
||||
|
||||
// Restore — the newest, or any earlier version.
|
||||
const { manifest, files: restored } = await client.pull();
|
||||
const old = await client.pull(2);
|
||||
|
||||
// Lazy: list a version, then fetch only what is opened.
|
||||
const m = await client.manifest();
|
||||
const bytes = await client.readEntry(m.entries[0]);
|
||||
|
||||
// History, and retention.
|
||||
const log = await client.history();
|
||||
await client.prune([log.head - 1, log.head]); // → { removedVersions, removedObjects, freedBytes }
|
||||
```
|
||||
|
||||
`push` takes `at` rather than reading the clock, so a queued backup records
|
||||
when it was *taken* rather than when it finally reached the relay.
|
||||
|
||||
**A push that changes nothing commits nothing.** Same paths, same modes, every
|
||||
file reused, no `message`: the result is `{ unchanged: true, seq: head }` and
|
||||
the log does not grow. Pushes run on every workspace change; a version per
|
||||
trigger would fill the log with empty commits. Pass a `message` to force one.
|
||||
|
||||
**The index** (`VaultIndex`, plain JSON) maps each path to its plaintext
|
||||
SHA-256 and the entry it was stored as. It is trusted only when its `vaultId`
|
||||
matches and its `seq` is still the relay's head; otherwise the push reads the
|
||||
head manifest and downloads only same-path, same-size candidates to compare. It
|
||||
holds plaintext hashes, so keep it with the files, never on the relay. After a
|
||||
restore, `vaultIndexFrom(vaultId, manifest, files)` builds one, so the first
|
||||
push from a fresh device is free too.
|
||||
|
||||
## Format (v2) — the cross-language contract
|
||||
|
||||
Every object is `nonce(12) || AES-256-GCM(contentKey, plaintext, aad)`, named
|
||||
by the lowercase hex SHA-256 of those bytes, with
|
||||
`aad = utf8("shade-vault-object-v1|" + vaultId)`.
|
||||
|
||||
**Entries.** A file's plaintext becomes its *stored* bytes, then *parts*:
|
||||
|
||||
1. Unless the plaintext is empty or starts with a known compressed signature —
|
||||
PNG `89 50 4E 47`, JPEG `FF D8 FF`, WebP `"RIFF"` + `"WEBP"` at offset 8,
|
||||
MP4 family `"ftyp"` at offset 4, GIF `"GIF8"`, gzip `1F 8B`, zip `"PK"` —
|
||||
deflate it (raw RFC 1951, zlib default level). Keep the result, and set
|
||||
`enc: "deflate-raw"`, only if `compressed * 20 <= plain * 19` (≤ 95 %, in
|
||||
integers so no port rounds differently).
|
||||
2. Split the stored bytes into slices of at most 4 MiB (4 194 304). An empty
|
||||
file is one empty slice.
|
||||
3. Seal each slice as its own object. One slice: `hash` names it and there is
|
||||
no `parts`. Several: `parts` lists their hashes in order and
|
||||
`hash = parts[0]`.
|
||||
|
||||
`size` is always the **plaintext** length. A reader fetches
|
||||
`parts ?? [hash]`, verifies and opens each, concatenates, inflates if `enc`,
|
||||
and checks the result against `size`. An unknown `enc` is refused.
|
||||
|
||||
**Manifests.** v2 plaintext is ASCII `"SVM2"` followed by deflate-raw of the
|
||||
UTF-8 JSON; v1 is the bare JSON. A reader inflates when the magic is present,
|
||||
parses, and accepts `version` 1 or 2 only — refusing beats guessing, since
|
||||
silently dropping a field it cannot represent would lose data on its next
|
||||
commit. JSON key order is not part of the contract. A v1-only reader fails on a
|
||||
v2 manifest at JSON parse, loudly, rather than misreading it.
|
||||
|
||||
**Commits** list every part of every entry in the signed `hashes`. The relay
|
||||
checks they exist and records them as what the version references; a part
|
||||
left out may be collected by the next prune.
|
||||
|
||||
**Signed bodies** are canonicalised as JSON of every field except
|
||||
`signature`, top-level keys sorted, nested values as-is; the signature is
|
||||
Ed25519 over those bytes with the vault's signing seed, base64 on the wire.
|
||||
|
||||
Vectors for all of the above: `test-vectors/vault-v2.json` (regenerate with
|
||||
`bun run scripts/generate-vectors.ts vault-v2.json`). Compressed bytes are
|
||||
pinned (`stored`) for writer parity; a reader needs only `wire`.
|
||||
|
||||
## Server
|
||||
|
||||
```ts
|
||||
import { createVaultRoutes } from '@shade/vault/server';
|
||||
import { SqliteVaultStore } from '@shade/storage-sqlite';
|
||||
|
||||
app.route('/', createVaultRoutes(new SqliteVaultStore('/data/shade-vault.db'), crypto));
|
||||
```
|
||||
|
||||
Routes:
|
||||
|
||||
| | |
|
||||
|---|---|
|
||||
| `GET /v1/vault/:id/log` | `{ entries, head }` |
|
||||
| `HEAD /v1/vault/:id/object/:hash` | 200 / 404 — the have-check |
|
||||
| `GET /v1/vault/:id/object/:hash` | raw ciphertext |
|
||||
| `PUT /v1/vault/:id/object/:hash` | signed; verifies hash matches bytes |
|
||||
| `POST /v1/vault/:id/commit` | signed; refuses a stale `seq` or a missing object |
|
||||
| `POST /v1/vault/:id/prune` | signed `{ keep: number[] }`; must keep the head |
|
||||
|
||||
Auth is TOFU-Ed25519, as for blobs: the first signed write pins a pubkey, and
|
||||
every later write must be signed by it. The pubkey travels **inside** the
|
||||
signed payload — appended afterwards it would not be covered by the signature,
|
||||
and could be swapped in transit on the pinning write.
|
||||
|
||||
### Configuration
|
||||
|
||||
```
|
||||
SHADE_VAULT_DB_PATH=/data/shade-vault.db # required — no in-memory fallback
|
||||
SHADE_DISABLE_VAULT=1 # optional: off entirely
|
||||
```
|
||||
|
||||
**There is deliberately no in-memory fallback.** The blob store has one, and on
|
||||
2026-08-12 a routine redeploy destroyed every profile because the path was
|
||||
never set in compose: the fallback worked perfectly right up until the
|
||||
container was recreated, and nothing ever failed loudly. A vault that forgets
|
||||
is worse than no vault, so an unset path means the routes are simply not
|
||||
mounted, with a warning that says why.
|
||||
|
||||
### Limits
|
||||
|
||||
Per object 8 MiB, per vault 512 MiB, both overridable via `VaultRoutesOptions`.
|
||||
Files larger than an object are split into 4 MiB parts by the client, so the
|
||||
per-object limit no longer caps file size.
|
||||
|
||||
### Retention
|
||||
|
||||
`prune` deletes every log entry not in `keep` and then every object no
|
||||
remaining entry references. The client chooses the policy — only it can read
|
||||
the manifests — and the relay executes it:
|
||||
|
||||
- `keep` must include the current head, or the request fails with
|
||||
`SEQ_CONFLICT` (and the head). That is also what a keep-list computed before
|
||||
another device's commit, or a replayed prune, runs into.
|
||||
- Prune never pins an owner: on a vault with no owner it is a 404.
|
||||
- An entry newer than the head the route checked is never removed, even if a
|
||||
commit lands mid-request.
|
||||
- An object no version has ever referenced (an upload whose commit is still
|
||||
in flight) survives for `pruneGraceMs`, default one hour.
|
||||
- **Versions committed before ref tracking** have no recorded hash list. Every
|
||||
object present when such a version was written (for SQLite: when the
|
||||
database was migrated) is pinned and never collected while any untracked
|
||||
version remains. Once the last one is pruned, nothing has an unknown
|
||||
reference set, and the pins are released.
|
||||
|
||||
`SqliteVaultStore` migrates in place on open: `refs_known` on the log,
|
||||
`pinned` on objects, a `shade_vault_refs` table. No manual step.
|
||||
|
||||
## What the relay learns
|
||||
|
||||
Object sizes, how many objects there are, when commits happen, and that some
|
||||
opaque 64-hex id is active. Not contents, not paths, not filenames, and not
|
||||
which user a vaultId belongs to — the id is itself derived from a secret.
|
||||
|
||||
Deduplication is **within** a version chain, not across independent seals:
|
||||
sealing uses a fresh nonce, so identical plaintext yields different names.
|
||||
Convergent encryption would dedupe globally but leak which files two users
|
||||
share, which is exactly what a blind store must not do.
|
||||
|
||||
## Status
|
||||
|
||||
Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and
|
||||
tested, v2 format and prune included, with cross-language vectors. Not yet: a
|
||||
Postgres store, rate limiting on the vault routes, and the Kotlin port of v2.
|
||||
@@ -1,7 +1,9 @@
|
||||
{
|
||||
"name": "shade",
|
||||
"private": true,
|
||||
"workspaces": ["packages/*"],
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"scripts": {
|
||||
"test": "bun test --recursive",
|
||||
"test:core": "cd packages/shade-core && bun test",
|
||||
@@ -25,7 +27,8 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"bun-types": "^1.3.11",
|
||||
"fast-check": "^3.22.0"
|
||||
"fast-check": "^3.22.0",
|
||||
"typescript": "7.0.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/curves": "^2.0.1",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/cli",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/cli.ts",
|
||||
"bin": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/core",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -138,8 +138,13 @@ export async function senderKeyEncrypt(
|
||||
* Decrypt a sender key message. Verifies signature then advances the
|
||||
* appropriate chain key.
|
||||
*
|
||||
* Handles out-of-order delivery via skipped-key cache (simpler than Double
|
||||
* Ratchet since there's no DH ratchet).
|
||||
* Out-of-order delivery is NOT handled: the chain only moves forward and
|
||||
* the keys of skipped iterations are discarded, so a message that arrives
|
||||
* after its successor throws "Stale iteration". (This comment used to
|
||||
* claim a skipped-key cache that never existed.) Senders must therefore
|
||||
* deliver in iteration order — `Inbox` keeps per-recipient order across
|
||||
* retries for this reason. Prism's Android receiver keeps skipped keys;
|
||||
* porting that here needs a `skippedKeys` field in every storage backend.
|
||||
*/
|
||||
export async function senderKeyDecrypt(
|
||||
crypto: CryptoProvider,
|
||||
|
||||
@@ -86,6 +86,14 @@ export class ShadeSessionManager {
|
||||
* fully concurrent.
|
||||
*/
|
||||
private readonly peerOpChains = new Map<string, Promise<unknown>>();
|
||||
/**
|
||||
* Memoized `alias → canonical` lookups; `null` records "no alias" so a
|
||||
* label without one costs a single storage read for the life of the
|
||||
* process instead of one per encrypt/decrypt. Aliases change only via
|
||||
* the mutators in this class, each of which clears the whole map — it
|
||||
* holds at most one entry per peer, so rebuilding is cheap.
|
||||
*/
|
||||
private readonly aliasCache = new Map<string, string | null>();
|
||||
|
||||
constructor(
|
||||
private readonly crypto: CryptoProvider,
|
||||
@@ -151,6 +159,46 @@ export class ShadeSessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map a session label onto the label its state actually lives under.
|
||||
*
|
||||
* `aliasSession` moves a session from a first-contact label (typically
|
||||
* `fp:<hex>`) to the peer's canonical address, but the peer keeps
|
||||
* sending under the old one. The persisted alias lets us follow that
|
||||
* move across restarts — see the alias block in `StorageProvider`.
|
||||
*
|
||||
* A live session under `label` always wins: after a re-link the peer
|
||||
* re-runs X3DH and a fresh session is established under the
|
||||
* first-contact label again, and that new session — not the stale
|
||||
* alias target — is the one that can decrypt what follows.
|
||||
*
|
||||
* Resolves one hop only. Aliases are always written pointing at a
|
||||
* canonical label, so a chain would mean corrupt state; following it
|
||||
* would risk a loop for no legitimate gain.
|
||||
*
|
||||
* MUST be called before taking the peer mutex: locking the alias while
|
||||
* mutating the canonical session would let an aliased caller and a
|
||||
* canonical caller ratchet the same state concurrently.
|
||||
*/
|
||||
private async resolveLabel(label: string): Promise<string> {
|
||||
let canonical = this.aliasCache.get(label);
|
||||
if (canonical === undefined) {
|
||||
canonical = (await this.storage.getSessionAlias?.(label)) ?? null;
|
||||
this.aliasCache.set(label, canonical);
|
||||
}
|
||||
if (canonical === null || canonical === label) return label;
|
||||
if (await this.storage.getSession(label)) return label;
|
||||
return canonical;
|
||||
}
|
||||
|
||||
/**
|
||||
* Public label resolution for callers that need to know where a
|
||||
* peer's state lives (e.g. a transport routing an inbound frame).
|
||||
*/
|
||||
async resolveSessionLabel(label: string): Promise<string> {
|
||||
return this.resolveLabel(label);
|
||||
}
|
||||
|
||||
/** Get the event emitter (if observability is enabled) */
|
||||
getEvents(): ShadeEventEmitter | undefined {
|
||||
return this.events;
|
||||
@@ -268,6 +316,11 @@ export class ShadeSessionManager {
|
||||
*/
|
||||
async resetSession(address: string): Promise<void> {
|
||||
await this.storage.removeSession(address);
|
||||
// Aliases pointing here are now dangling — drop them so the next
|
||||
// first-contact frame resolves to its own label and establishes the
|
||||
// fresh session this reset exists to force.
|
||||
await this.storage.removeSessionAliasesFor?.(address);
|
||||
this.aliasCache.clear();
|
||||
this.events?.emit('session.removed', { address });
|
||||
// Note: we keep the trusted identity; new session will verify against it.
|
||||
}
|
||||
@@ -336,6 +389,14 @@ export class ShadeSessionManager {
|
||||
await this.storage.bumpPeerIdentityVersion(newLabel);
|
||||
}
|
||||
await this.storage.removeSession(oldLabel);
|
||||
// Remember the move durably. The peer goes on sending under
|
||||
// `oldLabel` — its transport derives the same first-contact label
|
||||
// from our relay hint every time — so without this record every
|
||||
// inbound frame after a restart resolves to a label whose session
|
||||
// we just removed, and the peer (holding a valid session, never
|
||||
// re-running X3DH) can never recover on its own.
|
||||
await this.storage.saveSessionAlias?.(oldLabel, newLabel);
|
||||
this.aliasCache.clear();
|
||||
this.events?.emit('session.aliased', { oldLabel, newLabel });
|
||||
}
|
||||
|
||||
@@ -349,6 +410,10 @@ export class ShadeSessionManager {
|
||||
// because isTrustedIdentity() compares not retrieves; we just emit the new hash)
|
||||
await this.storage.saveTrustedIdentity(address, newIdentityKey);
|
||||
await this.storage.removeSession(address);
|
||||
// The peer rotated identity — any alias into the old session is
|
||||
// dangling and must not redirect frames meant for the new one.
|
||||
await this.storage.removeSessionAliasesFor?.(address);
|
||||
this.aliasCache.clear();
|
||||
|
||||
if (this.events) {
|
||||
const newHash = await shortHash(this.crypto, newIdentityKey);
|
||||
@@ -516,14 +581,19 @@ export class ShadeSessionManager {
|
||||
* Subsequent messages are standard RatchetMessages.
|
||||
*/
|
||||
async encrypt(address: string, plaintext: string): Promise<ShadeEnvelope> {
|
||||
return this.withSpan('encrypt', address, async () => {
|
||||
const session = await this.storage.getSession(address);
|
||||
if (!session) throw new NoSessionError(address);
|
||||
// Follow a persisted alias so a caller still holding a first-contact
|
||||
// label reaches the session that alias moved to — without this, a
|
||||
// restarted host can decrypt a peer's frames but not reply to them.
|
||||
// Resolved before the mutex so the lock lands on the canonical label.
|
||||
const target = await this.resolveLabel(address);
|
||||
return this.withSpan('encrypt', target, async () => {
|
||||
const session = await this.storage.getSession(target);
|
||||
if (!session) throw new NoSessionError(target);
|
||||
|
||||
const ratchetMsg = await ratchetEncrypt(this.crypto, session, enc.encode(plaintext));
|
||||
|
||||
this.events?.emit('message.encrypted', {
|
||||
address,
|
||||
address: target,
|
||||
counter: ratchetMsg.counter,
|
||||
ciphertextSize: ratchetMsg.ciphertext.length,
|
||||
});
|
||||
@@ -532,7 +602,7 @@ export class ShadeSessionManager {
|
||||
const x3dh = (session as any).__x3dh;
|
||||
if (x3dh) {
|
||||
delete (session as any).__x3dh;
|
||||
await this.storage.saveSession(address, session);
|
||||
await this.storage.saveSession(target, session);
|
||||
|
||||
const preKeyMsg: PreKeyMessage = {
|
||||
registrationId: x3dh.registrationId,
|
||||
@@ -546,16 +616,16 @@ export class ShadeSessionManager {
|
||||
type: 'prekey',
|
||||
content: preKeyMsg,
|
||||
timestamp: Date.now(),
|
||||
senderAddress: address,
|
||||
senderAddress: target,
|
||||
};
|
||||
}
|
||||
|
||||
await this.storage.saveSession(address, session);
|
||||
await this.storage.saveSession(target, session);
|
||||
return {
|
||||
type: 'ratchet',
|
||||
content: ratchetMsg,
|
||||
timestamp: Date.now(),
|
||||
senderAddress: address,
|
||||
senderAddress: target,
|
||||
};
|
||||
});
|
||||
}
|
||||
@@ -564,11 +634,17 @@ export class ShadeSessionManager {
|
||||
* Decrypt a message from a peer. Handles both PreKeyMessage and RatchetMessage.
|
||||
*/
|
||||
async decrypt(address: string, envelope: ShadeEnvelope): Promise<string> {
|
||||
return this.withSpan('decrypt', address, async () => {
|
||||
// A prekey envelope carries its own X3DH material and establishes a
|
||||
// fresh session, which must land under the label it arrived on —
|
||||
// that is exactly what a re-link looks like. Only ratchet envelopes,
|
||||
// which need state that already exists, follow an alias.
|
||||
const target =
|
||||
envelope.type === 'prekey' ? address : await this.resolveLabel(address);
|
||||
return this.withSpan('decrypt', target, async () => {
|
||||
if (envelope.type === 'prekey') {
|
||||
return this.decryptPreKeyMessage(address, envelope.content as PreKeyMessage);
|
||||
return this.decryptPreKeyMessage(target, envelope.content as PreKeyMessage);
|
||||
}
|
||||
return this.decryptRatchetMessage(address, envelope.content as RatchetMessage);
|
||||
return this.decryptRatchetMessage(target, envelope.content as RatchetMessage);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -165,6 +165,36 @@ export interface StorageProvider {
|
||||
/** Remove session for a peer */
|
||||
removeSession(address: string): Promise<void>;
|
||||
|
||||
// ─── Session label aliases (V4.12) ────────────────────────
|
||||
//
|
||||
// First contact forces the receiver to label a session by the only
|
||||
// sender hint the relay surfaces — an 8-byte signing-key fingerprint
|
||||
// (`fp:<hex>`). A later in-band announcement reveals the peer's
|
||||
// canonical address and `aliasSession` moves the session there.
|
||||
//
|
||||
// The peer, however, keeps sending under whatever label its own
|
||||
// transport derives — which for a fingerprint-hinted relay is still
|
||||
// `fp:<hex>`. Before V4.12 that binding lived only in the consumer's
|
||||
// memory: after a restart the alias was gone, inbound ratchet frames
|
||||
// resolved to `fp:<hex>`, found no session there, and failed forever
|
||||
// (the peer holds a valid session so it never re-runs X3DH).
|
||||
//
|
||||
// Persisting the alias makes the binding survive restarts, so
|
||||
// `getSession` can follow it. Optional so third-party storage
|
||||
// implementations keep compiling — they simply lose alias recovery.
|
||||
|
||||
/**
|
||||
* Record that `alias` names the same peer session as `canonical`.
|
||||
* Idempotent upsert on `alias`.
|
||||
*/
|
||||
saveSessionAlias?(alias: string, canonical: string): Promise<void>;
|
||||
|
||||
/** Resolve an alias to its canonical label (null when unaliased). */
|
||||
getSessionAlias?(alias: string): Promise<string | null>;
|
||||
|
||||
/** Drop every alias pointing at `canonical` (session teardown). */
|
||||
removeSessionAliasesFor?(canonical: string): Promise<void>;
|
||||
|
||||
/** Check if we trust a remote identity key (for TOFU or pinned keys) */
|
||||
isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean>;
|
||||
|
||||
|
||||
165
packages/shade-core/tests/session-aliases.test.ts
Normal file
165
packages/shade-core/tests/session-aliases.test.ts
Normal file
@@ -0,0 +1,165 @@
|
||||
import { describe, test, expect, beforeEach } from 'bun:test';
|
||||
import { SubtleCryptoProvider, MemoryStorage } from '@shade/crypto-web';
|
||||
import { ShadeSessionManager } from '../src/index.js';
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
|
||||
/**
|
||||
* Durable session-label aliases (V4.12).
|
||||
*
|
||||
* THE BUG THIS FILE EXISTS TO KILL — diagnosed live in Prism:
|
||||
*
|
||||
* A phone pairs with a host. First contact forces the host to label
|
||||
* the session by the only sender hint the relay surfaces, an 8-byte
|
||||
* signing-key fingerprint (`fp:<hex>`). The pair handshake then
|
||||
* announces the phone's canonical address and the host calls
|
||||
* `aliasSession(fp:<hex> → device:<addr>)`, which moved the session
|
||||
* on disk and dropped the binding.
|
||||
*
|
||||
* The phone, however, keeps sending under `fp:<hex>` — its transport
|
||||
* derives the same label from the same relay hint every time. While
|
||||
* the host process lived, an in-memory map papered over the gap.
|
||||
* After a restart that map was empty, every inbound ratchet frame
|
||||
* resolved to `fp:<hex>`, found no session, and failed. The phone
|
||||
* held a perfectly valid session so it never re-ran X3DH — meaning
|
||||
* the failure was permanent and self-inflicted, not transient.
|
||||
*
|
||||
* Observed as `No session for address: fp:579c3b335d66e2c0` on every
|
||||
* receive for three days, with the phone's RPCs timing out forever.
|
||||
*
|
||||
* The fix: `aliasSession` persists the binding, and session lookup
|
||||
* follows it. These tests pin the restart behaviour specifically —
|
||||
* a same-process test cannot fail the way production did.
|
||||
*/
|
||||
describe('session label aliases', () => {
|
||||
let alice: ShadeSessionManager;
|
||||
let bob: ShadeSessionManager;
|
||||
let aliceStorage: MemoryStorage;
|
||||
let bobStorage: MemoryStorage;
|
||||
|
||||
/** The first-contact label Alice is forced to use for Bob. */
|
||||
const FP = 'fp:579c3b335d66e2c0';
|
||||
|
||||
beforeEach(async () => {
|
||||
aliceStorage = new MemoryStorage();
|
||||
bobStorage = new MemoryStorage();
|
||||
alice = new ShadeSessionManager(crypto, aliceStorage);
|
||||
bob = new ShadeSessionManager(crypto, bobStorage);
|
||||
await alice.initialize();
|
||||
await bob.initialize();
|
||||
});
|
||||
|
||||
/**
|
||||
* Bob initiates X3DH against Alice, exactly like a phone reaching a
|
||||
* host it just scanned. Returns Bob's first (prekey) envelope.
|
||||
*/
|
||||
async function bobInitiates(target: ShadeSessionManager, initiator: ShadeSessionManager) {
|
||||
const otpks = await target.generateOneTimePreKeys(10);
|
||||
const bundle = await target.createPreKeyBundle();
|
||||
const otpk = otpks[0]!;
|
||||
bundle.oneTimePreKey = { keyId: otpk.keyId, publicKey: otpk.keyPair.publicKey };
|
||||
await initiator.initSessionFromBundle('alice', bundle);
|
||||
}
|
||||
|
||||
/** Simulate a host restart: fresh manager, same durable storage. */
|
||||
async function restartAlice(): Promise<ShadeSessionManager> {
|
||||
const revived = new ShadeSessionManager(crypto, aliceStorage);
|
||||
await revived.initialize();
|
||||
return revived;
|
||||
}
|
||||
|
||||
test('an aliased session still decrypts under the old label after a restart', async () => {
|
||||
await bobInitiates(alice, bob);
|
||||
|
||||
// First contact lands under the fingerprint label.
|
||||
const env1 = await bob.encrypt('alice', 'hello, my address is bob');
|
||||
expect(await alice.decrypt(FP, env1)).toBe('hello, my address is bob');
|
||||
|
||||
// Alice canonicalizes to Bob's announced address.
|
||||
await alice.aliasSession(FP, 'bob');
|
||||
|
||||
// The host restarts. Storage survives; every in-memory map does not.
|
||||
const alice2 = await restartAlice();
|
||||
|
||||
// Bob has a valid session and keeps sending under the same label he
|
||||
// always has. Before the fix this threw NoSessionError forever.
|
||||
const env2 = await bob.encrypt('alice', 'still here after restart');
|
||||
expect(await alice2.decrypt(FP, env2)).toBe('still here after restart');
|
||||
});
|
||||
|
||||
test('the host can reply under the old label after a restart', async () => {
|
||||
await bobInitiates(alice, bob);
|
||||
const env1 = await bob.encrypt('alice', 'hi');
|
||||
await alice.decrypt(FP, env1);
|
||||
await alice.aliasSession(FP, 'bob');
|
||||
|
||||
const alice2 = await restartAlice();
|
||||
|
||||
// Decrypting is only half of it — a host that cannot encrypt back
|
||||
// leaves every RPC hanging just the same.
|
||||
const reply = await alice2.encrypt(FP, 'reply from the host');
|
||||
expect(await bob.decrypt('alice', reply)).toBe('reply from the host');
|
||||
});
|
||||
|
||||
test('a live session under the label wins over an alias (re-link)', async () => {
|
||||
await bobInitiates(alice, bob);
|
||||
const env1 = await bob.encrypt('alice', 'first pairing');
|
||||
await alice.decrypt(FP, env1);
|
||||
await alice.aliasSession(FP, 'bob');
|
||||
const alice2 = await restartAlice();
|
||||
|
||||
// Bob reinstalls: brand-new identity, same relay fingerprint label.
|
||||
const bob2Storage = new MemoryStorage();
|
||||
const bob2 = new ShadeSessionManager(crypto, bob2Storage);
|
||||
await bob2.initialize();
|
||||
await bobInitiates(alice2, bob2);
|
||||
|
||||
// The prekey envelope must establish a FRESH session under FP rather
|
||||
// than being redirected into the stale aliased one.
|
||||
const fresh1 = await bob2.encrypt('alice', 'fresh contact');
|
||||
expect(await alice2.decrypt(FP, fresh1)).toBe('fresh contact');
|
||||
|
||||
// And subsequent ratchet frames must keep using that new session.
|
||||
const fresh2 = await bob2.encrypt('alice', 'second message');
|
||||
expect(await alice2.decrypt(FP, fresh2)).toBe('second message');
|
||||
});
|
||||
|
||||
test('resolveSessionLabel reports where the state actually lives', async () => {
|
||||
await bobInitiates(alice, bob);
|
||||
const env1 = await bob.encrypt('alice', 'hi');
|
||||
await alice.decrypt(FP, env1);
|
||||
|
||||
expect(await alice.resolveSessionLabel(FP)).toBe(FP);
|
||||
await alice.aliasSession(FP, 'bob');
|
||||
|
||||
const alice2 = await restartAlice();
|
||||
expect(await alice2.resolveSessionLabel(FP)).toBe('bob');
|
||||
// An unaliased label resolves to itself.
|
||||
expect(await alice2.resolveSessionLabel('carol')).toBe('carol');
|
||||
});
|
||||
|
||||
test('resetSession drops aliases pointing at the cleared session', async () => {
|
||||
await bobInitiates(alice, bob);
|
||||
const env1 = await bob.encrypt('alice', 'hi');
|
||||
await alice.decrypt(FP, env1);
|
||||
await alice.aliasSession(FP, 'bob');
|
||||
expect(await aliceStorage.getSessionAlias(FP)).toBe('bob');
|
||||
|
||||
await alice.resetSession('bob');
|
||||
|
||||
// A dangling alias would redirect the next first-contact frame into
|
||||
// a session that no longer exists, defeating the reset.
|
||||
expect(await aliceStorage.getSessionAlias(FP)).toBeNull();
|
||||
expect(await alice.resolveSessionLabel(FP)).toBe(FP);
|
||||
});
|
||||
|
||||
test('aliasing persists the binding to storage', async () => {
|
||||
await bobInitiates(alice, bob);
|
||||
const env1 = await bob.encrypt('alice', 'hi');
|
||||
await alice.decrypt(FP, env1);
|
||||
|
||||
expect(await aliceStorage.getSessionAlias(FP)).toBeNull();
|
||||
await alice.aliasSession(FP, 'bob');
|
||||
expect(await aliceStorage.getSessionAlias(FP)).toBe('bob');
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/crypto-web",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -15,6 +15,8 @@ export class MemoryStorage implements StorageProvider {
|
||||
private signedPreKeys = new Map<number, SignedPreKey>();
|
||||
private oneTimePreKeys = new Map<number, OneTimePreKey>();
|
||||
private sessions = new Map<string, SessionState>();
|
||||
/** alias → canonical session label (V4.12). */
|
||||
private sessionAliases = new Map<string, string>();
|
||||
private trustedIdentities = new Map<string, Uint8Array>();
|
||||
private retiredIdentities: RetiredIdentity[] = [];
|
||||
|
||||
@@ -82,6 +84,22 @@ export class MemoryStorage implements StorageProvider {
|
||||
this.sessions.delete(address);
|
||||
}
|
||||
|
||||
// ─── Session label aliases ────────────────────────────────
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
return this.sessionAliases.get(alias) ?? null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
this.sessionAliases.set(alias, canonical);
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
for (const [alias, target] of this.sessionAliases) {
|
||||
if (target === canonical) this.sessionAliases.delete(alias);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
|
||||
@@ -59,26 +59,40 @@ describe('Cryptographic Hardening', () => {
|
||||
const mismatchAtEnd = new Uint8Array(target);
|
||||
mismatchAtEnd[len - 1] ^= 0xff;
|
||||
|
||||
// Measure many iterations to get a stable signal
|
||||
const iterations = 50000;
|
||||
const iterations = 20000;
|
||||
const measure = (other: Uint8Array): number => {
|
||||
const t0 = performance.now();
|
||||
for (let i = 0; i < iterations; i++) crypto.constantTimeEqual(target, other);
|
||||
return performance.now() - t0;
|
||||
};
|
||||
|
||||
const start1 = performance.now();
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
crypto.constantTimeEqual(target, mismatchAtStart);
|
||||
// Warm up before measuring anything. The first loop through this code
|
||||
// pays for JIT compilation that the second one does not, which biased
|
||||
// whichever side ran first and is why the old version had to "allow 2x
|
||||
// for JIT/noise" — a tolerance covering a measurement artefact rather
|
||||
// than the property under test.
|
||||
measure(mismatchAtStart);
|
||||
measure(mismatchAtEnd);
|
||||
|
||||
// Paired, interleaved samples, compared by median. A single pair is one
|
||||
// GC pause away from a false alarm: this test failed roughly one run in
|
||||
// fourteen on a loaded machine on 08.09.2026, and a security test that
|
||||
// cries wolf under load is a security test people learn to re-run until
|
||||
// it passes. The median throws out the pause instead of the property.
|
||||
const ratios: number[] = [];
|
||||
for (let round = 0; round < 5; round++) {
|
||||
const a = measure(mismatchAtStart);
|
||||
const b = measure(mismatchAtEnd);
|
||||
ratios.push(Math.max(a, b) / Math.min(a, b));
|
||||
}
|
||||
const timeStart = performance.now() - start1;
|
||||
ratios.sort((x, y) => x - y);
|
||||
const median = ratios[Math.floor(ratios.length / 2)]!;
|
||||
|
||||
const start2 = performance.now();
|
||||
for (let i = 0; i < iterations; i++) {
|
||||
crypto.constantTimeEqual(target, mismatchAtEnd);
|
||||
}
|
||||
const timeEnd = performance.now() - start2;
|
||||
|
||||
// With constant-time comparison, these should be very close.
|
||||
// Non-constant-time would show timeEnd >> timeStart (early exit vs full scan).
|
||||
// Allow 2x variance for JIT/noise, but it should never be 10x.
|
||||
const ratio = Math.max(timeStart, timeEnd) / Math.min(timeStart, timeEnd);
|
||||
expect(ratio).toBeLessThan(3);
|
||||
// The threshold is unchanged and deliberately so: an early-exit compare
|
||||
// would take ~256x longer to reach a mismatch in the last byte than the
|
||||
// first, on every single round. Nothing about sampling weakens what this
|
||||
// catches — it only stops the scheduler from answering for the code.
|
||||
expect(median).toBeLessThan(3);
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/dashboard",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/files",
|
||||
"version": "4.11.2",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/inbox-server",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/inbox",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -409,7 +409,17 @@ export class Inbox {
|
||||
});
|
||||
if (attempts >= this.maxAttempts) {
|
||||
await this.queueStore.remove(entry.recipientAddress, entry.msgId);
|
||||
// Given up on: it no longer holds a place in the order.
|
||||
continue;
|
||||
}
|
||||
// Head-of-line, on purpose. Carrying on with the next entry
|
||||
// delivers it AHEAD of this one, which is retried next round —
|
||||
// exactly the reordering the sequential bucket exists to
|
||||
// prevent. For sender-key broadcasts that is not cosmetic: a
|
||||
// receiver that sees iteration N+1 first can no longer open N
|
||||
// unless it kept N's key. One recipient's bucket waits; the
|
||||
// others drain in parallel as before.
|
||||
break;
|
||||
}
|
||||
}
|
||||
return count;
|
||||
|
||||
@@ -467,6 +467,58 @@ describe('Inbox orchestrator', () => {
|
||||
await aliceInbox.tick();
|
||||
expect(await aliceInbox.pendingCount()).toBe(0);
|
||||
});
|
||||
|
||||
test('a failed PUT holds back the rest of its recipient\'s queue, so order survives the retry', async () => {
|
||||
const store = new MemoryInboxStore();
|
||||
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||
const alice = await makeIdentity();
|
||||
const bob = await makeIdentity();
|
||||
const bobClient = new InboxClient({
|
||||
baseUrl: 'http://localhost',
|
||||
crypto,
|
||||
signingPrivateKey: bob.signingPrivateKey,
|
||||
fetch: honoFetch(app),
|
||||
});
|
||||
await bobClient.register({ address: 'bob', signingKey: bob.signingPublicKey });
|
||||
|
||||
// The FIRST PUT fails once. Before the fix the second envelope was
|
||||
// delivered in the same round and the first only on the retry —
|
||||
// bob received them in the wrong order.
|
||||
let failsLeft = 1;
|
||||
const flakyFetch: typeof fetch = (async (input, init) => {
|
||||
const m = (init as RequestInit | undefined)?.method ?? 'GET';
|
||||
const u = typeof input === 'string' ? input : input instanceof URL ? input.toString() : (input as Request).url;
|
||||
if (m === 'POST' && u.includes('/v1/inbox/bob') && !u.includes('/fetch') && failsLeft > 0) {
|
||||
failsLeft--;
|
||||
throw new Error('transient network');
|
||||
}
|
||||
return honoFetch(app)(input, init);
|
||||
}) as typeof fetch;
|
||||
|
||||
const aliceInbox = new Inbox({
|
||||
baseUrl: 'http://localhost',
|
||||
ownAddress: 'alice',
|
||||
crypto,
|
||||
signingPrivateKey: alice.signingPrivateKey,
|
||||
signingPublicKey: alice.signingPublicKey,
|
||||
pollIntervalMs: 0,
|
||||
fetch: flakyFetch,
|
||||
queueStore: new MemoryOutgoingQueueStore(),
|
||||
});
|
||||
const delivered: string[] = [];
|
||||
aliceInbox.on((e) => {
|
||||
if (e.name === 'inbox.message_delivered') delivered.push(e.data.msgId);
|
||||
});
|
||||
|
||||
const first = await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(40) });
|
||||
const second = await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(40) });
|
||||
|
||||
await aliceInbox.tick();
|
||||
expect(delivered).toEqual([]);
|
||||
expect(await aliceInbox.pendingCount()).toBe(2);
|
||||
await aliceInbox.tick();
|
||||
expect(delivered).toEqual([first, second]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tamper detection', () => {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/key-transparency",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/keychain",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/observability",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/observer",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/proto",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/recovery",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/sdk",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { StorageProvider } from '@shade/core';
|
||||
import { ConfigurationError } from '@shade/core';
|
||||
import type { ObservabilityHook } from '@shade/observability';
|
||||
import { DEFAULT_REQUEST_TIMEOUT_MS } from '@shade/transport';
|
||||
|
||||
/**
|
||||
* Shade SDK configuration.
|
||||
@@ -84,6 +85,29 @@ export interface ShadeConfig {
|
||||
* Default: KT verification disabled. Set this to enable.
|
||||
*/
|
||||
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`. */
|
||||
@@ -117,6 +141,9 @@ export interface ResolvedConfig {
|
||||
};
|
||||
observability?: ObservabilityHook;
|
||||
keyTransparency?: ResolvedKTConfig;
|
||||
registration: 'await' | 'background';
|
||||
requestTimeoutMs: number;
|
||||
fetch?: typeof fetch;
|
||||
}
|
||||
|
||||
export interface ResolvedKTConfig {
|
||||
@@ -146,8 +173,20 @@ export function resolveConfig(input: ShadeConfig): ResolvedConfig {
|
||||
address: input.address,
|
||||
autoReplenish,
|
||||
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.token || input.observer.token.length < 16) {
|
||||
throw new ConfigurationError('observer.token must be at least 16 characters');
|
||||
|
||||
@@ -143,6 +143,9 @@ export interface ShadeUploadOptions extends TransferOptions {
|
||||
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.
|
||||
*
|
||||
@@ -157,6 +160,9 @@ export class Shade {
|
||||
private manager!: ShadeSessionManager;
|
||||
private transport!: ShadeFetchTransport;
|
||||
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 initialized = false;
|
||||
|
||||
@@ -279,28 +285,23 @@ export class Shade {
|
||||
};
|
||||
}
|
||||
|
||||
this.transport = new ShadeFetchTransport({
|
||||
baseUrl: this.config.prekeyServer,
|
||||
crypto: this.crypto,
|
||||
signingPrivateKey: identity.signingPrivateKey,
|
||||
...(ktOpts ? { keyTransparency: ktOpts } : {}),
|
||||
});
|
||||
this.transport = this.makeTransport(identity.signingPrivateKey, ktOpts);
|
||||
|
||||
// Step 5: Initial prekeys + register
|
||||
const otpks = await this.manager.generateOneTimePreKeys(20);
|
||||
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 {
|
||||
await this.transport.register(
|
||||
this.address,
|
||||
this.manager.getPublicIdentity(),
|
||||
bundle.signedPreKey,
|
||||
otpks,
|
||||
);
|
||||
await register();
|
||||
} catch (err) {
|
||||
console.warn(
|
||||
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${(err as Error).message}. Will retry on next replenish.`,
|
||||
);
|
||||
this.retryRegistration(register, 1, undefined, err as Error);
|
||||
}
|
||||
}
|
||||
|
||||
// Step 6: Background tasks
|
||||
@@ -701,6 +702,22 @@ export class Shade {
|
||||
this.decryptChains.delete(oldLabel);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a session label to the label its state actually lives under,
|
||||
* following any alias left behind by `aliasSession`.
|
||||
*
|
||||
* Transports need this to route by the canonical address after a
|
||||
* restart, when the only sender hint they hold is the first-contact
|
||||
* `fp:<hex>` label. `encrypt`/`decrypt` resolve internally — this is
|
||||
* for callers that must know the address itself.
|
||||
*
|
||||
* V4.12 — durable session-label aliases.
|
||||
*/
|
||||
async resolveSessionLabel(label: string): Promise<string> {
|
||||
if (!this.initialized) throw new Error('Not initialized');
|
||||
return this.manager.resolveSessionLabel(label);
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept a peer's rotated identity. Bumps the per-peer identity-version
|
||||
* counter so any earlier verification automatically goes stale, then
|
||||
@@ -726,6 +743,10 @@ export class Shade {
|
||||
async rotate(): Promise<void> {
|
||||
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
|
||||
const newBundle = await this.manager.rotateIdentity();
|
||||
|
||||
@@ -733,11 +754,7 @@ export class Shade {
|
||||
// signed operations (replenish, delete, register) work
|
||||
const identity = await this.storage.getIdentityKeyPair();
|
||||
if (!identity) throw new Error('Identity missing after rotate');
|
||||
this.transport = new ShadeFetchTransport({
|
||||
baseUrl: this.config.prekeyServer,
|
||||
crypto: this.crypto,
|
||||
signingPrivateKey: identity.signingPrivateKey,
|
||||
});
|
||||
this.transport = this.makeTransport(identity.signingPrivateKey);
|
||||
|
||||
// Re-upload the new bundle
|
||||
await this.transport.register(
|
||||
@@ -806,17 +823,79 @@ export class Shade {
|
||||
: {}),
|
||||
});
|
||||
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,
|
||||
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 */
|
||||
async shutdown(): Promise<void> {
|
||||
this._background?.stop();
|
||||
this.cancelRegistrationRetry();
|
||||
this.shutDown = true;
|
||||
if (this.transferEngine !== null) this.transferEngine.destroy();
|
||||
if (this.controlChannel !== null) this.controlChannel.destroy();
|
||||
if (this.webrtcRuntime !== null) {
|
||||
|
||||
@@ -14,8 +14,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
store: new MemoryPrekeyStore(),
|
||||
disableRateLimit: true,
|
||||
});
|
||||
const port = 19500 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
|
||||
@@ -12,8 +12,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
store: new MemoryPrekeyStore(),
|
||||
disableRateLimit: true,
|
||||
});
|
||||
const port = 19500 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
|
||||
@@ -36,8 +36,12 @@ async function startServer(): Promise<ServerHandle> {
|
||||
blobStore: new MemoryBlobStore(),
|
||||
disableRateLimit: true,
|
||||
});
|
||||
const port = 19000 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: app.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: app.fetch });
|
||||
const port = handle.port;
|
||||
return {
|
||||
url: `http://localhost:${port}`,
|
||||
stop: () => handle.stop(true),
|
||||
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -25,8 +25,12 @@ async function startPrekeyServer(): Promise<{
|
||||
disableRateLimit: true,
|
||||
events,
|
||||
});
|
||||
const port = 19500 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return {
|
||||
url: `http://localhost:${port}`,
|
||||
stop: () => handle.stop(),
|
||||
@@ -162,10 +166,15 @@ describe('createShade — happy path', () => {
|
||||
const env3 = await alice.send('bob', 'reply 2');
|
||||
expect(await bob.receive('alice', env3)).toBe('reply 2');
|
||||
|
||||
// The old fp-label has no session — receive under it would now
|
||||
// fail. (We don't assert the error shape, only that the label is
|
||||
// gone.)
|
||||
await expect(alice.receive(fpLabel, env3)).rejects.toThrow();
|
||||
// V4.12: the fp-label is no longer a dead end. `aliasSession` leaves
|
||||
// a durable binding behind, so a peer that keeps sending under the
|
||||
// first-contact label — which is exactly what a fingerprint-hinted
|
||||
// relay makes it do — still reaches the canonicalized session.
|
||||
// See `shade-core/tests/session-aliases.test.ts` for the restart
|
||||
// behaviour this binding exists to protect.
|
||||
expect(await alice.resolveSessionLabel(fpLabel)).toBe('bob');
|
||||
const env4 = await bob.send('alice', 'reply 3');
|
||||
expect(await alice.receive(fpLabel, env4)).toBe('reply 3');
|
||||
});
|
||||
|
||||
test('aliasSession refuses to overwrite an existing session', async () => {
|
||||
|
||||
@@ -26,8 +26,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
disableRateLimit: true,
|
||||
events,
|
||||
});
|
||||
const port = 21000 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
@@ -46,8 +50,12 @@ async function setupRig(): Promise<TestRig> {
|
||||
|
||||
// Spin up Bob's HTTP transfer endpoint.
|
||||
const bobApp = await bob.transferRoute();
|
||||
const port = 21500 + Math.floor(Math.random() * 500);
|
||||
const bobServer = Bun.serve({ port, fetch: bobApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const bobServer = Bun.serve({ port: 0, fetch: bobApp.fetch });
|
||||
const port = bobServer.port;
|
||||
const bobBaseUrl = `http://localhost:${port}`;
|
||||
|
||||
// Wire up Alice's outgoing transfer routing.
|
||||
|
||||
@@ -33,8 +33,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
disableRateLimit: true,
|
||||
events,
|
||||
});
|
||||
const port = 22000 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
@@ -49,8 +53,12 @@ async function setupRig(): Promise<TestRig> {
|
||||
},
|
||||
});
|
||||
const bobApp = await bob.transferRoute();
|
||||
const port = 22500 + Math.floor(Math.random() * 500);
|
||||
const bobServer = Bun.serve({ port, fetch: bobApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const bobServer = Bun.serve({ port: 0, fetch: bobApp.fetch });
|
||||
const port = bobServer.port;
|
||||
const bobBaseUrl = `http://localhost:${port}`;
|
||||
|
||||
alice.configureTransfers({
|
||||
|
||||
@@ -103,8 +103,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
disableRateLimit: true,
|
||||
events,
|
||||
});
|
||||
const port = 23000 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
@@ -127,13 +131,21 @@ async function setupRig(connectTimeoutMs: number): Promise<Rig> {
|
||||
bob.configureWebRTC({ factory: broken, connectTimeoutMs });
|
||||
|
||||
const bobApp = await bob.transferRoute();
|
||||
const bobPort = 23500 + Math.floor(Math.random() * 500);
|
||||
const bobServer = Bun.serve({ port: bobPort, fetch: bobApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const bobServer = Bun.serve({ port: 0, fetch: bobApp.fetch });
|
||||
const bobPort = bobServer.port;
|
||||
baseUrls.set('bob', `http://localhost:${bobPort}`);
|
||||
|
||||
const aliceApp = await alice.transferRoute();
|
||||
const alicePort = 24000 + Math.floor(Math.random() * 500);
|
||||
const aliceServer = Bun.serve({ port: alicePort, fetch: aliceApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const aliceServer = Bun.serve({ port: 0, fetch: aliceApp.fetch });
|
||||
const alicePort = aliceServer.port;
|
||||
baseUrls.set('alice', `http://localhost:${alicePort}`);
|
||||
|
||||
return {
|
||||
@@ -145,12 +157,18 @@ async function setupRig(connectTimeoutMs: number): Promise<Rig> {
|
||||
};
|
||||
}
|
||||
|
||||
async function teardownRig(rig: Rig): Promise<void> {
|
||||
await rig.alice.shutdown();
|
||||
await rig.bob.shutdown();
|
||||
rig.bobServerStop();
|
||||
rig.aliceServerStop();
|
||||
rig.prekeyStop();
|
||||
async function teardownRig(rig: Rig | undefined): Promise<void> {
|
||||
// Tolerates a rig that never finished being built. When setupRig threw —
|
||||
// EADDRINUSE, before ports stopped being guessed — this ran anyway and died
|
||||
// on `rig.alice`, so one failure became two and the second one, a TypeError
|
||||
// in teardown, is what you saw first. Cleanup must never be the loudest
|
||||
// thing in a failing test.
|
||||
if (!rig) return;
|
||||
await rig.alice?.shutdown().catch(() => {});
|
||||
await rig.bob?.shutdown().catch(() => {});
|
||||
try { rig.bobServerStop?.(); } catch { /* already gone */ }
|
||||
try { rig.aliceServerStop?.(); } catch { /* already gone */ }
|
||||
try { rig.prekeyStop?.(); } catch { /* already gone */ }
|
||||
}
|
||||
|
||||
function hex(b: Uint8Array): string {
|
||||
|
||||
@@ -40,8 +40,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
disableRateLimit: true,
|
||||
events,
|
||||
});
|
||||
const port = 22000 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
@@ -70,13 +74,21 @@ async function setupRig(): Promise<Rig> {
|
||||
bob.configureWebRTC({ factory, connectTimeoutMs: 10_000 });
|
||||
|
||||
const bobApp = await bob.transferRoute();
|
||||
const bobPort = 22500 + Math.floor(Math.random() * 500);
|
||||
const bobServer = Bun.serve({ port: bobPort, fetch: bobApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const bobServer = Bun.serve({ port: 0, fetch: bobApp.fetch });
|
||||
const bobPort = bobServer.port;
|
||||
const bobBaseUrl = `http://localhost:${bobPort}`;
|
||||
|
||||
const aliceApp = await alice.transferRoute();
|
||||
const alicePort = 22000 + Math.floor(Math.random() * 500);
|
||||
const aliceServer = Bun.serve({ port: alicePort, fetch: aliceApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const aliceServer = Bun.serve({ port: 0, fetch: aliceApp.fetch });
|
||||
const alicePort = aliceServer.port;
|
||||
const aliceBaseUrl = `http://localhost:${alicePort}`;
|
||||
|
||||
baseUrls.set('alice', aliceBaseUrl);
|
||||
|
||||
@@ -44,8 +44,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
||||
disableRateLimit: true,
|
||||
events,
|
||||
});
|
||||
const port = 24500 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
||||
const port = handle.port;
|
||||
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||
}
|
||||
|
||||
@@ -70,13 +74,21 @@ async function setupRig(opts: { withWebRTC: boolean }): Promise<Rig> {
|
||||
}
|
||||
|
||||
const bobApp = await bob.transferRoute();
|
||||
const bobPort = 25000 + Math.floor(Math.random() * 500);
|
||||
const bobServer = Bun.serve({ port: bobPort, fetch: bobApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const bobServer = Bun.serve({ port: 0, fetch: bobApp.fetch });
|
||||
const bobPort = bobServer.port;
|
||||
baseUrls.set('bob', `http://localhost:${bobPort}`);
|
||||
|
||||
const aliceApp = await alice.transferRoute();
|
||||
const alicePort = 25500 + Math.floor(Math.random() * 500);
|
||||
const aliceServer = Bun.serve({ port: alicePort, fetch: aliceApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const aliceServer = Bun.serve({ port: 0, fetch: aliceApp.fetch });
|
||||
const alicePort = aliceServer.port;
|
||||
baseUrls.set('alice', `http://localhost:${alicePort}`);
|
||||
|
||||
return {
|
||||
|
||||
@@ -9,10 +9,15 @@ COPY package.json bun.lock tsconfig.json ./
|
||||
# Copy all packages the server + observer + dashboard need
|
||||
COPY packages ./packages
|
||||
|
||||
RUN bun install --frozen-lockfile
|
||||
# BuildKit gives each RUN a 1024 soft file-descriptor limit while the hard
|
||||
# limit is ~1M. bun extracts tarballs in parallel, so a large package can
|
||||
# exhaust the descriptors and the install dies with "Fail extracting tarball"
|
||||
# — reproducible in a build, invisible outside one because `docker run`
|
||||
# inherits a far higher limit. Raise the soft limit to what the host allows.
|
||||
RUN ulimit -n "$(ulimit -Hn)" && bun install --frozen-lockfile
|
||||
|
||||
# Build the dashboard SPA → dist/, then copy to observer's dist/
|
||||
RUN cd packages/shade-dashboard && bun run build
|
||||
RUN ulimit -n "$(ulimit -Hn)" && cd packages/shade-dashboard && bun run build
|
||||
|
||||
# ─── Production stage ───────────────────────────────────────
|
||||
FROM oven/bun:1-alpine
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/server",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
@@ -9,6 +9,8 @@
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/key-transparency": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
"@shade/storage-sqlite": "workspace:*",
|
||||
"@shade/vault": "workspace:*",
|
||||
"hono": "^4.12.12"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
|
||||
@@ -83,6 +83,30 @@ async function createInboxStore(): Promise<InboxStore & { close?: () => void | P
|
||||
* also opt the blob store *off* entirely via `SHADE_DISABLE_BLOB=1` —
|
||||
* useful for relays that only want the inbox surface.
|
||||
*/
|
||||
/**
|
||||
* Build the vault store, or `null` when none is configured.
|
||||
*
|
||||
* Deliberately NOT falling back to an in-memory store the way the blob
|
||||
* primitive does. A vault holds the user's actual files: an in-memory one
|
||||
* accepts every write, serves every read, and loses the lot on the next
|
||||
* container recreate — a backup that reports success and is not there. The
|
||||
* blob store's silent fallback destroyed Prism's profile on 2026-08-12
|
||||
* precisely because nothing failed loudly. Here, no path means no vault.
|
||||
*/
|
||||
async function createVaultStore(): Promise<import('@shade/vault').VaultStore | null> {
|
||||
const sqlitePath = process.env.SHADE_VAULT_DB_PATH;
|
||||
if (!sqlitePath) {
|
||||
logger.warn(
|
||||
'Vault not enabled — set SHADE_VAULT_DB_PATH to a path on a persistent volume. ' +
|
||||
'There is no in-memory fallback on purpose: a vault that forgets is not a backup.',
|
||||
);
|
||||
return null;
|
||||
}
|
||||
const { SqliteVaultStore } = await import('@shade/storage-sqlite');
|
||||
logger.info('Using SQLite vault store', { path: sqlitePath });
|
||||
return new SqliteVaultStore(sqlitePath);
|
||||
}
|
||||
|
||||
async function createBlobStore(): Promise<BlobStore & { close?: () => void | Promise<void> }> {
|
||||
const sqlitePath = process.env.SHADE_BLOB_DB_PATH;
|
||||
const pgUrl = process.env.SHADE_BLOB_PG_URL ?? process.env.SHADE_PREKEY_PG_URL;
|
||||
@@ -255,6 +279,21 @@ if (blobDisabled) {
|
||||
logger.info('Blob primitive enabled', { route: '/v1/blob/:slotId' });
|
||||
}
|
||||
|
||||
// V4.13 — vault: server-side encrypted file store. Where the blob primitive
|
||||
// holds one small blob per account, a vault holds a whole collection with an
|
||||
// append-only version log. Off unless a store is configured, because a vault
|
||||
// that silently lives in RAM is worse than no vault at all — see the warning
|
||||
// on SHADE_VAULT_DB_PATH below.
|
||||
const vaultDisabled = process.env.SHADE_DISABLE_VAULT === '1';
|
||||
const vaultStore = vaultDisabled ? null : await createVaultStore();
|
||||
if (vaultDisabled) {
|
||||
logger.info('Vault disabled (SHADE_DISABLE_VAULT=1)');
|
||||
} else if (vaultStore) {
|
||||
const { createVaultRoutes } = await import('@shade/vault/server');
|
||||
app.route('/', createVaultRoutes(vaultStore, crypto));
|
||||
logger.info('Vault enabled', { route: '/v1/vault/:vaultId' });
|
||||
}
|
||||
|
||||
// ─── Optional: Observer + Dashboard ──────────────────────────
|
||||
|
||||
const observerToken = process.env.SHADE_OBSERVER_TOKEN;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-encrypted",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -34,12 +34,16 @@ export {
|
||||
deriveBlobSlotId,
|
||||
deriveBlobKey,
|
||||
deriveBlobSigningSeed,
|
||||
deriveVaultId,
|
||||
deriveVaultContentKey,
|
||||
deriveVaultSigningSeed,
|
||||
} from './crypto/kdf.js';
|
||||
export {
|
||||
AEAD_NONCE_LEN,
|
||||
AEAD_TAG_LEN,
|
||||
aeadSeal,
|
||||
aeadOpen,
|
||||
randomNonce,
|
||||
} from './crypto/aead.js';
|
||||
export {
|
||||
COL,
|
||||
|
||||
@@ -33,9 +33,32 @@ async function importKey(key: Uint8Array, usages: WebCryptoKeyUsage[]): Promise<
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a plaintext blob with the given key and a deterministic nonce.
|
||||
* Returns `nonce || ct||tag` as a single Uint8Array suitable for direct
|
||||
* BLOB storage.
|
||||
* A fresh random 12-byte nonce.
|
||||
*
|
||||
* AES-GCM tolerates key reuse but not (key, nonce) reuse: two ciphertexts
|
||||
* sealed under the same pair leak the XOR of their plaintexts and, worse,
|
||||
* the GHASH authentication subkey — the "forbidden attack", which yields
|
||||
* tag forgery for that key. Mutable rows are re-sealed on every change
|
||||
* (`saveSession` runs on each ratchet step), so a nonce derived from row
|
||||
* identity alone repeats by construction.
|
||||
*
|
||||
* Random beats a counter here because the codec is shared across SQLite
|
||||
* and Postgres and has no durable per-row write counter to lean on. At
|
||||
* 96 bits, collision probability stays negligible far past any realistic
|
||||
* number of re-saves.
|
||||
*/
|
||||
export function randomNonce(): Uint8Array {
|
||||
return globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LEN));
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt a plaintext blob with the given key and nonce. Returns
|
||||
* `nonce || ct||tag` as a single Uint8Array suitable for direct BLOB
|
||||
* storage.
|
||||
*
|
||||
* Callers must pass a nonce that is fresh for this key — see
|
||||
* {@link randomNonce}. Never derive one deterministically from row
|
||||
* identity for a row that can be written more than once.
|
||||
*/
|
||||
export async function aeadSeal(
|
||||
key: Uint8Array,
|
||||
@@ -58,9 +81,19 @@ export async function aeadSeal(
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt a `nonce || ct||tag` blob. The expected nonce is verified against
|
||||
* the prefix to detect tampering before we even reach the AEAD; if the
|
||||
* caller passes a `expectedNonce`, mismatch throws before SubtleCrypto runs.
|
||||
* Decrypt a `nonce || ct||tag` blob.
|
||||
*
|
||||
* The nonce always comes from the blob prefix, which is what makes the
|
||||
* move to random nonces backward compatible: a blob sealed under the old
|
||||
* deterministic scheme opens unchanged, because its nonce was already
|
||||
* stored the same way.
|
||||
*
|
||||
* @param expectedNonce **Deprecated.** Only meaningful when the nonce is
|
||||
* a pure function of row identity, which is exactly the pattern that made
|
||||
* (key, nonce) repeat. It adds no tamper detection that the AEAD tag and
|
||||
* the (table, column, pk) AAD do not already provide — a flipped bit in
|
||||
* the nonce fails the tag. Retained so existing callers keep compiling;
|
||||
* pass nothing.
|
||||
*/
|
||||
export async function aeadOpen(
|
||||
key: Uint8Array,
|
||||
|
||||
@@ -106,12 +106,20 @@ export function deriveFieldKey(storageKey: Uint8Array, table: string, column: st
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a deterministic 12-byte AEAD nonce from a row key (typically the
|
||||
* field key) plus (table, pk) binding. With per-field keys, deterministic
|
||||
* nonces are safe because each (key, plaintext) pair appears at most once
|
||||
* — re-saving the same row reuses the (nonce, key) pair only because the
|
||||
* plaintext also changes (chain ratchet, prekey state, etc.). The AAD
|
||||
* also binds (table, column, pk) so swapping is rejected on decrypt.
|
||||
* Derive a deterministic 12-byte AEAD nonce from a row key plus (table, pk).
|
||||
*
|
||||
* @deprecated Unsafe for anything that can be written twice, which is every
|
||||
* mutable row. The original rationale held that re-saving a row was fine
|
||||
* "because the plaintext also changes" — but that is precisely the case
|
||||
* AES-GCM forbids: reusing (key, nonce) across *different* plaintexts leaks
|
||||
* their XOR and the GHASH subkey (the forbidden attack), enabling tag
|
||||
* forgery. `saveSession` re-seals on every ratchet step, so the pair
|
||||
* repeated by construction. Use {@link randomNonce} from `./aead.js`.
|
||||
*
|
||||
* Kept exported (it is part of the published surface via `index.ts` and
|
||||
* `crypto.ts`) so consumers keep compiling. No caller inside this package
|
||||
* uses it any more. Reading old data needs no migration: `aeadOpen` has
|
||||
* always taken the nonce from the blob prefix.
|
||||
*/
|
||||
export function deriveNonce(rowKey: Uint8Array, table: string, pk: string): Uint8Array {
|
||||
const out = hkdfDerive(rowKey, `shade-row-nonce-v1:${table}:${pk}`, 12);
|
||||
@@ -161,3 +169,42 @@ export function deriveBlobKey(masterKey: Uint8Array, app: string): Uint8Array {
|
||||
export function deriveBlobSigningSeed(masterKey: Uint8Array, app: string): Uint8Array {
|
||||
return hkdfDerive(masterKey, `shade-blob-sig-v1:${app}`, 32);
|
||||
}
|
||||
|
||||
// ─── V4.13 — vault (server-side encrypted file store) ──────────
|
||||
//
|
||||
// The blob primitive above holds ONE small blob per slot. A vault holds
|
||||
// a whole collection — a project workspace, a mailbox, a drive folder —
|
||||
// as content-addressed objects plus an append-only log of manifests.
|
||||
//
|
||||
// Its own HKDF branch rather than a reuse of `shade-blob-*-v1`, for two
|
||||
// reasons. A vault key is used on far more ciphertext than a profile
|
||||
// blob ever is, and the two have different blast radii: whoever holds
|
||||
// the vault key can read every file, while the profile key exposes only
|
||||
// the host list. Separate labels mean compromising one cannot be turned
|
||||
// into the other, even though both hang off the same master.
|
||||
//
|
||||
// vaultId = HKDF(masterKey, info=`shade-vault-id-v1:${app}`)
|
||||
// contentKey = HKDF(masterKey, info=`shade-vault-content-v1:${app}`)
|
||||
// sigSeed = HKDF(masterKey, info=`shade-vault-sig-v1:${app}`)
|
||||
|
||||
/** 32-byte vault identifier. Opaque to the relay, like a slotId. */
|
||||
export function deriveVaultId(masterKey: Uint8Array, app: string): Uint8Array {
|
||||
return hkdfDerive(masterKey, `shade-vault-id-v1:${app}`, 32);
|
||||
}
|
||||
|
||||
/**
|
||||
* AEAD key for the vault's objects and manifests.
|
||||
*
|
||||
* One key for the whole collection, not one per file: per-file keys would
|
||||
* have to be stored somewhere, and that somewhere would be a manifest
|
||||
* encrypted under a collection key anyway. Object AAD binds the content
|
||||
* hash, so a ciphertext cannot be moved to another object's name.
|
||||
*/
|
||||
export function deriveVaultContentKey(masterKey: Uint8Array, app: string): Uint8Array {
|
||||
return hkdfDerive(masterKey, `shade-vault-content-v1:${app}`, 32);
|
||||
}
|
||||
|
||||
/** 32-byte Ed25519 signing seed; TOFU-pinned by the relay on first write. */
|
||||
export function deriveVaultSigningSeed(masterKey: Uint8Array, app: string): Uint8Array {
|
||||
return hkdfDerive(masterKey, `shade-vault-sig-v1:${app}`, 32);
|
||||
}
|
||||
|
||||
@@ -22,8 +22,8 @@ import {
|
||||
serializeSignedPreKey, deserializeSignedPreKey,
|
||||
toBase64, fromBase64,
|
||||
} from '@shade/core';
|
||||
import { aeadOpen, aeadSeal } from './aead.js';
|
||||
import { buildAad, deriveNonce } from './kdf.js';
|
||||
import { aeadOpen, aeadSeal, randomNonce } from './aead.js';
|
||||
import { buildAad } from './kdf.js';
|
||||
import type { KeyManager } from './key-manager.js';
|
||||
|
||||
const TEXT_ENCODER = new TextEncoder();
|
||||
@@ -64,9 +64,8 @@ export async function sealString(
|
||||
plaintext: string,
|
||||
): Promise<Uint8Array> {
|
||||
const key = km.fieldKey(table, column);
|
||||
const nonce = deriveNonce(key, table, pk);
|
||||
const aad = buildAad(table, column, pk);
|
||||
return aeadSeal(key, nonce, TEXT_ENCODER.encode(plaintext), aad);
|
||||
return aeadSeal(key, randomNonce(), TEXT_ENCODER.encode(plaintext), aad);
|
||||
}
|
||||
|
||||
/** Decrypt a blob into a string, reconstructing AAD from (table, column, pk). */
|
||||
@@ -78,9 +77,8 @@ export async function openString(
|
||||
blob: Uint8Array,
|
||||
): Promise<string> {
|
||||
const key = km.fieldKey(table, column);
|
||||
const expectedNonce = deriveNonce(key, table, pk);
|
||||
const aad = buildAad(table, column, pk);
|
||||
const pt = await aeadOpen(key, blob, aad, expectedNonce);
|
||||
const pt = await aeadOpen(key, blob, aad);
|
||||
return TEXT_DECODER.decode(pt);
|
||||
}
|
||||
|
||||
@@ -93,9 +91,8 @@ export async function sealBytes(
|
||||
plaintext: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const key = km.fieldKey(table, column);
|
||||
const nonce = deriveNonce(key, table, pk);
|
||||
const aad = buildAad(table, column, pk);
|
||||
return aeadSeal(key, nonce, plaintext, aad);
|
||||
return aeadSeal(key, randomNonce(), plaintext, aad);
|
||||
}
|
||||
|
||||
/** Decrypt arbitrary bytes payload. */
|
||||
@@ -107,9 +104,8 @@ export async function openBytes(
|
||||
blob: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
const key = km.fieldKey(table, column);
|
||||
const expectedNonce = deriveNonce(key, table, pk);
|
||||
const aad = buildAad(table, column, pk);
|
||||
return aeadOpen(key, blob, aad, expectedNonce);
|
||||
return aeadOpen(key, blob, aad);
|
||||
}
|
||||
|
||||
// ─── Typed encoders for each StorageProvider entity ──────────────────────
|
||||
|
||||
@@ -19,12 +19,16 @@ export {
|
||||
deriveBlobSlotId,
|
||||
deriveBlobKey,
|
||||
deriveBlobSigningSeed,
|
||||
deriveVaultId,
|
||||
deriveVaultContentKey,
|
||||
deriveVaultSigningSeed,
|
||||
} from './crypto/kdf.js';
|
||||
export {
|
||||
AEAD_NONCE_LEN,
|
||||
AEAD_TAG_LEN,
|
||||
aeadSeal,
|
||||
aeadOpen,
|
||||
randomNonce,
|
||||
} from './crypto/aead.js';
|
||||
export { EncryptedSQLiteStorage } from './storage/encrypted-sqlite.js';
|
||||
export {
|
||||
|
||||
@@ -100,6 +100,10 @@ export class EncryptedIndexedDBStorage implements StorageProvider {
|
||||
});
|
||||
members.createIndex('byChannelId', 'channelId');
|
||||
}
|
||||
if (oldVersion < 3) {
|
||||
const aliases = db.createObjectStore('session_aliases_enc', { keyPath: 'alias' });
|
||||
aliases.createIndex('byCanonical', 'canonical');
|
||||
}
|
||||
},
|
||||
});
|
||||
const store = new EncryptedIndexedDBStorage(db, opts.keyManager);
|
||||
@@ -212,6 +216,27 @@ export class EncryptedIndexedDBStorage implements StorageProvider {
|
||||
await this.db.delete('sessions_enc', address);
|
||||
}
|
||||
|
||||
// ─── Session label aliases ─────────────────────────────────
|
||||
//
|
||||
// Labels are already the clear-text keyPath of sessions_enc, so the
|
||||
// mapping between two of them exposes nothing the store didn't hold.
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
const row = await this.db.get('session_aliases_enc', alias);
|
||||
return row?.canonical ?? null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
await this.db.put('session_aliases_enc', { alias, canonical });
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
const tx = this.db.transaction('session_aliases_enc', 'readwrite');
|
||||
const matches = await tx.store.index('byCanonical').getAllKeys(canonical);
|
||||
await Promise.all(matches.map((key) => tx.store.delete(key)));
|
||||
await tx.done;
|
||||
}
|
||||
|
||||
// ─── Trust ─────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
@@ -466,7 +491,7 @@ export class EncryptedIndexedDBStorage implements StorageProvider {
|
||||
|
||||
// ─── Schema ────────────────────────────────────────────────
|
||||
|
||||
const SCHEMA_VERSION = 2;
|
||||
const SCHEMA_VERSION = 3;
|
||||
|
||||
interface MetaRow { key: string; value: string }
|
||||
interface IdentityRow { id: 1; ciphertext: Uint8Array }
|
||||
@@ -522,6 +547,11 @@ interface EncryptedShadeSchema extends DBSchema {
|
||||
signed_prekeys_enc: { key: number; value: SignedPreKeyRow };
|
||||
one_time_prekeys_enc: { key: number; value: OneTimePreKeyRow };
|
||||
sessions_enc: { key: string; value: SessionRow };
|
||||
session_aliases_enc: {
|
||||
key: string;
|
||||
value: { alias: string; canonical: string };
|
||||
indexes: { byCanonical: string };
|
||||
};
|
||||
trusted_identities_enc: { key: string; value: TrustedIdentityRow };
|
||||
retired_identities_enc: {
|
||||
key: number;
|
||||
|
||||
@@ -183,6 +183,30 @@ export class EncryptedPostgresStorage implements StorageProvider {
|
||||
await this.sql`DELETE FROM shade_sessions_enc WHERE address = ${address}`;
|
||||
}
|
||||
|
||||
// ─── Session label aliases ─────────────────────────────────
|
||||
//
|
||||
// Labels are already stored in the clear as the sessions_enc primary
|
||||
// key, so a mapping between two of them reveals nothing new.
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
const rows = await this.sql<Array<{ canonical: string }>>`
|
||||
SELECT canonical FROM shade_session_aliases_enc WHERE alias = ${alias}
|
||||
`;
|
||||
return rows.length ? rows[0]!.canonical : null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
await this.sql`
|
||||
INSERT INTO shade_session_aliases_enc (alias, canonical)
|
||||
VALUES (${alias}, ${canonical})
|
||||
ON CONFLICT (alias) DO UPDATE SET canonical = EXCLUDED.canonical
|
||||
`;
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
await this.sql`DELETE FROM shade_session_aliases_enc WHERE canonical = ${canonical}`;
|
||||
}
|
||||
|
||||
// ─── Trust ─────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
@@ -515,6 +539,16 @@ export async function ensureEncryptedClientTables(sql: Sql): Promise<void> {
|
||||
ciphertext BYTEA NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_session_aliases_enc (
|
||||
alias TEXT PRIMARY KEY,
|
||||
canonical TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_shade_session_aliases_enc_canonical
|
||||
ON shade_session_aliases_enc(canonical)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_trusted_identities_enc (
|
||||
address TEXT PRIMARY KEY,
|
||||
|
||||
@@ -52,6 +52,9 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
||||
getSession: ReturnType<Database['prepare']>;
|
||||
saveSession: ReturnType<Database['prepare']>;
|
||||
removeSession: ReturnType<Database['prepare']>;
|
||||
getSessionAlias: ReturnType<Database['prepare']>;
|
||||
saveSessionAlias: ReturnType<Database['prepare']>;
|
||||
removeAliasesFor: ReturnType<Database['prepare']>;
|
||||
getTrust: ReturnType<Database['prepare']>;
|
||||
saveTrust: ReturnType<Database['prepare']>;
|
||||
addRetired: ReturnType<Database['prepare']>;
|
||||
@@ -134,6 +137,15 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
||||
address TEXT PRIMARY KEY,
|
||||
ciphertext BLOB NOT NULL
|
||||
);
|
||||
-- Session-label aliases (V4.12). Labels are already stored in the
|
||||
-- clear as the sessions_enc primary key, so the mapping between two
|
||||
-- of them reveals nothing new; only session state is encrypted.
|
||||
CREATE TABLE IF NOT EXISTS session_aliases_enc (
|
||||
alias TEXT PRIMARY KEY,
|
||||
canonical TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_session_aliases_enc_canonical
|
||||
ON session_aliases_enc(canonical);
|
||||
CREATE TABLE IF NOT EXISTS trusted_identities_enc (
|
||||
address TEXT PRIMARY KEY,
|
||||
ciphertext BLOB NOT NULL
|
||||
@@ -203,6 +215,9 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
||||
getSession: this.db.prepare('SELECT ciphertext FROM sessions_enc WHERE address = ?'),
|
||||
saveSession: this.db.prepare('INSERT OR REPLACE INTO sessions_enc (address, ciphertext) VALUES (?, ?)'),
|
||||
removeSession: this.db.prepare('DELETE FROM sessions_enc WHERE address = ?'),
|
||||
getSessionAlias: this.db.prepare('SELECT canonical FROM session_aliases_enc WHERE alias = ?'),
|
||||
saveSessionAlias: this.db.prepare('INSERT OR REPLACE INTO session_aliases_enc (alias, canonical) VALUES (?, ?)'),
|
||||
removeAliasesFor: this.db.prepare('DELETE FROM session_aliases_enc WHERE canonical = ?'),
|
||||
getTrust: this.db.prepare('SELECT ciphertext FROM trusted_identities_enc WHERE address = ?'),
|
||||
saveTrust: this.db.prepare('INSERT OR REPLACE INTO trusted_identities_enc (address, ciphertext) VALUES (?, ?)'),
|
||||
addRetired: this.db.prepare('INSERT OR REPLACE INTO retired_identities_enc (retired_at, ciphertext) VALUES (?, ?)'),
|
||||
@@ -377,6 +392,21 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
||||
this.stmts.removeSession.run(address);
|
||||
}
|
||||
|
||||
// ─── Session label aliases ─────────────────────────────────
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
const row = this.stmts.getSessionAlias.get(alias) as { canonical: string } | undefined;
|
||||
return row?.canonical ?? null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
this.stmts.saveSessionAlias.run(alias, canonical);
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
this.stmts.removeAliasesFor.run(canonical);
|
||||
}
|
||||
|
||||
// ─── Trust ─────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
|
||||
141
packages/shade-storage-encrypted/tests/nonce-reuse.test.ts
Normal file
141
packages/shade-storage-encrypted/tests/nonce-reuse.test.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
/**
|
||||
* Regression tests for the AES-GCM nonce-reuse fix (G0).
|
||||
*
|
||||
* The codec used to derive its nonce from (fieldKey, table, pk) alone. That
|
||||
* is a pure function of row identity, so every re-seal of a mutable row —
|
||||
* `saveSession` runs on each ratchet step — reused (key, nonce) across
|
||||
* different plaintexts. AES-GCM forbids exactly that: it leaks the XOR of
|
||||
* the plaintexts and the GHASH subkey, which yields tag forgery under that
|
||||
* key. These tests fail if the derivation ever comes back.
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { KeyManager } from '../src/crypto/key-manager.js';
|
||||
import { AEAD_NONCE_LEN, aeadSeal } from '../src/crypto/aead.js';
|
||||
import { buildAad, deriveNonce } from '../src/crypto/kdf.js';
|
||||
import {
|
||||
COL,
|
||||
TBL,
|
||||
openBytes,
|
||||
openString,
|
||||
sealBytes,
|
||||
sealString,
|
||||
} from '../src/crypto/row-codec.js';
|
||||
|
||||
const TEXT = new TextEncoder();
|
||||
|
||||
function km(): Promise<KeyManager> {
|
||||
return KeyManager.open({ kind: 'injected', key: new Uint8Array(32).fill(0x42) });
|
||||
}
|
||||
|
||||
const nonceOf = (blob: Uint8Array) => blob.subarray(0, AEAD_NONCE_LEN);
|
||||
const hex = (b: Uint8Array) => Array.from(b, (x) => x.toString(16).padStart(2, '0')).join('');
|
||||
|
||||
describe('nonce uniqueness across re-saves', () => {
|
||||
test('two seals of the same row do not share a nonce', async () => {
|
||||
const k = await km();
|
||||
// The real shape of the bug: same (table, column, pk), different
|
||||
// plaintext, as a session row is re-sealed on every ratchet step.
|
||||
const first = await sealString(k, TBL.sessions, COL.session, 'alice', '{"messageCount":1}');
|
||||
const second = await sealString(k, TBL.sessions, COL.session, 'alice', '{"messageCount":2}');
|
||||
expect(hex(nonceOf(first))).not.toBe(hex(nonceOf(second)));
|
||||
k.destroy();
|
||||
});
|
||||
|
||||
test('a long run of re-saves produces all-distinct nonces', async () => {
|
||||
const k = await km();
|
||||
const seen = new Set<string>();
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const blob = await sealString(k, TBL.sessions, COL.session, 'alice', `state-${i}`);
|
||||
seen.add(hex(nonceOf(blob)));
|
||||
}
|
||||
expect(seen.size).toBe(200);
|
||||
k.destroy();
|
||||
});
|
||||
|
||||
test('sealBytes is covered by the same rule', async () => {
|
||||
const k = await km();
|
||||
const a = await sealBytes(k, TBL.config, COL.config, 'cfg', TEXT.encode('one'));
|
||||
const b = await sealBytes(k, TBL.config, COL.config, 'cfg', TEXT.encode('two'));
|
||||
expect(hex(nonceOf(a))).not.toBe(hex(nonceOf(b)));
|
||||
k.destroy();
|
||||
});
|
||||
|
||||
test('the nonce is not the derived one', async () => {
|
||||
const k = await km();
|
||||
const blob = await sealString(k, TBL.sessions, COL.session, 'alice', 'payload');
|
||||
const derived = deriveNonce(k.fieldKey(TBL.sessions, COL.session), TBL.sessions, 'alice');
|
||||
expect(hex(nonceOf(blob))).not.toBe(hex(derived));
|
||||
k.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('backward compatibility with deterministically-sealed blobs', () => {
|
||||
// `aeadOpen` has always read the nonce from the blob prefix, so data
|
||||
// written before the fix opens unchanged and needs no migration. This
|
||||
// test reproduces an old blob by sealing with the deprecated derivation.
|
||||
test('a blob sealed with the old derived nonce still opens', async () => {
|
||||
const k = await km();
|
||||
const key = k.fieldKey(TBL.sessions, COL.session);
|
||||
const legacy = await aeadSeal(
|
||||
key,
|
||||
deriveNonce(key, TBL.sessions, 'alice'),
|
||||
TEXT.encode('written before the fix'),
|
||||
buildAad(TBL.sessions, COL.session, 'alice'),
|
||||
);
|
||||
|
||||
const opened = await openString(k, TBL.sessions, COL.session, 'alice', legacy);
|
||||
expect(opened).toBe('written before the fix');
|
||||
k.destroy();
|
||||
});
|
||||
|
||||
test('openBytes reads an old blob too', async () => {
|
||||
const k = await km();
|
||||
const key = k.fieldKey(TBL.config, COL.config);
|
||||
const payload = TEXT.encode('legacy bytes');
|
||||
const legacy = await aeadSeal(
|
||||
key,
|
||||
deriveNonce(key, TBL.config, 'cfg'),
|
||||
payload,
|
||||
buildAad(TBL.config, COL.config, 'cfg'),
|
||||
);
|
||||
|
||||
expect(await openBytes(k, TBL.config, COL.config, 'cfg', legacy)).toEqual(payload);
|
||||
k.destroy();
|
||||
});
|
||||
|
||||
test('new and old blobs are both readable under one key', async () => {
|
||||
const k = await km();
|
||||
const key = k.fieldKey(TBL.sessions, COL.session);
|
||||
const legacy = await aeadSeal(
|
||||
key,
|
||||
deriveNonce(key, TBL.sessions, 'bob'),
|
||||
TEXT.encode('old'),
|
||||
buildAad(TBL.sessions, COL.session, 'bob'),
|
||||
);
|
||||
const fresh = await sealString(k, TBL.sessions, COL.session, 'bob', 'new');
|
||||
|
||||
expect(await openString(k, TBL.sessions, COL.session, 'bob', legacy)).toBe('old');
|
||||
expect(await openString(k, TBL.sessions, COL.session, 'bob', fresh)).toBe('new');
|
||||
k.destroy();
|
||||
});
|
||||
});
|
||||
|
||||
describe('tamper detection survives the switch', () => {
|
||||
// The dropped `expectedNonce` check was the stated reason for the
|
||||
// deterministic nonce. It detected nothing the AEAD tag misses.
|
||||
test('a flipped nonce byte is still rejected', async () => {
|
||||
const k = await km();
|
||||
const blob = await sealString(k, TBL.sessions, COL.session, 'alice', 'payload');
|
||||
const tampered = new Uint8Array(blob);
|
||||
tampered[0]! ^= 0x01;
|
||||
await expect(openString(k, TBL.sessions, COL.session, 'alice', tampered)).rejects.toThrow();
|
||||
k.destroy();
|
||||
});
|
||||
|
||||
test('a blob moved to another row is still rejected (AAD binding)', async () => {
|
||||
const k = await km();
|
||||
const blob = await sealString(k, TBL.sessions, COL.session, 'alice', 'alice-secret');
|
||||
await expect(openString(k, TBL.sessions, COL.session, 'bob', blob)).rejects.toThrow();
|
||||
k.destroy();
|
||||
});
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-indexeddb",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -74,6 +74,10 @@ export class IndexedDBStorage implements StorageProvider {
|
||||
const members = db.createObjectStore('broadcastMembers', { keyPath: ['channelId', 'peerAddress'] });
|
||||
members.createIndex('byChannelId', 'channelId');
|
||||
}
|
||||
if (oldVersion < 3) {
|
||||
const aliases = db.createObjectStore('sessionAliases', { keyPath: 'alias' });
|
||||
aliases.createIndex('byCanonical', 'canonical');
|
||||
}
|
||||
},
|
||||
});
|
||||
return new IndexedDBStorage(db);
|
||||
@@ -174,6 +178,24 @@ export class IndexedDBStorage implements StorageProvider {
|
||||
await this.db.delete('sessions', address);
|
||||
}
|
||||
|
||||
// ─── Session label aliases ────────────────────────────────
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
const row = await this.db.get('sessionAliases', alias);
|
||||
return row?.canonical ?? null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
await this.db.put('sessionAliases', { alias, canonical });
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
const tx = this.db.transaction('sessionAliases', 'readwrite');
|
||||
const matches = await tx.store.index('byCanonical').getAllKeys(canonical);
|
||||
await Promise.all(matches.map((key) => tx.store.delete(key)));
|
||||
await tx.done;
|
||||
}
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
@@ -360,7 +382,7 @@ export class IndexedDBStorage implements StorageProvider {
|
||||
|
||||
// ─── Schema ────────────────────────────────────────────────
|
||||
|
||||
const SCHEMA_VERSION = 2;
|
||||
const SCHEMA_VERSION = 3;
|
||||
|
||||
interface IdentityRow {
|
||||
id: 1;
|
||||
@@ -390,6 +412,11 @@ interface SessionRow {
|
||||
stateJson: string;
|
||||
}
|
||||
|
||||
interface SessionAliasRow {
|
||||
alias: string;
|
||||
canonical: string;
|
||||
}
|
||||
|
||||
interface TrustedIdentityRow {
|
||||
address: string;
|
||||
identityKey: string;
|
||||
@@ -457,6 +484,11 @@ interface ShadeSchema extends DBSchema {
|
||||
signedPreKeys: { key: number; value: SignedPreKeyRow };
|
||||
oneTimePreKeys: { key: number; value: OneTimePreKeyRow };
|
||||
sessions: { key: string; value: SessionRow };
|
||||
sessionAliases: {
|
||||
key: string;
|
||||
value: SessionAliasRow;
|
||||
indexes: { byCanonical: string };
|
||||
};
|
||||
trustedIdentities: { key: string; value: TrustedIdentityRow };
|
||||
retiredIdentities: {
|
||||
key: number;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-postgres",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -43,6 +43,16 @@ export async function ensureClientTables(sql: Sql): Promise<void> {
|
||||
state_json TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_session_aliases (
|
||||
alias TEXT PRIMARY KEY,
|
||||
canonical TEXT NOT NULL
|
||||
)
|
||||
`;
|
||||
await sql`
|
||||
CREATE INDEX IF NOT EXISTS idx_shade_session_aliases_canonical
|
||||
ON shade_session_aliases(canonical)
|
||||
`;
|
||||
await sql`
|
||||
CREATE TABLE IF NOT EXISTS shade_trusted_identities (
|
||||
address TEXT PRIMARY KEY,
|
||||
|
||||
@@ -160,6 +160,27 @@ export class PostgresStorage implements StorageProvider {
|
||||
await this.sql`DELETE FROM shade_sessions WHERE address = ${address}`;
|
||||
}
|
||||
|
||||
// ─── Session label aliases ────────────────────────────────
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
const rows = await this.sql<Array<{ canonical: string }>>`
|
||||
SELECT canonical FROM shade_session_aliases WHERE alias = ${alias}
|
||||
`;
|
||||
return rows.length ? rows[0]!.canonical : null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
await this.sql`
|
||||
INSERT INTO shade_session_aliases (alias, canonical)
|
||||
VALUES (${alias}, ${canonical})
|
||||
ON CONFLICT (alias) DO UPDATE SET canonical = EXCLUDED.canonical
|
||||
`;
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
await this.sql`DELETE FROM shade_session_aliases WHERE canonical = ${canonical}`;
|
||||
}
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/storage-sqlite",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
@@ -9,5 +9,8 @@
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/inbox-server": "workspace:*",
|
||||
"@shade/server": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@shade/vault": "workspace:*"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,3 +2,4 @@ export { SQLiteStorage } from './sqlite-storage.js';
|
||||
export { SqlitePrekeyStore } from './sqlite-prekey-store.js';
|
||||
export { SqliteInboxStore } from './sqlite-inbox-store.js';
|
||||
export { SqliteBlobStore } from './sqlite-blob-store.js';
|
||||
export { SqliteVaultStore } from './sqlite-vault-store.js';
|
||||
|
||||
@@ -41,6 +41,9 @@ export class SQLiteStorage implements StorageProvider {
|
||||
getSession: ReturnType<Database['prepare']>;
|
||||
saveSession: ReturnType<Database['prepare']>;
|
||||
removeSession: ReturnType<Database['prepare']>;
|
||||
getSessionAlias: ReturnType<Database['prepare']>;
|
||||
saveSessionAlias: ReturnType<Database['prepare']>;
|
||||
removeAliasesFor: ReturnType<Database['prepare']>;
|
||||
getTrust: ReturnType<Database['prepare']>;
|
||||
saveTrust: ReturnType<Database['prepare']>;
|
||||
addRetired: ReturnType<Database['prepare']>;
|
||||
@@ -100,6 +103,12 @@ export class SQLiteStorage implements StorageProvider {
|
||||
address TEXT PRIMARY KEY,
|
||||
state_json TEXT NOT NULL
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS session_aliases (
|
||||
alias TEXT PRIMARY KEY,
|
||||
canonical TEXT NOT NULL
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_session_aliases_canonical
|
||||
ON session_aliases(canonical);
|
||||
CREATE TABLE IF NOT EXISTS trusted_identities (
|
||||
address TEXT PRIMARY KEY,
|
||||
identity_key TEXT NOT NULL
|
||||
@@ -179,6 +188,9 @@ export class SQLiteStorage implements StorageProvider {
|
||||
getSession: this.db.prepare('SELECT state_json FROM sessions WHERE address = ?'),
|
||||
saveSession: this.db.prepare('INSERT OR REPLACE INTO sessions (address, state_json) VALUES (?, ?)'),
|
||||
removeSession: this.db.prepare('DELETE FROM sessions WHERE address = ?'),
|
||||
getSessionAlias: this.db.prepare('SELECT canonical FROM session_aliases WHERE alias = ?'),
|
||||
saveSessionAlias: this.db.prepare('INSERT OR REPLACE INTO session_aliases (alias, canonical) VALUES (?, ?)'),
|
||||
removeAliasesFor: this.db.prepare('DELETE FROM session_aliases WHERE canonical = ?'),
|
||||
getTrust: this.db.prepare('SELECT identity_key FROM trusted_identities WHERE address = ?'),
|
||||
saveTrust: this.db.prepare('INSERT OR REPLACE INTO trusted_identities (address, identity_key) VALUES (?, ?)'),
|
||||
addRetired: this.db.prepare('INSERT INTO retired_identities (data_json, retired_at) VALUES (?, ?)'),
|
||||
@@ -337,6 +349,21 @@ export class SQLiteStorage implements StorageProvider {
|
||||
this.stmts.removeSession.run(address);
|
||||
}
|
||||
|
||||
// ─── Session label aliases ────────────────────────────────
|
||||
|
||||
async getSessionAlias(alias: string): Promise<string | null> {
|
||||
const row = this.stmts.getSessionAlias.get(alias) as { canonical: string } | undefined;
|
||||
return row?.canonical ?? null;
|
||||
}
|
||||
|
||||
async saveSessionAlias(alias: string, canonical: string): Promise<void> {
|
||||
this.stmts.saveSessionAlias.run(alias, canonical);
|
||||
}
|
||||
|
||||
async removeSessionAliasesFor(canonical: string): Promise<void> {
|
||||
this.stmts.removeAliasesFor.run(canonical);
|
||||
}
|
||||
|
||||
// ─── Trust ────────────────────────────────────────────────
|
||||
|
||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||
|
||||
289
packages/shade-storage-sqlite/src/sqlite-vault-store.ts
Normal file
289
packages/shade-storage-sqlite/src/sqlite-vault-store.ts
Normal file
@@ -0,0 +1,289 @@
|
||||
import { Database } from 'bun:sqlite';
|
||||
import type { VaultLogEntry, VaultPrunePlan, VaultPruneResult, VaultStore } from '@shade/vault';
|
||||
|
||||
/**
|
||||
* SQLite-backed VaultStore for the V4.13 encrypted file store.
|
||||
*
|
||||
* Three tables, mirroring the model: an owner key per vault, the
|
||||
* content-addressed objects, and the append-only manifest log. The relay
|
||||
* never decrypts anything — it enforces auth, verifies that an object's bytes
|
||||
* hash to its name, and refuses a commit whose objects are not all present.
|
||||
*
|
||||
* A fourth table, `shade_vault_refs`, records which objects each version
|
||||
* references (the commit's signed hashes plus its manifest). The relay cannot
|
||||
* read manifests, so this is what prune computes garbage from. Versions from
|
||||
* before it existed have `refs_known = 0`, and every object that was in the
|
||||
* database when the columns were added is `pinned` — see `VaultPrunePlan` for
|
||||
* why that is the safe reading and how the pins are eventually released.
|
||||
*
|
||||
* Objects are stored as BLOBs rather than base64 text. A workspace backup is
|
||||
* a few hundred files where the blob primitive holds one small profile, so the
|
||||
* 33% base64 overhead stops being a rounding error.
|
||||
*
|
||||
* Docker usage: set `SHADE_VAULT_DB_PATH` (falls back to `/data/shade-vault.db`).
|
||||
* **Set it.** The blob store's equivalent was missing from `docker-compose.yml`
|
||||
* for months and nobody noticed, because the in-memory fallback works
|
||||
* perfectly until the container is recreated — at which point everything is
|
||||
* gone, with no error anywhere. That happened on 2026-08-12.
|
||||
*/
|
||||
export class SqliteVaultStore implements VaultStore {
|
||||
private db: Database;
|
||||
private stmts!: {
|
||||
getOwner: ReturnType<Database['prepare']>;
|
||||
setOwner: ReturnType<Database['prepare']>;
|
||||
hasObject: ReturnType<Database['prepare']>;
|
||||
putObject: ReturnType<Database['prepare']>;
|
||||
getObject: ReturnType<Database['prepare']>;
|
||||
head: ReturnType<Database['prepare']>;
|
||||
log: ReturnType<Database['prepare']>;
|
||||
logLimit: ReturnType<Database['prepare']>;
|
||||
appendLog: ReturnType<Database['prepare']>;
|
||||
appendRef: ReturnType<Database['prepare']>;
|
||||
pinAll: ReturnType<Database['prepare']>;
|
||||
usage: ReturnType<Database['prepare']>;
|
||||
};
|
||||
|
||||
constructor(dbPath?: string) {
|
||||
const path = dbPath ?? process.env.SHADE_VAULT_DB_PATH ?? '/data/shade-vault.db';
|
||||
this.db = new Database(path, { create: true });
|
||||
this.db.exec('PRAGMA journal_mode=WAL');
|
||||
this.ensureTables();
|
||||
this.prepareStatements();
|
||||
}
|
||||
|
||||
private ensureTables() {
|
||||
this.db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS shade_vault_owners (
|
||||
vault_id TEXT PRIMARY KEY,
|
||||
owner_pubkey BLOB NOT NULL,
|
||||
created_at INTEGER NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS 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,
|
||||
pinned INTEGER NOT NULL DEFAULT 0,
|
||||
PRIMARY KEY (vault_id, hash)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shade_vault_log (
|
||||
vault_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
manifest TEXT NOT NULL,
|
||||
at INTEGER NOT NULL,
|
||||
bytes INTEGER NOT NULL,
|
||||
refs_known INTEGER NOT NULL DEFAULT 1,
|
||||
PRIMARY KEY (vault_id, seq)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS shade_vault_refs (
|
||||
vault_id TEXT NOT NULL,
|
||||
seq INTEGER NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
PRIMARY KEY (vault_id, seq, hash)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS shade_vault_refs_by_hash ON shade_vault_refs (vault_id, hash);
|
||||
`);
|
||||
|
||||
// Databases from before ref tracking. The defaults here are the whole
|
||||
// migration: every existing log row becomes untracked (refs_known = 0),
|
||||
// and every existing object pinned (pinned = 1), because any of them may
|
||||
// be referenced by one of those rows. New rows always set both columns
|
||||
// explicitly, so these defaults only ever apply to the old ones.
|
||||
const has = (table: string, column: string): boolean =>
|
||||
(this.db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>).some(
|
||||
(c) => c.name === column,
|
||||
);
|
||||
this.db.transaction(() => {
|
||||
if (!has('shade_vault_log', 'refs_known')) {
|
||||
this.db.exec(
|
||||
'ALTER TABLE shade_vault_log ADD COLUMN refs_known INTEGER NOT NULL DEFAULT 0',
|
||||
);
|
||||
}
|
||||
if (!has('shade_vault_objects', 'pinned')) {
|
||||
this.db.exec('ALTER TABLE shade_vault_objects ADD COLUMN pinned INTEGER NOT NULL DEFAULT 1');
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
private prepareStatements() {
|
||||
this.stmts = {
|
||||
getOwner: this.db.prepare('SELECT owner_pubkey FROM shade_vault_owners WHERE vault_id = ?'),
|
||||
setOwner: this.db.prepare(
|
||||
'INSERT OR REPLACE INTO shade_vault_owners (vault_id, owner_pubkey, created_at) VALUES (?, ?, ?)',
|
||||
),
|
||||
hasObject: this.db.prepare(
|
||||
'SELECT 1 FROM shade_vault_objects WHERE vault_id = ? AND hash = ? LIMIT 1',
|
||||
),
|
||||
// An object's name IS its content hash, so a repeat upload is the same
|
||||
// bytes by definition — ignoring it is correct, not lossy.
|
||||
putObject: this.db.prepare(
|
||||
'INSERT OR IGNORE INTO shade_vault_objects (vault_id, hash, bytes, size, created_at, pinned) VALUES (?, ?, ?, ?, ?, 0)',
|
||||
),
|
||||
getObject: this.db.prepare(
|
||||
'SELECT bytes FROM shade_vault_objects WHERE vault_id = ? AND hash = ?',
|
||||
),
|
||||
head: this.db.prepare('SELECT MAX(seq) AS head FROM shade_vault_log WHERE vault_id = ?'),
|
||||
log: this.db.prepare(
|
||||
'SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq ASC',
|
||||
),
|
||||
logLimit: this.db.prepare(
|
||||
'SELECT seq, manifest, at, bytes FROM (SELECT seq, manifest, at, bytes FROM shade_vault_log WHERE vault_id = ? ORDER BY seq DESC LIMIT ?) ORDER BY seq ASC',
|
||||
),
|
||||
appendLog: this.db.prepare(
|
||||
'INSERT INTO shade_vault_log (vault_id, seq, manifest, at, bytes, refs_known) VALUES (?, ?, ?, ?, ?, ?)',
|
||||
),
|
||||
appendRef: this.db.prepare(
|
||||
'INSERT OR IGNORE INTO shade_vault_refs (vault_id, seq, hash) VALUES (?, ?, ?)',
|
||||
),
|
||||
pinAll: this.db.prepare('UPDATE shade_vault_objects SET pinned = 1 WHERE vault_id = ?'),
|
||||
usage: this.db.prepare(
|
||||
'SELECT COALESCE(SUM(size), 0) AS total FROM shade_vault_objects WHERE vault_id = ?',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
async getOwner(vaultId: string): Promise<Uint8Array | null> {
|
||||
const row = this.stmts.getOwner.get(vaultId) as { owner_pubkey: Uint8Array } | null;
|
||||
return row ? new Uint8Array(row.owner_pubkey) : null;
|
||||
}
|
||||
|
||||
async setOwner(vaultId: string, publicKey: Uint8Array): Promise<void> {
|
||||
this.stmts.setOwner.run(vaultId, publicKey, Date.now());
|
||||
}
|
||||
|
||||
async hasObject(vaultId: string, hash: string): Promise<boolean> {
|
||||
return this.stmts.hasObject.get(vaultId, hash) !== null;
|
||||
}
|
||||
|
||||
async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void> {
|
||||
this.stmts.putObject.run(vaultId, hash, bytes, bytes.length, Date.now());
|
||||
}
|
||||
|
||||
async getObject(vaultId: string, hash: string): Promise<Uint8Array | null> {
|
||||
const row = this.stmts.getObject.get(vaultId, hash) as { bytes: Uint8Array } | null;
|
||||
return row ? new Uint8Array(row.bytes) : null;
|
||||
}
|
||||
|
||||
async head(vaultId: string): Promise<number> {
|
||||
const row = this.stmts.head.get(vaultId) as { head: number | null } | null;
|
||||
return row?.head ?? 0;
|
||||
}
|
||||
|
||||
async log(vaultId: string, limit?: number): Promise<VaultLogEntry[]> {
|
||||
const rows = (
|
||||
limit === undefined
|
||||
? this.stmts.log.all(vaultId)
|
||||
: this.stmts.logLimit.all(vaultId, limit)
|
||||
) as VaultLogEntry[];
|
||||
return rows;
|
||||
}
|
||||
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||
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> {
|
||||
const row = this.stmts.usage.get(vaultId) as { total: number } | null;
|
||||
return row?.total ?? 0;
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
251
packages/shade-storage-sqlite/tests/sqlite-vault-store.test.ts
Normal file
251
packages/shade-storage-sqlite/tests/sqlite-vault-store.test.ts
Normal file
@@ -0,0 +1,251 @@
|
||||
/**
|
||||
* The SQLite vault store, with persistence as the headline property.
|
||||
*
|
||||
* This exists because of 2026-08-12: the blob store fell back to memory when
|
||||
* its path was unset, worked perfectly, and lost every profile on the next
|
||||
* container recreate — with no error anywhere. A backup store that forgets is
|
||||
* worse than none, so "survives a close and reopen" is tested directly rather
|
||||
* than assumed from the fact that SQLite is involved.
|
||||
*/
|
||||
import { describe, test, expect, afterEach } from 'bun:test';
|
||||
import { unlinkSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { SqliteVaultStore } from '../src/sqlite-vault-store.js';
|
||||
|
||||
const paths: string[] = [];
|
||||
function scratch(name: string): string {
|
||||
const p = join(tmpdir(), `shade-vault-${name}-${process.pid}-${Math.random().toString(36).slice(2)}.db`);
|
||||
paths.push(p);
|
||||
return p;
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
for (const p of paths.splice(0)) {
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try {
|
||||
unlinkSync(p + suffix);
|
||||
} catch {
|
||||
// Not every WAL sidecar exists; absence is fine.
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const VAULT = 'a'.repeat(64);
|
||||
const HASH = 'b'.repeat(64);
|
||||
|
||||
describe('persistence', () => {
|
||||
test('objects, owner and log survive a close and reopen', async () => {
|
||||
const path = scratch('reopen');
|
||||
const first = new SqliteVaultStore(path);
|
||||
await first.setOwner(VAULT, new Uint8Array([1, 2, 3, 4]));
|
||||
await first.putObject(VAULT, HASH, new Uint8Array([9, 8, 7]));
|
||||
await first.appendLog(VAULT, { seq: 1, manifest: HASH, at: 1700, bytes: 3 });
|
||||
first.close();
|
||||
|
||||
const second = new SqliteVaultStore(path);
|
||||
expect(await second.getOwner(VAULT)).toEqual(new Uint8Array([1, 2, 3, 4]));
|
||||
expect(await second.getObject(VAULT, HASH)).toEqual(new Uint8Array([9, 8, 7]));
|
||||
expect(await second.head(VAULT)).toBe(1);
|
||||
expect((await second.log(VAULT))[0]!.manifest).toBe(HASH);
|
||||
second.close();
|
||||
});
|
||||
|
||||
test('binary content round-trips without base64 mangling', async () => {
|
||||
// Objects are ciphertext: every byte value occurs, including 0x00.
|
||||
const path = scratch('binary');
|
||||
const store = new SqliteVaultStore(path);
|
||||
const bytes = new Uint8Array(256);
|
||||
for (let i = 0; i < 256; i++) bytes[i] = i;
|
||||
await store.putObject(VAULT, HASH, bytes);
|
||||
store.close();
|
||||
|
||||
const reopened = new SqliteVaultStore(path);
|
||||
expect(await reopened.getObject(VAULT, HASH)).toEqual(bytes);
|
||||
reopened.close();
|
||||
});
|
||||
});
|
||||
|
||||
describe('semantics', () => {
|
||||
test('an empty vault has head 0 and no owner', async () => {
|
||||
const store = new SqliteVaultStore(scratch('empty'));
|
||||
expect(await store.head(VAULT)).toBe(0);
|
||||
expect(await store.getOwner(VAULT)).toBeNull();
|
||||
expect(await store.log(VAULT)).toEqual([]);
|
||||
expect(await store.usage(VAULT)).toBe(0);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('re-putting the same hash is a no-op, not a duplicate', async () => {
|
||||
// The name IS the content hash, so a repeat is the same bytes by
|
||||
// definition. Usage must not double.
|
||||
const store = new SqliteVaultStore(scratch('dupe'));
|
||||
await store.putObject(VAULT, HASH, new Uint8Array(100));
|
||||
await store.putObject(VAULT, HASH, new Uint8Array(100));
|
||||
expect(await store.usage(VAULT)).toBe(100);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('vaults are isolated from each other', async () => {
|
||||
const store = new SqliteVaultStore(scratch('isolated'));
|
||||
const other = 'c'.repeat(64);
|
||||
await store.putObject(VAULT, HASH, new Uint8Array([1]));
|
||||
expect(await store.hasObject(other, HASH)).toBe(false);
|
||||
expect(await store.getObject(other, HASH)).toBeNull();
|
||||
expect(await store.usage(other)).toBe(0);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('the log is ordered oldest-first and limit counts back from the head', async () => {
|
||||
const store = new SqliteVaultStore(scratch('log'));
|
||||
for (let seq = 1; seq <= 5; seq++) {
|
||||
await store.appendLog(VAULT, { seq, manifest: `${seq}`.repeat(64), at: seq, bytes: seq });
|
||||
}
|
||||
expect((await store.log(VAULT)).map((e) => e.seq)).toEqual([1, 2, 3, 4, 5]);
|
||||
// A client asking for the last two wants 4 and 5, still in order.
|
||||
expect((await store.log(VAULT, 2)).map((e) => e.seq)).toEqual([4, 5]);
|
||||
expect(await store.head(VAULT)).toBe(5);
|
||||
store.close();
|
||||
});
|
||||
|
||||
test('a duplicate seq is rejected by the primary key', async () => {
|
||||
// The route layer refuses this first, but the store is the last line:
|
||||
// two rows with the same seq would make history ambiguous.
|
||||
const store = new SqliteVaultStore(scratch('seq'));
|
||||
await store.appendLog(VAULT, { seq: 1, manifest: HASH, at: 1, bytes: 1 });
|
||||
expect(store.appendLog(VAULT, { seq: 1, manifest: HASH, at: 2, bytes: 1 })).rejects.toThrow();
|
||||
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",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transfer",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -451,7 +451,7 @@ export class TransferEngine {
|
||||
for (const q of queues.values()) q.abort(err);
|
||||
throw err;
|
||||
}
|
||||
await Promise.all(workers);
|
||||
await settleWorkers(workers);
|
||||
}
|
||||
|
||||
private async runRoundRobinUploadResumed(
|
||||
@@ -518,7 +518,7 @@ export class TransferEngine {
|
||||
for (const q of queues.values()) q.abort(err);
|
||||
throw err;
|
||||
}
|
||||
await Promise.all(workers);
|
||||
await settleWorkers(workers);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -774,7 +774,7 @@ export class TransferEngine {
|
||||
for (const q of queues.values()) q.abort(err);
|
||||
throw err;
|
||||
}
|
||||
await Promise.all(workers);
|
||||
await settleWorkers(workers);
|
||||
}
|
||||
|
||||
private async runRoundRobinUpload(state: OutgoingState): Promise<void> {
|
||||
@@ -851,7 +851,7 @@ export class TransferEngine {
|
||||
for (const q of queues.values()) q.abort(err);
|
||||
throw err;
|
||||
}
|
||||
await Promise.all(workers);
|
||||
await settleWorkers(workers);
|
||||
}
|
||||
|
||||
private async runLaneWorker(
|
||||
@@ -1596,3 +1596,25 @@ function snapshotIncomingLanes(
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for every lane worker, then report the first real failure.
|
||||
*
|
||||
* `Promise.all` rejects the moment one worker throws and leaves the others
|
||||
* running with nobody holding their rejections — so an abort, which fails
|
||||
* every lane at once, produces one propagated error and N-1 unhandled ones.
|
||||
* Bun counts an unhandled rejection as a test failure, which is how the resume
|
||||
* test failed roughly one run in fourteen on 08.09.2026 with a
|
||||
* `TransferAbortError` the test had already caught through the handle.
|
||||
*
|
||||
* An abort is not the interesting failure when a real one is present, so a
|
||||
* genuine error is preferred over `TransferAbortError` when both occurred.
|
||||
*/
|
||||
async function settleWorkers(workers: Promise<unknown>[]): Promise<void> {
|
||||
const results = await Promise.allSettled(workers);
|
||||
const errors = results
|
||||
.filter((r): r is PromiseRejectedResult => r.status === 'rejected')
|
||||
.map((r) => r.reason);
|
||||
if (errors.length === 0) return;
|
||||
throw errors.find((e) => !(e instanceof TransferAbortError)) ?? errors[0];
|
||||
}
|
||||
|
||||
@@ -41,8 +41,12 @@ describe('Resume protocol — kill-restart-verify', () => {
|
||||
myAddress: 'bob',
|
||||
});
|
||||
const receiverApp = await createTransferRoutes(receiverEngine);
|
||||
const port = 22000 + Math.floor(Math.random() * 500);
|
||||
const server = Bun.serve({ port, fetch: receiverApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const server = Bun.serve({ port: 0, fetch: receiverApp.fetch });
|
||||
const port = server.port;
|
||||
const baseUrl = `http://localhost:${port}`;
|
||||
|
||||
// Receiver accepts incoming.
|
||||
|
||||
@@ -39,8 +39,12 @@ describe('WS opt-in transport with HTTP fallback', () => {
|
||||
myAddress: 'bob',
|
||||
});
|
||||
const httpApp = await createTransferRoutes(receiverEngine);
|
||||
const httpPort = 23000 + Math.floor(Math.random() * 500);
|
||||
const httpServer = Bun.serve({ port: httpPort, fetch: httpApp.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const httpServer = Bun.serve({ port: 0, fetch: httpApp.fetch });
|
||||
const httpPort = httpServer.port;
|
||||
const httpBaseUrl = `http://localhost:${httpPort}`;
|
||||
cleanups.push(() => httpServer.stop());
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transport-bridge",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transport-webrtc",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/transport",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -14,6 +14,9 @@ import {
|
||||
KTVerificationError,
|
||||
} 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.
|
||||
*
|
||||
@@ -67,15 +70,31 @@ export class ShadeFetchTransport {
|
||||
private readonly crypto: CryptoProvider;
|
||||
private readonly signingPrivateKey?: Uint8Array;
|
||||
private readonly kt?: KTVerifierOptions;
|
||||
private readonly fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
|
||||
private readonly requestTimeoutMs: number;
|
||||
|
||||
constructor(options: {
|
||||
baseUrl: string;
|
||||
crypto: CryptoProvider;
|
||||
signingPrivateKey?: Uint8Array;
|
||||
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.crypto = options.crypto;
|
||||
this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
|
||||
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||
if (options.signingPrivateKey !== undefined) {
|
||||
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> {
|
||||
return { 'Content-Type': 'application/json' };
|
||||
}
|
||||
@@ -133,7 +168,7 @@ export class ShadeFetchTransport {
|
||||
|
||||
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',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(signed),
|
||||
@@ -159,7 +194,7 @@ export class ShadeFetchTransport {
|
||||
* direct access to the proof side-channel.
|
||||
*/
|
||||
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(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
@@ -283,7 +318,7 @@ export class ShadeFetchTransport {
|
||||
};
|
||||
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',
|
||||
headers: this.headers(),
|
||||
body: JSON.stringify(signed),
|
||||
@@ -295,7 +330,7 @@ export class ShadeFetchTransport {
|
||||
|
||||
/** Get remaining one-time prekey count (anonymous) */
|
||||
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(),
|
||||
});
|
||||
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) */
|
||||
async unregister(address: string): Promise<void> {
|
||||
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',
|
||||
headers: this.headers(),
|
||||
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 { ShadeWebSocket } from './ws-adapter.js';
|
||||
|
||||
@@ -31,8 +31,12 @@ describe('ShadeFetchTransport with KT verifier', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const port = 20100 + Math.floor(Math.random() * 500);
|
||||
const handle = Bun.serve({ port, fetch: app.fetch });
|
||||
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||
// range and hoped — and several files here guessed inside the SAME range,
|
||||
// so with test files serving in parallel the collision arrived about a
|
||||
// quarter of the time as EADDRINUSE.
|
||||
const handle = Bun.serve({ port: 0, fetch: app.fetch });
|
||||
const port = handle.port;
|
||||
try {
|
||||
const baseUrl = `http://localhost:${port}`;
|
||||
|
||||
|
||||
@@ -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']);
|
||||
});
|
||||
});
|
||||
|
||||
74
packages/shade-vault/live-e2e.ts
Normal file
74
packages/shade-vault/live-e2e.ts
Normal file
@@ -0,0 +1,74 @@
|
||||
/**
|
||||
* Full backup mot en KJØRENDE vault — ikke Hono-fetch, men ekte HTTP.
|
||||
*
|
||||
* Kjøres manuelt mot en container eller en deployet tjeneste:
|
||||
* SCAFFOLDD_SOCKET=... RELAY=https://scaffold.zyon.no bun live-e2e.ts
|
||||
*/
|
||||
import { connect } from 'node:net';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import { HttpVaultTransport, VaultClient, deriveVaultKeys } from './src/index.js';
|
||||
|
||||
const SOCKET = process.env.SCAFFOLDD_SOCKET!;
|
||||
const RELAY = process.env.RELAY!;
|
||||
|
||||
function ask(req: object): Promise<any> {
|
||||
return new Promise((res, rej) => {
|
||||
const s = connect(SOCKET);
|
||||
let buf = '';
|
||||
s.on('connect', () => s.write(`${JSON.stringify(req)}\n`));
|
||||
s.on('data', (c) => {
|
||||
buf += c.toString();
|
||||
const nl = buf.indexOf('\n');
|
||||
if (nl === -1) return;
|
||||
s.destroy();
|
||||
const r = JSON.parse(buf.slice(0, nl));
|
||||
r.ok ? res(r.result) : rej(new Error(r.error));
|
||||
});
|
||||
s.on('error', rej);
|
||||
});
|
||||
}
|
||||
|
||||
const set = await ask({ op: 'backupSet' });
|
||||
const files: { path: string; bytes: Uint8Array }[] = [];
|
||||
for (const f of set.files) {
|
||||
try {
|
||||
files.push({ path: f.path, bytes: new Uint8Array(await readFile(f.source)) });
|
||||
} catch {
|
||||
/* uleselig fil hoppes over, som i broen */
|
||||
}
|
||||
}
|
||||
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
const keys = await deriveVaultKeys(new Uint8Array(32).fill(77), 'scaffold-live');
|
||||
const client = new VaultClient(crypto, keys, new HttpVaultTransport(RELAY));
|
||||
|
||||
console.log(`push: ${files.length} filer …`);
|
||||
let t = Date.now();
|
||||
const r1 = await client.push(files, Date.now(), 'live e2e');
|
||||
console.log(
|
||||
` versjon ${r1.seq}: ${r1.uploaded} opplastet, ` +
|
||||
`${(r1.bytesUploaded / 1024 / 1024).toFixed(1)} MB, ${((Date.now() - t) / 1000).toFixed(1)}s`,
|
||||
);
|
||||
|
||||
const edited = files.map((f, i) =>
|
||||
i === 0 ? { path: f.path, bytes: new TextEncoder().encode('endret') } : f,
|
||||
);
|
||||
t = Date.now();
|
||||
const r2 = await client.push(edited, Date.now(), 'én endring');
|
||||
console.log(
|
||||
` versjon ${r2.seq}: ${r2.uploaded} opplastet, ${r2.reused} gjenbrukt, ` +
|
||||
`${(r2.bytesUploaded / 1024).toFixed(0)} KB, ${((Date.now() - t) / 1000).toFixed(1)}s`,
|
||||
);
|
||||
|
||||
const back = await client.pull(1);
|
||||
let identical = 0;
|
||||
let differ = 0;
|
||||
for (const f of files) {
|
||||
const got = back.files.get(f.path);
|
||||
if (got && Buffer.from(got).equals(Buffer.from(f.bytes))) identical++;
|
||||
else differ++;
|
||||
}
|
||||
console.log(`pull versjon 1: ${identical} bit-identiske, ${differ} avvik`);
|
||||
const log = await client.history();
|
||||
console.log(`historikk: ${log.entries.map((e) => e.seq).join(', ')} (head ${log.head})`);
|
||||
26
packages/shade-vault/package.json
Normal file
26
packages/shade-vault/package.json
Normal file
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"name": "@shade/vault",
|
||||
"version": "4.14.1",
|
||||
"description": "Server-side encrypted file store for Shade — content-addressed objects with an append-only manifest log",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./server": "./src/server.ts",
|
||||
"./testing": "./src/testing.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@noble/hashes": "^2.0.1",
|
||||
"@shade/core": "workspace:*",
|
||||
"@shade/crypto-web": "workspace:*",
|
||||
"@shade/observability": "workspace:*",
|
||||
"@shade/server": "workspace:*",
|
||||
"@shade/storage-encrypted": "workspace:*",
|
||||
"hono": "^4.12.18"
|
||||
},
|
||||
"scripts": {
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit"
|
||||
}
|
||||
}
|
||||
509
packages/shade-vault/src/client.ts
Normal file
509
packages/shade-vault/src/client.ts
Normal file
@@ -0,0 +1,509 @@
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* A workspace changes a few lines at a time, so a push has to cost what
|
||||
* changed, not what exists. Everything unchanged keeps the entry — and so the
|
||||
* objects — it had in the previous version, and costs nothing. Recognising
|
||||
* "unchanged" is the expensive part: with a `VaultIndex` from the previous
|
||||
* push it is a local hash comparison; without one, the previous manifest is
|
||||
* read and only same-path, same-size candidates are downloaded to compare.
|
||||
*/
|
||||
|
||||
import type { CryptoProvider } from '@shade/core';
|
||||
import { toBase64 } from '@shade/core';
|
||||
// The pubkey derivation is not on `CryptoProvider` — it is a pure function of
|
||||
// the seed, and lives with the curve implementation.
|
||||
import { ed25519PublicKeyFromSeed } from '@shade/crypto-web';
|
||||
import { signPayload } from '@shade/server';
|
||||
import {
|
||||
deriveVaultContentKey,
|
||||
deriveVaultId,
|
||||
deriveVaultSigningSeed,
|
||||
} from '@shade/storage-encrypted';
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import {
|
||||
entryObjectHashes,
|
||||
openEntryBytes,
|
||||
openManifest,
|
||||
sealEntry,
|
||||
sealManifest,
|
||||
toHex,
|
||||
} from './crypto.js';
|
||||
import type {
|
||||
VaultEntry,
|
||||
VaultIndex,
|
||||
VaultIndexEntry,
|
||||
VaultLog,
|
||||
VaultLogEntry,
|
||||
VaultManifest,
|
||||
VaultPruneResult,
|
||||
} from './types.js';
|
||||
|
||||
/** A file as the app sees it, before encryption. */
|
||||
export interface VaultFile {
|
||||
path: string;
|
||||
bytes: Uint8Array;
|
||||
mode?: string;
|
||||
}
|
||||
|
||||
export interface VaultKeys {
|
||||
vaultId: string;
|
||||
contentKey: Uint8Array;
|
||||
signingSeed: Uint8Array;
|
||||
publicKey: Uint8Array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive everything a vault needs from the account master key.
|
||||
*
|
||||
* This is what makes recovery "username and password": a fresh device that
|
||||
* can derive the profile master can derive these too, and the relay hands
|
||||
* over ciphertext it has never been able to read.
|
||||
*/
|
||||
export async function deriveVaultKeys(masterKey: Uint8Array, app: string): Promise<VaultKeys> {
|
||||
const signingSeed = deriveVaultSigningSeed(masterKey, app);
|
||||
const publicKey = ed25519PublicKeyFromSeed(signingSeed);
|
||||
return {
|
||||
vaultId: toHex(deriveVaultId(masterKey, app)),
|
||||
contentKey: deriveVaultContentKey(masterKey, app),
|
||||
signingSeed,
|
||||
publicKey,
|
||||
};
|
||||
}
|
||||
|
||||
export interface VaultTransport {
|
||||
/** Does the relay already hold this object? */
|
||||
has(vaultId: string, hash: string): Promise<boolean>;
|
||||
put(vaultId: string, hash: string, body: unknown): Promise<void>;
|
||||
get(vaultId: string, hash: string): Promise<Uint8Array>;
|
||||
log(vaultId: string, limit?: number): Promise<VaultLog>;
|
||||
commit(vaultId: string, body: unknown): Promise<{ seq: number }>;
|
||||
prune(vaultId: string, body: unknown): Promise<VaultPruneResult>;
|
||||
}
|
||||
|
||||
export interface PushOptions {
|
||||
/**
|
||||
* The index the previous push returned. Trusted only when it belongs to
|
||||
* this vault and its `seq` is still the relay's head; otherwise ignored.
|
||||
*/
|
||||
index?: VaultIndex;
|
||||
}
|
||||
|
||||
export interface PushResult {
|
||||
/** The version now at the head — the new one, or the old one if `unchanged`. */
|
||||
seq: number;
|
||||
/** Data objects sent (the manifest is not counted). */
|
||||
uploaded: number;
|
||||
/** Files whose previous entry was reused without sealing anything. */
|
||||
reused: number;
|
||||
bytesUploaded: number;
|
||||
/** Nothing differed from the head, so no version was committed. */
|
||||
unchanged: boolean;
|
||||
/** Describes the head after this push; persist it and pass it to the next one. */
|
||||
index: VaultIndex;
|
||||
}
|
||||
|
||||
export interface VaultClientOptions {
|
||||
/**
|
||||
* Override the 4 MiB part size. Internal — tests and vectors only. A real
|
||||
* writer must use the default so every implementation splits identically.
|
||||
*/
|
||||
chunkSize?: number;
|
||||
}
|
||||
|
||||
export class VaultClient {
|
||||
constructor(
|
||||
private readonly crypto: CryptoProvider,
|
||||
private readonly keys: VaultKeys,
|
||||
private readonly transport: VaultTransport,
|
||||
private readonly options: VaultClientOptions = {},
|
||||
) {}
|
||||
|
||||
get vaultId(): string {
|
||||
return this.keys.vaultId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sign a request body, with the pubkey inside the signed payload.
|
||||
*
|
||||
* The key has to be part of what gets signed, not appended afterwards:
|
||||
* `verifyPayload` canonicalises every field, so an appended key would both
|
||||
* break the signature and — if the scheme ignored it — let anyone swap the
|
||||
* claimed identity in transit on a first, TOFU-pinning write.
|
||||
*/
|
||||
private async sign(body: Record<string, unknown>): Promise<Record<string, unknown>> {
|
||||
return signPayload(this.crypto, this.keys.signingSeed, {
|
||||
...body,
|
||||
publicKey: toBase64(this.keys.publicKey),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Encrypt and upload `files`, then commit a manifest naming them.
|
||||
*
|
||||
* `at` is passed in rather than read from the clock so a caller can make a
|
||||
* commit reproducible in tests, and so a queued backup records when it was
|
||||
* *taken* rather than when it finally reached the relay.
|
||||
*
|
||||
* When nothing differs from the head — same paths, same modes, every file
|
||||
* reused — and no `message` asks for a version anyway, nothing is
|
||||
* committed. Pushes run on every workspace change, and a version per
|
||||
* trigger that changed nothing would grow the log for nothing.
|
||||
*/
|
||||
async push(
|
||||
files: VaultFile[],
|
||||
at: number,
|
||||
message?: string,
|
||||
opts: PushOptions = {},
|
||||
): Promise<PushResult> {
|
||||
const { head, entries: tail } = await this.transport.log(this.keys.vaultId, 1);
|
||||
const headRow = tail.find((e) => e.seq === head);
|
||||
|
||||
const fresh = (prior: VaultIndex | undefined): prior is VaultIndex =>
|
||||
prior !== undefined && prior.vaultId === this.keys.vaultId && prior.seq === head;
|
||||
|
||||
// Reuse beats re-sealing: sealing is nondeterministic (fresh nonce), so
|
||||
// re-sealing an untouched file would produce a new hash and a pointless
|
||||
// upload every single time.
|
||||
//
|
||||
// With a fresh index, reuse is decided locally by plaintext hash — also
|
||||
// across paths, so a renamed or copied file costs nothing either. Without
|
||||
// one, read only the head manifest, and download a previous file only
|
||||
// when its path and size both match (a different size cannot be the same
|
||||
// content). That is the old behaviour's correctness at a fraction of its
|
||||
// cost: it used to download every file of the head on every push.
|
||||
let headEntries: VaultEntry[] | null = null;
|
||||
const byHash = new Map<string, VaultEntry>();
|
||||
let byPath = new Map<string, VaultEntry>();
|
||||
if (fresh(opts.index)) {
|
||||
headEntries = Object.values(opts.index.entries).map((e) => e.entry);
|
||||
for (const e of Object.values(opts.index.entries)) byHash.set(e.sha256, e.entry);
|
||||
} else if (headRow) {
|
||||
// A head this client cannot read (a newer format, a corrupt manifest)
|
||||
// must not block a backup; it only costs the reuse.
|
||||
const manifest = await this.openRow(headRow).catch(() => null);
|
||||
if (manifest) {
|
||||
headEntries = manifest.entries;
|
||||
byPath = new Map(manifest.entries.map((e) => [e.path, e]));
|
||||
}
|
||||
}
|
||||
|
||||
const entries: VaultEntry[] = [];
|
||||
const indexEntries: Record<string, VaultIndexEntry> = {};
|
||||
let uploaded = 0;
|
||||
let reused = 0;
|
||||
let bytesUploaded = 0;
|
||||
|
||||
for (const file of files) {
|
||||
const digest = toHex(sha256(file.bytes));
|
||||
let prior = byHash.get(digest);
|
||||
if (!prior) {
|
||||
const candidate = byPath.get(file.path);
|
||||
if (candidate && candidate.size === file.bytes.length) {
|
||||
const old = await this.readEntry(candidate).catch(() => null);
|
||||
if (old && sameBytes(old, file.bytes)) prior = candidate;
|
||||
}
|
||||
}
|
||||
|
||||
let entry: VaultEntry;
|
||||
if (prior) {
|
||||
entry = { ...prior, path: file.path, size: file.bytes.length };
|
||||
reused++;
|
||||
} else {
|
||||
const sealed = await sealEntry(
|
||||
this.crypto,
|
||||
this.keys.contentKey,
|
||||
this.keys.vaultId,
|
||||
file.bytes,
|
||||
this.options.chunkSize === undefined ? {} : { chunkSize: this.options.chunkSize },
|
||||
);
|
||||
// No have-check first: every object here was just sealed under a
|
||||
// fresh nonce, so its name is new by construction, and asking would
|
||||
// only add a round trip per part.
|
||||
for (const obj of sealed.objects) {
|
||||
await this.transport.put(
|
||||
this.keys.vaultId,
|
||||
obj.hash,
|
||||
await this.sign({ data: toBase64(obj.bytes) }),
|
||||
);
|
||||
uploaded++;
|
||||
bytesUploaded += obj.bytes.length;
|
||||
}
|
||||
entry = { path: file.path, ...sealed.locator, size: file.bytes.length };
|
||||
// A second copy later in this same push reuses what was just sealed.
|
||||
byHash.set(digest, entry);
|
||||
}
|
||||
// The mode is metadata of this push, not of the content: a reused entry
|
||||
// takes the new one, and loses the old one if the file has none now.
|
||||
delete entry.mode;
|
||||
if (file.mode !== undefined) entry.mode = file.mode;
|
||||
|
||||
entries.push(entry);
|
||||
indexEntries[file.path] = { sha256: digest, entry };
|
||||
}
|
||||
|
||||
if (
|
||||
message === undefined &&
|
||||
headRow &&
|
||||
headEntries &&
|
||||
uploaded === 0 &&
|
||||
sameEntries(headEntries, entries)
|
||||
) {
|
||||
return {
|
||||
seq: head,
|
||||
uploaded: 0,
|
||||
reused,
|
||||
bytesUploaded: 0,
|
||||
unchanged: true,
|
||||
index: { vaultId: this.keys.vaultId, seq: head, entries: indexEntries },
|
||||
};
|
||||
}
|
||||
|
||||
const manifest: VaultManifest = { version: 2, seq: head + 1, at, entries };
|
||||
if (message !== undefined) manifest.message = message;
|
||||
|
||||
const sealedManifest = await sealManifest(
|
||||
this.crypto,
|
||||
this.keys.contentKey,
|
||||
this.keys.vaultId,
|
||||
manifest,
|
||||
);
|
||||
await this.transport.put(
|
||||
this.keys.vaultId,
|
||||
sealedManifest.hash,
|
||||
await this.sign({ data: toBase64(sealedManifest.bytes) }),
|
||||
);
|
||||
|
||||
// Every part, not just each entry's `hash`: the relay checks these exist
|
||||
// before publishing the version, and records them as what it references —
|
||||
// a part missing here would be fair game for the next prune.
|
||||
const hashes = [...new Set(entries.flatMap((e) => entryObjectHashes(e)))];
|
||||
const { seq } = await this.transport.commit(
|
||||
this.keys.vaultId,
|
||||
await this.sign({
|
||||
manifest: sealedManifest.hash,
|
||||
seq: manifest.seq,
|
||||
at,
|
||||
hashes,
|
||||
}),
|
||||
);
|
||||
|
||||
return {
|
||||
seq,
|
||||
uploaded,
|
||||
reused,
|
||||
bytesUploaded,
|
||||
unchanged: false,
|
||||
index: { vaultId: this.keys.vaultId, seq, entries: indexEntries },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Change a few files against the head that was actually read, and only it.
|
||||
*
|
||||
* `push` publishes a whole collection — right for a backup, where this
|
||||
* client is the only writer and the files on disk are the truth. It is
|
||||
* wrong for a vault two devices write to, such as a queue a phone appends
|
||||
* to while a PC drains it: a push computed from a stale view would commit
|
||||
* a collection without the other device's latest file, and it would be
|
||||
* gone. `edit` instead reads the head, lets `change` decide from exactly
|
||||
* that manifest, keeps every entry it did not touch as-is, and commits
|
||||
* `head + 1`. If another device committed in between, the relay refuses
|
||||
* with SEQ_CONFLICT and this starts over from the new head — `change` is
|
||||
* called again, so it must be a pure decision about the manifest it gets.
|
||||
*
|
||||
* Returning `null` (or an edit that changes nothing) commits nothing.
|
||||
*/
|
||||
async edit(
|
||||
change: (head: VaultManifest | null) => VaultEdit | null | Promise<VaultEdit | null>,
|
||||
at: number,
|
||||
opts: { maxAttempts?: number } = {},
|
||||
): Promise<{ seq: number; committed: boolean }> {
|
||||
const attempts = Math.max(1, opts.maxAttempts ?? 5);
|
||||
for (let attempt = 1; ; attempt++) {
|
||||
const { head, entries: tail } = await this.transport.log(this.keys.vaultId, 1);
|
||||
const row = tail.find((e) => e.seq === head);
|
||||
const manifest = row ? await this.openRow(row) : null;
|
||||
const edit = await change(manifest);
|
||||
const put = edit?.put ?? [];
|
||||
const remove = new Set(edit?.remove ?? []);
|
||||
const current = manifest?.entries ?? [];
|
||||
const replaced = new Set(put.map((f) => f.path));
|
||||
if (put.length === 0 && !current.some((e) => remove.has(e.path))) {
|
||||
return { seq: head, committed: false };
|
||||
}
|
||||
|
||||
const entries = current.filter((e) => !remove.has(e.path) && !replaced.has(e.path));
|
||||
for (const file of put) {
|
||||
const sealed = await sealEntry(
|
||||
this.crypto,
|
||||
this.keys.contentKey,
|
||||
this.keys.vaultId,
|
||||
file.bytes,
|
||||
this.options.chunkSize === undefined ? {} : { chunkSize: this.options.chunkSize },
|
||||
);
|
||||
for (const obj of sealed.objects) {
|
||||
await this.transport.put(this.keys.vaultId, obj.hash, await this.sign({ data: toBase64(obj.bytes) }));
|
||||
}
|
||||
const entry: VaultEntry = { path: file.path, ...sealed.locator, size: file.bytes.length };
|
||||
if (file.mode !== undefined) entry.mode = file.mode;
|
||||
entries.push(entry);
|
||||
}
|
||||
|
||||
const next: VaultManifest = { version: 2, seq: head + 1, at, entries };
|
||||
const sealedManifest = await sealManifest(this.crypto, this.keys.contentKey, this.keys.vaultId, next);
|
||||
await this.transport.put(
|
||||
this.keys.vaultId,
|
||||
sealedManifest.hash,
|
||||
await this.sign({ data: toBase64(sealedManifest.bytes) }),
|
||||
);
|
||||
try {
|
||||
const { seq } = await this.transport.commit(
|
||||
this.keys.vaultId,
|
||||
await this.sign({
|
||||
manifest: sealedManifest.hash,
|
||||
seq: next.seq,
|
||||
at,
|
||||
hashes: [...new Set(entries.flatMap((e) => entryObjectHashes(e)))],
|
||||
}),
|
||||
);
|
||||
return { seq, committed: true };
|
||||
} catch (e) {
|
||||
// The objects just uploaded are orphans now; the relay's prune grace
|
||||
// and GC take care of them. Only a lost race is worth another go.
|
||||
if (attempt >= attempts || !isSeqConflict(e)) throw e;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and open just a version's manifest. Defaults to the newest.
|
||||
*
|
||||
* The cheap way to answer "what is in the backup?" — a file browser lists a
|
||||
* thousand-file workspace with one download, then `readEntry`s what the
|
||||
* user actually opens.
|
||||
*/
|
||||
async manifest(seq?: number): Promise<VaultManifest> {
|
||||
// The head needs only the newest row; an older version needs the log to
|
||||
// find its row, since `limit` counts back from the head.
|
||||
const log = await this.transport.log(this.keys.vaultId, seq === undefined ? 1 : undefined);
|
||||
const wanted = seq ?? log.head;
|
||||
const row = log.entries.find((e) => e.seq === wanted);
|
||||
if (!row) throw new Error(`vault has no version ${wanted}`);
|
||||
return this.openRow(row);
|
||||
}
|
||||
|
||||
/** Fetch, verify, decrypt and reassemble one file of a manifest. */
|
||||
async readEntry(entry: VaultEntry): Promise<Uint8Array> {
|
||||
const objects: Uint8Array[] = [];
|
||||
for (const hash of entryObjectHashes(entry)) {
|
||||
objects.push(await this.transport.get(this.keys.vaultId, hash));
|
||||
}
|
||||
return openEntryBytes(this.crypto, this.keys.contentKey, this.keys.vaultId, entry, objects);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a version and decrypt all of it. Defaults to the newest.
|
||||
*
|
||||
* Restoring is the whole point of the exercise, so this returns the plain
|
||||
* files rather than a handle: a caller that has to make a second round of
|
||||
* decisions to get their data back does not have a backup. Callers that do
|
||||
* want to choose use `manifest` + `readEntry`, which this is built from.
|
||||
*/
|
||||
async pull(seq?: number): Promise<{ manifest: VaultManifest; files: Map<string, Uint8Array> }> {
|
||||
const manifest = await this.manifest(seq);
|
||||
const files = new Map<string, Uint8Array>();
|
||||
for (const entry of manifest.entries) files.set(entry.path, await this.readEntry(entry));
|
||||
return { manifest, files };
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop every version not in `keep`, and let the relay delete the objects
|
||||
* only those versions used. `keep` must include the current head; the
|
||||
* relay refuses with SEQ_CONFLICT otherwise, which is also what a
|
||||
* keep-list computed before another device's commit runs into.
|
||||
*/
|
||||
async prune(keep: number[]): Promise<VaultPruneResult> {
|
||||
const res = await this.transport.prune(this.keys.vaultId, await this.sign({ keep }));
|
||||
return {
|
||||
removedVersions: res.removedVersions,
|
||||
removedObjects: res.removedObjects,
|
||||
freedBytes: res.freedBytes,
|
||||
};
|
||||
}
|
||||
|
||||
private async openRow(row: VaultLogEntry): Promise<VaultManifest> {
|
||||
const bytes = await this.transport.get(this.keys.vaultId, row.manifest);
|
||||
return openManifest(this.crypto, this.keys.contentKey, this.keys.vaultId, row.manifest, bytes);
|
||||
}
|
||||
|
||||
/** Version history, newest last. */
|
||||
async history(limit?: number): Promise<VaultLog> {
|
||||
return this.transport.log(this.keys.vaultId, limit);
|
||||
}
|
||||
}
|
||||
|
||||
/** A few files changed, for `VaultClient.edit`. */
|
||||
export interface VaultEdit {
|
||||
/** Files to add, or to replace at the same path. */
|
||||
put?: VaultFile[];
|
||||
/** Paths to drop. A path that is not there is ignored. */
|
||||
remove?: string[];
|
||||
}
|
||||
|
||||
/** The relay's "someone committed first" — the one failure worth retrying. */
|
||||
function isSeqConflict(e: unknown): boolean {
|
||||
return e instanceof Error && /SEQ_CONFLICT/.test(e.message);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the index for a version you already hold in plaintext — after a
|
||||
* restore, say, so the first push from a fresh device needs no download.
|
||||
*/
|
||||
export function vaultIndexFrom(
|
||||
vaultId: string,
|
||||
manifest: VaultManifest,
|
||||
files: Map<string, Uint8Array>,
|
||||
): VaultIndex {
|
||||
const entries: Record<string, VaultIndexEntry> = {};
|
||||
for (const entry of manifest.entries) {
|
||||
const bytes = files.get(entry.path);
|
||||
if (bytes) entries[entry.path] = { sha256: toHex(sha256(bytes)), entry };
|
||||
}
|
||||
return { vaultId, seq: manifest.seq, entries };
|
||||
}
|
||||
|
||||
/**
|
||||
* Would committing `next` publish the same collection as `head`?
|
||||
*
|
||||
* Compared as a set by path, field by field, rather than by JSON: order of
|
||||
* files is not meaningful, and a reader's view of an entry is exactly these
|
||||
* fields.
|
||||
*/
|
||||
function sameEntries(head: VaultEntry[], next: VaultEntry[]): boolean {
|
||||
if (head.length !== next.length) return false;
|
||||
const byPath = new Map(head.map((e) => [e.path, e]));
|
||||
if (byPath.size !== head.length) return false;
|
||||
for (const e of next) {
|
||||
const h = byPath.get(e.path);
|
||||
if (
|
||||
!h ||
|
||||
h.hash !== e.hash ||
|
||||
h.size !== e.size ||
|
||||
h.mode !== e.mode ||
|
||||
h.enc !== e.enc ||
|
||||
(h.parts ?? []).join(',') !== (e.parts ?? []).join(',')
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
byPath.delete(e.path);
|
||||
}
|
||||
return byPath.size === 0;
|
||||
}
|
||||
|
||||
function sameBytes(a: Uint8Array, b: Uint8Array): boolean {
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
|
||||
return true;
|
||||
}
|
||||
439
packages/shade-vault/src/crypto.ts
Normal file
439
packages/shade-vault/src/crypto.ts
Normal file
@@ -0,0 +1,439 @@
|
||||
/**
|
||||
* Sealing and naming for vault objects.
|
||||
*
|
||||
* Every object on the relay is `nonce(12) || ciphertext||tag`, named by the
|
||||
* SHA-256 of those bytes. Hashing the *ciphertext* rather than the plaintext
|
||||
* is what lets the relay verify that an upload is what it claims to be
|
||||
* without holding a key — it recomputes the hash and compares.
|
||||
*
|
||||
* The cost is that identical plaintext yields different names on each seal,
|
||||
* because the nonce is fresh. Deduplication is therefore *within* a version
|
||||
* chain (an unchanged file keeps its hash across commits because the client
|
||||
* reuses the object it already uploaded), not across independent seals. That
|
||||
* is the right trade: convergent encryption would leak which files two users
|
||||
* share, which is exactly what a blind store must not do.
|
||||
*/
|
||||
|
||||
import { sha256 } from '@noble/hashes/sha2.js';
|
||||
import type { CryptoProvider } from '@shade/core';
|
||||
import type { VaultEntry, VaultEntryEncoding, VaultManifest } from './types.js';
|
||||
|
||||
const NONCE_LEN = 12;
|
||||
const TAG_LEN = 16;
|
||||
|
||||
/**
|
||||
* Largest stored (post-compression) slice sealed as one object: 4 MiB.
|
||||
*
|
||||
* The relay's per-object ceiling defaults to 8 MiB, and a file used to be
|
||||
* exactly one object — so a 9 MB PDF simply could not be backed up. Splitting
|
||||
* at 4 MiB leaves headroom under that ceiling for the nonce and tag, keeps a
|
||||
* single upload short enough to retry cheaply on a phone, and is part of the
|
||||
* wire contract: a Kotlin writer must split at the same boundary, or the two
|
||||
* would produce manifests the other cannot reproduce in a vector test.
|
||||
*/
|
||||
export const VAULT_CHUNK_SIZE = 4 * 1024 * 1024;
|
||||
|
||||
/**
|
||||
* Ceiling on an inflated manifest, as a defence against a decompression bomb.
|
||||
*
|
||||
* Every manifest is sealed under our own key, so a bomb could only come from
|
||||
* a device that already holds that key — but an accident (a corrupted write,
|
||||
* a buggy port) should fail with a message, not by exhausting memory.
|
||||
*/
|
||||
const MAX_MANIFEST_BYTES = 256 * 1024 * 1024;
|
||||
|
||||
/** ASCII "SVM2" — the prefix that marks a compressed v2 manifest. */
|
||||
const MANIFEST_V2_MAGIC = new Uint8Array([0x53, 0x56, 0x4d, 0x32]);
|
||||
|
||||
/** Lowercase hex SHA-256 — the name of an object. */
|
||||
export function objectHash(sealed: Uint8Array): string {
|
||||
return Array.from(sha256(sealed))
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
|
||||
/**
|
||||
* AAD for an object.
|
||||
*
|
||||
* Binds the vault it belongs to, so a ciphertext lifted from one vault cannot
|
||||
* be planted in another even by someone who can write to both. The content
|
||||
* hash is deliberately NOT in the AAD: it is derived from the very bytes
|
||||
* being sealed, so it cannot be known before sealing, and the relay's own
|
||||
* hash check already covers substitution.
|
||||
*/
|
||||
export function vaultObjectAad(vaultId: string): Uint8Array {
|
||||
return new TextEncoder().encode(`shade-vault-object-v1|${vaultId}`);
|
||||
}
|
||||
|
||||
export interface SealedObject {
|
||||
hash: string;
|
||||
bytes: Uint8Array;
|
||||
}
|
||||
|
||||
/** Encrypt one object and give it its name. */
|
||||
export async function sealObject(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
plaintext: Uint8Array,
|
||||
): Promise<SealedObject> {
|
||||
const { ciphertext, nonce } = await crypto.aesGcmEncrypt(
|
||||
contentKey,
|
||||
plaintext,
|
||||
vaultObjectAad(vaultId),
|
||||
);
|
||||
const bytes = new Uint8Array(NONCE_LEN + ciphertext.length);
|
||||
bytes.set(nonce, 0);
|
||||
bytes.set(ciphertext, NONCE_LEN);
|
||||
return { hash: objectHash(bytes), bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Decrypt one object.
|
||||
*
|
||||
* Throws when the hash does not match the bytes: a relay that returned the
|
||||
* wrong object would otherwise surface as an AEAD failure, which reads like
|
||||
* key corruption and sends the user looking in the wrong place.
|
||||
*/
|
||||
export async function openObject(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
expectedHash: string,
|
||||
bytes: Uint8Array,
|
||||
): Promise<Uint8Array> {
|
||||
if (bytes.length < NONCE_LEN + TAG_LEN) {
|
||||
throw new Error('vault object too short to be a sealed object');
|
||||
}
|
||||
const actual = objectHash(bytes);
|
||||
if (actual !== expectedHash) {
|
||||
throw new Error(`vault object hash mismatch: expected ${expectedHash}, got ${actual}`);
|
||||
}
|
||||
return crypto.aesGcmDecrypt(
|
||||
contentKey,
|
||||
bytes.subarray(NONCE_LEN),
|
||||
bytes.subarray(0, NONCE_LEN),
|
||||
vaultObjectAad(vaultId),
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Compression ─────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Run bytes through a (De)CompressionStream, refusing to produce more than
|
||||
* `limit` bytes.
|
||||
*
|
||||
* The streams API rather than `node:zlib`: it is the one deflate that exists
|
||||
* in browsers, Bun, Node and Deno alike, so the same client can run in a web
|
||||
* app without a polyfill. It offers no level knob — it compresses at zlib's
|
||||
* default, which is byte-identical to `deflateRawSync` without options and to
|
||||
* `java.util.zip.Deflater(DEFAULT_COMPRESSION, nowrap = true)` on the JVM. The
|
||||
* difference to level 9 on text is a percent or two; portability wins.
|
||||
*/
|
||||
async function pump(
|
||||
bytes: Uint8Array,
|
||||
stream: CompressionStream | DecompressionStream,
|
||||
limit: number,
|
||||
): Promise<Uint8Array> {
|
||||
const writer = stream.writable.getWriter();
|
||||
// Not awaited before reading: a stream applies backpressure, so waiting for
|
||||
// the write to drain before anyone reads would deadlock on large inputs.
|
||||
// Its failure surfaces through the reader below, so swallowing it here only
|
||||
// prevents an unhandled-rejection warning.
|
||||
const written = writer
|
||||
.write(bytes as unknown as Uint8Array<ArrayBuffer>)
|
||||
.then(() => writer.close())
|
||||
.catch(() => {});
|
||||
const reader = stream.readable.getReader();
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for (;;) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) break;
|
||||
total += value.length;
|
||||
if (total > limit) {
|
||||
await reader.cancel().catch(() => {});
|
||||
throw new Error(`vault inflate exceeded ${limit} bytes`);
|
||||
}
|
||||
chunks.push(value);
|
||||
}
|
||||
await written;
|
||||
return concatBytes(chunks, total);
|
||||
}
|
||||
|
||||
/** Raw DEFLATE (RFC 1951) — no zlib or gzip header, which a port would have to strip. */
|
||||
export async function deflateRaw(bytes: Uint8Array): Promise<Uint8Array> {
|
||||
return pump(bytes, new CompressionStream('deflate-raw'), Number.MAX_SAFE_INTEGER);
|
||||
}
|
||||
|
||||
/** Inverse of `deflateRaw`, refusing output longer than `limit`. */
|
||||
export async function inflateRaw(bytes: Uint8Array, limit: number): Promise<Uint8Array> {
|
||||
try {
|
||||
return await pump(bytes, new DecompressionStream('deflate-raw'), limit);
|
||||
} catch (e) {
|
||||
// The streams API rejects corrupt input with an empty message in some
|
||||
// runtimes, which would surface as "Error: " with nothing to go on.
|
||||
const why = (e as Error)?.message || 'corrupt deflate stream';
|
||||
throw new Error(`vault inflate failed: ${why}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Does this file start with the signature of a format that is already
|
||||
* compressed?
|
||||
*
|
||||
* Purely a CPU saving: the ≤95 % rule below would reject a JPEG anyway, but
|
||||
* only after deflating every byte of it. The list is part of the contract so
|
||||
* that a port makes the same choices and produces the same `enc` on the same
|
||||
* input — PNG, JPEG, WebP ("RIFF"…"WEBP"), MP4/MOV/HEIC ("ftyp" at offset 4),
|
||||
* GIF, gzip and zip ("PK", which also covers docx/xlsx/jar/apk).
|
||||
*/
|
||||
export function looksCompressed(b: Uint8Array): boolean {
|
||||
const at = (offset: number, sig: number[]): boolean =>
|
||||
b.length >= offset + sig.length && sig.every((v, i) => b[offset + i] === v);
|
||||
return (
|
||||
at(0, [0x89, 0x50, 0x4e, 0x47]) || // PNG
|
||||
at(0, [0xff, 0xd8, 0xff]) || // JPEG
|
||||
(at(0, [0x52, 0x49, 0x46, 0x46]) && at(8, [0x57, 0x45, 0x42, 0x50])) || // RIFF....WEBP
|
||||
at(4, [0x66, 0x74, 0x79, 0x70]) || // ....ftyp (MP4 family)
|
||||
at(0, [0x47, 0x49, 0x46, 0x38]) || // GIF8
|
||||
at(0, [0x1f, 0x8b]) || // gzip
|
||||
at(0, [0x50, 0x4b]) // PK (zip)
|
||||
);
|
||||
}
|
||||
|
||||
// ─── Entries ─────────────────────────────────────────────────
|
||||
|
||||
/** A file's bytes as they will be stored, before sealing. */
|
||||
export interface PackedEntry {
|
||||
/** Set only when the stored bytes are deflate-raw of the plaintext. */
|
||||
enc?: VaultEntryEncoding;
|
||||
/** The stored bytes: the plaintext, or its deflate-raw. */
|
||||
stored: Uint8Array;
|
||||
/** `stored`, split into slices of at most the chunk size. Never empty. */
|
||||
chunks: Uint8Array[];
|
||||
}
|
||||
|
||||
export interface PackOptions {
|
||||
/**
|
||||
* Override the slice size. Internal: exists so tests and cross-language
|
||||
* vectors can exercise multi-part entries without megabytes of fixture.
|
||||
* Production writers must use `VAULT_CHUNK_SIZE`.
|
||||
*/
|
||||
chunkSize?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a file's plaintext into the slices that get sealed — deterministic,
|
||||
* and the half of the format a port has to reproduce byte for byte.
|
||||
*
|
||||
* Compression is kept only when it saves at least 5 %, written as the integer
|
||||
* test `compressed * 20 <= plain * 19` so no implementation can disagree with
|
||||
* another over floating-point rounding at the boundary. Below that, the
|
||||
* reader's inflate pass costs more than the bytes it saves.
|
||||
*
|
||||
* Compression runs over the whole file and THEN the result is split, not per
|
||||
* chunk: a reader concatenates the opened parts and inflates once. That keeps
|
||||
* the dictionary spanning the whole file, and means `parts` are opaque slices
|
||||
* with no framing of their own.
|
||||
*/
|
||||
export async function packEntry(plaintext: Uint8Array, opts: PackOptions = {}): Promise<PackedEntry> {
|
||||
const chunkSize = opts.chunkSize ?? VAULT_CHUNK_SIZE;
|
||||
if (!Number.isInteger(chunkSize) || chunkSize < 1) {
|
||||
throw new Error(`vault chunk size must be a positive integer, got ${chunkSize}`);
|
||||
}
|
||||
|
||||
let stored = plaintext;
|
||||
let enc: VaultEntryEncoding | undefined;
|
||||
if (plaintext.length > 0 && !looksCompressed(plaintext)) {
|
||||
const deflated = await deflateRaw(plaintext);
|
||||
if (deflated.length * 20 <= plaintext.length * 19) {
|
||||
stored = deflated;
|
||||
enc = 'deflate-raw';
|
||||
}
|
||||
}
|
||||
|
||||
// An empty file is still one (empty) object, exactly as in v1: an entry
|
||||
// always names something the relay holds, so a reader never special-cases.
|
||||
const chunks: Uint8Array[] = [];
|
||||
for (let i = 0; i < stored.length || chunks.length === 0; i += chunkSize) {
|
||||
chunks.push(stored.subarray(i, i + chunkSize));
|
||||
}
|
||||
return enc ? { enc, stored, chunks } : { stored, chunks };
|
||||
}
|
||||
|
||||
/** The manifest fields that locate a file's ciphertext. */
|
||||
export interface EntryLocator {
|
||||
hash: string;
|
||||
parts?: string[];
|
||||
enc?: VaultEntryEncoding;
|
||||
}
|
||||
|
||||
/** Shape an entry's locator from its sealed parts (one part → no `parts`). */
|
||||
export function entryLocator(packed: PackedEntry, sealed: SealedObject[]): EntryLocator {
|
||||
const locator: EntryLocator = { hash: sealed[0]!.hash };
|
||||
if (sealed.length > 1) locator.parts = sealed.map((o) => o.hash);
|
||||
if (packed.enc) locator.enc = packed.enc;
|
||||
return locator;
|
||||
}
|
||||
|
||||
/** Pack and seal one file: the locator for its manifest entry, and the objects to upload. */
|
||||
export async function sealEntry(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
plaintext: Uint8Array,
|
||||
opts: PackOptions = {},
|
||||
): Promise<{ locator: EntryLocator; objects: SealedObject[] }> {
|
||||
const packed = await packEntry(plaintext, opts);
|
||||
const objects: SealedObject[] = [];
|
||||
for (const chunk of packed.chunks) {
|
||||
objects.push(await sealObject(crypto, contentKey, vaultId, chunk));
|
||||
}
|
||||
return { locator: entryLocator(packed, objects), objects };
|
||||
}
|
||||
|
||||
/**
|
||||
* Every object an entry needs, in read order.
|
||||
*
|
||||
* This is also what a commit's signed `hashes` must list. The relay cannot
|
||||
* read manifests, so `hashes` is the only way it learns what a version
|
||||
* references — for the missing-object check, and since prune, for deciding
|
||||
* what is still in use. A part left out of it may be garbage-collected.
|
||||
*/
|
||||
export function entryObjectHashes(entry: Pick<VaultEntry, 'hash' | 'parts'>): string[] {
|
||||
return entry.parts && entry.parts.length > 0 ? entry.parts : [entry.hash];
|
||||
}
|
||||
|
||||
/**
|
||||
* Reassemble a file from its fetched objects, in `entryObjectHashes` order:
|
||||
* verify and open each part, concatenate, inflate if `enc`, check the size.
|
||||
*
|
||||
* Order is guarded by the manifest: `parts` sits inside the sealed manifest,
|
||||
* and each fetched object must hash to the name in its slot. The size check
|
||||
* covers the rest — every part authenticates on its own, so an entry whose
|
||||
* part list lost or gained an element would otherwise open cleanly into a
|
||||
* truncated or padded file.
|
||||
*/
|
||||
export async function openEntryBytes(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
entry: VaultEntry,
|
||||
objects: Uint8Array[],
|
||||
): Promise<Uint8Array> {
|
||||
const hashes = entryObjectHashes(entry);
|
||||
if (entry.parts && entry.parts.length > 0 && entry.parts[0] !== entry.hash) {
|
||||
throw new Error(`vault entry ${entry.path}: hash must equal parts[0]`);
|
||||
}
|
||||
if (objects.length !== hashes.length) {
|
||||
throw new Error(
|
||||
`vault entry ${entry.path}: expected ${hashes.length} object(s), got ${objects.length}`,
|
||||
);
|
||||
}
|
||||
|
||||
const opened: Uint8Array[] = [];
|
||||
let storedLen = 0;
|
||||
for (let i = 0; i < hashes.length; i++) {
|
||||
const plain = await openObject(crypto, contentKey, vaultId, hashes[i]!, objects[i]!);
|
||||
opened.push(plain);
|
||||
storedLen += plain.length;
|
||||
}
|
||||
const stored = concatBytes(opened, storedLen);
|
||||
|
||||
let plaintext: Uint8Array;
|
||||
if (entry.enc === undefined) {
|
||||
plaintext = stored;
|
||||
} else if (entry.enc === 'deflate-raw') {
|
||||
plaintext = await inflateRaw(stored, entry.size);
|
||||
} else {
|
||||
// Same reasoning as an unknown manifest version: guessing would hand back
|
||||
// bytes that look like the file and are not.
|
||||
throw new Error(`vault entry ${entry.path}: unsupported encoding ${String(entry.enc)}`);
|
||||
}
|
||||
|
||||
if (plaintext.length !== entry.size) {
|
||||
throw new Error(
|
||||
`vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.length}`,
|
||||
);
|
||||
}
|
||||
return plaintext;
|
||||
}
|
||||
|
||||
// ─── Manifests ───────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* A manifest's plaintext before sealing.
|
||||
*
|
||||
* v1 is bare UTF-8 JSON. v2 is "SVM2" followed by deflate-raw of that JSON:
|
||||
* a workspace manifest is hundreds of near-identical path/hash lines, which
|
||||
* compress roughly 2:1 even though the hashes are random, and a new manifest
|
||||
* object is written on every single push. The magic, rather than sniffing for
|
||||
* `{`, makes the format self-describing — and a v1-only reader fails on it
|
||||
* loudly at JSON.parse instead of misreading it.
|
||||
*
|
||||
* The version field decides the container, so the same function writes the
|
||||
* v1 vectors that keep old manifests readable.
|
||||
*/
|
||||
export async function encodeManifest(manifest: VaultManifest): Promise<Uint8Array> {
|
||||
const json = new TextEncoder().encode(JSON.stringify(manifest));
|
||||
if (manifest.version === 1) return json;
|
||||
const deflated = await deflateRaw(json);
|
||||
return concatBytes([MANIFEST_V2_MAGIC, deflated], MANIFEST_V2_MAGIC.length + deflated.length);
|
||||
}
|
||||
|
||||
/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */
|
||||
export async function decodeManifest(plain: Uint8Array): Promise<VaultManifest> {
|
||||
const isV2 =
|
||||
plain.length >= MANIFEST_V2_MAGIC.length &&
|
||||
MANIFEST_V2_MAGIC.every((v, i) => plain[i] === v);
|
||||
const json = isV2
|
||||
? await inflateRaw(plain.subarray(MANIFEST_V2_MAGIC.length), MAX_MANIFEST_BYTES)
|
||||
: plain;
|
||||
const parsed = JSON.parse(new TextDecoder().decode(json)) as VaultManifest;
|
||||
if (parsed.version !== 1 && parsed.version !== 2) {
|
||||
// Refusing beats guessing: a future manifest may mean a file the reader
|
||||
// cannot represent, and silently dropping it would lose data on the next
|
||||
// commit made from this client.
|
||||
throw new Error(`unsupported vault manifest version: ${String(parsed.version)}`);
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
/** A manifest is stored as an ordinary object; this is the encoding step around it. */
|
||||
export async function sealManifest(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
manifest: VaultManifest,
|
||||
): Promise<SealedObject> {
|
||||
return sealObject(crypto, contentKey, vaultId, await encodeManifest(manifest));
|
||||
}
|
||||
|
||||
export async function openManifest(
|
||||
crypto: CryptoProvider,
|
||||
contentKey: Uint8Array,
|
||||
vaultId: string,
|
||||
expectedHash: string,
|
||||
bytes: Uint8Array,
|
||||
): Promise<VaultManifest> {
|
||||
return decodeManifest(await openObject(crypto, contentKey, vaultId, expectedHash, bytes));
|
||||
}
|
||||
|
||||
function concatBytes(chunks: Uint8Array[], total: number): Uint8Array {
|
||||
if (chunks.length === 1 && chunks[0]!.length === total) return chunks[0]!;
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset);
|
||||
offset += c.length;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Lowercase hex of arbitrary bytes — used for vaultId and pubkeys on the wire. */
|
||||
export function toHex(bytes: Uint8Array): string {
|
||||
return Array.from(bytes)
|
||||
.map((b) => b.toString(16).padStart(2, '0'))
|
||||
.join('');
|
||||
}
|
||||
90
packages/shade-vault/src/http-transport.ts
Normal file
90
packages/shade-vault/src/http-transport.ts
Normal file
@@ -0,0 +1,90 @@
|
||||
/**
|
||||
* The default transport: plain HTTP against a relay running the vault routes.
|
||||
*
|
||||
* Takes a `fetch` rather than calling the global one, so the same client works
|
||||
* against a live server, a Hono app under test, and anything else that can
|
||||
* answer a Request — which is how the tests exercise the real route handlers
|
||||
* instead of a mock that agrees with them by construction.
|
||||
*/
|
||||
|
||||
import { fromBase64 } from '@shade/core';
|
||||
import type { VaultTransport } from './client.js';
|
||||
import type { VaultLog, VaultPruneResult } from './types.js';
|
||||
|
||||
type FetchLike = (input: string, init?: RequestInit) => Promise<Response>;
|
||||
|
||||
export class HttpVaultTransport implements VaultTransport {
|
||||
constructor(
|
||||
private readonly baseUrl: string,
|
||||
private readonly fetchImpl: FetchLike = globalThis.fetch.bind(globalThis),
|
||||
) {}
|
||||
|
||||
private url(path: string): string {
|
||||
return `${this.baseUrl.replace(/\/$/, '')}${path}`;
|
||||
}
|
||||
|
||||
/** Turn a non-2xx into an Error that names the relay's own code. */
|
||||
private async fail(res: Response, what: string): Promise<never> {
|
||||
let detail = res.statusText;
|
||||
try {
|
||||
const body = (await res.json()) as { error?: { code?: string; message?: string } };
|
||||
if (body?.error) detail = `${body.error.code}: ${body.error.message}`;
|
||||
} catch {
|
||||
// Non-JSON error body; the status line is all we have.
|
||||
}
|
||||
throw new Error(`vault ${what} failed (${res.status}) — ${detail}`);
|
||||
}
|
||||
|
||||
async has(vaultId: string, hash: string): Promise<boolean> {
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/object/${hash}`), {
|
||||
method: 'HEAD',
|
||||
});
|
||||
if (res.status === 200) return true;
|
||||
if (res.status === 404) return false;
|
||||
return this.fail(res, 'have-check');
|
||||
}
|
||||
|
||||
async put(vaultId: string, hash: string, body: unknown): Promise<void> {
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/object/${hash}`), {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) return this.fail(res, 'upload');
|
||||
}
|
||||
|
||||
async get(vaultId: string, hash: string): Promise<Uint8Array> {
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/object/${hash}`));
|
||||
if (!res.ok) return this.fail(res, 'download');
|
||||
return new Uint8Array(await res.arrayBuffer());
|
||||
}
|
||||
|
||||
async log(vaultId: string, limit?: number): Promise<VaultLog> {
|
||||
const q = limit === undefined ? '' : `?limit=${limit}`;
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/log${q}`));
|
||||
if (!res.ok) return this.fail(res, 'log');
|
||||
return (await res.json()) as VaultLog;
|
||||
}
|
||||
|
||||
async commit(vaultId: string, body: unknown): Promise<{ seq: number }> {
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/commit`), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) return this.fail(res, 'commit');
|
||||
return (await res.json()) as { seq: number };
|
||||
}
|
||||
|
||||
async prune(vaultId: string, body: unknown): Promise<VaultPruneResult> {
|
||||
const res = await this.fetchImpl(this.url(`/v1/vault/${vaultId}/prune`), {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) return this.fail(res, 'prune');
|
||||
return (await res.json()) as VaultPruneResult;
|
||||
}
|
||||
}
|
||||
|
||||
export { fromBase64 };
|
||||
6
packages/shade-vault/src/index.ts
Normal file
6
packages/shade-vault/src/index.ts
Normal file
@@ -0,0 +1,6 @@
|
||||
export * from './types.js';
|
||||
export * from './crypto.js';
|
||||
export * from './client.js';
|
||||
export { MemoryVaultStore } from './store.js';
|
||||
export type { VaultStore, VaultPrunePlan } from './store.js';
|
||||
export { HttpVaultTransport } from './http-transport.js';
|
||||
308
packages/shade-vault/src/server.ts
Normal file
308
packages/shade-vault/src/server.ts
Normal file
@@ -0,0 +1,308 @@
|
||||
/**
|
||||
* Relay-side vault routes.
|
||||
*
|
||||
* GET /v1/vault/:vaultId/log → { entries, head }
|
||||
* GET /v1/vault/:vaultId/object/:hash → raw ciphertext bytes
|
||||
* HEAD /v1/vault/:vaultId/object/:hash → 200 | 404 (have-check)
|
||||
* PUT /v1/vault/:vaultId/object/:hash → { stored } (signed)
|
||||
* POST /v1/vault/:vaultId/commit → { seq } (signed)
|
||||
* POST /v1/vault/:vaultId/prune → { removedVersions, removedObjects,
|
||||
* freedBytes, head } (signed)
|
||||
*
|
||||
* Auth is the same TOFU-Ed25519 scheme the blob primitive uses: the first
|
||||
* signed write pins a pubkey for the vault, and every later write must be
|
||||
* signed by it. There is no account, no password, and nothing for the relay
|
||||
* to leak — it cannot even tell which user a vaultId belongs to.
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
import type { ContentfulStatusCode } from 'hono/utils/http-status';
|
||||
import type { CryptoProvider } from '@shade/core';
|
||||
import { fromBase64 } from '@shade/core';
|
||||
import { verifyPayload } from '@shade/server';
|
||||
import { objectHash } from './crypto.js';
|
||||
import type { VaultStore } from './store.js';
|
||||
import type { VaultManifest } from './types.js';
|
||||
|
||||
const ID_REGEX = /^[0-9a-f]{64}$/;
|
||||
const HASH_REGEX = /^[0-9a-f]{64}$/;
|
||||
|
||||
export interface VaultRoutesOptions {
|
||||
/** Per-object ceiling. Defaults to 8 MiB. */
|
||||
maxObjectBytes?: number;
|
||||
/** Whole-vault ceiling. Defaults to 512 MiB. */
|
||||
maxVaultBytes?: number;
|
||||
/**
|
||||
* How long an uploaded-but-never-committed object survives a prune.
|
||||
* Defaults to one hour — long enough for a slow phone to finish a large
|
||||
* push between its first upload and its commit.
|
||||
*/
|
||||
pruneGraceMs?: number;
|
||||
}
|
||||
|
||||
const DEFAULT_MAX_OBJECT = 8 * 1024 * 1024;
|
||||
const DEFAULT_MAX_VAULT = 512 * 1024 * 1024;
|
||||
const DEFAULT_PRUNE_GRACE = 60 * 60 * 1000;
|
||||
/** A keep-list longer than this is not a retention policy, it is a mistake. */
|
||||
const MAX_KEEP = 100_000;
|
||||
|
||||
function fail(code: string, message: string, status: ContentfulStatusCode) {
|
||||
return { body: { error: { code, message } }, status };
|
||||
}
|
||||
|
||||
export function createVaultRoutes(
|
||||
store: VaultStore,
|
||||
crypto: CryptoProvider,
|
||||
options: VaultRoutesOptions = {},
|
||||
): Hono {
|
||||
const app = new Hono();
|
||||
const maxObject = options.maxObjectBytes ?? DEFAULT_MAX_OBJECT;
|
||||
const maxVault = options.maxVaultBytes ?? DEFAULT_MAX_VAULT;
|
||||
const pruneGrace = options.pruneGraceMs ?? DEFAULT_PRUNE_GRACE;
|
||||
|
||||
/**
|
||||
* Check a signed request against the vault's pinned key, pinning it on the
|
||||
* first write. `publicKey` is only honoured when nothing is pinned yet —
|
||||
* otherwise anyone could rotate the owner by simply asserting a new key.
|
||||
*/
|
||||
async function authorize(
|
||||
vaultId: string,
|
||||
payload: Record<string, unknown>,
|
||||
): Promise<
|
||||
{ ok: true } | { ok: false; code: string; message: string; status: ContentfulStatusCode }
|
||||
> {
|
||||
const claimed = typeof payload.publicKey === 'string' ? payload.publicKey : null;
|
||||
const pinned = await store.getOwner(vaultId);
|
||||
|
||||
if (!pinned) {
|
||||
if (!claimed) {
|
||||
return { ok: false, code: 'UNAUTHORIZED', message: 'first write must carry publicKey', status: 401 };
|
||||
}
|
||||
const key = fromBase64(claimed);
|
||||
try {
|
||||
await verifyPayload(crypto, key, payload);
|
||||
} catch (e) {
|
||||
return { ok: false, code: 'UNAUTHORIZED', message: String((e as Error).message), status: 401 };
|
||||
}
|
||||
await store.setOwner(vaultId, key);
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
try {
|
||||
await verifyPayload(crypto, pinned, payload);
|
||||
} catch (e) {
|
||||
return { ok: false, code: 'UNAUTHORIZED', message: String((e as Error).message), status: 401 };
|
||||
}
|
||||
return { ok: true };
|
||||
}
|
||||
|
||||
app.get('/v1/vault/:vaultId/log', 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 limitRaw = c.req.query('limit');
|
||||
const limit = limitRaw ? Number(limitRaw) : undefined;
|
||||
const entries = await store.log(vaultId, Number.isFinite(limit) ? limit : undefined);
|
||||
return c.json({ entries, head: await store.head(vaultId) });
|
||||
});
|
||||
|
||||
// A have-check before uploading. This is what makes an unchanged file free:
|
||||
// the client asks about every hash in the new manifest and only sends the
|
||||
// ones the relay is missing.
|
||||
app.on(['HEAD', 'GET'], '/v1/vault/:vaultId/object/:hash', async (c) => {
|
||||
const vaultId = c.req.param('vaultId');
|
||||
const hash = c.req.param('hash');
|
||||
if (!ID_REGEX.test(vaultId) || !HASH_REGEX.test(hash)) {
|
||||
const f = fail('BAD_REQUEST', 'bad vaultId or hash', 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
if (c.req.method === 'HEAD') {
|
||||
return c.body(null, (await store.hasObject(vaultId, hash)) ? 200 : 404);
|
||||
}
|
||||
const bytes = await store.getObject(vaultId, hash);
|
||||
if (!bytes) {
|
||||
const f = fail('NOT_FOUND', 'no such object', 404);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
return c.body(bytes as unknown as ArrayBuffer, 200, {
|
||||
'content-type': 'application/octet-stream',
|
||||
});
|
||||
});
|
||||
|
||||
app.put('/v1/vault/:vaultId/object/:hash', async (c) => {
|
||||
const vaultId = c.req.param('vaultId');
|
||||
const hash = c.req.param('hash');
|
||||
if (!ID_REGEX.test(vaultId) || !HASH_REGEX.test(hash)) {
|
||||
const f = fail('BAD_REQUEST', 'bad vaultId or hash', 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
const body = (await c.req.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
if (!body || typeof body.data !== 'string') {
|
||||
const f = fail('BAD_REQUEST', 'expected { data, signedAt, signature }', 400);
|
||||
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 bytes = fromBase64(body.data);
|
||||
if (bytes.length > maxObject) {
|
||||
const f = fail('TOO_LARGE', `object exceeds ${maxObject} bytes`, 413);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
if ((await store.usage(vaultId)) + bytes.length > maxVault) {
|
||||
const f = fail('TOO_LARGE', `vault exceeds ${maxVault} bytes`, 413);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
// The name must be the hash of the bytes. Without this the store would
|
||||
// accept a mislabelled object, and every later read of that name would
|
||||
// fail decryption somewhere far away from the cause.
|
||||
const actual = objectHash(bytes);
|
||||
if (actual !== hash) {
|
||||
const f = fail('BAD_REQUEST', `hash mismatch: bytes hash to ${actual}`, 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
await store.putObject(vaultId, hash, bytes);
|
||||
return c.json({ stored: true, hash });
|
||||
});
|
||||
|
||||
app.post('/v1/vault/:vaultId/commit', 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;
|
||||
if (!body || typeof body.manifest !== 'string' || typeof body.seq !== 'number') {
|
||||
const f = fail('BAD_REQUEST', 'expected { manifest, seq, hashes, signedAt, signature }', 400);
|
||||
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 (body.seq !== head + 1) {
|
||||
// Two devices committed from the same head. The loser has to re-read
|
||||
// and re-commit; retrying the same seq would overwrite a version that
|
||||
// is already part of the history.
|
||||
const f = fail('SEQ_CONFLICT', `expected seq ${head + 1}, got ${body.seq}`, 409);
|
||||
return c.json({ ...f.body, head }, f.status);
|
||||
}
|
||||
|
||||
if (!(await store.hasObject(vaultId, body.manifest))) {
|
||||
const f = fail('MISSING_OBJECTS', 'manifest object not uploaded', 409);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
// Every object the manifest references must already be here, or the
|
||||
// commit would publish a version that cannot be restored. Checking at
|
||||
// commit time is what makes the log trustworthy.
|
||||
const hashes = Array.isArray(body.hashes) ? (body.hashes as string[]) : [];
|
||||
const missing: string[] = [];
|
||||
for (const h of hashes) {
|
||||
if (!HASH_REGEX.test(h) || !(await store.hasObject(vaultId, h))) missing.push(h);
|
||||
}
|
||||
if (missing.length > 0) {
|
||||
const f = fail('MISSING_OBJECTS', `${missing.length} referenced object(s) missing`, 409);
|
||||
return c.json({ ...f.body, missing: missing.slice(0, 20) }, f.status);
|
||||
}
|
||||
|
||||
// The signed `hashes` plus the manifest are everything this version
|
||||
// references. Recording them is what lets prune collect garbage later
|
||||
// without ever reading a manifest — so a client that leaves a part out of
|
||||
// `hashes` is telling the relay that part may be deleted.
|
||||
const refs = [...new Set([body.manifest, ...hashes])];
|
||||
await store.appendLog(
|
||||
vaultId,
|
||||
{
|
||||
seq: body.seq,
|
||||
manifest: body.manifest,
|
||||
at: typeof body.at === 'number' ? body.at : Date.now(),
|
||||
bytes: await store.usage(vaultId),
|
||||
},
|
||||
refs,
|
||||
);
|
||||
|
||||
return c.json({ seq: body.seq, head: body.seq });
|
||||
});
|
||||
|
||||
/**
|
||||
* Retention: drop versions and the objects only they used.
|
||||
*
|
||||
* Without this the log is append-only in the literal sense, and a vault
|
||||
* pushed on every edit grows until it hits the quota and stops accepting
|
||||
* backups — the failure arriving exactly when the user is relying on it.
|
||||
* The client decides the policy (keep the last N, one per day, …) because
|
||||
* only it can read the manifests; the relay just executes a keep-list.
|
||||
*/
|
||||
app.post('/v1/vault/:vaultId/prune', async (c) => {
|
||||
const vaultId = c.req.param('vaultId');
|
||||
if (!ID_REGEX.test(vaultId)) {
|
||||
const f = fail('BAD_REQUEST', 'vaultId must be 64 lowercase hex chars', 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
const body = (await c.req.json().catch(() => null)) as Record<string, unknown> | null;
|
||||
const keep = body?.keep;
|
||||
if (
|
||||
!body ||
|
||||
!Array.isArray(keep) ||
|
||||
keep.length > MAX_KEEP ||
|
||||
!keep.every((s) => Number.isSafeInteger(s) && (s as number) >= 0)
|
||||
) {
|
||||
const f = fail('BAD_REQUEST', 'expected { keep: number[], signedAt, signature }', 400);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
// Deliberately not `authorize`'s TOFU path: a prune must never be the
|
||||
// write that pins an owner. On a vault nobody has written to there is
|
||||
// nothing to prune, and accepting it would hand the vault to whoever
|
||||
// asked first.
|
||||
if (!(await store.getOwner(vaultId))) {
|
||||
const f = fail('NOT_FOUND', 'no such vault', 404);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
const auth = await authorize(vaultId, body);
|
||||
if (!auth.ok) {
|
||||
const f = fail(auth.code, auth.message, auth.status);
|
||||
return c.json(f.body, f.status);
|
||||
}
|
||||
|
||||
const head = await store.head(vaultId);
|
||||
if (!(keep as number[]).includes(head)) {
|
||||
// Pruning the head would leave the vault restoring to something other
|
||||
// than what was last backed up. It is also what a keep-list computed
|
||||
// before another device's commit looks like — so this is a conflict the
|
||||
// client resolves by re-reading, not a malformed request. A replayed
|
||||
// prune hits the same wall as soon as anything has been committed.
|
||||
const f = fail('SEQ_CONFLICT', `keep must include the current head ${head}`, 409);
|
||||
return c.json({ ...f.body, head }, f.status);
|
||||
}
|
||||
|
||||
const result = await store.prune(vaultId, {
|
||||
keep: keep as number[],
|
||||
upTo: head,
|
||||
protectSince: Date.now() - pruneGrace,
|
||||
});
|
||||
return c.json({ ...result, head });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
export type { VaultStore, VaultPrunePlan } from './store.js';
|
||||
export { MemoryVaultStore } from './store.js';
|
||||
export type { VaultManifest };
|
||||
217
packages/shade-vault/src/store.ts
Normal file
217
packages/shade-vault/src/store.ts
Normal file
@@ -0,0 +1,217 @@
|
||||
/**
|
||||
* Relay-side storage for a vault.
|
||||
*
|
||||
* The interface is deliberately dumb: put bytes under a hash, list a log,
|
||||
* append to it. Nothing here can decrypt, and nothing needs to — which is
|
||||
* what makes a SQLite, Postgres or object-store implementation equivalent.
|
||||
*/
|
||||
|
||||
import type { VaultLogEntry, VaultPruneResult } from './types.js';
|
||||
|
||||
/**
|
||||
* What the relay is asked to forget, already checked by the route.
|
||||
*
|
||||
* The relay cannot read a manifest, so it cannot know on its own which
|
||||
* objects a version uses. It knows because every commit since prune existed
|
||||
* hands the store its `refs` — the signed `hashes` plus the manifest object —
|
||||
* and that list is what garbage collection is computed from.
|
||||
*
|
||||
* **Versions committed before ref tracking have no list.** Their objects are
|
||||
* "pinned": every object present when such an entry was appended (or, for a
|
||||
* SQLite database, when it was migrated) is treated as referenced for as long
|
||||
* as any untracked entry remains in the log. Pinning is coarse — it protects
|
||||
* objects the old entry may not use — but it is the only safe reading of "we
|
||||
* do not know", and it is self-limiting: once the last untracked version has
|
||||
* been pruned, no unknown reference set is left, the pins are dropped and
|
||||
* those objects are collected like any other.
|
||||
*/
|
||||
export interface VaultPrunePlan {
|
||||
/** Sequence numbers to keep. The route has checked that the head is among them. */
|
||||
keep: readonly number[];
|
||||
/**
|
||||
* Only entries with `seq <= upTo` may be removed — the head the route saw.
|
||||
* A commit that lands between that check and the prune is newer, and must
|
||||
* survive even though it is not in `keep`.
|
||||
*/
|
||||
upTo: number;
|
||||
/**
|
||||
* Epoch millis. An object no version has ever referenced, stored after
|
||||
* this, is left alone: it is most likely an upload whose commit is still
|
||||
* on its way, and deleting it would fail that push with MISSING_OBJECTS.
|
||||
* Objects that a removed version referenced get no such grace.
|
||||
*/
|
||||
protectSince: number;
|
||||
}
|
||||
|
||||
export interface VaultStore {
|
||||
/** Ed25519 pubkey pinned on first write (TOFU), or null for a fresh vault. */
|
||||
getOwner(vaultId: string): Promise<Uint8Array | null>;
|
||||
setOwner(vaultId: string, publicKey: Uint8Array): Promise<void>;
|
||||
|
||||
hasObject(vaultId: string, hash: string): Promise<boolean>;
|
||||
putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void>;
|
||||
getObject(vaultId: string, hash: string): Promise<Uint8Array | null>;
|
||||
|
||||
/** Highest committed seq, or 0 when empty. */
|
||||
head(vaultId: string): Promise<number>;
|
||||
/** Newest last. `limit` counts back from the head. */
|
||||
log(vaultId: string, limit?: number): Promise<VaultLogEntry[]>;
|
||||
/**
|
||||
* Append a version. `refs` is every object hash it references, manifest
|
||||
* included; the routes always pass it. Omitting it records the entry as
|
||||
* untracked, with the pinning described on `VaultPrunePlan` — that is how
|
||||
* entries from before ref tracking behave, and how tests simulate them.
|
||||
*/
|
||||
appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void>;
|
||||
|
||||
/**
|
||||
* Remove log entries and garbage-collect the objects nothing left uses.
|
||||
* Must be atomic with respect to other writes to the same vault.
|
||||
*/
|
||||
prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult>;
|
||||
|
||||
/** Total stored bytes, for quota decisions. */
|
||||
usage(vaultId: string): Promise<number>;
|
||||
}
|
||||
|
||||
/**
|
||||
* In-memory store. Real for tests, a footgun in production — the same shape
|
||||
* as `MemoryBlobStore`, and the same warning applies: a restart loses
|
||||
* everything, and it will do so without an error.
|
||||
*/
|
||||
export class MemoryVaultStore implements VaultStore {
|
||||
private owners = new Map<string, Uint8Array>();
|
||||
private objects = new Map<string, Map<string, Uint8Array>>();
|
||||
private logs = new Map<string, VaultLogEntry[]>();
|
||||
/** Per vault: seq → referenced hashes, or null for an untracked entry. */
|
||||
private refs = new Map<string, Map<number, Set<string> | null>>();
|
||||
/** Per vault: objects an untracked entry may reference. */
|
||||
private pinned = new Map<string, Set<string>>();
|
||||
/** Per vault: when each object was first stored, for the prune grace. */
|
||||
private storedAt = new Map<string, Map<string, number>>();
|
||||
|
||||
async getOwner(vaultId: string): Promise<Uint8Array | null> {
|
||||
return this.owners.get(vaultId) ?? null;
|
||||
}
|
||||
|
||||
async setOwner(vaultId: string, publicKey: Uint8Array): Promise<void> {
|
||||
this.owners.set(vaultId, publicKey);
|
||||
}
|
||||
|
||||
private bucket(vaultId: string): Map<string, Uint8Array> {
|
||||
let b = this.objects.get(vaultId);
|
||||
if (!b) {
|
||||
b = new Map();
|
||||
this.objects.set(vaultId, b);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
async hasObject(vaultId: string, hash: string): Promise<boolean> {
|
||||
return this.bucket(vaultId).has(hash);
|
||||
}
|
||||
|
||||
async putObject(vaultId: string, hash: string, bytes: Uint8Array): Promise<void> {
|
||||
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> {
|
||||
return this.bucket(vaultId).get(hash) ?? null;
|
||||
}
|
||||
|
||||
async head(vaultId: string): Promise<number> {
|
||||
const l = this.logs.get(vaultId);
|
||||
return l && l.length > 0 ? l[l.length - 1]!.seq : 0;
|
||||
}
|
||||
|
||||
async log(vaultId: string, limit?: number): Promise<VaultLogEntry[]> {
|
||||
const l = this.logs.get(vaultId) ?? [];
|
||||
return limit === undefined ? [...l] : l.slice(Math.max(0, l.length - limit));
|
||||
}
|
||||
|
||||
async appendLog(vaultId: string, entry: VaultLogEntry, refs?: readonly string[]): Promise<void> {
|
||||
const l = this.logs.get(vaultId) ?? [];
|
||||
if (l.some((e) => e.seq === entry.seq)) {
|
||||
// Mirrors the SQLite primary key: two rows with one seq would make
|
||||
// history ambiguous, and prune would not know which refs to drop.
|
||||
throw new Error(`vault ${vaultId} already has seq ${entry.seq}`);
|
||||
}
|
||||
l.push(entry);
|
||||
this.logs.set(vaultId, l);
|
||||
|
||||
let byseq = this.refs.get(vaultId);
|
||||
if (!byseq) {
|
||||
byseq = new Map();
|
||||
this.refs.set(vaultId, byseq);
|
||||
}
|
||||
if (refs) {
|
||||
byseq.set(entry.seq, new Set(refs));
|
||||
} else {
|
||||
// An untracked entry can only reference what was here when it was
|
||||
// committed — so pin exactly that.
|
||||
byseq.set(entry.seq, null);
|
||||
const pins = this.pinned.get(vaultId) ?? new Set<string>();
|
||||
for (const h of this.bucket(vaultId).keys()) pins.add(h);
|
||||
this.pinned.set(vaultId, pins);
|
||||
}
|
||||
}
|
||||
|
||||
async prune(vaultId: string, plan: VaultPrunePlan): Promise<VaultPruneResult> {
|
||||
// No await anywhere below: the whole prune runs in one turn of the event
|
||||
// loop, which is what makes it atomic against a concurrent commit.
|
||||
const keep = new Set(plan.keep);
|
||||
const log = this.logs.get(vaultId) ?? [];
|
||||
const byseq = this.refs.get(vaultId) ?? new Map<number, Set<string> | null>();
|
||||
const bucket = this.bucket(vaultId);
|
||||
const times = this.storedAt.get(vaultId) ?? new Map<string, number>();
|
||||
|
||||
const removed = log.filter((e) => e.seq <= plan.upTo && !keep.has(e.seq));
|
||||
const remaining = log.filter((e) => !(e.seq <= plan.upTo && !keep.has(e.seq)));
|
||||
|
||||
const everReferenced = new Set<string>();
|
||||
for (const e of log) {
|
||||
everReferenced.add(e.manifest);
|
||||
for (const h of byseq.get(e.seq) ?? []) everReferenced.add(h);
|
||||
}
|
||||
|
||||
const inUse = new Set<string>();
|
||||
let untrackedRemains = false;
|
||||
for (const e of remaining) {
|
||||
inUse.add(e.manifest);
|
||||
const r = byseq.get(e.seq);
|
||||
if (r === undefined || r === null) untrackedRemains = true;
|
||||
else for (const h of r) inUse.add(h);
|
||||
}
|
||||
if (!untrackedRemains) this.pinned.delete(vaultId);
|
||||
const pins = this.pinned.get(vaultId) ?? new Set<string>();
|
||||
|
||||
let removedObjects = 0;
|
||||
let freedBytes = 0;
|
||||
for (const [hash, bytes] of [...bucket]) {
|
||||
if (inUse.has(hash) || pins.has(hash)) continue;
|
||||
if (!everReferenced.has(hash) && (times.get(hash) ?? 0) > plan.protectSince) continue;
|
||||
bucket.delete(hash);
|
||||
times.delete(hash);
|
||||
removedObjects++;
|
||||
freedBytes += bytes.length;
|
||||
}
|
||||
|
||||
for (const e of removed) byseq.delete(e.seq);
|
||||
this.logs.set(vaultId, remaining);
|
||||
return { removedVersions: removed.length, removedObjects, freedBytes };
|
||||
}
|
||||
|
||||
async usage(vaultId: string): Promise<number> {
|
||||
let total = 0;
|
||||
for (const bytes of this.bucket(vaultId).values()) total += bytes.length;
|
||||
return total;
|
||||
}
|
||||
}
|
||||
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 };
|
||||
}
|
||||
149
packages/shade-vault/src/types.ts
Normal file
149
packages/shade-vault/src/types.ts
Normal file
@@ -0,0 +1,149 @@
|
||||
/**
|
||||
* The vault's data model.
|
||||
*
|
||||
* A vault is a collection of files that lives encrypted on the relay: the
|
||||
* pieces Shade was missing to let an app offer backup, or to let a client
|
||||
* read data while the peer that owns it is switched off.
|
||||
*
|
||||
* Three ideas, and the shape follows from them:
|
||||
*
|
||||
* 1. **Objects are content-addressed.** An object's name is the hash of its
|
||||
* *ciphertext*, so the relay can store and dedupe without understanding
|
||||
* anything. Re-uploading an unchanged file is free, which matters when a
|
||||
* workspace of several hundred files changes three lines at a time.
|
||||
*
|
||||
* 2. **A manifest names the collection.** Paths live in the manifest, not in
|
||||
* object names — the relay must not learn that a user has a file called
|
||||
* `Projects/Divorce/plan.md`. The manifest is itself encrypted and stored
|
||||
* as an object.
|
||||
*
|
||||
* 3. **The log is append-only.** Each commit adds an entry pointing at a
|
||||
* manifest. History, rollback and "what changed last Tuesday" all fall out
|
||||
* of that, which is the versioning half of the requirement.
|
||||
*/
|
||||
|
||||
/**
|
||||
* How an entry's stored bytes relate to its plaintext. Absent means stored
|
||||
* as-is; `deflate-raw` means RFC 1951 raw DEFLATE (no zlib/gzip header).
|
||||
*/
|
||||
export type VaultEntryEncoding = 'deflate-raw';
|
||||
|
||||
/**
|
||||
* One file in a manifest. `hash` names the ciphertext object.
|
||||
*
|
||||
* v2 adds two optional fields, and an entry without them is exactly a v1
|
||||
* entry — so a v2 reader needs no separate path for old manifests:
|
||||
*
|
||||
* - `enc`: the stored bytes are compressed. Set only when that saved at least
|
||||
* 5 %, so a reader can never assume it.
|
||||
* - `parts`: the stored bytes were split into several objects (files larger
|
||||
* than one 4 MiB chunk). Listed in order; `hash` is then `parts[0]`, which
|
||||
* keeps "`hash` names an object the relay holds" true for every entry.
|
||||
*/
|
||||
export interface VaultEntry {
|
||||
/** Path within the collection, as the app understands it. */
|
||||
path: string;
|
||||
/** Lowercase hex SHA-256 of the (first) ciphertext object. */
|
||||
hash: string;
|
||||
/**
|
||||
* PLAINTEXT byte length — before compression, whatever `enc` says. Readers
|
||||
* check the reassembled file against it.
|
||||
*/
|
||||
size: number;
|
||||
/** Optional app-defined mode/metadata, opaque to the vault. */
|
||||
mode?: string;
|
||||
/** Present only when the stored bytes are compressed. */
|
||||
enc?: VaultEntryEncoding;
|
||||
/** Present only when there is more than one object; `parts[0] === hash`. */
|
||||
parts?: string[];
|
||||
}
|
||||
|
||||
/** The full contents of a collection at one point in time. */
|
||||
export interface VaultManifest {
|
||||
/**
|
||||
* Schema version — a client that does not know it must refuse, not guess.
|
||||
* 1: bare JSON. 2: "SVM2" + deflate-raw(JSON), entries may carry `enc` and
|
||||
* `parts`. Writers emit 2; readers accept both.
|
||||
*/
|
||||
version: 1 | 2;
|
||||
/** Monotonic, assigned by the client and checked by the relay. */
|
||||
seq: number;
|
||||
/** Epoch millis when the commit was made. */
|
||||
at: number;
|
||||
/** Optional human note, e.g. "nattlig backup". */
|
||||
message?: string;
|
||||
entries: VaultEntry[];
|
||||
}
|
||||
|
||||
/** One row of the append-only log. */
|
||||
export interface VaultLogEntry {
|
||||
seq: number;
|
||||
/** Hash of the encrypted manifest object. */
|
||||
manifest: string;
|
||||
at: number;
|
||||
/** Total bytes of all objects the manifest references, for quota display. */
|
||||
bytes: number;
|
||||
}
|
||||
|
||||
/** What `GET /v1/vault/:id/log` returns. */
|
||||
export interface VaultLog {
|
||||
entries: VaultLogEntry[];
|
||||
/** Highest seq the relay holds; `0` when the vault is empty. */
|
||||
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.
|
||||
*
|
||||
* `SEQ_CONFLICT` is the important one: two devices committed from the same
|
||||
* head, and the loser must re-read and re-commit rather than retry blindly.
|
||||
*/
|
||||
export type VaultErrorCode =
|
||||
| 'BAD_REQUEST'
|
||||
| 'UNAUTHORIZED'
|
||||
| 'NOT_FOUND'
|
||||
| 'SEQ_CONFLICT'
|
||||
| 'TOO_LARGE'
|
||||
| 'MISSING_OBJECTS';
|
||||
153
packages/shade-vault/tests/scaffoldd-e2e.test.ts
Normal file
153
packages/shade-vault/tests/scaffoldd-e2e.test.ts
Normal file
@@ -0,0 +1,153 @@
|
||||
/**
|
||||
* The whole backup chain, against real data.
|
||||
*
|
||||
* Talks to a running `scaffoldd` over its unix socket, asks what the backup
|
||||
* set is, reads those files off disk, pushes them through the vault, and pulls
|
||||
* them back — then compares byte-for-byte.
|
||||
*
|
||||
* This is the test that would catch the things unit tests cannot: a path that
|
||||
* survives the round trip wrong, a 600 KB log that trips a size ceiling, a
|
||||
* workspace whose file count makes the manifest too large to commit. It is
|
||||
* skipped when no daemon is listening, so it never blocks an ordinary run.
|
||||
*
|
||||
* scaffoldd --socket /tmp/scaffoldd-e2e.sock &
|
||||
* SCAFFOLDD_SOCKET=/tmp/scaffoldd-e2e.sock bun test scaffoldd-e2e
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { connect } from 'node:net';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import { createVaultRoutes } from '../src/server.js';
|
||||
import { MemoryVaultStore } from '../src/store.js';
|
||||
import { HttpVaultTransport } from '../src/http-transport.js';
|
||||
import { VaultClient, deriveVaultKeys } from '../src/client.js';
|
||||
import type { VaultFile } from '../src/client.js';
|
||||
|
||||
const SOCKET = process.env.SCAFFOLDD_SOCKET;
|
||||
const crypto = new SubtleCryptoProvider();
|
||||
|
||||
interface BackupFile {
|
||||
path: string;
|
||||
source: string;
|
||||
size: number;
|
||||
}
|
||||
|
||||
function ask(socketPath: string, request: object): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const sock = connect(socketPath);
|
||||
let buf = '';
|
||||
const timer = setTimeout(() => {
|
||||
sock.destroy();
|
||||
reject(new Error('scaffoldd svarte ikke innen 20 s'));
|
||||
}, 20_000);
|
||||
// Deliberately no `end()` after writing: Bun's socket closes both
|
||||
// directions, so the daemon's reply is discarded before it arrives. The
|
||||
// protocol is line-delimited, so read until the first complete line and
|
||||
// close from here instead.
|
||||
sock.on('connect', () => {
|
||||
sock.write(`${JSON.stringify(request)}\n`);
|
||||
});
|
||||
sock.on('data', (c) => {
|
||||
buf += c.toString();
|
||||
const nl = buf.indexOf('\n');
|
||||
if (nl === -1) return;
|
||||
clearTimeout(timer);
|
||||
sock.destroy();
|
||||
const res = JSON.parse(buf.slice(0, nl));
|
||||
res.ok ? resolve(res.result) : reject(new Error(`${res.code}: ${res.error}`));
|
||||
});
|
||||
sock.on('end', () => {
|
||||
clearTimeout(timer);
|
||||
if (!buf.includes('\n')) reject(new Error('tomt svar'));
|
||||
});
|
||||
sock.on('error', (e) => {
|
||||
clearTimeout(timer);
|
||||
reject(e);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function harness() {
|
||||
const store = new MemoryVaultStore();
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const transport = new HttpVaultTransport('http://vault.test', (i, init) =>
|
||||
routes.fetch(new Request(i, init)),
|
||||
);
|
||||
const keys = await deriveVaultKeys(new Uint8Array(32).fill(42), 'scaffold-e2e');
|
||||
return { store, client: new VaultClient(crypto, keys, transport) };
|
||||
}
|
||||
|
||||
describe.skipIf(!SOCKET)('scaffoldd → vault, real workspace', () => {
|
||||
test('the whole backup set round-trips byte-for-byte', async () => {
|
||||
const set = (await ask(SOCKET!, { op: 'backupSet' })) as {
|
||||
files: BackupFile[];
|
||||
count: number;
|
||||
bytes: number;
|
||||
};
|
||||
expect(set.count).toBeGreaterThan(50);
|
||||
|
||||
const files: VaultFile[] = [];
|
||||
for (const f of set.files) {
|
||||
try {
|
||||
files.push({ path: f.path, bytes: new Uint8Array(await readFile(f.source)) });
|
||||
} catch {
|
||||
// Matches the bridge: one unreadable file is skipped, not fatal.
|
||||
}
|
||||
}
|
||||
|
||||
const { client } = await harness();
|
||||
const push = await client.push(files, 1_786_600_000_000, 'e2e');
|
||||
expect(push.seq).toBe(1);
|
||||
expect(push.uploaded).toBe(files.length);
|
||||
|
||||
const { files: back } = await client.pull();
|
||||
expect(back.size).toBe(files.length);
|
||||
|
||||
// Every single file, not a sample: a backup that restores 99% of a
|
||||
// workspace is not a backup.
|
||||
for (const f of files) {
|
||||
const restored = back.get(f.path);
|
||||
expect(restored).toBeDefined();
|
||||
expect(restored!.length).toBe(f.bytes.length);
|
||||
expect(Buffer.from(restored!).equals(Buffer.from(f.bytes))).toBe(true);
|
||||
}
|
||||
}, 120_000);
|
||||
|
||||
test('a second push after one edit sends almost nothing', async () => {
|
||||
// The property that decides whether hourly backup is affordable.
|
||||
const set = (await ask(SOCKET!, { op: 'backupSet' })) as { files: BackupFile[] };
|
||||
const files: VaultFile[] = [];
|
||||
for (const f of set.files.slice(0, 120)) {
|
||||
try {
|
||||
files.push({ path: f.path, bytes: new Uint8Array(await readFile(f.source)) });
|
||||
} catch {
|
||||
/* skipped */
|
||||
}
|
||||
}
|
||||
|
||||
const { client } = await harness();
|
||||
const first = await client.push(files, 1_786_600_000_000);
|
||||
|
||||
const edited = files.map((f, i) =>
|
||||
i === 0 ? { path: f.path, bytes: new TextEncoder().encode('endret én linje') } : f,
|
||||
);
|
||||
const second = await client.push(edited, 1_786_600_001_000);
|
||||
|
||||
expect(first.uploaded).toBe(files.length);
|
||||
expect(second.uploaded).toBe(1);
|
||||
expect(second.reused).toBe(files.length - 1);
|
||||
}, 120_000);
|
||||
|
||||
test('the largest file in the workspace survives the round trip', async () => {
|
||||
// Terra's log.md is ~617 KB. Nothing in the chain may quietly cap it.
|
||||
const set = (await ask(SOCKET!, { op: 'backupSet' })) as { files: BackupFile[] };
|
||||
const biggest = set.files.reduce((a, b) => (a.size > b.size ? a : b));
|
||||
expect(biggest.size).toBeGreaterThan(100_000);
|
||||
|
||||
const bytes = new Uint8Array(await readFile(biggest.source));
|
||||
const { client } = await harness();
|
||||
await client.push([{ path: biggest.path, bytes }], 1_786_600_000_000);
|
||||
const { files } = await client.pull();
|
||||
expect(files.get(biggest.path)!.length).toBe(bytes.length);
|
||||
}, 120_000);
|
||||
});
|
||||
714
packages/shade-vault/tests/vault-v2.test.ts
Normal file
714
packages/shade-vault/tests/vault-v2.test.ts
Normal file
@@ -0,0 +1,714 @@
|
||||
/**
|
||||
* 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]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('edit against the head that was read', () => {
|
||||
const text = (s: string) => new TextEncoder().encode(s);
|
||||
const decode = (b: Uint8Array) => new TextDecoder().decode(b);
|
||||
|
||||
test('a drain that raced an append keeps the appended file', async () => {
|
||||
// The queue case: a phone appends while the PC removes what it applied.
|
||||
// A whole-collection push from the PC's stale view would drop the
|
||||
// phone's new file; edit retries on the new head instead.
|
||||
const { client, device } = await harness();
|
||||
const phone = device();
|
||||
await phone.edit(() => ({ put: [{ path: 'intents/a.json', bytes: text('a') }] }), 1);
|
||||
|
||||
let calls = 0;
|
||||
const res = await client.edit(async (head) => {
|
||||
calls++;
|
||||
if (calls === 1) {
|
||||
// Between this read and the commit, the phone appends.
|
||||
await phone.edit(() => ({ put: [{ path: 'intents/b.json', bytes: text('b') }] }), 2);
|
||||
}
|
||||
expect(head).not.toBeNull();
|
||||
return { remove: ['intents/a.json'] };
|
||||
}, 3);
|
||||
|
||||
expect(calls).toBe(2);
|
||||
expect(res.committed).toBe(true);
|
||||
const after = await client.manifest();
|
||||
expect(after.entries.map((e) => e.path)).toEqual(['intents/b.json']);
|
||||
expect(decode(await client.readEntry(after.entries[0]!))).toBe('b');
|
||||
});
|
||||
|
||||
test('an edit that changes nothing commits nothing', async () => {
|
||||
const { client, transport } = await harness();
|
||||
await client.edit(() => ({ put: [{ path: 'x', bytes: text('x') }] }), 1);
|
||||
const before = transport.counts.commit;
|
||||
const res = await client.edit(() => ({ remove: ['not-there'] }), 2);
|
||||
expect(res).toEqual({ seq: 1, committed: false });
|
||||
expect(await client.edit(() => null, 3)).toEqual({ seq: 1, committed: false });
|
||||
expect(transport.counts.commit).toBe(before);
|
||||
});
|
||||
|
||||
test('untouched entries keep their objects', async () => {
|
||||
const { client } = await harness();
|
||||
await client.edit(() => ({ put: [{ path: 'keep', bytes: text('k') }, { path: 'drop', bytes: text('d') }] }), 1);
|
||||
const first = await client.manifest();
|
||||
await client.edit(() => ({ remove: ['drop'], put: [{ path: 'new', bytes: text('n') }] }), 2);
|
||||
const second = await client.manifest();
|
||||
const keep = (m: typeof first) => m.entries.find((e) => e.path === 'keep')!;
|
||||
expect(keep(second).hash).toBe(keep(first).hash);
|
||||
expect(second.entries.map((e) => e.path).sort()).toEqual(['keep', 'new']);
|
||||
});
|
||||
});
|
||||
313
packages/shade-vault/tests/vault.test.ts
Normal file
313
packages/shade-vault/tests/vault.test.ts
Normal file
@@ -0,0 +1,313 @@
|
||||
/**
|
||||
* End-to-end tests for the vault.
|
||||
*
|
||||
* The client talks to the REAL route handlers through Hono's `fetch`, not to a
|
||||
* mock. A mock transport would agree with the client by construction and prove
|
||||
* nothing about the wire contract — which is exactly the surface a phone and a
|
||||
* daemon have to share.
|
||||
*/
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||
import { createVaultRoutes } from '../src/server.js';
|
||||
import { MemoryVaultStore } from '../src/store.js';
|
||||
import { HttpVaultTransport } from '../src/http-transport.js';
|
||||
import { VaultClient, deriveVaultKeys } from '../src/client.js';
|
||||
import { objectHash } from '../src/crypto.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);
|
||||
}
|
||||
|
||||
/** A client wired to a fresh in-memory relay. */
|
||||
async function harness(masterKey = new Uint8Array(32).fill(7), app = 'scaffold') {
|
||||
const store = new MemoryVaultStore();
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const transport = new HttpVaultTransport('http://vault.test', (input, init) =>
|
||||
routes.fetch(new Request(input, init)),
|
||||
);
|
||||
const keys = await deriveVaultKeys(masterKey, app);
|
||||
return { store, keys, client: new VaultClient(crypto, keys, transport) };
|
||||
}
|
||||
|
||||
describe('round trip', () => {
|
||||
test('files pushed can be pulled back byte-for-byte', async () => {
|
||||
const { client } = await harness();
|
||||
const files = [
|
||||
{ path: '.scaffold/plan.md', bytes: enc('# Plan\n\n## Nå\n- [ ] noe\n') },
|
||||
{ path: '.scaffold/tasks.yaml', bytes: enc('tasks: []\n') },
|
||||
];
|
||||
|
||||
const res = await client.push(files, AT, 'første backup');
|
||||
expect(res.seq).toBe(1);
|
||||
expect(res.uploaded).toBe(2);
|
||||
|
||||
const { manifest, files: back } = await client.pull();
|
||||
expect(manifest.seq).toBe(1);
|
||||
expect(manifest.message).toBe('første backup');
|
||||
expect(dec(back.get('.scaffold/plan.md')!)).toBe('# Plan\n\n## Nå\n- [ ] noe\n');
|
||||
expect(dec(back.get('.scaffold/tasks.yaml')!)).toBe('tasks: []\n');
|
||||
});
|
||||
|
||||
test('a fresh device with only the credentials can restore', async () => {
|
||||
// The recovery story: same master key, nothing else carried over.
|
||||
const master = new Uint8Array(32).fill(11);
|
||||
const { client, store } = await harness(master);
|
||||
await client.push([{ path: 'notes.yaml', bytes: enc('notes: [en, to]\n') }], AT);
|
||||
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const transport = new HttpVaultTransport('http://vault.test', (i, init) =>
|
||||
routes.fetch(new Request(i, init)),
|
||||
);
|
||||
const keys = await deriveVaultKeys(master, 'scaffold');
|
||||
const fresh = new VaultClient(crypto, keys, transport);
|
||||
|
||||
const { files } = await fresh.pull();
|
||||
expect(dec(files.get('notes.yaml')!)).toBe('notes: [en, to]\n');
|
||||
});
|
||||
|
||||
test('a different master key cannot read the vault', async () => {
|
||||
const { store } = await harness(new Uint8Array(32).fill(1));
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const transport = new HttpVaultTransport('http://vault.test', (i, init) =>
|
||||
routes.fetch(new Request(i, init)),
|
||||
);
|
||||
const wrong = await deriveVaultKeys(new Uint8Array(32).fill(2), 'scaffold');
|
||||
const intruder = new VaultClient(crypto, wrong, transport);
|
||||
// A different master derives a different vaultId, so there is nothing
|
||||
// there to read in the first place — the id is itself a secret.
|
||||
await expect(intruder.pull()).rejects.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('versioning', () => {
|
||||
test('each push is a new version and old ones stay readable', async () => {
|
||||
const { client } = await harness();
|
||||
await client.push([{ path: 'plan.md', bytes: enc('versjon 1') }], AT);
|
||||
await client.push([{ path: 'plan.md', bytes: enc('versjon 2') }], AT + 1000);
|
||||
await client.push([{ path: 'plan.md', bytes: enc('versjon 3') }], AT + 2000);
|
||||
|
||||
const log = await client.history();
|
||||
expect(log.head).toBe(3);
|
||||
expect(log.entries.map((e) => e.seq)).toEqual([1, 2, 3]);
|
||||
|
||||
// Rollback: the whole point of keeping the log.
|
||||
expect(dec((await client.pull(1)).files.get('plan.md')!)).toBe('versjon 1');
|
||||
expect(dec((await client.pull(2)).files.get('plan.md')!)).toBe('versjon 2');
|
||||
expect(dec((await client.pull()).files.get('plan.md')!)).toBe('versjon 3');
|
||||
});
|
||||
|
||||
test('unchanged files are not re-uploaded', async () => {
|
||||
// The property that makes backing up a 9 MB workspace on every change
|
||||
// affordable: only what actually moved goes over the wire.
|
||||
const { client } = await harness();
|
||||
const stable = { path: 'stor-logg.md', bytes: enc('x'.repeat(50_000)) };
|
||||
|
||||
const first = await client.push([stable, { path: 'plan.md', bytes: enc('en') }], AT);
|
||||
expect(first.uploaded).toBe(2);
|
||||
|
||||
const second = await client.push([stable, { path: 'plan.md', bytes: enc('to') }], AT + 1);
|
||||
expect(second.uploaded).toBe(1);
|
||||
expect(second.reused).toBe(1);
|
||||
expect(second.bytesUploaded).toBeLessThan(1000);
|
||||
|
||||
// And the reused file is still intact in the new version.
|
||||
const { files } = await client.pull();
|
||||
expect(files.get('stor-logg.md')!.length).toBe(50_000);
|
||||
});
|
||||
|
||||
test('a deleted file is absent from the new version but present in the old', async () => {
|
||||
const { client } = await harness();
|
||||
await client.push(
|
||||
[
|
||||
{ path: 'a.md', bytes: enc('A') },
|
||||
{ path: 'b.md', bytes: enc('B') },
|
||||
],
|
||||
AT,
|
||||
);
|
||||
await client.push([{ path: 'a.md', bytes: enc('A') }], AT + 1);
|
||||
|
||||
expect((await client.pull()).files.has('b.md')).toBe(false);
|
||||
expect(dec((await client.pull(1)).files.get('b.md')!)).toBe('B');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the relay is blind', () => {
|
||||
test('stored objects contain no plaintext', async () => {
|
||||
const { client, store } = await harness();
|
||||
await client.push([{ path: 'hemmelig/plan.md', bytes: enc('SENSITIVT INNHOLD') }], AT);
|
||||
|
||||
const log = await store.log(client.vaultId);
|
||||
const manifestBytes = await store.getObject(client.vaultId, log[0]!.manifest);
|
||||
const asText = dec(manifestBytes!);
|
||||
// Neither the contents nor the path leaks: paths live inside the
|
||||
// encrypted manifest, not in object names.
|
||||
expect(asText).not.toContain('SENSITIVT');
|
||||
expect(asText).not.toContain('hemmelig');
|
||||
});
|
||||
|
||||
test('object names are the hash of the ciphertext, so the relay can verify', async () => {
|
||||
const { client, store } = await harness();
|
||||
await client.push([{ path: 'x', bytes: enc('hei') }], AT);
|
||||
const log = await store.log(client.vaultId);
|
||||
const bytes = await store.getObject(client.vaultId, log[0]!.manifest);
|
||||
expect(objectHash(bytes!)).toBe(log[0]!.manifest);
|
||||
});
|
||||
|
||||
test('an object whose bytes do not match its name is rejected', async () => {
|
||||
const store = new MemoryVaultStore();
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const keys = await deriveVaultKeys(new Uint8Array(32).fill(3), 'scaffold');
|
||||
const { signPayload } = await import('@shade/server');
|
||||
const { toBase64 } = await import('@shade/core');
|
||||
|
||||
const body = await signPayload(crypto, keys.signingSeed, {
|
||||
data: toBase64(enc('juks')),
|
||||
publicKey: toBase64(keys.publicKey),
|
||||
});
|
||||
const res = await routes.fetch(
|
||||
new Request(`http://v/v1/vault/${keys.vaultId}/object/${'0'.repeat(64)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect((await res.json()).error.code).toBe('BAD_REQUEST');
|
||||
});
|
||||
});
|
||||
|
||||
describe('concurrent writers', () => {
|
||||
test('a commit from a stale head is refused', async () => {
|
||||
// Two devices push from the same version. The second must not be able to
|
||||
// overwrite a sequence number that is already history.
|
||||
const { client, keys, store } = await harness();
|
||||
await client.push([{ path: 'plan.md', bytes: enc('en')}], AT);
|
||||
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const { signPayload } = await import('@shade/server');
|
||||
const { toBase64 } = await import('@shade/core');
|
||||
const log = await store.log(keys.vaultId);
|
||||
const body = await signPayload(crypto, keys.signingSeed, {
|
||||
manifest: log[0]!.manifest,
|
||||
seq: 1, // already taken
|
||||
at: AT,
|
||||
hashes: [],
|
||||
publicKey: toBase64(keys.publicKey),
|
||||
});
|
||||
|
||||
const res = await routes.fetch(
|
||||
new Request(`http://v/v1/vault/${keys.vaultId}/commit`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(409);
|
||||
const err = await res.json();
|
||||
expect(err.error.code).toBe('SEQ_CONFLICT');
|
||||
expect(err.head).toBe(1);
|
||||
});
|
||||
|
||||
test('a commit referencing a missing object is refused', async () => {
|
||||
// Otherwise the log would publish a version that cannot be restored.
|
||||
const { client, keys, store } = await harness();
|
||||
await client.push([{ path: 'plan.md', bytes: enc('en') }], AT);
|
||||
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const { signPayload } = await import('@shade/server');
|
||||
const { toBase64 } = await import('@shade/core');
|
||||
const log = await store.log(keys.vaultId);
|
||||
const body = await signPayload(crypto, keys.signingSeed, {
|
||||
manifest: log[0]!.manifest,
|
||||
seq: 2,
|
||||
at: AT,
|
||||
hashes: ['a'.repeat(64)],
|
||||
publicKey: toBase64(keys.publicKey),
|
||||
});
|
||||
|
||||
const res = await routes.fetch(
|
||||
new Request(`http://v/v1/vault/${keys.vaultId}/commit`, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(409);
|
||||
expect((await res.json()).error.code).toBe('MISSING_OBJECTS');
|
||||
});
|
||||
});
|
||||
|
||||
describe('authorisation', () => {
|
||||
test('a second key cannot write to a vault another key pinned', async () => {
|
||||
const { client, keys, store } = await harness();
|
||||
await client.push([{ path: 'plan.md', bytes: enc('mitt') }], AT);
|
||||
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const { signPayload } = await import('@shade/server');
|
||||
const { toBase64 } = await import('@shade/core');
|
||||
const attacker = await deriveVaultKeys(new Uint8Array(32).fill(9), 'scaffold');
|
||||
|
||||
// Signed correctly — but by the wrong key, and asserting its own pubkey.
|
||||
const body = await signPayload(crypto, attacker.signingSeed, {
|
||||
data: toBase64(enc('tull')),
|
||||
publicKey: toBase64(attacker.publicKey),
|
||||
});
|
||||
const res = await routes.fetch(
|
||||
new Request(
|
||||
`http://v/v1/vault/${keys.vaultId}/object/${objectHash(enc('tull'))}`,
|
||||
{
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
},
|
||||
),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
test('an unsigned write is refused', async () => {
|
||||
const store = new MemoryVaultStore();
|
||||
const routes = createVaultRoutes(store, crypto);
|
||||
const res = await routes.fetch(
|
||||
new Request(`http://v/v1/vault/${'a'.repeat(64)}/object/${'b'.repeat(64)}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ data: 'aGk=' }),
|
||||
}),
|
||||
);
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe('key derivation', () => {
|
||||
test('the same credentials derive the same vault, different ones do not', async () => {
|
||||
const a = await deriveVaultKeys(new Uint8Array(32).fill(4), 'scaffold');
|
||||
const b = await deriveVaultKeys(new Uint8Array(32).fill(4), 'scaffold');
|
||||
const c = await deriveVaultKeys(new Uint8Array(32).fill(5), 'scaffold');
|
||||
expect(a.vaultId).toBe(b.vaultId);
|
||||
expect(a.vaultId).not.toBe(c.vaultId);
|
||||
});
|
||||
|
||||
test('two apps under one master do not share a vault', async () => {
|
||||
const master = new Uint8Array(32).fill(6);
|
||||
const scaffold = await deriveVaultKeys(master, 'scaffold');
|
||||
const mail = await deriveVaultKeys(master, 'mail');
|
||||
expect(scaffold.vaultId).not.toBe(mail.vaultId);
|
||||
expect(scaffold.contentKey).not.toEqual(mail.contentKey);
|
||||
});
|
||||
|
||||
test('the vault branch is separate from the profile-blob branch', async () => {
|
||||
// A vault key reads every file; a profile-blob key reads a host list.
|
||||
// Sharing a derivation would make one compromise into the other.
|
||||
const master = new Uint8Array(32).fill(8);
|
||||
const { deriveBlobKey } = await import('@shade/storage-encrypted');
|
||||
const vault = await deriveVaultKeys(master, 'prism');
|
||||
expect(vault.contentKey).not.toEqual(deriveBlobKey(master, 'prism'));
|
||||
});
|
||||
});
|
||||
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);
|
||||
}
|
||||
});
|
||||
});
|
||||
5
packages/shade-vault/tsconfig.json
Normal file
5
packages/shade-vault/tsconfig.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"extends": "../../tsconfig.json",
|
||||
"compilerOptions": { "outDir": "dist", "rootDir": "src", "lib": ["ES2022", "DOM"] },
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@shade/widgets",
|
||||
"version": "4.11.1",
|
||||
"version": "4.14.1",
|
||||
"type": "module",
|
||||
"main": "src/index.ts",
|
||||
"types": "src/index.ts",
|
||||
|
||||
@@ -9,7 +9,9 @@
|
||||
* Bump `VECTOR_FILE_VERSION` whenever the vector schema (NOT just values)
|
||||
* changes, so downstream consumers can fail loudly on mismatch.
|
||||
*
|
||||
* Usage: bun run scripts/generate-vectors.ts
|
||||
* Usage: bun run scripts/generate-vectors.ts [file.json …]
|
||||
* With file names, only those are regenerated — so adding a vector file
|
||||
* does not churn the others.
|
||||
*/
|
||||
import { writeFileSync } from 'fs';
|
||||
import { join } from 'path';
|
||||
@@ -38,6 +40,18 @@ import {
|
||||
buildApprovalRequest,
|
||||
type ApprovalRequestFrame,
|
||||
} from '../packages/shade-sdk/src/index.js';
|
||||
import { deriveVaultKeys } from '../packages/shade-vault/src/client.js';
|
||||
import {
|
||||
encodeManifest,
|
||||
entryObjectHashes,
|
||||
vaultObjectAad,
|
||||
} from '../packages/shade-vault/src/crypto.js';
|
||||
import {
|
||||
sealEntryWithNonces,
|
||||
sealObjectWithNonce,
|
||||
} from '../packages/shade-vault/src/testing.js';
|
||||
import type { VaultEntry, VaultManifest } from '../packages/shade-vault/src/types.js';
|
||||
import { canonicalizePayload } from '../packages/shade-server/src/auth.js';
|
||||
|
||||
const VECTOR_FILE_VERSION = 2;
|
||||
|
||||
@@ -821,6 +835,146 @@ async function generateApprovalVectors(): Promise<Vector[]> {
|
||||
return [...payloads, e2e];
|
||||
}
|
||||
|
||||
async function generateVaultV2Vectors(): Promise<Vector[]> {
|
||||
// One vault, derived from a pinned master, used by every vector below —
|
||||
// so a port checks its key derivation once and then the formats on top.
|
||||
const masterKey = new Uint8Array(32).map((_, i) => i + 1);
|
||||
const app = 'scaffold';
|
||||
const keys = await deriveVaultKeys(masterKey, app);
|
||||
const te = new TextEncoder();
|
||||
|
||||
const vectors: Vector[] = [
|
||||
{
|
||||
description:
|
||||
'vault-v2 keys: vaultId/contentKey/signingSeed = HKDF branches of masterKey for app; publicKey = Ed25519(signingSeed)',
|
||||
masterKey: hex(masterKey),
|
||||
app,
|
||||
vaultId: keys.vaultId,
|
||||
contentKey: hex(keys.contentKey),
|
||||
signingSeed: hex(keys.signingSeed),
|
||||
publicKey: hex(keys.publicKey),
|
||||
objectAad: hex(vaultObjectAad(keys.vaultId)),
|
||||
objectAadUtf8: `shade-vault-object-v1|${keys.vaultId}`,
|
||||
},
|
||||
];
|
||||
|
||||
// Entries. `stored` is pinned so a writer can be checked byte for byte
|
||||
// (zlib default level, raw deflate); a reader must only need `wire`.
|
||||
const pngLike = new Uint8Array(48);
|
||||
pngLike.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
const entryCases: Array<{ name: string; path: string; plaintext: Uint8Array; chunkSize?: number; mode?: string }> = [
|
||||
{
|
||||
name: 'small text, compressed, one part',
|
||||
path: '.scaffold/plan.md',
|
||||
plaintext: te.encode('# Plan\n\n## Nå\n- [ ] noe\n- [ ] noe\n- [ ] noe\n- [ ] noe annet\n'.repeat(4)),
|
||||
},
|
||||
{
|
||||
name: 'multi-part (chunkSize 32), compressed — concatenate parts, then inflate',
|
||||
path: 'logs/2026-10-16.md',
|
||||
plaintext: te.encode(
|
||||
Array.from({ length: 40 }, (_, i) => `linje ${i}: ${(i * 7919) % 1000}\n`).join(''),
|
||||
),
|
||||
chunkSize: 32,
|
||||
mode: '644',
|
||||
},
|
||||
{
|
||||
name: 'PNG magic, never compressed, one part',
|
||||
path: 'bilde.png',
|
||||
plaintext: pngLike,
|
||||
},
|
||||
];
|
||||
|
||||
const committedHashes: string[] = [];
|
||||
const manifestEntries: VaultEntry[] = [];
|
||||
for (const [n, c] of entryCases.entries()) {
|
||||
const sealed = await sealEntryWithNonces(
|
||||
keys.contentKey,
|
||||
keys.vaultId,
|
||||
c.plaintext,
|
||||
(part) => new Uint8Array(12).map((_, i) => (n + 1) * 0x10 + part + i),
|
||||
c.chunkSize === undefined ? {} : { chunkSize: c.chunkSize },
|
||||
);
|
||||
const entry: VaultEntry = { path: c.path, ...sealed.locator, size: c.plaintext.length };
|
||||
if (c.mode !== undefined) entry.mode = c.mode;
|
||||
manifestEntries.push(entry);
|
||||
committedHashes.push(...entryObjectHashes(entry));
|
||||
vectors.push({
|
||||
description: `vault-v2 entry: ${c.name}`,
|
||||
chunkSize: c.chunkSize ?? 4 * 1024 * 1024,
|
||||
plaintext: hex(c.plaintext),
|
||||
stored: hex(sealed.packed.stored),
|
||||
enc: sealed.packed.enc ?? null,
|
||||
parts: sealed.objects.map((o, i) => ({
|
||||
nonce: hex(o.bytes.subarray(0, 12)),
|
||||
plaintext: hex(sealed.packed.chunks[i]!),
|
||||
wire: hex(o.bytes),
|
||||
hash: o.hash,
|
||||
})),
|
||||
entry,
|
||||
});
|
||||
}
|
||||
|
||||
// Manifests: v2 (what push writes) and v1 (what old vaults hold).
|
||||
const v2: VaultManifest = { version: 2, seq: 7, at: 1_786_600_000_000, entries: manifestEntries, message: 'nattlig backup' };
|
||||
const v1: VaultManifest = {
|
||||
version: 1,
|
||||
seq: 1,
|
||||
at: 1_786_500_000_000,
|
||||
entries: [{ path: 'notes.yaml', hash: manifestEntries[2]!.hash, size: 48 }],
|
||||
};
|
||||
let manifestHash = '';
|
||||
for (const [m, nonceByte] of [[v2, 0xc0], [v1, 0xd0]] as const) {
|
||||
const plain = await encodeManifest(m);
|
||||
const sealed = await sealObjectWithNonce(keys.contentKey, keys.vaultId, plain, new Uint8Array(12).fill(nonceByte));
|
||||
if (m.version === 2) manifestHash = sealed.hash;
|
||||
vectors.push({
|
||||
description:
|
||||
m.version === 2
|
||||
? 'vault-v2 manifest v2: plaintext = "SVM2" || deflate-raw(json utf-8)'
|
||||
: 'vault-v2 manifest v1: plaintext = json utf-8 (back-compat, still readable)',
|
||||
manifest: m,
|
||||
json: JSON.stringify(m),
|
||||
plaintext: hex(plain),
|
||||
nonce: hex(sealed.bytes.subarray(0, 12)),
|
||||
wire: hex(sealed.bytes),
|
||||
hash: sealed.hash,
|
||||
});
|
||||
}
|
||||
|
||||
// Signed request bodies. Canonical form: every field except `signature`,
|
||||
// top-level keys sorted, JSON.stringify — the same function the relay
|
||||
// verifies with. Nested arrays keep their order.
|
||||
const signed: Array<[string, Record<string, unknown>]> = [
|
||||
[
|
||||
'commit',
|
||||
{
|
||||
manifest: manifestHash,
|
||||
seq: 7,
|
||||
at: 1_786_600_000_000,
|
||||
hashes: [...new Set(committedHashes)],
|
||||
publicKey: Buffer.from(keys.publicKey).toString('base64'),
|
||||
},
|
||||
],
|
||||
['prune', { keep: [5, 7], publicKey: Buffer.from(keys.publicKey).toString('base64') }],
|
||||
];
|
||||
for (const [what, body] of signed) {
|
||||
const signedAt = 1_786_600_000_123;
|
||||
const canonical = canonicalizePayload({ ...body, signedAt, signature: '' });
|
||||
const sig = await crypto.sign(keys.signingSeed, canonical);
|
||||
vectors.push({
|
||||
description: `vault-v2 signed ${what}: signature = Ed25519(signingSeed, canonical); wire body = fields + signedAt + signature(base64)`,
|
||||
body,
|
||||
signedAt,
|
||||
canonical: new TextDecoder().decode(canonical),
|
||||
canonicalHex: hex(canonical),
|
||||
signature: hex(sig),
|
||||
signatureBase64: Buffer.from(sig).toString('base64'),
|
||||
});
|
||||
}
|
||||
|
||||
return vectors;
|
||||
}
|
||||
|
||||
async function main() {
|
||||
console.log('Generating cross-platform test vectors…');
|
||||
|
||||
@@ -837,9 +991,12 @@ async function main() {
|
||||
['storage-hkdf.json', { vectors: await generateStorageEncryptionSubset() }],
|
||||
['blob.json', { vectors: await generateBlobVectors() }],
|
||||
['approval.json', { vectors: await generateApprovalVectors() }],
|
||||
['vault-v2.json', { vectors: await generateVaultV2Vectors() }],
|
||||
];
|
||||
|
||||
const only = new Set(process.argv.slice(2));
|
||||
for (const [name, data] of files) {
|
||||
if (only.size > 0 && !only.has(name)) continue;
|
||||
const path = join(OUT_DIR, name);
|
||||
const versioned = { version: VECTOR_FILE_VERSION, ...data };
|
||||
writeFileSync(path, JSON.stringify(versioned, null, 2) + '\n');
|
||||
|
||||
@@ -38,6 +38,7 @@ const PACKAGES = [
|
||||
'shade-transport-webrtc',
|
||||
'shade-server',
|
||||
'shade-inbox-server',
|
||||
'shade-vault',
|
||||
'shade-inbox',
|
||||
'shade-transfer',
|
||||
'shade-files',
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user