Compare commits
21 Commits
v4.11.0
...
fb7f2e55c0
| Author | SHA1 | Date | |
|---|---|---|---|
| fb7f2e55c0 | |||
| a1c370359e | |||
| b82a803e0c | |||
| bcae7b346e | |||
| 5d04e18482 | |||
| f6e4ac8aeb | |||
| baddf5f56e | |||
| 53ce776c02 | |||
| 3c69995097 | |||
| 9789b6fc16 | |||
| 40286a8542 | |||
| cc6b1d53d7 | |||
| d8f6da55ef | |||
| 3da977207c | |||
| 84d3166ca1 | |||
| 012d7f5289 | |||
| 96c20cb4b2 | |||
| b44acf867b | |||
| 8c67a00f37 | |||
| 306bf08452 | |||
| 3243647aa1 |
@@ -28,6 +28,13 @@ jobs:
|
|||||||
- name: Install dependencies
|
- name: Install dependencies
|
||||||
run: ~/.bun/bin/bun install --frozen-lockfile
|
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
|
- name: Run tests
|
||||||
env:
|
env:
|
||||||
SHADE_TEST_PG_URL: postgres://postgres:test@localhost:5432/postgres
|
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
|
||||||
**/.tmp-*.db-shm
|
**/.tmp-*.db-shm
|
||||||
**/.tmp-*.db-wal
|
**/.tmp-*.db-wal
|
||||||
|
|
||||||
|
# Byggeartefakt fra @shade/observer (outDir-avviket i G0)
|
||||||
|
dist-build/
|
||||||
|
|||||||
24
.scaffold/log.md
Normal file
24
.scaffold/log.md
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
# 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.
|
||||||
|
|
||||||
|
## 2026-05-15 — v4.11: streaming Double-Ratchet sub-sessions
|
||||||
|
Siste post-GA-økning på 4.x-linjen: `ShadeStream` gir in-memory sub-sessions (seal/open uten keystore-I/O per frame) med nye wire-typer 0x31–0x33. Låst beslutning: stream-ratchets persisteres aldri — en droppet stream gjenåpnes, aldri gjenopptas.
|
||||||
|
|
||||||
|
## 2026-05-09 — Android M-Cross 1–4 fullført + Keystore-adapter
|
||||||
|
All kryptografisk paritet TS↔Kotlin grønn via delte test-vektorer: KDF-kjede, HKDF-labels, X3DH, ratchet-steg, fingerprint, wire 0x02 og 0x11 (streams), backup-HKDF, group sender-keys og storage-HKDF. Etterslepet fra Android-roadmapen landet samme dag: scrypt + argon2id via Bouncy Castle og `shade-android-keystore`-modulen (hardware-backed master key + `KeystoreStorage`). Gjenstår: socket-interop-test og instrumenterte Keystore-tester.
|
||||||
|
|
||||||
|
## 2026-05-03 — V4.0 GA: V3.x-konsolidering og audit-pakking
|
||||||
|
Alle fasene V3.1–V3.12 ferdige og merget: dokumentasjon/hardening, at-rest storage-kryptering, trust-UX, observability (OTel), Android-paritet, inbox (store-and-forward), transport-bridge, web workers-krypto, filmetadata, social key recovery, WebRTC P2P og key transparency. Wire-formatet låst — uendret fra 0.4.x, så 4.0-peers interopererer byte-for-byte med 0.4.x. Kjernen pakket for ekstern review. Låst beslutning: alt VOIP/video skilt ut til V5.0, bygget oppå den frosne 4.0-stacken via reserverte envelope-typer (ikke breaking).
|
||||||
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`.
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
title: "Vault v2 og Kotlin-vaulten (4.14.0/4.14.1)"
|
||||||
|
date: 2026-10-16
|
||||||
|
author: "Claude"
|
||||||
|
---
|
||||||
|
|
||||||
|
Shade fikk det Scaffold-vaulten trengte for å bli telefonens kilde når PC-en er av, uten at serveren fylles opp.
|
||||||
|
|
||||||
|
- **4.14.0 — vault v2:**
|
||||||
|
- Filer komprimeres med deflate-raw når det lønner seg, og deles i forseglede biter på 4 MiB. Manifestene komprimeres også (`SVM2`).
|
||||||
|
- Push bruker en lokal indeks og laster ikke ned forrige versjon. En push uten endringer committer ingenting.
|
||||||
|
- Ny lat lesing med `manifest` og `readEntry`.
|
||||||
|
- Relayet registrerer hvilke objekter hver versjon refererer til, og har fått en signert `prune`-rute. SQLite-lageret migrerer seg selv.
|
||||||
|
- Kryss-språk-vektorene ligger i `test-vectors/vault-v2.json`.
|
||||||
|
- **4.14.1 — `edit`:** endrer noen få filer mot hodet som faktisk ble lest, og prøver igjen ved `SEQ_CONFLICT`. Dette er det en kø med to skrivere trenger. `push` publiserer hele samlingen, og ville mistet en fil som en annen enhet la til i mellomtiden.
|
||||||
|
- **Kotlin, `no.zyon.shade.vault`:** en full port av v2 (lese, forsegle, signere, `edit`).
|
||||||
|
- 71 Android-tester er grønne.
|
||||||
|
- Live kryss-sjekk TS↔Kotlin mot ekte vault-ruter (`scripts/vault-live-kotlin.ts`).
|
||||||
|
|
||||||
|
Verifisert: shade-vault 61, storage-sqlite 47 og shade-server 55 grønne, og typecheck er ren for alle 26 pakkene. Publisert til Gitea-registeret. Commitet lokalt og tagget (`v4.14.0`, `v4.14.1`), men ikke pushet til remote. Kotlin-filene i `android/` er ennå ikke commitet.
|
||||||
64
.scaffold/plan.md
Normal file
64
.scaffold/plan.md
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
---
|
||||||
|
project: "Shade"
|
||||||
|
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
|
||||||
|
|
||||||
|
## 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/`.
|
||||||
|
- 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å
|
||||||
|
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
|
||||||
|
- **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
|
||||||
|
- **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.
|
||||||
328
.scaffold/tasks.yaml
Normal file
328
.scaffold/tasks.yaml
Normal file
@@ -0,0 +1,328 @@
|
|||||||
|
# Scaffold kanban-kort. Skjema per kort:
|
||||||
|
# - id: kort-slug # unik i fila
|
||||||
|
# title: ""
|
||||||
|
# description: ""
|
||||||
|
# status: todo # todo | doing | done | blocked
|
||||||
|
# column: todo # speiler status (kanban-kolonne)
|
||||||
|
# priority: medium # low | medium | high
|
||||||
|
# assignee: human # cursor | claude | human | any
|
||||||
|
# context: "" # valgfri: hvorfor/hvor i koden
|
||||||
|
# acceptance: "" # valgfri: hva «ferdig» betyr
|
||||||
|
# todos:
|
||||||
|
# - text: "Underoppgave"
|
||||||
|
# done: false
|
||||||
|
# created: 2026-07-09
|
||||||
|
# updated: 2026-07-09
|
||||||
|
# completed_at: null
|
||||||
|
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
|
||||||
100
CHANGELOG.md
100
CHANGELOG.md
@@ -5,6 +5,106 @@ All notable changes to Shade are documented in this file.
|
|||||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [4.14.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`**
|
||||||
|
|
||||||
|
- Fix a construction race in HTTP pull-mode clients: an immediate streamed
|
||||||
|
read/write now awaits asynchronous stream-bridge registration instead of
|
||||||
|
treating the not-yet-created queue drainer as proof that the client is
|
||||||
|
inline-only.
|
||||||
|
- Add a deterministic integration test that holds incoming-transfer
|
||||||
|
registration, starts a 512 KiB write immediately, and verifies that it
|
||||||
|
remains pending until streaming is ready.
|
||||||
|
- Add `publish-all.ts --only <pkg>` so isolated package hotfixes do not publish
|
||||||
|
unrelated workspace packages.
|
||||||
|
|
||||||
## [4.11.0] — 2026-05-15 — Streaming Double-Ratchet sub-sessions
|
## [4.11.0] — 2026-05-15 — Streaming Double-Ratchet sub-sessions
|
||||||
|
|
||||||
Answers Vyvern FR `shade-ws-streaming-ratchet.md` (the last Phase-2
|
Answers Vyvern FR `shade-ws-streaming-ratchet.md` (the last Phase-2
|
||||||
|
|||||||
4
CLAUDE.md
Normal file
4
CLAUDE.md
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
## Planlegging
|
||||||
|
Planen for dette prosjektet bor i `.scaffold/`: `plan.md` er nåbildet (hold den kort,
|
||||||
|
bump `updated` i frontmatter ved endring), `log.md` er append-only historikk (nyeste øverst),
|
||||||
|
`tasks.yaml` er kanban. Ikke opprett planfiler andre steder.
|
||||||
@@ -49,6 +49,9 @@ dependencies {
|
|||||||
|
|
||||||
tasks.withType<Test>().configureEach {
|
tasks.withType<Test>().configureEach {
|
||||||
useJUnit()
|
useJUnit()
|
||||||
|
// VaultLiveTest is gated on this; as an input, a new spec (a new live
|
||||||
|
// relay) reruns the tests instead of reporting a stale UP-TO-DATE.
|
||||||
|
inputs.property("shadeVaultLiveSpec", System.getenv("SHADE_VAULT_LIVE_SPEC") ?: "")
|
||||||
testLogging {
|
testLogging {
|
||||||
events("passed", "failed", "skipped")
|
events("passed", "failed", "skipped")
|
||||||
showStandardStreams = false
|
showStandardStreams = false
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
package no.zyon.shade.blob
|
package no.zyon.shade.blob
|
||||||
|
|
||||||
import no.zyon.shade.crypto.CryptoProvider
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import no.zyon.shade.serialization.canonicalJson
|
||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import java.net.URI
|
import java.net.URI
|
||||||
import java.net.http.HttpClient
|
import java.net.http.HttpClient
|
||||||
@@ -187,62 +188,6 @@ class BlobClient(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Mirror of TS `signPayload`'s canonicalization: sorted keys, compact
|
|
||||||
* JSON, signature field absent. Only handles the subset of types we
|
|
||||||
* need (strings + longs + base64 strings) — keeping the implementation
|
|
||||||
* narrow so it can't accidentally diverge from `JSON.stringify` on
|
|
||||||
* structurally-different inputs.
|
|
||||||
*/
|
|
||||||
internal fun canonicalJson(map: Map<String, Any>): String {
|
|
||||||
val sb = StringBuilder()
|
|
||||||
sb.append('{')
|
|
||||||
var first = true
|
|
||||||
for ((key, value) in map.toSortedMap()) {
|
|
||||||
if (!first) sb.append(',')
|
|
||||||
first = false
|
|
||||||
appendJsonString(sb, key)
|
|
||||||
sb.append(':')
|
|
||||||
appendJsonValue(sb, value)
|
|
||||||
}
|
|
||||||
sb.append('}')
|
|
||||||
return sb.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun appendJsonValue(sb: StringBuilder, value: Any) {
|
|
||||||
when (value) {
|
|
||||||
is String -> appendJsonString(sb, value)
|
|
||||||
is Long, is Int -> sb.append(value.toString())
|
|
||||||
is Boolean -> sb.append(value.toString())
|
|
||||||
else -> throw IllegalArgumentException(
|
|
||||||
"canonicalJson: unsupported value type ${value::class.java}",
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private fun appendJsonString(sb: StringBuilder, s: String) {
|
|
||||||
sb.append('"')
|
|
||||||
for (c in s) {
|
|
||||||
when (c) {
|
|
||||||
'\\' -> sb.append("\\\\")
|
|
||||||
'"' -> sb.append("\\\"")
|
|
||||||
'\b' -> sb.append("\\b")
|
|
||||||
'\u000C' -> sb.append("\\f")
|
|
||||||
'\n' -> sb.append("\\n")
|
|
||||||
'\r' -> sb.append("\\r")
|
|
||||||
'\t' -> sb.append("\\t")
|
|
||||||
else -> {
|
|
||||||
if (c.code < 0x20) {
|
|
||||||
sb.append("\\u").append("%04x".format(c.code))
|
|
||||||
} else {
|
|
||||||
sb.append(c)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
sb.append('"')
|
|
||||||
}
|
|
||||||
|
|
||||||
class BlobClientException(
|
class BlobClientException(
|
||||||
val code: String,
|
val code: String,
|
||||||
val statusCode: Int,
|
val statusCode: Int,
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
package no.zyon.shade.blob
|
package no.zyon.shade.blob
|
||||||
|
|
||||||
import com.google.crypto.tink.subtle.Ed25519Sign
|
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
|
||||||
import no.zyon.shade.crypto.CryptoProvider
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -72,13 +72,20 @@ fun deriveBlobSigningSeed(crypto: CryptoProvider, masterKey: ByteArray, app: Str
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Recover the Ed25519 public key from a 32-byte seed. Mirrors
|
* Recover the Ed25519 public key from a 32-byte seed. Mirrors
|
||||||
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`. Tink's
|
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`.
|
||||||
* `Ed25519Sign.KeyPair.newKeyPairFromSeed(seed)` exposes both halves;
|
*
|
||||||
* we discard the private half here.
|
* BouncyCastle rather than Tink, although the rest of the module signs with
|
||||||
|
* Tink: this is the one primitive the vault and blob code use OUTSIDE the
|
||||||
|
* injected [CryptoProvider], so whatever it calls is a hard dependency of
|
||||||
|
* every app that reads a vault. An Android app cannot take JVM Tink (it
|
||||||
|
* drags in full `protobuf-java`, which collides with Firebase's
|
||||||
|
* `protobuf-javalite`), while BouncyCastle is already here for scrypt and
|
||||||
|
* already in every app that embeds this module. RFC 8032 fixes the result,
|
||||||
|
* so the two produce the same bytes — the blob and vault vectors pin it.
|
||||||
*/
|
*/
|
||||||
fun ed25519PublicKeyFromSeed(seed: ByteArray): ByteArray {
|
fun ed25519PublicKeyFromSeed(seed: ByteArray): ByteArray {
|
||||||
require(seed.size == 32) { "Ed25519 seed must be 32 bytes" }
|
require(seed.size == 32) { "Ed25519 seed must be 32 bytes" }
|
||||||
return Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey
|
return Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */
|
/** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package no.zyon.shade.serialization
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSON written exactly the way JavaScript's `JSON.stringify` writes it —
|
||||||
|
* because signatures are computed over these bytes, and a TS relay verifies
|
||||||
|
* them over *its* re-serialisation of the parsed body.
|
||||||
|
*
|
||||||
|
* Two entry points:
|
||||||
|
*
|
||||||
|
* - [canonicalJson]: mirror of TS `canonicalizePayload` (`@shade/server`).
|
||||||
|
* Top-level keys sorted, nested values serialised as-is — `JSON.stringify`
|
||||||
|
* of an object built by inserting the sorted keys, so a nested object keeps
|
||||||
|
* its insertion order and is NOT sorted. The vault's signed bodies carry an
|
||||||
|
* array of hashes and an array of seqs, which is why arrays are supported.
|
||||||
|
* - [stringifyJson]: plain `JSON.stringify` of a value, insertion order kept.
|
||||||
|
* Used where key order is not part of any contract but reproducing the TS
|
||||||
|
* bytes keeps vector tests exact (vault manifests).
|
||||||
|
*
|
||||||
|
* Deliberately narrow: strings, integers, booleans, null, lists and string-
|
||||||
|
* keyed maps. Floating-point numbers are refused rather than formatted —
|
||||||
|
* JavaScript's shortest-round-trip number printing is not something to
|
||||||
|
* approximate in a signature path, and no Shade payload needs it.
|
||||||
|
*/
|
||||||
|
internal fun canonicalJson(map: Map<String, Any>): String {
|
||||||
|
val sb = StringBuilder()
|
||||||
|
sb.append('{')
|
||||||
|
var first = true
|
||||||
|
for ((key, value) in map.toSortedMap()) {
|
||||||
|
if (!first) sb.append(',')
|
||||||
|
first = false
|
||||||
|
appendJsonString(sb, key)
|
||||||
|
sb.append(':')
|
||||||
|
appendJsonValue(sb, value)
|
||||||
|
}
|
||||||
|
sb.append('}')
|
||||||
|
return sb.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `JSON.stringify(value)` — maps keep their iteration (insertion) order. */
|
||||||
|
internal fun stringifyJson(value: Any?): String {
|
||||||
|
val sb = StringBuilder()
|
||||||
|
appendJsonValue(sb, value)
|
||||||
|
return sb.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun appendJsonValue(sb: StringBuilder, value: Any?) {
|
||||||
|
when (value) {
|
||||||
|
null -> sb.append("null")
|
||||||
|
is String -> appendJsonString(sb, value)
|
||||||
|
is Long, is Int, is Short, is Byte -> sb.append(value.toString())
|
||||||
|
is Boolean -> sb.append(value.toString())
|
||||||
|
is Map<*, *> -> {
|
||||||
|
sb.append('{')
|
||||||
|
var first = true
|
||||||
|
for ((k, v) in value) {
|
||||||
|
require(k is String) { "stringifyJson: map keys must be strings, got ${k?.javaClass}" }
|
||||||
|
if (!first) sb.append(',')
|
||||||
|
first = false
|
||||||
|
appendJsonString(sb, k)
|
||||||
|
sb.append(':')
|
||||||
|
appendJsonValue(sb, v)
|
||||||
|
}
|
||||||
|
sb.append('}')
|
||||||
|
}
|
||||||
|
is Iterable<*> -> {
|
||||||
|
sb.append('[')
|
||||||
|
var first = true
|
||||||
|
for (v in value) {
|
||||||
|
if (!first) sb.append(',')
|
||||||
|
first = false
|
||||||
|
appendJsonValue(sb, v)
|
||||||
|
}
|
||||||
|
sb.append(']')
|
||||||
|
}
|
||||||
|
is Array<*> -> appendJsonValue(sb, value.asList())
|
||||||
|
else -> throw IllegalArgumentException(
|
||||||
|
"canonicalJson: unsupported value type ${value::class.java}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `JSON.stringify` string escaping (ES2019 "well-formed"): the two-character
|
||||||
|
* escapes for `" \ \b \f \n \r \t`, `\u00XX` (lowercase) for other control
|
||||||
|
* characters and for lone surrogates, everything else — including non-ASCII
|
||||||
|
* — emitted literally and left to UTF-8.
|
||||||
|
*/
|
||||||
|
private fun appendJsonString(sb: StringBuilder, s: String) {
|
||||||
|
sb.append('"')
|
||||||
|
var i = 0
|
||||||
|
while (i < s.length) {
|
||||||
|
val c = s[i]
|
||||||
|
when {
|
||||||
|
c == '\\' -> sb.append("\\\\")
|
||||||
|
c == '"' -> sb.append("\\\"")
|
||||||
|
c == '\b' -> sb.append("\\b")
|
||||||
|
c == '\u000C' -> sb.append("\\f")
|
||||||
|
c == '\n' -> sb.append("\\n")
|
||||||
|
c == '\r' -> sb.append("\\r")
|
||||||
|
c == '\t' -> sb.append("\\t")
|
||||||
|
c.code < 0x20 -> sb.append("\\u").append("%04x".format(c.code))
|
||||||
|
c.isHighSurrogate() && i + 1 < s.length && s[i + 1].isLowSurrogate() -> {
|
||||||
|
sb.append(c).append(s[i + 1])
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
c.isSurrogate() -> sb.append("\\u").append("%04x".format(c.code))
|
||||||
|
else -> sb.append(c)
|
||||||
|
}
|
||||||
|
i++
|
||||||
|
}
|
||||||
|
sb.append('"')
|
||||||
|
}
|
||||||
@@ -0,0 +1,223 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.util.Base64
|
||||||
|
|
||||||
|
/** A file as the app sees it, before encryption. */
|
||||||
|
class VaultFile(val path: String, val bytes: ByteArray, val mode: String? = null)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A few files changed, for [VaultClient.edit] — mirror of TS `VaultEdit`.
|
||||||
|
*/
|
||||||
|
class VaultEdit(
|
||||||
|
/** Files to add, or to replace at the same path. Paths must be distinct. */
|
||||||
|
val put: List<VaultFile> = emptyList(),
|
||||||
|
/** Paths to drop. A path that is not there is ignored. */
|
||||||
|
val remove: List<String> = emptyList(),
|
||||||
|
)
|
||||||
|
|
||||||
|
/** What [VaultClient.edit] did. */
|
||||||
|
data class VaultEditResult(
|
||||||
|
/** The head after the edit: the new version, or the unchanged head. */
|
||||||
|
val seq: Long,
|
||||||
|
/** False when the edit changed nothing and no version was committed. */
|
||||||
|
val committed: Boolean,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** A whole version, decrypted. */
|
||||||
|
class VaultPull(val manifest: VaultManifest, val files: Map<String, ByteArray>)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The client half of `@shade/vault` v2 for a phone: read a vault whose writer
|
||||||
|
* (the PC) may be switched off, and edit a vault several devices write to —
|
||||||
|
* such as a queue of changes the phone appends to and the PC drains.
|
||||||
|
*
|
||||||
|
* What it deliberately does not port is TS `push` (publish a whole
|
||||||
|
* collection from local files, with an index): a phone is not the source of
|
||||||
|
* truth for a workspace, and a whole-collection push from a stale view is
|
||||||
|
* exactly how another device's latest file gets lost. [edit] is the write
|
||||||
|
* primitive here.
|
||||||
|
*
|
||||||
|
* Blocking, like the transport: call from a background dispatcher.
|
||||||
|
*
|
||||||
|
* @param clock wall clock for `signedAt` — the relay rejects signatures older
|
||||||
|
* than five minutes, so this must be real time outside tests.
|
||||||
|
* @param chunkSize part size; tests only. Real writers use [VAULT_CHUNK_SIZE]
|
||||||
|
* so every implementation splits identically.
|
||||||
|
*/
|
||||||
|
class VaultClient(
|
||||||
|
private val crypto: CryptoProvider,
|
||||||
|
private val keys: VaultKeys,
|
||||||
|
private val transport: VaultTransport,
|
||||||
|
private val chunkSize: Int = VAULT_CHUNK_SIZE,
|
||||||
|
private val clock: () -> Long = System::currentTimeMillis,
|
||||||
|
) {
|
||||||
|
val vaultId: String get() = keys.vaultId
|
||||||
|
|
||||||
|
/** Version history, newest last. [limit] counts back from the head. */
|
||||||
|
fun log(limit: Int? = null): VaultLog = transport.log(keys.vaultId, limit)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch and open just a version's manifest; defaults to the head. The
|
||||||
|
* cheap way to list a thousand-file workspace: one download, then
|
||||||
|
* [readEntry] only what the user opens.
|
||||||
|
*
|
||||||
|
* @throws VaultException `NOT_FOUND` when there is no such version
|
||||||
|
* (including the head of an empty vault — see [headManifest]).
|
||||||
|
*/
|
||||||
|
fun manifest(seq: Long? = null): 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.
|
||||||
|
val log = transport.log(keys.vaultId, if (seq == null) 1 else null)
|
||||||
|
val wanted = seq ?: log.head
|
||||||
|
val row = log.entries.firstOrNull { it.seq == wanted }
|
||||||
|
?: throw VaultException(VaultException.CODE_NOT_FOUND, 0, "vault has no version $wanted")
|
||||||
|
return openRow(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The head manifest, or null when nothing has ever been committed. */
|
||||||
|
fun headManifest(): VaultManifest? {
|
||||||
|
val log = transport.log(keys.vaultId, 1)
|
||||||
|
val row = log.entries.firstOrNull { it.seq == log.head } ?: return null
|
||||||
|
return openRow(row)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetch, verify, decrypt and reassemble one file of a manifest. */
|
||||||
|
fun readEntry(entry: VaultEntry): ByteArray {
|
||||||
|
val objects = entryObjectHashes(entry).map { transport.get(keys.vaultId, it) }
|
||||||
|
return openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, objects)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Fetch a version and decrypt all of it; defaults to the head. */
|
||||||
|
fun pull(seq: Long? = null): VaultPull {
|
||||||
|
val manifest = manifest(seq)
|
||||||
|
val files = LinkedHashMap<String, ByteArray>()
|
||||||
|
for (entry in manifest.entries) files[entry.path] = readEntry(entry)
|
||||||
|
return VaultPull(manifest, files)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change a few files against the head that was actually read, and only it
|
||||||
|
* — mirror of TS `VaultClient.edit`.
|
||||||
|
*
|
||||||
|
* Reads the head, lets [change] decide from exactly that manifest (null
|
||||||
|
* for an empty vault), keeps every entry it did not touch as-is — same
|
||||||
|
* hash, same parts, never re-sealed — and commits `head + 1`. If another
|
||||||
|
* device committed in between, the relay answers SEQ_CONFLICT and this
|
||||||
|
* starts over from the new head, calling [change] again: it must be a
|
||||||
|
* pure decision about the manifest it is given.
|
||||||
|
*
|
||||||
|
* Returning null, or an edit with no puts that removes nothing present,
|
||||||
|
* commits nothing.
|
||||||
|
*
|
||||||
|
* One deliberate difference from TS: a file sealed in a lost attempt is
|
||||||
|
* not sealed again on the retry. Its objects are already on the relay
|
||||||
|
* (covered by the prune grace period), and on a phone the upload is the
|
||||||
|
* expensive part. The committed manifest is the same either way.
|
||||||
|
*
|
||||||
|
* @throws VaultException SEQ_CONFLICT after [maxAttempts] lost races, or
|
||||||
|
* any other relay refusal at once.
|
||||||
|
* @throws VaultFormatException when the head cannot be read — editing on
|
||||||
|
* top of a manifest this client cannot parse would drop its files.
|
||||||
|
*/
|
||||||
|
fun edit(at: Long, maxAttempts: Int = 5, change: (VaultManifest?) -> VaultEdit?): VaultEditResult {
|
||||||
|
val attempts = maxOf(1, maxAttempts)
|
||||||
|
// Plaintext digest + path → the entry its upload produced, across attempts.
|
||||||
|
val sealedThisEdit = HashMap<String, VaultEntry>()
|
||||||
|
var attempt = 1
|
||||||
|
while (true) {
|
||||||
|
val log = transport.log(keys.vaultId, 1)
|
||||||
|
val head = log.head
|
||||||
|
val row = log.entries.firstOrNull { it.seq == head }
|
||||||
|
val manifest = row?.let { openRow(it) }
|
||||||
|
val edit = change(manifest)
|
||||||
|
val put = edit?.put.orEmpty()
|
||||||
|
val remove = edit?.remove.orEmpty().toSet()
|
||||||
|
val current = manifest?.entries.orEmpty()
|
||||||
|
val replaced = put.map { it.path }.toSet()
|
||||||
|
require(replaced.size == put.size) { "VaultEdit.put lists the same path more than once" }
|
||||||
|
if (put.isEmpty() && current.none { it.path in remove }) {
|
||||||
|
return VaultEditResult(seq = head, committed = false)
|
||||||
|
}
|
||||||
|
|
||||||
|
val entries = current.filterTo(ArrayList()) { it.path !in remove && it.path !in replaced }
|
||||||
|
for (file in put) {
|
||||||
|
val key = sha256Hex(file.bytes) + "\u0000" + file.path
|
||||||
|
val located = sealedThisEdit.getOrPut(key) { upload(file) }
|
||||||
|
entries.add(located.copy(mode = file.mode))
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
val seq = commitManifest(entries, head + 1, at)
|
||||||
|
return VaultEditResult(seq = seq, committed = true)
|
||||||
|
} catch (e: VaultException) {
|
||||||
|
// Only a lost race is worth another go; the manifest object
|
||||||
|
// just uploaded is an orphan the relay's GC will collect.
|
||||||
|
if (attempt >= attempts || !e.isSeqConflict) throw e
|
||||||
|
}
|
||||||
|
attempt++
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Add or replace [files], keeping everything else — [edit] with only puts. */
|
||||||
|
fun append(files: List<VaultFile>, at: Long, maxAttempts: Int = 5): VaultEditResult =
|
||||||
|
edit(at, maxAttempts) { VaultEdit(put = files) }
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drop every version not in [keep] and let the relay delete objects only
|
||||||
|
* those versions used. [keep] must include the current head.
|
||||||
|
*/
|
||||||
|
fun prune(keep: List<Long>): VaultPruneResult =
|
||||||
|
transport.prune(keys.vaultId, sign(mapOf("keep" to keep)))
|
||||||
|
|
||||||
|
// ─── Internals ───────────────────────────────────────────
|
||||||
|
|
||||||
|
/** Seal one file into fresh objects and PUT them; the entry, without mode. */
|
||||||
|
private fun upload(file: VaultFile): VaultEntry {
|
||||||
|
val sealed = sealEntry(crypto, keys.contentKey, keys.vaultId, file.bytes, chunkSize)
|
||||||
|
// No have-check: every object was just sealed under a fresh nonce,
|
||||||
|
// so its name is new by construction.
|
||||||
|
for (obj in sealed.objects) {
|
||||||
|
transport.put(keys.vaultId, obj.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(obj.bytes))))
|
||||||
|
}
|
||||||
|
return VaultEntry(
|
||||||
|
path = file.path,
|
||||||
|
hash = sealed.locator.hash,
|
||||||
|
size = file.bytes.size.toLong(),
|
||||||
|
enc = sealed.locator.enc,
|
||||||
|
parts = sealed.locator.parts,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seal and upload a v2 manifest naming [entries], then commit it as [seq].
|
||||||
|
* Every entry's objects must already be on the relay. `hashes` lists every
|
||||||
|
* part of every entry: the relay checks they exist, and records them as
|
||||||
|
* what the version references — a part left out may be pruned.
|
||||||
|
*/
|
||||||
|
private fun commitManifest(entries: List<VaultEntry>, seq: Long, at: Long): Long {
|
||||||
|
val manifest = VaultManifest(version = 2, seq = seq, at = at, entries = entries)
|
||||||
|
val sealed = sealManifest(crypto, keys.contentKey, keys.vaultId, manifest)
|
||||||
|
transport.put(keys.vaultId, sealed.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(sealed.bytes))))
|
||||||
|
val hashes = LinkedHashSet<String>().apply { entries.forEach { addAll(entryObjectHashes(it)) } }
|
||||||
|
return transport.commit(
|
||||||
|
keys.vaultId,
|
||||||
|
sign(
|
||||||
|
linkedMapOf(
|
||||||
|
"manifest" to sealed.hash,
|
||||||
|
"seq" to seq,
|
||||||
|
"at" to at,
|
||||||
|
"hashes" to hashes.toList(),
|
||||||
|
),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun sign(body: Map<String, Any>): String = signVaultBody(crypto, keys, body, clock()).json
|
||||||
|
|
||||||
|
private fun openRow(row: VaultLogEntry): VaultManifest =
|
||||||
|
openManifest(crypto, keys.contentKey, keys.vaultId, row.manifest, transport.get(keys.vaultId, row.manifest))
|
||||||
|
|
||||||
|
private fun sha256Hex(bytes: ByteArray): String = toHex(MessageDigest.getInstance("SHA-256").digest(bytes))
|
||||||
|
}
|
||||||
@@ -0,0 +1,364 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
import no.zyon.shade.blob.aeadSeal
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import no.zyon.shade.serialization.stringifyJson
|
||||||
|
import java.io.ByteArrayOutputStream
|
||||||
|
import java.security.GeneralSecurityException
|
||||||
|
import java.security.MessageDigest
|
||||||
|
import java.util.zip.DataFormatException
|
||||||
|
import java.util.zip.Deflater
|
||||||
|
import java.util.zip.Inflater
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sealing, naming, packing and manifest encoding — mirror of
|
||||||
|
* `@shade/vault/src/crypto.ts`. The cross-language contract is the
|
||||||
|
* "Format (v2)" section of `docs/vault.md`; vectors in
|
||||||
|
* `test-vectors/vault-v2.json`.
|
||||||
|
*
|
||||||
|
* Every object on the relay is `nonce(12) || ciphertext || tag(16)`, named by
|
||||||
|
* the lowercase hex SHA-256 of those bytes. Hashing the *ciphertext* is what
|
||||||
|
* lets the relay check an upload without holding a key; the price is that
|
||||||
|
* identical plaintext gets a new name on every seal (fresh nonce), so
|
||||||
|
* unchanged files must reuse their old entry instead of being re-sealed.
|
||||||
|
*/
|
||||||
|
|
||||||
|
private const val NONCE_LEN = 12
|
||||||
|
private const val TAG_LEN = 16
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Largest stored (post-compression) slice sealed as one object: 4 MiB.
|
||||||
|
* Part of the wire contract — every writer splits at the same boundary.
|
||||||
|
*/
|
||||||
|
const val VAULT_CHUNK_SIZE = 4 * 1024 * 1024
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Ceiling on an inflated manifest. Manifests are sealed under our own key, so
|
||||||
|
* a decompression bomb could only come from a device that holds it — but a
|
||||||
|
* corrupted write should fail with a message, not by exhausting the heap.
|
||||||
|
*/
|
||||||
|
private const val MAX_MANIFEST_BYTES = 256L * 1024 * 1024
|
||||||
|
|
||||||
|
/** ASCII "SVM2" — marks a compressed v2 manifest. */
|
||||||
|
private val MANIFEST_V2_MAGIC = byteArrayOf(0x53, 0x56, 0x4d, 0x32)
|
||||||
|
|
||||||
|
/** One sealed object: its relay name and its bytes. */
|
||||||
|
class SealedObject(val hash: String, val bytes: ByteArray)
|
||||||
|
|
||||||
|
/** Lowercase hex SHA-256 — the name of an object. */
|
||||||
|
fun objectHash(sealed: ByteArray): String =
|
||||||
|
toHex(MessageDigest.getInstance("SHA-256").digest(sealed))
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AAD for an object: binds the vault, 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 it — it is derived from the very bytes
|
||||||
|
* being sealed.
|
||||||
|
*/
|
||||||
|
fun vaultObjectAad(vaultId: String): ByteArray =
|
||||||
|
"shade-vault-object-v1|$vaultId".toByteArray(Charsets.UTF_8)
|
||||||
|
|
||||||
|
/** Encrypt one object under a fresh random nonce and give it its name. */
|
||||||
|
fun sealObject(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, plaintext: ByteArray): SealedObject {
|
||||||
|
val (ciphertext, nonce) = crypto.aesGcmEncrypt(contentKey, plaintext, vaultObjectAad(vaultId))
|
||||||
|
val bytes = ByteArray(NONCE_LEN + ciphertext.size)
|
||||||
|
System.arraycopy(nonce, 0, bytes, 0, NONCE_LEN)
|
||||||
|
System.arraycopy(ciphertext, 0, bytes, NONCE_LEN, ciphertext.size)
|
||||||
|
return SealedObject(objectHash(bytes), bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [sealObject] with a caller-chosen nonce — for cross-language vectors ONLY.
|
||||||
|
* Mirror of `@shade/vault/testing`'s `sealObjectWithNonce`. `internal` so it
|
||||||
|
* is reachable from this module's tests and from nowhere else: a nonce reused
|
||||||
|
* under one content key breaks AES-GCM outright.
|
||||||
|
*/
|
||||||
|
internal fun sealObjectWithNonce(contentKey: ByteArray, vaultId: String, plaintext: ByteArray, nonce: ByteArray): SealedObject {
|
||||||
|
val bytes = aeadSeal(contentKey, nonce, plaintext, vaultObjectAad(vaultId))
|
||||||
|
return SealedObject(objectHash(bytes), bytes)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decrypt one object, verifying its name first: 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.
|
||||||
|
*/
|
||||||
|
fun openObject(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
contentKey: ByteArray,
|
||||||
|
vaultId: String,
|
||||||
|
expectedHash: String,
|
||||||
|
bytes: ByteArray,
|
||||||
|
): ByteArray {
|
||||||
|
if (bytes.size < NONCE_LEN + TAG_LEN) {
|
||||||
|
throw VaultFormatException("vault object too short to be a sealed object")
|
||||||
|
}
|
||||||
|
val actual = objectHash(bytes)
|
||||||
|
if (actual != expectedHash) {
|
||||||
|
throw VaultFormatException("vault object hash mismatch: expected $expectedHash, got $actual")
|
||||||
|
}
|
||||||
|
return try {
|
||||||
|
crypto.aesGcmDecrypt(
|
||||||
|
contentKey,
|
||||||
|
bytes.copyOfRange(NONCE_LEN, bytes.size),
|
||||||
|
bytes.copyOfRange(0, NONCE_LEN),
|
||||||
|
vaultObjectAad(vaultId),
|
||||||
|
)
|
||||||
|
} catch (e: GeneralSecurityException) {
|
||||||
|
// The hash matched, so the relay returned what was asked for; a tag
|
||||||
|
// failure now means a wrong key or an object from another vault.
|
||||||
|
throw VaultFormatException("vault object $expectedHash failed authentication (wrong key or vault?)", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Compression ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Raw DEFLATE (RFC 1951) at zlib's default level — what the TS side's
|
||||||
|
* `CompressionStream('deflate-raw')` produces. Readers never depend on the
|
||||||
|
* exact bytes, only on the stream inflating to the original.
|
||||||
|
*/
|
||||||
|
fun deflateRaw(bytes: ByteArray): ByteArray {
|
||||||
|
val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
|
||||||
|
try {
|
||||||
|
deflater.setInput(bytes)
|
||||||
|
deflater.finish()
|
||||||
|
val out = ByteArrayOutputStream(maxOf(64, bytes.size / 2))
|
||||||
|
val buf = ByteArray(64 * 1024)
|
||||||
|
while (!deflater.finished()) {
|
||||||
|
val n = deflater.deflate(buf)
|
||||||
|
out.write(buf, 0, n)
|
||||||
|
}
|
||||||
|
return out.toByteArray()
|
||||||
|
} finally {
|
||||||
|
deflater.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Inverse of [deflateRaw], refusing to produce more than [limit] bytes.
|
||||||
|
*
|
||||||
|
* Strict about the stream's end, like the TS `DecompressionStream`: a stream
|
||||||
|
* that stops before its final block is "truncated", and bytes after the final
|
||||||
|
* block are "trailing data" — both are corruption, not something to paper
|
||||||
|
* over by returning whatever inflated so far.
|
||||||
|
*/
|
||||||
|
fun inflateRaw(bytes: ByteArray, limit: Long): ByteArray {
|
||||||
|
val inflater = Inflater(true)
|
||||||
|
try {
|
||||||
|
// With `nowrap`, zlib may need one byte past the end of the stream
|
||||||
|
// before it reports `finished()` (documented on Inflater's
|
||||||
|
// constructor). Feed a dummy byte so a valid stream always finishes;
|
||||||
|
// it is never consumed, which is how trailing data is recognised below.
|
||||||
|
inflater.setInput(bytes.copyOf(bytes.size + 1))
|
||||||
|
val out = ByteArrayOutputStream()
|
||||||
|
val buf = ByteArray(64 * 1024)
|
||||||
|
var stalls = 0
|
||||||
|
while (!inflater.finished()) {
|
||||||
|
val n = try {
|
||||||
|
inflater.inflate(buf)
|
||||||
|
} catch (e: DataFormatException) {
|
||||||
|
throw VaultFormatException("vault inflate failed: ${e.message ?: "corrupt deflate stream"}", e)
|
||||||
|
}
|
||||||
|
if (n == 0) {
|
||||||
|
if (inflater.finished()) break
|
||||||
|
if (inflater.needsDictionary()) throw VaultFormatException("vault inflate failed: stream wants a preset dictionary")
|
||||||
|
if (inflater.needsInput()) throw VaultFormatException("vault inflate failed: truncated deflate stream")
|
||||||
|
// Neither progress nor a reason: never spin forever on it.
|
||||||
|
if (++stalls > 2) throw VaultFormatException("vault inflate failed: no progress")
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
stalls = 0
|
||||||
|
if (out.size().toLong() + n > limit) throw VaultFormatException("vault inflate exceeded $limit bytes")
|
||||||
|
out.write(buf, 0, n)
|
||||||
|
}
|
||||||
|
if (inflater.remaining > 1) {
|
||||||
|
throw VaultFormatException("vault inflate failed: ${inflater.remaining - 1} byte(s) of trailing data")
|
||||||
|
}
|
||||||
|
return out.toByteArray()
|
||||||
|
} finally {
|
||||||
|
inflater.end()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Does this file start with the signature of an already-compressed format?
|
||||||
|
* Part of the contract so ports make the same `enc` choice: PNG, JPEG, WebP
|
||||||
|
* ("RIFF"…"WEBP"), MP4 family ("ftyp" at offset 4), GIF, gzip, zip ("PK",
|
||||||
|
* which also covers docx/xlsx/jar/apk).
|
||||||
|
*/
|
||||||
|
fun looksCompressed(b: ByteArray): Boolean {
|
||||||
|
fun at(offset: Int, vararg sig: Int): Boolean =
|
||||||
|
b.size >= offset + sig.size && sig.indices.all { (b[offset + it].toInt() and 0xff) == sig[it] }
|
||||||
|
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
|
||||||
|
at(0, 0x47, 0x49, 0x46, 0x38) || // GIF8
|
||||||
|
at(0, 0x1f, 0x8b) || // gzip
|
||||||
|
at(0, 0x50, 0x4b) // PK
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Entries ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/** A file's bytes as they will be stored, before sealing. */
|
||||||
|
class PackedEntry(
|
||||||
|
/** [VAULT_ENC_DEFLATE_RAW] when the stored bytes are compressed, else null. */
|
||||||
|
val enc: String?,
|
||||||
|
/** The plaintext, or its deflate-raw. */
|
||||||
|
val stored: ByteArray,
|
||||||
|
/** [stored] in slices of at most the chunk size. Never empty. */
|
||||||
|
val chunks: List<ByteArray>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Turn a file's plaintext into the slices that get sealed.
|
||||||
|
*
|
||||||
|
* Compression is kept only when it saves at least 5 %, as the integer test
|
||||||
|
* `compressed * 20 <= plain * 19` so no port disagrees over rounding. The
|
||||||
|
* whole file is compressed first and THEN split: a reader concatenates the
|
||||||
|
* opened parts and inflates once, so parts carry no framing of their own.
|
||||||
|
*
|
||||||
|
* [chunkSize] exists for tests and vectors; real writers use the default.
|
||||||
|
*/
|
||||||
|
fun packEntry(plaintext: ByteArray, chunkSize: Int = VAULT_CHUNK_SIZE): PackedEntry {
|
||||||
|
require(chunkSize >= 1) { "vault chunk size must be a positive integer, got $chunkSize" }
|
||||||
|
var stored = plaintext
|
||||||
|
var enc: String? = null
|
||||||
|
if (plaintext.isNotEmpty() && !looksCompressed(plaintext)) {
|
||||||
|
val deflated = deflateRaw(plaintext)
|
||||||
|
if (deflated.size.toLong() * 20 <= plaintext.size.toLong() * 19) {
|
||||||
|
stored = deflated
|
||||||
|
enc = VAULT_ENC_DEFLATE_RAW
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// An empty file is still one (empty) object: an entry always names
|
||||||
|
// something the relay holds, so a reader never special-cases.
|
||||||
|
val chunks = ArrayList<ByteArray>()
|
||||||
|
var i = 0
|
||||||
|
while (i < stored.size || chunks.isEmpty()) {
|
||||||
|
chunks.add(stored.copyOfRange(i, minOf(stored.size, i + chunkSize)))
|
||||||
|
i += chunkSize
|
||||||
|
}
|
||||||
|
return PackedEntry(enc, stored, chunks)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The manifest fields that locate a file's ciphertext. */
|
||||||
|
data class EntryLocator(val hash: String, val parts: List<String>? = null, val enc: String? = null)
|
||||||
|
|
||||||
|
/** Shape an entry's locator from its sealed parts (one part → no `parts`). */
|
||||||
|
fun entryLocator(packed: PackedEntry, sealed: List<SealedObject>): EntryLocator {
|
||||||
|
require(sealed.isNotEmpty()) { "an entry has at least one object" }
|
||||||
|
return EntryLocator(
|
||||||
|
hash = sealed[0].hash,
|
||||||
|
parts = if (sealed.size > 1) sealed.map { it.hash } else null,
|
||||||
|
enc = packed.enc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The locator for a file's manifest entry, and the objects to upload. */
|
||||||
|
class SealedEntry(val locator: EntryLocator, val objects: List<SealedObject>)
|
||||||
|
|
||||||
|
/** Pack and seal one file. */
|
||||||
|
fun sealEntry(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
contentKey: ByteArray,
|
||||||
|
vaultId: String,
|
||||||
|
plaintext: ByteArray,
|
||||||
|
chunkSize: Int = VAULT_CHUNK_SIZE,
|
||||||
|
): SealedEntry {
|
||||||
|
val packed = packEntry(plaintext, chunkSize)
|
||||||
|
val objects = packed.chunks.map { sealObject(crypto, contentKey, vaultId, it) }
|
||||||
|
return SealedEntry(entryLocator(packed, objects), objects)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every object an entry needs, in read order — also exactly what a commit's
|
||||||
|
* signed `hashes` must list, or a part may be collected by the next prune.
|
||||||
|
*/
|
||||||
|
fun entryObjectHashes(entry: VaultEntry): List<String> =
|
||||||
|
if (!entry.parts.isNullOrEmpty()) entry.parts else listOf(entry.hash)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reassemble a file from its fetched objects, in [entryObjectHashes] order:
|
||||||
|
* verify and open each part, concatenate, inflate if `enc`, check the size.
|
||||||
|
*
|
||||||
|
* The size check is what catches a part list that lost or gained an element
|
||||||
|
* — every part authenticates on its own, so such an entry would otherwise
|
||||||
|
* open cleanly into a truncated or padded file.
|
||||||
|
*/
|
||||||
|
fun openEntryBytes(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
contentKey: ByteArray,
|
||||||
|
vaultId: String,
|
||||||
|
entry: VaultEntry,
|
||||||
|
objects: List<ByteArray>,
|
||||||
|
): ByteArray {
|
||||||
|
val hashes = entryObjectHashes(entry)
|
||||||
|
if (!entry.parts.isNullOrEmpty() && entry.parts[0] != entry.hash) {
|
||||||
|
throw VaultFormatException("vault entry ${entry.path}: hash must equal parts[0]")
|
||||||
|
}
|
||||||
|
if (objects.size != hashes.size) {
|
||||||
|
throw VaultFormatException("vault entry ${entry.path}: expected ${hashes.size} object(s), got ${objects.size}")
|
||||||
|
}
|
||||||
|
if (entry.size < 0 || entry.size > Int.MAX_VALUE - 8) {
|
||||||
|
throw VaultFormatException("vault entry ${entry.path}: size ${entry.size} cannot be held in memory")
|
||||||
|
}
|
||||||
|
|
||||||
|
val stored = ByteArrayOutputStream()
|
||||||
|
for (i in hashes.indices) {
|
||||||
|
stored.write(openObject(crypto, contentKey, vaultId, hashes[i], objects[i]))
|
||||||
|
}
|
||||||
|
|
||||||
|
val plaintext = when (entry.enc) {
|
||||||
|
null -> stored.toByteArray()
|
||||||
|
VAULT_ENC_DEFLATE_RAW -> inflateRaw(stored.toByteArray(), entry.size)
|
||||||
|
// Guessing would hand back bytes that look like the file and are not.
|
||||||
|
else -> throw VaultFormatException("vault entry ${entry.path}: unsupported encoding ${entry.enc}")
|
||||||
|
}
|
||||||
|
if (plaintext.size.toLong() != entry.size) {
|
||||||
|
throw VaultFormatException(
|
||||||
|
"vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.size}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return plaintext
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Manifests ───────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A manifest's plaintext before sealing: v1 is bare UTF-8 JSON, v2 is "SVM2"
|
||||||
|
* + deflate-raw of it. The version field decides the container.
|
||||||
|
*/
|
||||||
|
fun encodeManifest(manifest: VaultManifest): ByteArray {
|
||||||
|
require(manifest.version == 1 || manifest.version == 2) {
|
||||||
|
"unsupported vault manifest version: ${manifest.version}"
|
||||||
|
}
|
||||||
|
val json = stringifyJson(manifest.toJsonMap()).toByteArray(Charsets.UTF_8)
|
||||||
|
if (manifest.version == 1) return json
|
||||||
|
return MANIFEST_V2_MAGIC + deflateRaw(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */
|
||||||
|
fun decodeManifest(plain: ByteArray): VaultManifest {
|
||||||
|
val isV2 = plain.size >= MANIFEST_V2_MAGIC.size &&
|
||||||
|
MANIFEST_V2_MAGIC.indices.all { plain[it] == MANIFEST_V2_MAGIC[it] }
|
||||||
|
val json = if (isV2) {
|
||||||
|
inflateRaw(plain.copyOfRange(MANIFEST_V2_MAGIC.size, plain.size), MAX_MANIFEST_BYTES)
|
||||||
|
} else {
|
||||||
|
plain
|
||||||
|
}
|
||||||
|
return parseManifestJson(String(json, Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** A manifest is stored as an ordinary object; this is the encoding step around it. */
|
||||||
|
fun sealManifest(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, manifest: VaultManifest): SealedObject =
|
||||||
|
sealObject(crypto, contentKey, vaultId, encodeManifest(manifest))
|
||||||
|
|
||||||
|
fun openManifest(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
contentKey: ByteArray,
|
||||||
|
vaultId: String,
|
||||||
|
expectedHash: String,
|
||||||
|
bytes: ByteArray,
|
||||||
|
): VaultManifest = decodeManifest(openObject(crypto, contentKey, vaultId, expectedHash, bytes))
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The relay refused a request. [code] is the relay's own error code
|
||||||
|
* (`BAD_REQUEST`, `UNAUTHORIZED`, `NOT_FOUND`, `SEQ_CONFLICT`, `TOO_LARGE`,
|
||||||
|
* `MISSING_OBJECTS`), or `SHADE_NETWORK` when the response carried none.
|
||||||
|
*
|
||||||
|
* Kept apart from [VaultFormatException] because the reactions differ: a
|
||||||
|
* relay refusal may be retried or shown as "offline / rejected", while a
|
||||||
|
* format failure means the bytes themselves are wrong and retrying is futile.
|
||||||
|
*/
|
||||||
|
class VaultException(
|
||||||
|
val code: String,
|
||||||
|
/** HTTP status, or 0 when the failure is local (e.g. a missing version). */
|
||||||
|
val statusCode: Int,
|
||||||
|
message: String,
|
||||||
|
/** The relay's head, sent along with `SEQ_CONFLICT`. */
|
||||||
|
val head: Long? = null,
|
||||||
|
/** Up to 20 hashes the relay reported missing with `MISSING_OBJECTS`. */
|
||||||
|
val missing: List<String> = emptyList(),
|
||||||
|
cause: Throwable? = null,
|
||||||
|
) : RuntimeException("[$code @ $statusCode] $message", cause) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Two devices committed from the same head and this one lost. The answer
|
||||||
|
* is to re-read the head and rebuild the edit on top of it — never to
|
||||||
|
* resend the same commit, which would just lose again.
|
||||||
|
*/
|
||||||
|
val isSeqConflict: Boolean get() = code == CODE_SEQ_CONFLICT
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val CODE_SEQ_CONFLICT = "SEQ_CONFLICT"
|
||||||
|
const val CODE_NOT_FOUND = "NOT_FOUND"
|
||||||
|
const val CODE_MISSING_OBJECTS = "MISSING_OBJECTS"
|
||||||
|
const val CODE_NETWORK = "SHADE_NETWORK"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bytes that do not decode to what the vault format promises: a hash
|
||||||
|
* mismatch, a failed AEAD tag, corrupt or oversized deflate, an unknown
|
||||||
|
* manifest version or entry encoding, a size that does not add up.
|
||||||
|
*/
|
||||||
|
class VaultFormatException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Everything a vault needs, derived from the account master key.
|
||||||
|
*
|
||||||
|
* Mirror of `@shade/vault`'s `VaultKeys` / `deriveVaultKeys`, and of the three
|
||||||
|
* `deriveVault*` functions in `@shade/storage-encrypted/crypto/kdf.ts`:
|
||||||
|
*
|
||||||
|
* vaultId = hex(HKDF(masterKey, info=`shade-vault-id-v1:<app>`)) // relay-visible opaque id
|
||||||
|
* contentKey = HKDF(masterKey, info=`shade-vault-content-v1:<app>`) // AES-256-GCM key for every object
|
||||||
|
* signingSeed = HKDF(masterKey, info=`shade-vault-sig-v1:<app>`) // Ed25519 seed, TOFU-pinned by the relay
|
||||||
|
* publicKey = Ed25519 public key of signingSeed
|
||||||
|
*
|
||||||
|
* This is what makes recovery "username and password": a phone that can
|
||||||
|
* derive the profile master can derive these too, and read a vault whose
|
||||||
|
* writer — the PC — is switched off.
|
||||||
|
*
|
||||||
|
* Its own HKDF branch rather than a reuse of `shade-blob-*-v1`: whoever holds
|
||||||
|
* a vault key reads every file, so it must not be derivable from the profile
|
||||||
|
* blob's key or vice versa. Reference vectors: `test-vectors/vault-v2.json`
|
||||||
|
* ("vault-v2 keys").
|
||||||
|
*/
|
||||||
|
class VaultKeys(
|
||||||
|
/** Lowercase hex (64 chars) — the id in every relay URL. */
|
||||||
|
val vaultId: String,
|
||||||
|
val contentKey: ByteArray,
|
||||||
|
val signingSeed: ByteArray,
|
||||||
|
val publicKey: ByteArray,
|
||||||
|
)
|
||||||
|
|
||||||
|
private const val VAULT_ID_INFO_PREFIX = "shade-vault-id-v1:"
|
||||||
|
private const val VAULT_CONTENT_INFO_PREFIX = "shade-vault-content-v1:"
|
||||||
|
private const val VAULT_SIG_INFO_PREFIX = "shade-vault-sig-v1:"
|
||||||
|
|
||||||
|
private const val DERIVED_LEN = 32
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive a vault's keys for namespace [app] (e.g. `"scaffold"`). Distinct
|
||||||
|
* collections under one master MUST use distinct `app` strings — the phone's
|
||||||
|
* outgoing change queue is a second vault with its own `app`, not a path
|
||||||
|
* prefix inside the first, so the two never contend for one `seq`.
|
||||||
|
*
|
||||||
|
* No HKDF salt: the TS side passes `undefined`, which RFC 5869 (and
|
||||||
|
* `@noble/hashes`) turn into 32 zero bytes — exactly what Tink does with an
|
||||||
|
* empty salt. The vectors pin it.
|
||||||
|
*/
|
||||||
|
fun deriveVaultKeys(crypto: CryptoProvider, masterKey: ByteArray, app: String): VaultKeys {
|
||||||
|
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
|
||||||
|
require(app.isNotEmpty()) { "app namespace must be non-empty" }
|
||||||
|
fun derive(prefix: String): ByteArray =
|
||||||
|
crypto.hkdf(masterKey, ByteArray(0), (prefix + app).toByteArray(Charsets.UTF_8), DERIVED_LEN)
|
||||||
|
|
||||||
|
val signingSeed = derive(VAULT_SIG_INFO_PREFIX)
|
||||||
|
return VaultKeys(
|
||||||
|
vaultId = toHex(derive(VAULT_ID_INFO_PREFIX)),
|
||||||
|
contentKey = derive(VAULT_CONTENT_INFO_PREFIX),
|
||||||
|
signingSeed = signingSeed,
|
||||||
|
publicKey = ed25519PublicKeyFromSeed(signingSeed),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Lowercase hex — the encoding of vault ids and object names on the wire. */
|
||||||
|
fun toHex(bytes: ByteArray): String {
|
||||||
|
val out = CharArray(bytes.size * 2)
|
||||||
|
val digits = "0123456789abcdef"
|
||||||
|
for (i in bytes.indices) {
|
||||||
|
val v = bytes[i].toInt() and 0xff
|
||||||
|
out[i * 2] = digits[v ushr 4]
|
||||||
|
out[i * 2 + 1] = digits[v and 0x0f]
|
||||||
|
}
|
||||||
|
return String(out)
|
||||||
|
}
|
||||||
|
|
||||||
|
private val HEX64 = Regex("^[0-9a-f]{64}$")
|
||||||
|
|
||||||
|
/** True for a 64-char lowercase hex string — a vault id or an object name. */
|
||||||
|
internal fun isHex64(s: String): Boolean = HEX64.matches(s)
|
||||||
@@ -0,0 +1,183 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONException
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The vault's data model — mirror of `@shade/vault/src/types.ts`.
|
||||||
|
*
|
||||||
|
* Objects are content-addressed (named by the SHA-256 of their ciphertext), a
|
||||||
|
* manifest names the collection (paths live only inside it, encrypted), and
|
||||||
|
* the log is append-only. See `docs/vault.md` for why.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** The only entry encoding v2 defines: RFC 1951 raw DEFLATE, no zlib/gzip header. */
|
||||||
|
const val VAULT_ENC_DEFLATE_RAW = "deflate-raw"
|
||||||
|
|
||||||
|
/**
|
||||||
|
* One file in a manifest.
|
||||||
|
*
|
||||||
|
* [enc] is kept as a raw string rather than an enum on purpose: a manifest
|
||||||
|
* written by a newer client may name an encoding this one does not know, and
|
||||||
|
* the right reaction is to refuse *reading that file* (see [openEntryBytes]),
|
||||||
|
* not to refuse the whole manifest — every other file is still readable.
|
||||||
|
*/
|
||||||
|
data class VaultEntry(
|
||||||
|
/** Path within the collection, as the app understands it. */
|
||||||
|
val path: String,
|
||||||
|
/** Lowercase hex SHA-256 of the (first) ciphertext object. */
|
||||||
|
val hash: String,
|
||||||
|
/** PLAINTEXT byte length — before compression, whatever [enc] says. */
|
||||||
|
val size: Long,
|
||||||
|
/** Optional app-defined mode/metadata, opaque to the vault. */
|
||||||
|
val mode: String? = null,
|
||||||
|
/** Present only when the stored bytes are compressed. */
|
||||||
|
val enc: String? = null,
|
||||||
|
/** Present only when there is more than one object; `parts[0] == hash`. */
|
||||||
|
val parts: List<String>? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** The full contents of a collection at one point in time. */
|
||||||
|
data class VaultManifest(
|
||||||
|
/** 1: bare JSON. 2: "SVM2" + deflate-raw(JSON). Writers emit 2; readers accept both. */
|
||||||
|
val version: Int,
|
||||||
|
/** Monotonic, assigned by the client and checked by the relay. */
|
||||||
|
val seq: Long,
|
||||||
|
/** Epoch millis when the commit was made. */
|
||||||
|
val at: Long,
|
||||||
|
/** Optional human note, e.g. "nattlig backup". */
|
||||||
|
val message: String? = null,
|
||||||
|
val entries: List<VaultEntry>,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** One row of the append-only log. */
|
||||||
|
data class VaultLogEntry(
|
||||||
|
val seq: Long,
|
||||||
|
/** Hash of the encrypted manifest object. */
|
||||||
|
val manifest: String,
|
||||||
|
val at: Long,
|
||||||
|
/** Total bytes of all objects the manifest references, for quota display. */
|
||||||
|
val bytes: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** What `GET /v1/vault/:id/log` returns. */
|
||||||
|
data class VaultLog(
|
||||||
|
val entries: List<VaultLogEntry>,
|
||||||
|
/** Highest seq the relay holds; `0` when the vault is empty. */
|
||||||
|
val head: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** What `POST /v1/vault/:id/prune` returns. */
|
||||||
|
data class VaultPruneResult(
|
||||||
|
val removedVersions: Long,
|
||||||
|
val removedObjects: Long,
|
||||||
|
val freedBytes: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
// ─── JSON ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The entry as an insertion-ordered map, in the order TS builds it
|
||||||
|
* (`{ path, ...locator, size }`, then `mode`), so `JSON.stringify` on either
|
||||||
|
* side yields the same bytes. Key order is not part of the contract — readers
|
||||||
|
* never depend on it — but matching it keeps the manifest vector exact.
|
||||||
|
* Absent optionals are left out, as `JSON.stringify` drops `undefined`.
|
||||||
|
*/
|
||||||
|
internal fun VaultEntry.toJsonMap(): Map<String, Any> {
|
||||||
|
val m = LinkedHashMap<String, Any>()
|
||||||
|
m["path"] = path
|
||||||
|
m["hash"] = hash
|
||||||
|
if (parts != null) m["parts"] = parts
|
||||||
|
if (enc != null) m["enc"] = enc
|
||||||
|
m["size"] = size
|
||||||
|
if (mode != null) m["mode"] = mode
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
internal fun VaultManifest.toJsonMap(): Map<String, Any> {
|
||||||
|
val m = LinkedHashMap<String, Any>()
|
||||||
|
m["version"] = version
|
||||||
|
m["seq"] = seq
|
||||||
|
m["at"] = at
|
||||||
|
m["entries"] = entries.map { it.toJsonMap() }
|
||||||
|
if (message != null) m["message"] = message
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse a manifest's JSON. Malformed structure surfaces as
|
||||||
|
* [VaultFormatException], never as a raw `JSONException` — a caller showing
|
||||||
|
* "the backup could not be read" should not have to know which parser ran.
|
||||||
|
*/
|
||||||
|
internal fun parseManifestJson(text: String): VaultManifest {
|
||||||
|
try {
|
||||||
|
val o = JSONObject(text)
|
||||||
|
// Strict like TS `version !== 1 && version !== 2`: "2" or 2.5 are refused.
|
||||||
|
val version = when ((o.opt("version") as? Number)?.toDouble()) {
|
||||||
|
1.0 -> 1
|
||||||
|
2.0 -> 2
|
||||||
|
else -> -1
|
||||||
|
}
|
||||||
|
if (version != 1 && version != 2) {
|
||||||
|
// Refusing beats guessing: a future manifest may describe a file
|
||||||
|
// this reader cannot represent, and committing on top of a
|
||||||
|
// half-understood head would drop it.
|
||||||
|
throw VaultFormatException(
|
||||||
|
"unsupported vault manifest version: ${if (o.has("version")) o.get("version") else "undefined"}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val arr = o.getJSONArray("entries")
|
||||||
|
val entries = ArrayList<VaultEntry>(arr.length())
|
||||||
|
for (i in 0 until arr.length()) entries.add(parseEntryJson(arr.getJSONObject(i)))
|
||||||
|
return VaultManifest(
|
||||||
|
version = version,
|
||||||
|
seq = o.getLong("seq"),
|
||||||
|
at = o.getLong("at"),
|
||||||
|
message = optString(o, "message"),
|
||||||
|
entries = entries,
|
||||||
|
)
|
||||||
|
} catch (e: JSONException) {
|
||||||
|
throw VaultFormatException("vault manifest is not valid JSON: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseEntryJson(o: JSONObject): VaultEntry {
|
||||||
|
val parts = if (o.has("parts") && !o.isNull("parts")) {
|
||||||
|
val a = o.getJSONArray("parts")
|
||||||
|
List(a.length()) { a.getString(it) }
|
||||||
|
} else {
|
||||||
|
null
|
||||||
|
}
|
||||||
|
return VaultEntry(
|
||||||
|
path = o.getString("path"),
|
||||||
|
hash = o.getString("hash"),
|
||||||
|
size = o.getLong("size"),
|
||||||
|
mode = optString(o, "mode"),
|
||||||
|
enc = optString(o, "enc"),
|
||||||
|
parts = parts,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `org.json`'s `optString` turns null into "null" and numbers into strings; this does not. */
|
||||||
|
private fun optString(o: JSONObject, key: String): String? =
|
||||||
|
if (o.has(key) && !o.isNull(key)) o.getString(key) else null
|
||||||
|
|
||||||
|
internal fun parseLogJson(text: String): VaultLog {
|
||||||
|
try {
|
||||||
|
val o = JSONObject(text)
|
||||||
|
val arr: JSONArray = o.getJSONArray("entries")
|
||||||
|
val entries = List(arr.length()) { i ->
|
||||||
|
val e = arr.getJSONObject(i)
|
||||||
|
VaultLogEntry(
|
||||||
|
seq = e.getLong("seq"),
|
||||||
|
manifest = e.getString("manifest"),
|
||||||
|
at = e.getLong("at"),
|
||||||
|
bytes = e.optLong("bytes", 0L),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return VaultLog(entries = entries, head = o.getLong("head"))
|
||||||
|
} catch (e: JSONException) {
|
||||||
|
throw VaultFormatException("vault log response is malformed: ${e.message}", e)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import no.zyon.shade.serialization.canonicalJson
|
||||||
|
import no.zyon.shade.serialization.stringifyJson
|
||||||
|
import java.util.Base64
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A request body signed the way the relay verifies it.
|
||||||
|
*
|
||||||
|
* [canonical] is kept alongside the wire JSON so tests can compare it with
|
||||||
|
* the TS bytes directly instead of reverse-engineering a failing signature.
|
||||||
|
*/
|
||||||
|
class SignedPayload(
|
||||||
|
/** The JSON to send: the payload fields + `signedAt` + `signature`. */
|
||||||
|
val json: String,
|
||||||
|
/** The exact bytes the signature covers. */
|
||||||
|
val canonical: ByteArray,
|
||||||
|
val signedAt: Long,
|
||||||
|
val signature: ByteArray,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mirror of `@shade/server`'s `signPayload`: Ed25519 over `JSON.stringify` of
|
||||||
|
* every field except `signature` (with `signedAt` added), top-level keys
|
||||||
|
* sorted, nested values as-is; the wire body then carries `signedAt` and the
|
||||||
|
* signature in standard base64.
|
||||||
|
*
|
||||||
|
* [signedAt] is a parameter so the vectors can pin it; the relay rejects a
|
||||||
|
* value more than five minutes old or one minute in the future, so real
|
||||||
|
* callers pass the current wall clock.
|
||||||
|
*/
|
||||||
|
fun signPayload(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
signingSeed: ByteArray,
|
||||||
|
payload: Map<String, Any>,
|
||||||
|
signedAt: Long,
|
||||||
|
): SignedPayload {
|
||||||
|
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
|
||||||
|
require("signature" !in payload && "signedAt" !in payload) {
|
||||||
|
"payload must not carry signature/signedAt — they are added here"
|
||||||
|
}
|
||||||
|
val withTime = LinkedHashMap(payload).apply { put("signedAt", signedAt) }
|
||||||
|
val canonical = canonicalJson(withTime).toByteArray(Charsets.UTF_8)
|
||||||
|
val signature = crypto.sign(signingSeed, canonical)
|
||||||
|
val wire = LinkedHashMap<String, Any>(withTime).apply {
|
||||||
|
put("signature", Base64.getEncoder().encodeToString(signature))
|
||||||
|
}
|
||||||
|
return SignedPayload(stringifyJson(wire), canonical, signedAt, signature)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign a vault request body with the vault's key, the pubkey INSIDE the
|
||||||
|
* signed payload — appended afterwards it would not be covered, and could be
|
||||||
|
* swapped in transit on the first (TOFU-pinning) write.
|
||||||
|
*/
|
||||||
|
fun signVaultBody(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
keys: VaultKeys,
|
||||||
|
body: Map<String, Any>,
|
||||||
|
signedAt: Long,
|
||||||
|
): SignedPayload {
|
||||||
|
val withKey = LinkedHashMap(body).apply {
|
||||||
|
put("publicKey", Base64.getEncoder().encodeToString(keys.publicKey))
|
||||||
|
}
|
||||||
|
return signPayload(crypto, keys.signingSeed, withKey, signedAt)
|
||||||
|
}
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
package no.zyon.shade.vault
|
||||||
|
|
||||||
|
import org.json.JSONException
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.io.IOException
|
||||||
|
import java.io.InputStream
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
|
|
||||||
|
/**
|
||||||
|
* How a [VaultClient] reaches the relay — mirror of `@shade/vault`'s
|
||||||
|
* `VaultTransport`. Bodies arrive already signed (as JSON text): the
|
||||||
|
* transport moves bytes and maps errors, it never holds a key.
|
||||||
|
*
|
||||||
|
* Blocking by design, like [no.zyon.shade.blob.BlobClient]: call it from a
|
||||||
|
* background dispatcher (`Dispatchers.IO`), never from the main thread.
|
||||||
|
*/
|
||||||
|
interface VaultTransport {
|
||||||
|
/** Does the relay already hold this object? */
|
||||||
|
fun has(vaultId: String, hash: String): Boolean
|
||||||
|
|
||||||
|
fun put(vaultId: String, hash: String, signedBody: String)
|
||||||
|
|
||||||
|
/** The raw sealed object. */
|
||||||
|
fun get(vaultId: String, hash: String): ByteArray
|
||||||
|
|
||||||
|
fun log(vaultId: String, limit: Int? = null): VaultLog
|
||||||
|
|
||||||
|
/** Returns the committed seq. Throws [VaultException] with `SEQ_CONFLICT` when beaten to it. */
|
||||||
|
fun commit(vaultId: String, signedBody: String): Long
|
||||||
|
|
||||||
|
fun prune(vaultId: String, signedBody: String): VaultPruneResult
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plain HTTP against a relay running `createVaultRoutes`.
|
||||||
|
*
|
||||||
|
* Built on `HttpURLConnection` rather than `java.net.http.HttpClient` (which
|
||||||
|
* [no.zyon.shade.blob.BlobClient] uses): `java.net.http` does not exist on
|
||||||
|
* Android at any API level, and this client exists for a phone. OkHttp would
|
||||||
|
* also work but would add a dependency to a library that has none for HTTP;
|
||||||
|
* `HttpURLConnection` is on both the JVM (tests) and Android.
|
||||||
|
*/
|
||||||
|
class VaultHttpTransport(
|
||||||
|
baseUrl: String,
|
||||||
|
private val connectTimeoutMs: Int = 15_000,
|
||||||
|
/** Generous: one object is up to 4 MiB, and phones sit on slow uplinks. */
|
||||||
|
private val readTimeoutMs: Int = 60_000,
|
||||||
|
) : VaultTransport {
|
||||||
|
|
||||||
|
private val base = baseUrl.trimEnd('/')
|
||||||
|
|
||||||
|
override fun has(vaultId: String, hash: String): Boolean {
|
||||||
|
val res = request("HEAD", objectPath(vaultId, hash), null)
|
||||||
|
return when (res.status) {
|
||||||
|
200 -> true
|
||||||
|
404 -> false
|
||||||
|
else -> fail(res, "have-check")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun put(vaultId: String, hash: String, signedBody: String) {
|
||||||
|
val res = request("PUT", objectPath(vaultId, hash), signedBody)
|
||||||
|
if (res.status !in 200..299) fail(res, "upload")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun get(vaultId: String, hash: String): ByteArray {
|
||||||
|
val res = request("GET", objectPath(vaultId, hash), null)
|
||||||
|
if (res.status !in 200..299) fail(res, "download")
|
||||||
|
return res.body
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun log(vaultId: String, limit: Int?): VaultLog {
|
||||||
|
val q = if (limit == null) "" else "?limit=$limit"
|
||||||
|
val res = request("GET", "${vaultPath(vaultId)}/log$q", null)
|
||||||
|
if (res.status !in 200..299) fail(res, "log")
|
||||||
|
return parseLogJson(res.body.toString(Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun commit(vaultId: String, signedBody: String): Long {
|
||||||
|
val res = request("POST", "${vaultPath(vaultId)}/commit", signedBody)
|
||||||
|
if (res.status !in 200..299) fail(res, "commit")
|
||||||
|
return jsonBody(res, "commit").getLong("seq")
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun prune(vaultId: String, signedBody: String): VaultPruneResult {
|
||||||
|
val res = request("POST", "${vaultPath(vaultId)}/prune", signedBody)
|
||||||
|
if (res.status !in 200..299) fail(res, "prune")
|
||||||
|
val o = jsonBody(res, "prune")
|
||||||
|
return VaultPruneResult(
|
||||||
|
removedVersions = o.getLong("removedVersions"),
|
||||||
|
removedObjects = o.getLong("removedObjects"),
|
||||||
|
freedBytes = o.getLong("freedBytes"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Plumbing ────────────────────────────────────────────
|
||||||
|
|
||||||
|
private class Response(val status: Int, val body: ByteArray)
|
||||||
|
|
||||||
|
/** Ids are validated before they reach a URL, so nothing can smuggle a path. */
|
||||||
|
private fun vaultPath(vaultId: String): String {
|
||||||
|
require(isHex64(vaultId)) { "vaultId must be 64 lowercase hex chars" }
|
||||||
|
return "/v1/vault/$vaultId"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun objectPath(vaultId: String, hash: String): String {
|
||||||
|
require(isHex64(hash)) { "object hash must be 64 lowercase hex chars" }
|
||||||
|
return "${vaultPath(vaultId)}/object/$hash"
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun request(method: String, path: String, jsonBody: String?): Response {
|
||||||
|
val conn = try {
|
||||||
|
URL(base + path).openConnection() as HttpURLConnection
|
||||||
|
} catch (e: IOException) {
|
||||||
|
throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e)
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
conn.requestMethod = method
|
||||||
|
conn.connectTimeout = connectTimeoutMs
|
||||||
|
conn.readTimeout = readTimeoutMs
|
||||||
|
conn.useCaches = false
|
||||||
|
if (jsonBody != null) {
|
||||||
|
val bytes = jsonBody.toByteArray(Charsets.UTF_8)
|
||||||
|
conn.doOutput = true
|
||||||
|
conn.setRequestProperty("content-type", "application/json")
|
||||||
|
conn.setFixedLengthStreamingMode(bytes.size)
|
||||||
|
conn.outputStream.use { it.write(bytes) }
|
||||||
|
}
|
||||||
|
val status = conn.responseCode
|
||||||
|
// A non-2xx body is on the error stream; HEAD has neither.
|
||||||
|
val stream: InputStream? = if (status >= 400) conn.errorStream else if (method == "HEAD") null else conn.inputStream
|
||||||
|
val body = stream?.use { it.readBytes() } ?: ByteArray(0)
|
||||||
|
return Response(status, body)
|
||||||
|
} catch (e: IOException) {
|
||||||
|
throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e)
|
||||||
|
} finally {
|
||||||
|
conn.disconnect()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun jsonBody(res: Response, what: String): JSONObject = try {
|
||||||
|
JSONObject(res.body.toString(Charsets.UTF_8))
|
||||||
|
} catch (e: JSONException) {
|
||||||
|
throw VaultException(VaultException.CODE_NETWORK, res.status, "vault $what response not JSON", cause = e)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Turn a non-2xx into a [VaultException] that carries the relay's own code. */
|
||||||
|
private fun fail(res: Response, what: String): Nothing {
|
||||||
|
var code = VaultException.CODE_NETWORK
|
||||||
|
var detail = "HTTP ${res.status}"
|
||||||
|
var head: Long? = null
|
||||||
|
var missing = emptyList<String>()
|
||||||
|
try {
|
||||||
|
val o = JSONObject(res.body.toString(Charsets.UTF_8))
|
||||||
|
o.optJSONObject("error")?.let { err ->
|
||||||
|
code = err.optString("code", code)
|
||||||
|
detail = err.optString("message", detail)
|
||||||
|
}
|
||||||
|
if (o.has("head") && !o.isNull("head")) head = o.getLong("head")
|
||||||
|
o.optJSONArray("missing")?.let { a -> missing = List(a.length()) { a.getString(it) } }
|
||||||
|
} catch (_: JSONException) {
|
||||||
|
// Non-JSON error body (a proxy's HTML page): the status is all we have.
|
||||||
|
}
|
||||||
|
throw VaultException(code, res.status, "vault $what failed — $detail", head = head, missing = missing)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,280 @@
|
|||||||
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import com.sun.net.httpserver.HttpServer
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import no.zyon.shade.crypto.TinkProvider
|
||||||
|
import no.zyon.shade.serialization.canonicalJson
|
||||||
|
import no.zyon.shade.vault.VaultClient
|
||||||
|
import no.zyon.shade.vault.VaultEdit
|
||||||
|
import no.zyon.shade.vault.VaultException
|
||||||
|
import no.zyon.shade.vault.VaultFile
|
||||||
|
import no.zyon.shade.vault.VaultFormatException
|
||||||
|
import no.zyon.shade.vault.VaultHttpTransport
|
||||||
|
import no.zyon.shade.vault.VaultKeys
|
||||||
|
import no.zyon.shade.vault.VaultLog
|
||||||
|
import no.zyon.shade.vault.VaultLogEntry
|
||||||
|
import no.zyon.shade.vault.VaultManifest
|
||||||
|
import no.zyon.shade.vault.VaultPruneResult
|
||||||
|
import no.zyon.shade.vault.VaultTransport
|
||||||
|
import no.zyon.shade.vault.deriveVaultKeys
|
||||||
|
import no.zyon.shade.vault.entryObjectHashes
|
||||||
|
import no.zyon.shade.vault.objectHash
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.net.InetSocketAddress
|
||||||
|
import java.util.Base64
|
||||||
|
|
||||||
|
/**
|
||||||
|
* [VaultClient.edit] and friends against an in-memory relay that enforces
|
||||||
|
* what the real routes enforce: hash-checked uploads, TOFU Ed25519 over the
|
||||||
|
* canonical body, `seq == head + 1`, and every referenced object present.
|
||||||
|
* A signature or hash the TS relay would refuse fails here too.
|
||||||
|
*/
|
||||||
|
class VaultClientTest {
|
||||||
|
|
||||||
|
private val crypto = TinkProvider()
|
||||||
|
private val master = ByteArray(32) { (it * 7 + 3).toByte() }
|
||||||
|
private val keys = deriveVaultKeys(crypto, master, "prism-queue-test")
|
||||||
|
private val at = 1_786_600_000_000L
|
||||||
|
|
||||||
|
/** The relay, minus HTTP. */
|
||||||
|
private class MemoryRelay(private val crypto: CryptoProvider) : VaultTransport {
|
||||||
|
val objects = HashMap<String, ByteArray>()
|
||||||
|
val log = ArrayList<VaultLogEntry>()
|
||||||
|
val committedHashes = HashMap<Long, List<String>>()
|
||||||
|
var pinned: ByteArray? = null
|
||||||
|
var puts = 0
|
||||||
|
/** Runs just before a commit is checked — the "other device" hook. */
|
||||||
|
var beforeCommit: (() -> Unit)? = null
|
||||||
|
|
||||||
|
private fun authorize(body: JSONObject) {
|
||||||
|
val sig = Base64.getDecoder().decode(body.getString("signature"))
|
||||||
|
val fields = LinkedHashMap<String, Any>()
|
||||||
|
for (k in body.keys()) if (k != "signature") fields[k] = plain(body.get(k))
|
||||||
|
val canonical = canonicalJson(fields).toByteArray()
|
||||||
|
val key = pinned ?: Base64.getDecoder().decode(body.getString("publicKey")).also { pinned = it }
|
||||||
|
if (!crypto.verify(key, canonical, sig)) throw VaultException("UNAUTHORIZED", 401, "bad signature")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun plain(v: Any): Any = when (v) {
|
||||||
|
is JSONArray -> List(v.length()) { plain(v.get(it)) }
|
||||||
|
is Int -> v.toLong()
|
||||||
|
else -> v
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun head() = log.lastOrNull()?.seq ?: 0L
|
||||||
|
|
||||||
|
override fun has(vaultId: String, hash: String) = hash in objects
|
||||||
|
|
||||||
|
override fun put(vaultId: String, hash: String, signedBody: String) {
|
||||||
|
val body = JSONObject(signedBody)
|
||||||
|
authorize(body)
|
||||||
|
val data = Base64.getDecoder().decode(body.getString("data"))
|
||||||
|
if (objectHash(data) != hash) throw VaultException("BAD_REQUEST", 400, "hash mismatch")
|
||||||
|
objects[hash] = data
|
||||||
|
puts++
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun get(vaultId: String, hash: String) =
|
||||||
|
objects[hash] ?: throw VaultException("NOT_FOUND", 404, "no such object")
|
||||||
|
|
||||||
|
override fun log(vaultId: String, limit: Int?) =
|
||||||
|
VaultLog(if (limit == null) log.toList() else log.takeLast(limit), head())
|
||||||
|
|
||||||
|
override fun commit(vaultId: String, signedBody: String): Long {
|
||||||
|
beforeCommit?.let { beforeCommit = null; it() }
|
||||||
|
val body = JSONObject(signedBody)
|
||||||
|
authorize(body)
|
||||||
|
val seq = body.getLong("seq")
|
||||||
|
if (seq != head() + 1) throw VaultException("SEQ_CONFLICT", 409, "expected seq ${head() + 1}, got $seq", head = head())
|
||||||
|
val hashes = List(body.getJSONArray("hashes").length()) { body.getJSONArray("hashes").getString(it) }
|
||||||
|
val manifest = body.getString("manifest")
|
||||||
|
if (manifest !in objects || hashes.any { it !in objects }) throw VaultException("MISSING_OBJECTS", 409, "missing")
|
||||||
|
log.add(VaultLogEntry(seq, manifest, body.getLong("at"), 0))
|
||||||
|
committedHashes[seq] = hashes
|
||||||
|
return seq
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun prune(vaultId: String, signedBody: String) = VaultPruneResult(0, 0, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun text(s: String) = s.toByteArray()
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun emptyVaultAndNoOpEditsCommitNothing() {
|
||||||
|
val relay = MemoryRelay(crypto)
|
||||||
|
val client = VaultClient(crypto, keys, relay)
|
||||||
|
assertNull(client.headManifest())
|
||||||
|
assertThrows(VaultException::class.java) { client.manifest() }
|
||||||
|
|
||||||
|
var seen: VaultManifest? = VaultManifest(2, 99, 0, null, emptyList())
|
||||||
|
assertEquals(0L, client.edit(at) { seen = it; null }.seq)
|
||||||
|
assertNull(seen)
|
||||||
|
val noop = client.edit(at) { VaultEdit(remove = listOf("not-there")) }
|
||||||
|
assertFalse(noop.committed)
|
||||||
|
assertEquals(0, relay.puts)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun appendThenEditKeepsUntouchedEntriesByteForByte() {
|
||||||
|
val relay = MemoryRelay(crypto)
|
||||||
|
val client = VaultClient(crypto, keys, relay, chunkSize = 64)
|
||||||
|
val big = ByteArray(1000).also { java.util.Random(1).nextBytes(it) } // 16 parts, incompressible
|
||||||
|
val note = text("# Plan\n" + "- [ ] gjør noe\n".repeat(40))
|
||||||
|
val r1 = client.append(
|
||||||
|
listOf(VaultFile("big.bin", big), VaultFile("plan.md", note, mode = "644"), VaultFile("empty", ByteArray(0))),
|
||||||
|
at,
|
||||||
|
)
|
||||||
|
assertEquals(1L, r1.seq)
|
||||||
|
assertTrue(r1.committed)
|
||||||
|
|
||||||
|
val m1 = client.manifest()
|
||||||
|
assertEquals(2, m1.version)
|
||||||
|
val bigEntry = m1.entries.single { it.path == "big.bin" }
|
||||||
|
assertEquals(16, bigEntry.parts!!.size)
|
||||||
|
assertEquals(bigEntry.parts!![0], bigEntry.hash)
|
||||||
|
assertNull(bigEntry.enc)
|
||||||
|
val planEntry = m1.entries.single { it.path == "plan.md" }
|
||||||
|
assertEquals("deflate-raw", planEntry.enc)
|
||||||
|
assertEquals("644", planEntry.mode)
|
||||||
|
assertArrayEquals(big, client.readEntry(bigEntry))
|
||||||
|
assertArrayEquals(note, client.readEntry(planEntry))
|
||||||
|
assertArrayEquals(ByteArray(0), client.readEntry(m1.entries.single { it.path == "empty" }))
|
||||||
|
// Commit lists every part of every entry.
|
||||||
|
assertEquals(m1.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[1L]!!.toSet())
|
||||||
|
|
||||||
|
val putsBefore = relay.puts
|
||||||
|
val r2 = client.edit(at + 1) { head ->
|
||||||
|
assertEquals(1L, head!!.seq)
|
||||||
|
VaultEdit(put = listOf(VaultFile("queue/001.json", text("""{"op":"check"}"""))), remove = listOf("empty"))
|
||||||
|
}
|
||||||
|
assertEquals(2L, r2.seq)
|
||||||
|
assertEquals(2, relay.puts - putsBefore) // one new object + the manifest; nothing re-sealed
|
||||||
|
|
||||||
|
val m2 = client.manifest()
|
||||||
|
assertEquals(listOf("big.bin", "plan.md", "queue/001.json"), m2.entries.map { it.path })
|
||||||
|
assertEquals(bigEntry, m2.entries[0])
|
||||||
|
assertEquals(planEntry, m2.entries[1])
|
||||||
|
assertEquals(m2.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[2L]!!.toSet())
|
||||||
|
|
||||||
|
// Old versions stay readable; pull decrypts everything.
|
||||||
|
assertEquals(3, client.manifest(1).entries.size)
|
||||||
|
val pulled = client.pull()
|
||||||
|
assertArrayEquals(text("""{"op":"check"}"""), pulled.files["queue/001.json"])
|
||||||
|
assertEquals(2L, client.log().head)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun seqConflictRereadsTheHeadAndRetries() {
|
||||||
|
val relay = MemoryRelay(crypto)
|
||||||
|
val phone = VaultClient(crypto, keys, relay)
|
||||||
|
val pc = VaultClient(crypto, keys, relay)
|
||||||
|
phone.append(listOf(VaultFile("a.txt", text("a"))), at)
|
||||||
|
|
||||||
|
// The PC drains the queue between the phone's read and its commit.
|
||||||
|
relay.beforeCommit = { pc.edit(at) { VaultEdit(remove = listOf("a.txt"), put = listOf(VaultFile("pc.txt", text("pc")))) } }
|
||||||
|
|
||||||
|
val heads = ArrayList<Long?>()
|
||||||
|
val putsBefore = relay.puts
|
||||||
|
val r = phone.edit(at + 5) { head ->
|
||||||
|
heads.add(head?.seq)
|
||||||
|
VaultEdit(put = listOf(VaultFile("b.txt", text("b"))))
|
||||||
|
}
|
||||||
|
assertEquals(listOf<Long?>(1L, 2L), heads) // change() saw the new head on the retry
|
||||||
|
assertEquals(3L, r.seq)
|
||||||
|
assertTrue(r.committed)
|
||||||
|
val m = phone.manifest()
|
||||||
|
assertEquals(setOf("pc.txt", "b.txt"), m.entries.map { it.path }.toSet()) // the PC's edit survived
|
||||||
|
assertArrayEquals(text("b"), phone.readEntry(m.entries.single { it.path == "b.txt" }))
|
||||||
|
// Phone: b.txt sealed once + two manifests. PC: pc.txt + its manifest.
|
||||||
|
assertEquals(5, relay.puts - putsBefore)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun givesUpAfterMaxAttemptsAndPassesOtherErrorsThrough() {
|
||||||
|
val relay = MemoryRelay(crypto)
|
||||||
|
val client = VaultClient(crypto, keys, relay)
|
||||||
|
val other = VaultClient(crypto, keys, relay)
|
||||||
|
var calls = 0
|
||||||
|
val loseEveryRace = object : VaultTransport by relay {
|
||||||
|
override fun commit(vaultId: String, signedBody: String): Long {
|
||||||
|
other.append(listOf(VaultFile("x${calls++}", text("x"))), at)
|
||||||
|
return relay.commit(vaultId, signedBody)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
val e = assertThrows(VaultException::class.java) {
|
||||||
|
VaultClient(crypto, keys, loseEveryRace).edit(at, maxAttempts = 3) { VaultEdit(put = listOf(VaultFile("p", text("p")))) }
|
||||||
|
}
|
||||||
|
assertTrue(e.isSeqConflict)
|
||||||
|
assertEquals(3, calls)
|
||||||
|
|
||||||
|
val refusing = object : VaultTransport by relay {
|
||||||
|
override fun commit(vaultId: String, signedBody: String): Long =
|
||||||
|
throw VaultException("MISSING_OBJECTS", 409, "missing")
|
||||||
|
}
|
||||||
|
var attempts = 0
|
||||||
|
val e2 = assertThrows(VaultException::class.java) {
|
||||||
|
VaultClient(crypto, keys, refusing).edit(at) { attempts++; VaultEdit(put = listOf(VaultFile("q", text("q")))) }
|
||||||
|
}
|
||||||
|
assertEquals("MISSING_OBJECTS", e2.code)
|
||||||
|
assertEquals(1, attempts)
|
||||||
|
assertTrue(client.headManifest() != null)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun refusesToEditOnTopOfAnUnreadableHead() {
|
||||||
|
val relay = MemoryRelay(crypto)
|
||||||
|
VaultClient(crypto, keys, relay).append(listOf(VaultFile("a", text("a"))), at)
|
||||||
|
val wrongKey = VaultKeys(keys.vaultId, ByteArray(32) { 9 }, keys.signingSeed, keys.publicKey)
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
VaultClient(crypto, wrongKey, relay).edit(at) { VaultEdit(put = listOf(VaultFile("b", text("b")))) }
|
||||||
|
}
|
||||||
|
assertEquals(1L, relay.log.size.toLong())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun httpTransportMapsRelayErrors() {
|
||||||
|
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
|
||||||
|
server.createContext("/") { ex ->
|
||||||
|
val path = ex.requestURI.path
|
||||||
|
val (status, body) = when {
|
||||||
|
path.endsWith("/commit") -> 409 to """{"error":{"code":"SEQ_CONFLICT","message":"expected seq 4, got 3"},"head":3}"""
|
||||||
|
path.endsWith("/log") -> 200 to """{"entries":[{"seq":3,"manifest":"${"a".repeat(64)}","at":5,"bytes":10}],"head":3}"""
|
||||||
|
ex.requestMethod == "HEAD" -> 404 to ""
|
||||||
|
ex.requestMethod == "GET" -> 200 to "raw-bytes"
|
||||||
|
else -> 502 to "<html>bad gateway</html>"
|
||||||
|
}
|
||||||
|
val bytes = body.toByteArray()
|
||||||
|
ex.sendResponseHeaders(status, if (ex.requestMethod == "HEAD" || bytes.isEmpty()) -1 else bytes.size.toLong())
|
||||||
|
if (bytes.isNotEmpty() && ex.requestMethod != "HEAD") ex.responseBody.use { it.write(bytes) }
|
||||||
|
ex.close()
|
||||||
|
}
|
||||||
|
server.start()
|
||||||
|
try {
|
||||||
|
val t = VaultHttpTransport("http://127.0.0.1:${server.address.port}/")
|
||||||
|
val id = keys.vaultId
|
||||||
|
val hash = "b".repeat(64)
|
||||||
|
assertEquals(3L, t.log(id, 1).head)
|
||||||
|
assertEquals(10L, t.log(id).entries.single().bytes)
|
||||||
|
assertFalse(t.has(id, hash))
|
||||||
|
assertArrayEquals("raw-bytes".toByteArray(), t.get(id, hash))
|
||||||
|
val e = assertThrows(VaultException::class.java) { t.commit(id, "{}") }
|
||||||
|
assertTrue(e.isSeqConflict)
|
||||||
|
assertEquals(409, e.statusCode)
|
||||||
|
assertEquals(3L, e.head)
|
||||||
|
val e2 = assertThrows(VaultException::class.java) { t.put(id, hash, "{}") }
|
||||||
|
assertEquals(VaultException.CODE_NETWORK, e2.code)
|
||||||
|
assertEquals(502, e2.statusCode)
|
||||||
|
assertThrows(IllegalArgumentException::class.java) { t.get(id, "../../etc/passwd") }
|
||||||
|
} finally {
|
||||||
|
server.stop(0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.TinkProvider
|
||||||
|
import no.zyon.shade.vault.VaultClient
|
||||||
|
import no.zyon.shade.vault.VaultEdit
|
||||||
|
import no.zyon.shade.vault.VaultFile
|
||||||
|
import no.zyon.shade.vault.VaultHttpTransport
|
||||||
|
import no.zyon.shade.vault.deriveVaultKeys
|
||||||
|
import no.zyon.shade.vault.toHex
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Assume.assumeTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.File
|
||||||
|
import java.security.MessageDigest
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Live cross-check against the real TS vault routes — skipped unless
|
||||||
|
* `SHADE_VAULT_LIVE_SPEC` points at the spec file a TS driver wrote.
|
||||||
|
*
|
||||||
|
* Run it via `bun run scripts/vault-live-kotlin.ts`: the driver serves `createVaultRoutes`
|
||||||
|
* on a local port, pushes files with the TS client and writes
|
||||||
|
* `{ url, masterKey, app, files: {path: sha256}, kotlinOut }`. This test reads
|
||||||
|
* every file back, then edits the vault from Kotlin and records what it wrote
|
||||||
|
* in `kotlinOut`; the driver then reads that back with the TS client.
|
||||||
|
*/
|
||||||
|
class VaultLiveTest {
|
||||||
|
|
||||||
|
private fun sha256(b: ByteArray) = toHex(MessageDigest.getInstance("SHA-256").digest(b))
|
||||||
|
|
||||||
|
private fun fromHex(s: String) =
|
||||||
|
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun readsTsWritesAndAppendsForTs() {
|
||||||
|
val specPath = System.getenv("SHADE_VAULT_LIVE_SPEC")
|
||||||
|
assumeTrue("SHADE_VAULT_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
|
||||||
|
val spec = JSONObject(File(specPath!!).readText())
|
||||||
|
val crypto = TinkProvider()
|
||||||
|
val keys = deriveVaultKeys(crypto, fromHex(spec.getString("masterKey")), spec.getString("app"))
|
||||||
|
val client = VaultClient(crypto, keys, VaultHttpTransport(spec.getString("url")))
|
||||||
|
|
||||||
|
// Read what TS pushed.
|
||||||
|
val head = client.manifest()
|
||||||
|
val want = spec.getJSONObject("files")
|
||||||
|
assertEquals(want.keySet(), head.entries.map { it.path }.toSet())
|
||||||
|
for (entry in head.entries) {
|
||||||
|
assertEquals(entry.path, want.getString(entry.path), sha256(client.readEntry(entry)))
|
||||||
|
}
|
||||||
|
assertTrue("TS pushed a multi-part file", head.entries.any { (it.parts?.size ?: 0) > 1 })
|
||||||
|
assertTrue("TS pushed a compressed file", head.entries.any { it.enc == "deflate-raw" })
|
||||||
|
|
||||||
|
// Append from Kotlin: a compressible note, a 2-part binary, a removal.
|
||||||
|
val note = ("# Fra telefonen\n" + "- [x] lest workspace mens PC-en var av\n".repeat(200)).toByteArray()
|
||||||
|
val big = ByteArray(5 * 1024 * 1024).also { java.util.Random(42).nextBytes(it) }
|
||||||
|
val result = client.edit(System.currentTimeMillis()) { h ->
|
||||||
|
assertEquals(head.seq, h!!.seq)
|
||||||
|
VaultEdit(
|
||||||
|
put = listOf(VaultFile("from-kotlin/note.md", note, mode = "644"), VaultFile("from-kotlin/big.bin", big)),
|
||||||
|
remove = listOf("hello.txt"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
assertTrue(result.committed)
|
||||||
|
assertEquals(head.seq + 1, result.seq)
|
||||||
|
|
||||||
|
val out = JSONObject()
|
||||||
|
.put("seq", result.seq)
|
||||||
|
.put("removed", "hello.txt")
|
||||||
|
.put("files", JSONObject().put("from-kotlin/note.md", sha256(note)).put("from-kotlin/big.bin", sha256(big)))
|
||||||
|
File(spec.getString("kotlinOut")).writeText(out.toString())
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,333 @@
|
|||||||
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.TinkProvider
|
||||||
|
import no.zyon.shade.vault.VAULT_CHUNK_SIZE
|
||||||
|
import no.zyon.shade.vault.VaultEntry
|
||||||
|
import no.zyon.shade.vault.VaultFormatException
|
||||||
|
import no.zyon.shade.vault.VaultKeys
|
||||||
|
import no.zyon.shade.vault.VaultManifest
|
||||||
|
import no.zyon.shade.vault.decodeManifest
|
||||||
|
import no.zyon.shade.vault.deflateRaw
|
||||||
|
import no.zyon.shade.vault.deriveVaultKeys
|
||||||
|
import no.zyon.shade.vault.encodeManifest
|
||||||
|
import no.zyon.shade.vault.entryLocator
|
||||||
|
import no.zyon.shade.vault.entryObjectHashes
|
||||||
|
import no.zyon.shade.vault.inflateRaw
|
||||||
|
import no.zyon.shade.vault.looksCompressed
|
||||||
|
import no.zyon.shade.vault.openEntryBytes
|
||||||
|
import no.zyon.shade.vault.openManifest
|
||||||
|
import no.zyon.shade.vault.openObject
|
||||||
|
import no.zyon.shade.vault.packEntry
|
||||||
|
import no.zyon.shade.vault.sealObject
|
||||||
|
import no.zyon.shade.vault.sealObjectWithNonce
|
||||||
|
import no.zyon.shade.vault.signPayload
|
||||||
|
import no.zyon.shade.vault.signVaultBody
|
||||||
|
import no.zyon.shade.vault.toHex
|
||||||
|
import no.zyon.shade.vault.vaultObjectAad
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertThrows
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
import java.io.File
|
||||||
|
import java.util.Base64
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `@shade/vault` v2 against `test-vectors/vault-v2.json` — the cross-language
|
||||||
|
* contract in `docs/vault.md`. Every byte a reader or signer depends on is
|
||||||
|
* compared exactly; generated by `scripts/generate-vectors.ts vault-v2.json`.
|
||||||
|
*/
|
||||||
|
class VaultVectorTest {
|
||||||
|
|
||||||
|
private val crypto = TinkProvider()
|
||||||
|
private val vectors: JSONArray = run {
|
||||||
|
val obj = JSONObject(File("../../test-vectors/vault-v2.json").readText())
|
||||||
|
assertEquals("vault-v2.json schema version", 2, obj.getInt("version"))
|
||||||
|
obj.getJSONArray("vectors")
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun byPrefix(prefix: String): List<JSONObject> =
|
||||||
|
(0 until vectors.length()).map { vectors.getJSONObject(it) }
|
||||||
|
.filter { it.getString("description").startsWith(prefix) }
|
||||||
|
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
|
||||||
|
|
||||||
|
private fun fromHex(s: String): ByteArray =
|
||||||
|
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
|
||||||
|
|
||||||
|
private val keyVector = byPrefix("vault-v2 keys").single()
|
||||||
|
private val keys: VaultKeys = deriveVaultKeys(crypto, fromHex(keyVector.getString("masterKey")), keyVector.getString("app"))
|
||||||
|
|
||||||
|
private fun entryFrom(o: JSONObject): VaultEntry = VaultEntry(
|
||||||
|
path = o.getString("path"),
|
||||||
|
hash = o.getString("hash"),
|
||||||
|
size = o.getLong("size"),
|
||||||
|
mode = if (o.has("mode")) o.getString("mode") else null,
|
||||||
|
enc = if (o.has("enc") && !o.isNull("enc")) o.getString("enc") else null,
|
||||||
|
parts = o.optJSONArray("parts")?.let { a -> List(a.length()) { a.getString(it) } },
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun manifestFrom(o: JSONObject): VaultManifest {
|
||||||
|
val a = o.getJSONArray("entries")
|
||||||
|
return VaultManifest(
|
||||||
|
version = o.getInt("version"),
|
||||||
|
seq = o.getLong("seq"),
|
||||||
|
at = o.getLong("at"),
|
||||||
|
message = if (o.has("message")) o.getString("message") else null,
|
||||||
|
entries = List(a.length()) { entryFrom(a.getJSONObject(it)) },
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Vector JSON → plain Kotlin values, keeping key order (org.json does not, but only top-level is sorted anyway). */
|
||||||
|
private fun toKotlin(v: Any?): Any = when (v) {
|
||||||
|
is JSONObject -> LinkedHashMap<String, Any>().apply { for (k in v.keys()) put(k, toKotlin(v.get(k))) }
|
||||||
|
is JSONArray -> List(v.length()) { toKotlin(v.get(it)) }
|
||||||
|
is Int -> v.toLong()
|
||||||
|
is Long, is String, is Boolean -> v
|
||||||
|
else -> error("unexpected vector value ${v?.javaClass}")
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Keys ────────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun keysMatchVector() {
|
||||||
|
assertEquals(keyVector.getString("vaultId"), keys.vaultId)
|
||||||
|
assertEquals(keyVector.getString("contentKey"), toHex(keys.contentKey))
|
||||||
|
assertEquals(keyVector.getString("signingSeed"), toHex(keys.signingSeed))
|
||||||
|
assertEquals(keyVector.getString("publicKey"), toHex(keys.publicKey))
|
||||||
|
assertEquals(keyVector.getString("objectAad"), toHex(vaultObjectAad(keys.vaultId)))
|
||||||
|
assertEquals(keyVector.getString("objectAadUtf8"), String(vaultObjectAad(keys.vaultId), Charsets.UTF_8))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Entries ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun entryPackingMatchesVectors() {
|
||||||
|
for (v in byPrefix("vault-v2 entry")) {
|
||||||
|
val what = v.getString("description")
|
||||||
|
val plaintext = fromHex(v.getString("plaintext"))
|
||||||
|
val chunkSize = v.getInt("chunkSize")
|
||||||
|
val packed = packEntry(plaintext, chunkSize)
|
||||||
|
val wantEnc = if (v.isNull("enc")) null else v.getString("enc")
|
||||||
|
assertEquals("$what: enc", wantEnc, packed.enc)
|
||||||
|
// Compressed bytes need not match zlib-for-zlib (readers never
|
||||||
|
// depend on them; the JDK's zlib and Bun's diverge on longer
|
||||||
|
// inputs) — but ours must inflate back, and the vector's must too.
|
||||||
|
if (packed.enc != null) {
|
||||||
|
assertArrayEquals("$what: own stored inflates", plaintext, inflateRaw(packed.stored, plaintext.size.toLong()))
|
||||||
|
assertArrayEquals("$what: vector stored inflates", plaintext, inflateRaw(fromHex(v.getString("stored")), plaintext.size.toLong()))
|
||||||
|
} else {
|
||||||
|
assertEquals("$what: stored", v.getString("stored"), toHex(packed.stored))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Splitting and sealing are exact: chunk the vector's stored bytes
|
||||||
|
// the way packEntry does and seal each slice under the pinned nonce.
|
||||||
|
val stored = fromHex(v.getString("stored"))
|
||||||
|
val chunks = stored.toList().chunked(chunkSize).map { it.toByteArray() }.ifEmpty { listOf(ByteArray(0)) }
|
||||||
|
val parts = v.getJSONArray("parts")
|
||||||
|
assertEquals("$what: part count", parts.length(), chunks.size)
|
||||||
|
val sealed = (0 until parts.length()).map { i ->
|
||||||
|
val p = parts.getJSONObject(i)
|
||||||
|
assertEquals("$what: part $i plaintext", p.getString("plaintext"), toHex(chunks[i]))
|
||||||
|
val obj = sealObjectWithNonce(keys.contentKey, keys.vaultId, chunks[i], fromHex(p.getString("nonce")))
|
||||||
|
assertEquals("$what: part $i wire", p.getString("wire"), toHex(obj.bytes))
|
||||||
|
assertEquals("$what: part $i hash", p.getString("hash"), obj.hash)
|
||||||
|
obj
|
||||||
|
}
|
||||||
|
val vectorPacked = no.zyon.shade.vault.PackedEntry(wantEnc, stored, chunks)
|
||||||
|
|
||||||
|
val want = entryFrom(v.getJSONObject("entry"))
|
||||||
|
val loc = entryLocator(vectorPacked, sealed)
|
||||||
|
assertEquals("$what: hash", want.hash, loc.hash)
|
||||||
|
assertEquals("$what: parts", want.parts, loc.parts)
|
||||||
|
assertEquals("$what: locator enc", want.enc, loc.enc)
|
||||||
|
assertEquals("$what: object hashes", sealed.map { it.hash }, entryObjectHashes(want))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun entryReadsBackFromWire() {
|
||||||
|
for (v in byPrefix("vault-v2 entry")) {
|
||||||
|
val entry = entryFrom(v.getJSONObject("entry"))
|
||||||
|
val parts = v.getJSONArray("parts")
|
||||||
|
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
|
||||||
|
val plain = openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, wires)
|
||||||
|
assertEquals(v.getString("description"), v.getString("plaintext"), toHex(plain))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun entryReadRefusesWhatDoesNotAddUp() {
|
||||||
|
val v = byPrefix("vault-v2 entry: multi-part").single()
|
||||||
|
val entry = entryFrom(v.getJSONObject("entry"))
|
||||||
|
val parts = v.getJSONArray("parts")
|
||||||
|
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
|
||||||
|
|
||||||
|
// Parts swapped: each fetched object must hash to its slot.
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, listOf(wires[1], wires[0]) + wires.drop(2))
|
||||||
|
}
|
||||||
|
// A part dropped from the list (consistently, so every hash checks out).
|
||||||
|
val shorter = entry.copy(parts = entry.parts!!.dropLast(1))
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openEntryBytes(crypto, keys.contentKey, keys.vaultId, shorter, wires.dropLast(1))
|
||||||
|
}
|
||||||
|
// Size lies.
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(size = entry.size + 1), wires)
|
||||||
|
}
|
||||||
|
// An encoding this reader does not know is refused, not guessed.
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(enc = "zstd"), wires)
|
||||||
|
}
|
||||||
|
// hash must equal parts[0].
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(hash = entry.parts!![1]), wires)
|
||||||
|
}
|
||||||
|
// A flipped ciphertext bit no longer matches its name.
|
||||||
|
val tampered = wires[0].copyOf().also { it[20] = (it[20].toInt() xor 1).toByte() }
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openObject(crypto, keys.contentKey, keys.vaultId, entry.parts!![0], tampered)
|
||||||
|
}
|
||||||
|
// Right name, wrong vault: the AAD binds the vaultId.
|
||||||
|
assertThrows(VaultFormatException::class.java) {
|
||||||
|
openObject(crypto, keys.contentKey, "0".repeat(64), entry.parts!![0], wires[0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Manifests ───────────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun manifestsDecodeFromWire() {
|
||||||
|
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
|
||||||
|
val v = byPrefix(prefix).single()
|
||||||
|
val want = manifestFrom(v.getJSONObject("manifest"))
|
||||||
|
val got = openManifest(crypto, keys.contentKey, keys.vaultId, v.getString("hash"), fromHex(v.getString("wire")))
|
||||||
|
assertEquals(prefix, want, got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun manifestsEncodeLikeTypeScript() {
|
||||||
|
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
|
||||||
|
val v = byPrefix(prefix).single()
|
||||||
|
val m = manifestFrom(v.getJSONObject("manifest"))
|
||||||
|
val plain = encodeManifest(m)
|
||||||
|
// Key order is not contract, but writing it in TS order makes the
|
||||||
|
// JSON identical; v1 is that JSON, so its whole plaintext matches.
|
||||||
|
val ownJson = if (m.version == 2) String(inflateRaw(plain.copyOfRange(4, plain.size), 1L shl 20)) else String(plain)
|
||||||
|
assertEquals("$prefix: json", v.getString("json"), ownJson)
|
||||||
|
assertArrayEquals("$prefix: magic", if (m.version == 2) "SVM2".toByteArray() else "{\"v".toByteArray(), plain.copyOf(if (m.version == 2) 4 else 3))
|
||||||
|
if (m.version == 1) assertEquals("$prefix: plaintext", v.getString("plaintext"), toHex(plain))
|
||||||
|
val sealed = sealObjectWithNonce(keys.contentKey, keys.vaultId, fromHex(v.getString("plaintext")), fromHex(v.getString("nonce")))
|
||||||
|
assertEquals("$prefix: wire", v.getString("wire"), toHex(sealed.bytes))
|
||||||
|
assertEquals("$prefix: hash", v.getString("hash"), sealed.hash)
|
||||||
|
assertEquals("$prefix: round trip", m, decodeManifest(plain))
|
||||||
|
}
|
||||||
|
val v2 = byPrefix("vault-v2 manifest v2").single()
|
||||||
|
val json = String(inflateRaw(fromHex(v2.getString("plaintext")).copyOfRange(4, fromHex(v2.getString("plaintext")).size), 1 shl 20))
|
||||||
|
assertEquals(v2.getString("json"), json)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun manifestRefusesUnknownVersion() {
|
||||||
|
for (bad in listOf("""{"version":3,"seq":1,"at":1,"entries":[]}""", """{"version":"2","seq":1,"at":1,"entries":[]}""", """{"seq":1,"at":1,"entries":[]}""")) {
|
||||||
|
assertThrows(bad, VaultFormatException::class.java) { decodeManifest(bad.toByteArray()) }
|
||||||
|
}
|
||||||
|
val v3 = byteArrayOf(0x53, 0x56, 0x4d, 0x32) + deflateRaw("""{"version":3,"seq":1,"at":1,"entries":[]}""".toByteArray())
|
||||||
|
assertThrows(VaultFormatException::class.java) { decodeManifest(v3) }
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun freshSealOpensAndRoundTripsAManifest() {
|
||||||
|
val m = manifestFrom(byPrefix("vault-v2 manifest v2").single().getJSONObject("manifest"))
|
||||||
|
val a = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
|
||||||
|
val b = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
|
||||||
|
// Fresh nonce: same plaintext, different names — why unchanged entries are reused, not re-sealed.
|
||||||
|
assertFalse(a.hash == b.hash)
|
||||||
|
assertEquals(m, openManifest(crypto, keys.contentKey, keys.vaultId, a.hash, a.bytes))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Signing ─────────────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun signedBodiesMatchVectors() {
|
||||||
|
for (v in byPrefix("vault-v2 signed")) {
|
||||||
|
val what = v.getString("description")
|
||||||
|
@Suppress("UNCHECKED_CAST")
|
||||||
|
val body = toKotlin(v.getJSONObject("body")) as Map<String, Any>
|
||||||
|
val signed = signPayload(crypto, keys.signingSeed, body, v.getLong("signedAt"))
|
||||||
|
assertEquals("$what: canonical", v.getString("canonical"), String(signed.canonical, Charsets.UTF_8))
|
||||||
|
assertEquals("$what: canonicalHex", v.getString("canonicalHex"), toHex(signed.canonical))
|
||||||
|
assertEquals("$what: signature", v.getString("signature"), toHex(signed.signature))
|
||||||
|
|
||||||
|
val wire = JSONObject(signed.json)
|
||||||
|
assertEquals(v.getString("signatureBase64"), wire.getString("signature"))
|
||||||
|
assertEquals(v.getLong("signedAt"), wire.getLong("signedAt"))
|
||||||
|
assertTrue(crypto.verify(keys.publicKey, signed.canonical, Base64.getDecoder().decode(wire.getString("signature"))))
|
||||||
|
|
||||||
|
// The vault helper adds publicKey itself and must land on the same bytes.
|
||||||
|
val withoutKey = body.filterKeys { it != "publicKey" }
|
||||||
|
val viaKeys = signVaultBody(crypto, keys, withoutKey, v.getLong("signedAt"))
|
||||||
|
assertArrayEquals("$what: signVaultBody", signed.canonical, viaKeys.canonical)
|
||||||
|
assertArrayEquals(signed.signature, viaKeys.signature)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Packing rules ───────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun packingRules() {
|
||||||
|
// Empty file: one empty part, never compressed.
|
||||||
|
val empty = packEntry(ByteArray(0))
|
||||||
|
assertNull(empty.enc)
|
||||||
|
assertEquals(1, empty.chunks.size)
|
||||||
|
assertEquals(0, empty.chunks[0].size)
|
||||||
|
|
||||||
|
// Random bytes do not shrink ≥5 %: stored as-is.
|
||||||
|
val random = ByteArray(10_000).also { java.util.Random(7).nextBytes(it) }
|
||||||
|
assertNull(packEntry(random).enc)
|
||||||
|
|
||||||
|
// Exactly at a chunk boundary: no trailing empty part.
|
||||||
|
val twoChunks = packEntry(random, chunkSize = 5_000)
|
||||||
|
assertEquals(2, twoChunks.chunks.size)
|
||||||
|
assertEquals(VAULT_CHUNK_SIZE, 4 * 1024 * 1024)
|
||||||
|
|
||||||
|
// Compressible text compresses and inflates back.
|
||||||
|
val text = "hei hei hei hei\n".repeat(500).toByteArray()
|
||||||
|
val p = packEntry(text)
|
||||||
|
assertEquals("deflate-raw", p.enc)
|
||||||
|
assertArrayEquals(text, inflateRaw(p.stored, text.size.toLong()))
|
||||||
|
|
||||||
|
val magics = listOf(
|
||||||
|
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47),
|
||||||
|
byteArrayOf(0xff.toByte(), 0xd8.toByte(), 0xff.toByte()),
|
||||||
|
"RIFF\u0000\u0000\u0000\u0000WEBP".toByteArray(),
|
||||||
|
"\u0000\u0000\u0000\u0018ftypmp42".toByteArray(),
|
||||||
|
"GIF89a".toByteArray(),
|
||||||
|
byteArrayOf(0x1f, 0x8b.toByte()),
|
||||||
|
"PK\u0003\u0004".toByteArray(),
|
||||||
|
)
|
||||||
|
for (m in magics) {
|
||||||
|
assertTrue(toHex(m), looksCompressed(m))
|
||||||
|
assertNull(packEntry(m + ByteArray(4000)).enc)
|
||||||
|
}
|
||||||
|
assertFalse(looksCompressed("RIFF\u0000\u0000\u0000\u0000WAVE".toByteArray()))
|
||||||
|
assertFalse(looksCompressed("P".toByteArray()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun inflateIsStrictAboutTheStreamEnd() {
|
||||||
|
val text = "abcabcabc-".repeat(1000).toByteArray()
|
||||||
|
val d = deflateRaw(text)
|
||||||
|
assertArrayEquals(text, inflateRaw(d, text.size.toLong()))
|
||||||
|
assertThrows(VaultFormatException::class.java) { inflateRaw(d.copyOf(d.size - 3), text.size.toLong()) }
|
||||||
|
assertThrows(VaultFormatException::class.java) { inflateRaw(d + byteArrayOf(1, 2, 3), text.size.toLong()) }
|
||||||
|
assertThrows(VaultFormatException::class.java) { inflateRaw(d, text.size.toLong() - 1) }
|
||||||
|
assertThrows(VaultFormatException::class.java) { inflateRaw(byteArrayOf(0xff.toByte(), 0xff.toByte(), 0xff.toByte()), 100) }
|
||||||
|
assertArrayEquals(ByteArray(0), inflateRaw(deflateRaw(ByteArray(0)), 0))
|
||||||
|
}
|
||||||
|
}
|
||||||
123
bun.lock
123
bun.lock
@@ -13,11 +13,12 @@
|
|||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"bun-types": "^1.3.11",
|
"bun-types": "^1.3.11",
|
||||||
"fast-check": "^3.22.0",
|
"fast-check": "^3.22.0",
|
||||||
|
"typescript": "7.0.2",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"packages/shade-cli": {
|
"packages/shade-cli": {
|
||||||
"name": "@shade/cli",
|
"name": "@shade/cli",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"bin": {
|
"bin": {
|
||||||
"shade": "src/cli.ts",
|
"shade": "src/cli.ts",
|
||||||
},
|
},
|
||||||
@@ -36,7 +37,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-core": {
|
"packages/shade-core": {
|
||||||
"name": "@shade/core",
|
"name": "@shade/core",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
},
|
},
|
||||||
@@ -49,7 +50,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-crypto-web": {
|
"packages/shade-crypto-web": {
|
||||||
"name": "@shade/crypto-web",
|
"name": "@shade/crypto-web",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/curves": "^2.0.1",
|
"@noble/curves": "^2.0.1",
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
@@ -59,7 +60,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-dashboard": {
|
"packages/shade-dashboard": {
|
||||||
"name": "@shade/dashboard",
|
"name": "@shade/dashboard",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/widgets": "workspace:*",
|
"@shade/widgets": "workspace:*",
|
||||||
"react": "^19.0.0",
|
"react": "^19.0.0",
|
||||||
@@ -74,7 +75,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-files": {
|
"packages/shade-files": {
|
||||||
"name": "@shade/files",
|
"name": "@shade/files",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -101,7 +102,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-inbox": {
|
"packages/shade-inbox": {
|
||||||
"name": "@shade/inbox",
|
"name": "@shade/inbox",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/proto": "workspace:*",
|
"@shade/proto": "workspace:*",
|
||||||
@@ -114,7 +115,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-inbox-server": {
|
"packages/shade-inbox-server": {
|
||||||
"name": "@shade/inbox-server",
|
"name": "@shade/inbox-server",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
@@ -132,7 +133,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-key-transparency": {
|
"packages/shade-key-transparency": {
|
||||||
"name": "@shade/key-transparency",
|
"name": "@shade/key-transparency",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
@@ -144,11 +145,11 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-keychain": {
|
"packages/shade-keychain": {
|
||||||
"name": "@shade/keychain",
|
"name": "@shade/keychain",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
},
|
},
|
||||||
"packages/shade-observability": {
|
"packages/shade-observability": {
|
||||||
"name": "@shade/observability",
|
"name": "@shade/observability",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
},
|
},
|
||||||
@@ -166,7 +167,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-observer": {
|
"packages/shade-observer": {
|
||||||
"name": "@shade/observer",
|
"name": "@shade/observer",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/server": "workspace:*",
|
"@shade/server": "workspace:*",
|
||||||
@@ -178,14 +179,14 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-proto": {
|
"packages/shade-proto": {
|
||||||
"name": "@shade/proto",
|
"name": "@shade/proto",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
"packages/shade-recovery": {
|
"packages/shade-recovery": {
|
||||||
"name": "@shade/recovery",
|
"name": "@shade/recovery",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -198,7 +199,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-sdk": {
|
"packages/shade-sdk": {
|
||||||
"name": "@shade/sdk",
|
"name": "@shade/sdk",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -228,12 +229,14 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-server": {
|
"packages/shade-server": {
|
||||||
"name": "@shade/server",
|
"name": "@shade/server",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/key-transparency": "workspace:*",
|
"@shade/key-transparency": "workspace:*",
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
|
"@shade/storage-sqlite": "workspace:*",
|
||||||
|
"@shade/vault": "workspace:*",
|
||||||
"hono": "^4.12.12",
|
"hono": "^4.12.12",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
@@ -248,7 +251,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-storage-encrypted": {
|
"packages/shade-storage-encrypted": {
|
||||||
"name": "@shade/storage-encrypted",
|
"name": "@shade/storage-encrypted",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
@@ -270,7 +273,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-storage-indexeddb": {
|
"packages/shade-storage-indexeddb": {
|
||||||
"name": "@shade/storage-indexeddb",
|
"name": "@shade/storage-indexeddb",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"idb": "^8.0.3",
|
"idb": "^8.0.3",
|
||||||
@@ -282,7 +285,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-storage-postgres": {
|
"packages/shade-storage-postgres": {
|
||||||
"name": "@shade/storage-postgres",
|
"name": "@shade/storage-postgres",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
@@ -297,17 +300,20 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-storage-sqlite": {
|
"packages/shade-storage-sqlite": {
|
||||||
"name": "@shade/storage-sqlite",
|
"name": "@shade/storage-sqlite",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/server": "workspace:*",
|
"@shade/server": "workspace:*",
|
||||||
},
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@shade/vault": "workspace:*",
|
||||||
|
},
|
||||||
},
|
},
|
||||||
"packages/shade-streams": {
|
"packages/shade-streams": {
|
||||||
"name": "@shade/streams",
|
"name": "@shade/streams",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
@@ -319,7 +325,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transfer": {
|
"packages/shade-transfer": {
|
||||||
"name": "@shade/transfer",
|
"name": "@shade/transfer",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -336,7 +342,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transport": {
|
"packages/shade-transport": {
|
||||||
"name": "@shade/transport",
|
"name": "@shade/transport",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -347,7 +353,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transport-bridge": {
|
"packages/shade-transport-bridge": {
|
||||||
"name": "@shade/transport-bridge",
|
"name": "@shade/transport-bridge",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/server": "workspace:*",
|
"@shade/server": "workspace:*",
|
||||||
@@ -369,16 +375,29 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transport-webrtc": {
|
"packages/shade-transport-webrtc": {
|
||||||
"name": "@shade/transport-webrtc",
|
"name": "@shade/transport-webrtc",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/streams": "workspace:*",
|
"@shade/streams": "workspace:*",
|
||||||
"@shade/transfer": "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": {
|
"packages/shade-widgets": {
|
||||||
"name": "@shade/widgets",
|
"name": "@shade/widgets",
|
||||||
"version": "4.8.5",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/recovery": "workspace:*",
|
"@shade/recovery": "workspace:*",
|
||||||
"@shade/sdk": "workspace:*",
|
"@shade/sdk": "workspace:*",
|
||||||
@@ -603,6 +622,8 @@
|
|||||||
|
|
||||||
"@shade/transport-webrtc": ["@shade/transport-webrtc@workspace:packages/shade-transport-webrtc"],
|
"@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"],
|
"@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=="],
|
"@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=="],
|
"@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=="],
|
"@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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"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=="],
|
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
|
||||||
|
|
||||||
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
|
"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",
|
"name": "shade",
|
||||||
"private": true,
|
"private": true,
|
||||||
"workspaces": ["packages/*"],
|
"workspaces": [
|
||||||
|
"packages/*"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "bun test --recursive",
|
"test": "bun test --recursive",
|
||||||
"test:core": "cd packages/shade-core && bun test",
|
"test:core": "cd packages/shade-core && bun test",
|
||||||
@@ -25,7 +27,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"bun-types": "^1.3.11",
|
"bun-types": "^1.3.11",
|
||||||
"fast-check": "^3.22.0"
|
"fast-check": "^3.22.0",
|
||||||
|
"typescript": "7.0.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/curves": "^2.0.1",
|
"@noble/curves": "^2.0.1",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/cli",
|
"name": "@shade/cli",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/cli.ts",
|
"main": "src/cli.ts",
|
||||||
"bin": {
|
"bin": {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/core",
|
"name": "@shade/core",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "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
|
* Decrypt a sender key message. Verifies signature then advances the
|
||||||
* appropriate chain key.
|
* appropriate chain key.
|
||||||
*
|
*
|
||||||
* Handles out-of-order delivery via skipped-key cache (simpler than Double
|
* Out-of-order delivery is NOT handled: the chain only moves forward and
|
||||||
* Ratchet since there's no DH ratchet).
|
* 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(
|
export async function senderKeyDecrypt(
|
||||||
crypto: CryptoProvider,
|
crypto: CryptoProvider,
|
||||||
|
|||||||
@@ -86,6 +86,14 @@ export class ShadeSessionManager {
|
|||||||
* fully concurrent.
|
* fully concurrent.
|
||||||
*/
|
*/
|
||||||
private readonly peerOpChains = new Map<string, Promise<unknown>>();
|
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(
|
constructor(
|
||||||
private readonly crypto: CryptoProvider,
|
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) */
|
/** Get the event emitter (if observability is enabled) */
|
||||||
getEvents(): ShadeEventEmitter | undefined {
|
getEvents(): ShadeEventEmitter | undefined {
|
||||||
return this.events;
|
return this.events;
|
||||||
@@ -268,6 +316,11 @@ export class ShadeSessionManager {
|
|||||||
*/
|
*/
|
||||||
async resetSession(address: string): Promise<void> {
|
async resetSession(address: string): Promise<void> {
|
||||||
await this.storage.removeSession(address);
|
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 });
|
this.events?.emit('session.removed', { address });
|
||||||
// Note: we keep the trusted identity; new session will verify against it.
|
// 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.bumpPeerIdentityVersion(newLabel);
|
||||||
}
|
}
|
||||||
await this.storage.removeSession(oldLabel);
|
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 });
|
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)
|
// because isTrustedIdentity() compares not retrieves; we just emit the new hash)
|
||||||
await this.storage.saveTrustedIdentity(address, newIdentityKey);
|
await this.storage.saveTrustedIdentity(address, newIdentityKey);
|
||||||
await this.storage.removeSession(address);
|
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) {
|
if (this.events) {
|
||||||
const newHash = await shortHash(this.crypto, newIdentityKey);
|
const newHash = await shortHash(this.crypto, newIdentityKey);
|
||||||
@@ -516,14 +581,19 @@ export class ShadeSessionManager {
|
|||||||
* Subsequent messages are standard RatchetMessages.
|
* Subsequent messages are standard RatchetMessages.
|
||||||
*/
|
*/
|
||||||
async encrypt(address: string, plaintext: string): Promise<ShadeEnvelope> {
|
async encrypt(address: string, plaintext: string): Promise<ShadeEnvelope> {
|
||||||
return this.withSpan('encrypt', address, async () => {
|
// Follow a persisted alias so a caller still holding a first-contact
|
||||||
const session = await this.storage.getSession(address);
|
// label reaches the session that alias moved to — without this, a
|
||||||
if (!session) throw new NoSessionError(address);
|
// 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));
|
const ratchetMsg = await ratchetEncrypt(this.crypto, session, enc.encode(plaintext));
|
||||||
|
|
||||||
this.events?.emit('message.encrypted', {
|
this.events?.emit('message.encrypted', {
|
||||||
address,
|
address: target,
|
||||||
counter: ratchetMsg.counter,
|
counter: ratchetMsg.counter,
|
||||||
ciphertextSize: ratchetMsg.ciphertext.length,
|
ciphertextSize: ratchetMsg.ciphertext.length,
|
||||||
});
|
});
|
||||||
@@ -532,7 +602,7 @@ export class ShadeSessionManager {
|
|||||||
const x3dh = (session as any).__x3dh;
|
const x3dh = (session as any).__x3dh;
|
||||||
if (x3dh) {
|
if (x3dh) {
|
||||||
delete (session as any).__x3dh;
|
delete (session as any).__x3dh;
|
||||||
await this.storage.saveSession(address, session);
|
await this.storage.saveSession(target, session);
|
||||||
|
|
||||||
const preKeyMsg: PreKeyMessage = {
|
const preKeyMsg: PreKeyMessage = {
|
||||||
registrationId: x3dh.registrationId,
|
registrationId: x3dh.registrationId,
|
||||||
@@ -546,16 +616,16 @@ export class ShadeSessionManager {
|
|||||||
type: 'prekey',
|
type: 'prekey',
|
||||||
content: preKeyMsg,
|
content: preKeyMsg,
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
senderAddress: address,
|
senderAddress: target,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
await this.storage.saveSession(address, session);
|
await this.storage.saveSession(target, session);
|
||||||
return {
|
return {
|
||||||
type: 'ratchet',
|
type: 'ratchet',
|
||||||
content: ratchetMsg,
|
content: ratchetMsg,
|
||||||
timestamp: Date.now(),
|
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.
|
* Decrypt a message from a peer. Handles both PreKeyMessage and RatchetMessage.
|
||||||
*/
|
*/
|
||||||
async decrypt(address: string, envelope: ShadeEnvelope): Promise<string> {
|
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') {
|
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 */
|
/** Remove session for a peer */
|
||||||
removeSession(address: string): Promise<void>;
|
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) */
|
/** Check if we trust a remote identity key (for TOFU or pinned keys) */
|
||||||
isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean>;
|
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",
|
"name": "@shade/crypto-web",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -15,6 +15,8 @@ export class MemoryStorage implements StorageProvider {
|
|||||||
private signedPreKeys = new Map<number, SignedPreKey>();
|
private signedPreKeys = new Map<number, SignedPreKey>();
|
||||||
private oneTimePreKeys = new Map<number, OneTimePreKey>();
|
private oneTimePreKeys = new Map<number, OneTimePreKey>();
|
||||||
private sessions = new Map<string, SessionState>();
|
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 trustedIdentities = new Map<string, Uint8Array>();
|
||||||
private retiredIdentities: RetiredIdentity[] = [];
|
private retiredIdentities: RetiredIdentity[] = [];
|
||||||
|
|
||||||
@@ -82,6 +84,22 @@ export class MemoryStorage implements StorageProvider {
|
|||||||
this.sessions.delete(address);
|
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 ────────────────────────────────────────────────
|
// ─── Trust ────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||||
|
|||||||
@@ -59,26 +59,40 @@ describe('Cryptographic Hardening', () => {
|
|||||||
const mismatchAtEnd = new Uint8Array(target);
|
const mismatchAtEnd = new Uint8Array(target);
|
||||||
mismatchAtEnd[len - 1] ^= 0xff;
|
mismatchAtEnd[len - 1] ^= 0xff;
|
||||||
|
|
||||||
// Measure many iterations to get a stable signal
|
const iterations = 20000;
|
||||||
const iterations = 50000;
|
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();
|
// Warm up before measuring anything. The first loop through this code
|
||||||
for (let i = 0; i < iterations; i++) {
|
// pays for JIT compilation that the second one does not, which biased
|
||||||
crypto.constantTimeEqual(target, mismatchAtStart);
|
// 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();
|
// The threshold is unchanged and deliberately so: an early-exit compare
|
||||||
for (let i = 0; i < iterations; i++) {
|
// would take ~256x longer to reach a mismatch in the last byte than the
|
||||||
crypto.constantTimeEqual(target, mismatchAtEnd);
|
// first, on every single round. Nothing about sampling weakens what this
|
||||||
}
|
// catches — it only stops the scheduler from answering for the code.
|
||||||
const timeEnd = performance.now() - start2;
|
expect(median).toBeLessThan(3);
|
||||||
|
|
||||||
// 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);
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/dashboard",
|
"name": "@shade/dashboard",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/files",
|
"name": "@shade/files",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -444,8 +444,12 @@ export function createFilesHttpClient(
|
|||||||
};
|
};
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
// Streamed read — only supported when the queue drainer is wired.
|
// Streamed read — only supported when pull-mode was configured.
|
||||||
if (drainer === null) {
|
// `drainer` is assigned asynchronously after the streams bridge has
|
||||||
|
// subscribed, so checking it here races client construction. The
|
||||||
|
// promise itself is the synchronous configuration signal; awaiting it
|
||||||
|
// also guarantees the drainer has been installed by its `.then()`.
|
||||||
|
if (streamsBridgePromise === null) {
|
||||||
throw new InternalFileError(
|
throw new InternalFileError(
|
||||||
`http RPC client received a streamed read (size ${wire.size}) but is in inline-only mode. Pass { outboundQueueUrl, transferBaseUrl } when constructing the client to enable streamed reads.`,
|
`http RPC client received a streamed read (size ${wire.size}) but is in inline-only mode. Pass { outboundQueueUrl, transferBaseUrl } when constructing the client to enable streamed reads.`,
|
||||||
);
|
);
|
||||||
@@ -507,8 +511,11 @@ export function createFilesHttpClient(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Streamed write — requires the queue drainer + streams-bridge.
|
// Streamed write — requires pull-mode configuration. Do not inspect
|
||||||
if (drainer === null) {
|
// `drainer` as a readiness flag: bridge registration is asynchronous,
|
||||||
|
// and an immediate large write must wait for it instead of being
|
||||||
|
// misclassified as an inline-only client.
|
||||||
|
if (streamsBridgePromise === null) {
|
||||||
throw new ConflictError(
|
throw new ConflictError(
|
||||||
`http RPC client supports inline writes only (≤ ${INLINE_THRESHOLD} bytes). The supplied input was promoted to streams (size ${decision.size ?? 'unknown'}). Pass { outboundQueueUrl, transferBaseUrl } to enable streamed writes.`,
|
`http RPC client supports inline writes only (≤ ${INLINE_THRESHOLD} bytes). The supplied input was promoted to streams (size ${decision.size ?? 'unknown'}). Pass { outboundQueueUrl, transferBaseUrl } to enable streamed writes.`,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import {
|
|||||||
} from '@shade/server';
|
} from '@shade/server';
|
||||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
import { createFilesHttpClient, type FileEntry } from '../../src/index.js';
|
||||||
|
|
||||||
const crypto = new SubtleCryptoProvider();
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
type ShadeInstance = Awaited<ReturnType<typeof createShade>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stand up the full pull-mode rig:
|
* Stand up the full pull-mode rig:
|
||||||
@@ -20,7 +22,8 @@ const crypto = new SubtleCryptoProvider();
|
|||||||
* no inbound listener, streams supported via long-poll.
|
* no inbound listener, streams supported via long-poll.
|
||||||
*/
|
*/
|
||||||
async function setupPullRig(opts: {
|
async function setupPullRig(opts: {
|
||||||
bobHandler: Parameters<NonNullable<Awaited<ReturnType<typeof createShade>>['files']>['serve']>[0];
|
bobHandler: Parameters<NonNullable<ShadeInstance['files']>['serve']>[0];
|
||||||
|
wrapClientShade?: (shade: ShadeInstance) => Parameters<typeof createFilesHttpClient>[0];
|
||||||
}) {
|
}) {
|
||||||
const prekey = createPrekeyServer({
|
const prekey = createPrekeyServer({
|
||||||
crypto,
|
crypto,
|
||||||
@@ -46,7 +49,7 @@ async function setupPullRig(opts: {
|
|||||||
const bobServer = Bun.serve({ port: 0, fetch: app.fetch });
|
const bobServer = Bun.serve({ port: 0, fetch: app.fetch });
|
||||||
const baseUrl = `http://localhost:${bobServer.port}`;
|
const baseUrl = `http://localhost:${bobServer.port}`;
|
||||||
|
|
||||||
const fs = alice.files.httpClient('bob', {
|
const fs = createFilesHttpClient(opts.wrapClientShade?.(alice) ?? alice, 'bob', {
|
||||||
rpcUrl: `${baseUrl}/rpc`,
|
rpcUrl: `${baseUrl}/rpc`,
|
||||||
outboundQueueUrl: `${baseUrl}/queue`,
|
outboundQueueUrl: `${baseUrl}/queue`,
|
||||||
transferBaseUrl: baseUrl,
|
transferBaseUrl: baseUrl,
|
||||||
@@ -70,6 +73,83 @@ async function setupPullRig(opts: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('@shade/files HTTP RPC — pull-mode streams', () => {
|
describe('@shade/files HTTP RPC — pull-mode streams', () => {
|
||||||
|
test('immediate streamed write waits for asynchronous stream-bridge registration', async () => {
|
||||||
|
const payload = new Uint8Array(512 * 1024);
|
||||||
|
for (let i = 0; i < payload.length; i++) payload[i] = (i * 53) & 0xff;
|
||||||
|
|
||||||
|
let releaseRegistration!: () => void;
|
||||||
|
const registrationGate = new Promise<void>((resolve) => {
|
||||||
|
releaseRegistration = resolve;
|
||||||
|
});
|
||||||
|
let registrationStarted!: () => void;
|
||||||
|
const started = new Promise<void>((resolve) => {
|
||||||
|
registrationStarted = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const rig = await setupPullRig({
|
||||||
|
wrapClientShade: (alice) =>
|
||||||
|
new Proxy(alice, {
|
||||||
|
get(target, property) {
|
||||||
|
if (property === 'onIncomingTransfer') {
|
||||||
|
return async (handler: Parameters<typeof target.onIncomingTransfer>[0]) => {
|
||||||
|
registrationStarted();
|
||||||
|
await registrationGate;
|
||||||
|
return await target.onIncomingTransfer(handler);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const value = Reflect.get(target, property, target) as unknown;
|
||||||
|
return typeof value === 'function' ? value.bind(target) : value;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
bobHandler: {
|
||||||
|
write: async (ctx) => {
|
||||||
|
const content = ctx.args.content;
|
||||||
|
if (content.kind !== 'streams') throw new Error('expected streamed content');
|
||||||
|
const reader = content.stream.getReader();
|
||||||
|
let received = 0;
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
received += value?.byteLength ?? 0;
|
||||||
|
}
|
||||||
|
reader.releaseLock();
|
||||||
|
await content.sha256;
|
||||||
|
const entry: FileEntry = {
|
||||||
|
name: 'immediate.bin',
|
||||||
|
kind: 'file',
|
||||||
|
size: received,
|
||||||
|
mtime: Date.now(),
|
||||||
|
metadata: {},
|
||||||
|
};
|
||||||
|
return { entry };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
let settled = false;
|
||||||
|
const write = rig.fs.write('/immediate.bin', payload);
|
||||||
|
void write.then(
|
||||||
|
() => {
|
||||||
|
settled = true;
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
settled = true;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await started;
|
||||||
|
await Bun.sleep(10);
|
||||||
|
expect(settled).toBe(false);
|
||||||
|
|
||||||
|
releaseRegistration();
|
||||||
|
const result = await write;
|
||||||
|
expect(result.entry.size).toBe(payload.byteLength);
|
||||||
|
} finally {
|
||||||
|
releaseRegistration();
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
|
||||||
test('streamed read (4 MiB) via long-poll queue', async () => {
|
test('streamed read (4 MiB) via long-poll queue', async () => {
|
||||||
const payload = new Uint8Array(4 * 1024 * 1024);
|
const payload = new Uint8Array(4 * 1024 * 1024);
|
||||||
for (let i = 0; i < payload.length; i++) payload[i] = (i * 97) & 0xff;
|
for (let i = 0; i < payload.length; i++) payload[i] = (i * 97) & 0xff;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/inbox-server",
|
"name": "@shade/inbox-server",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/inbox",
|
"name": "@shade/inbox",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -409,7 +409,17 @@ export class Inbox {
|
|||||||
});
|
});
|
||||||
if (attempts >= this.maxAttempts) {
|
if (attempts >= this.maxAttempts) {
|
||||||
await this.queueStore.remove(entry.recipientAddress, entry.msgId);
|
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;
|
return count;
|
||||||
|
|||||||
@@ -467,6 +467,58 @@ describe('Inbox orchestrator', () => {
|
|||||||
await aliceInbox.tick();
|
await aliceInbox.tick();
|
||||||
expect(await aliceInbox.pendingCount()).toBe(0);
|
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', () => {
|
describe('tamper detection', () => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/key-transparency",
|
"name": "@shade/key-transparency",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/keychain",
|
"name": "@shade/keychain",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/observability",
|
"name": "@shade/observability",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/observer",
|
"name": "@shade/observer",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/proto",
|
"name": "@shade/proto",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/recovery",
|
"name": "@shade/recovery",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/sdk",
|
"name": "@shade/sdk",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import type { StorageProvider } from '@shade/core';
|
import type { StorageProvider } from '@shade/core';
|
||||||
import { ConfigurationError } from '@shade/core';
|
import { ConfigurationError } from '@shade/core';
|
||||||
import type { ObservabilityHook } from '@shade/observability';
|
import type { ObservabilityHook } from '@shade/observability';
|
||||||
|
import { DEFAULT_REQUEST_TIMEOUT_MS } from '@shade/transport';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Shade SDK configuration.
|
* Shade SDK configuration.
|
||||||
@@ -84,6 +85,29 @@ export interface ShadeConfig {
|
|||||||
* Default: KT verification disabled. Set this to enable.
|
* Default: KT verification disabled. Set this to enable.
|
||||||
*/
|
*/
|
||||||
keyTransparency?: ShadeKTConfig;
|
keyTransparency?: ShadeKTConfig;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* What `initialize()` does about registering with the prekey server.
|
||||||
|
*
|
||||||
|
* - `'await'` (default): wait for it — at most `requestTimeoutMs` — so a
|
||||||
|
* peer can fetch this identity's bundle the moment `createShade`
|
||||||
|
* resolves.
|
||||||
|
* - `'background'`: don't wait. For apps where opening the identity must
|
||||||
|
* not depend on the network, e.g. a local unlock gate.
|
||||||
|
*
|
||||||
|
* Either way a registration that fails is retried in the background with
|
||||||
|
* backoff until it succeeds or `shutdown()` runs.
|
||||||
|
*/
|
||||||
|
registration?: 'await' | 'background';
|
||||||
|
|
||||||
|
/** Every prekey-server request gives up after this many ms. Default 15 000. */
|
||||||
|
requestTimeoutMs?: number;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Fetch for every prekey-server request — to observe the server's
|
||||||
|
* reachability, or to stub the network in tests. Default: global fetch.
|
||||||
|
*/
|
||||||
|
fetch?: typeof fetch;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Public configuration shape for `Shade.keyTransparency`. */
|
/** Public configuration shape for `Shade.keyTransparency`. */
|
||||||
@@ -117,6 +141,9 @@ export interface ResolvedConfig {
|
|||||||
};
|
};
|
||||||
observability?: ObservabilityHook;
|
observability?: ObservabilityHook;
|
||||||
keyTransparency?: ResolvedKTConfig;
|
keyTransparency?: ResolvedKTConfig;
|
||||||
|
registration: 'await' | 'background';
|
||||||
|
requestTimeoutMs: number;
|
||||||
|
fetch?: typeof fetch;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ResolvedKTConfig {
|
export interface ResolvedKTConfig {
|
||||||
@@ -146,8 +173,20 @@ export function resolveConfig(input: ShadeConfig): ResolvedConfig {
|
|||||||
address: input.address,
|
address: input.address,
|
||||||
autoReplenish,
|
autoReplenish,
|
||||||
autoRotate: input.autoRotate ?? false,
|
autoRotate: input.autoRotate ?? false,
|
||||||
|
registration: input.registration ?? 'await',
|
||||||
|
requestTimeoutMs: input.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
if (resolved.registration !== 'await' && resolved.registration !== 'background') {
|
||||||
|
throw new ConfigurationError(`registration must be 'await' or 'background'`);
|
||||||
|
}
|
||||||
|
if (!Number.isFinite(resolved.requestTimeoutMs) || resolved.requestTimeoutMs <= 0) {
|
||||||
|
throw new ConfigurationError('requestTimeoutMs must be a positive number');
|
||||||
|
}
|
||||||
|
if (input.fetch !== undefined) {
|
||||||
|
resolved.fetch = input.fetch;
|
||||||
|
}
|
||||||
|
|
||||||
if (input.observer) {
|
if (input.observer) {
|
||||||
if (!input.observer.token || input.observer.token.length < 16) {
|
if (!input.observer.token || input.observer.token.length < 16) {
|
||||||
throw new ConfigurationError('observer.token must be at least 16 characters');
|
throw new ConfigurationError('observer.token must be at least 16 characters');
|
||||||
|
|||||||
@@ -143,6 +143,9 @@ export interface ShadeUploadOptions extends TransferOptions {
|
|||||||
generateThumbnail?: boolean | ThumbnailGenerationOptions;
|
generateThumbnail?: boolean | ThumbnailGenerationOptions;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Delays between retries of the initial registration; the last repeats. */
|
||||||
|
const REGISTRATION_RETRY_MS: readonly number[] = [5_000, 15_000, 30_000, 60_000];
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* The high-level Shade API.
|
* The high-level Shade API.
|
||||||
*
|
*
|
||||||
@@ -157,6 +160,9 @@ export class Shade {
|
|||||||
private manager!: ShadeSessionManager;
|
private manager!: ShadeSessionManager;
|
||||||
private transport!: ShadeFetchTransport;
|
private transport!: ShadeFetchTransport;
|
||||||
private _background: BackgroundTasks | null = null;
|
private _background: BackgroundTasks | null = null;
|
||||||
|
/** Pending retry of the initial registration; see [retryRegistration]. */
|
||||||
|
private registrationRetry: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private shutDown = false;
|
||||||
private address!: string;
|
private address!: string;
|
||||||
private initialized = false;
|
private initialized = false;
|
||||||
|
|
||||||
@@ -279,28 +285,23 @@ export class Shade {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
this.transport = new ShadeFetchTransport({
|
this.transport = this.makeTransport(identity.signingPrivateKey, ktOpts);
|
||||||
baseUrl: this.config.prekeyServer,
|
|
||||||
crypto: this.crypto,
|
|
||||||
signingPrivateKey: identity.signingPrivateKey,
|
|
||||||
...(ktOpts ? { keyTransparency: ktOpts } : {}),
|
|
||||||
});
|
|
||||||
|
|
||||||
// Step 5: Initial prekeys + register
|
// Step 5: Initial prekeys + register
|
||||||
const otpks = await this.manager.generateOneTimePreKeys(20);
|
const otpks = await this.manager.generateOneTimePreKeys(20);
|
||||||
const bundle = await this.manager.createPreKeyBundle();
|
const bundle = await this.manager.createPreKeyBundle();
|
||||||
|
const publicIdentity = this.manager.getPublicIdentity();
|
||||||
|
const register = () =>
|
||||||
|
this.transport.register(this.address, publicIdentity, bundle.signedPreKey, otpks);
|
||||||
|
|
||||||
|
if (this.config.registration === 'background') {
|
||||||
|
this.retryRegistration(register, 0, 0);
|
||||||
|
} else {
|
||||||
try {
|
try {
|
||||||
await this.transport.register(
|
await register();
|
||||||
this.address,
|
|
||||||
this.manager.getPublicIdentity(),
|
|
||||||
bundle.signedPreKey,
|
|
||||||
otpks,
|
|
||||||
);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.warn(
|
this.retryRegistration(register, 1, undefined, err as Error);
|
||||||
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${(err as Error).message}. Will retry on next replenish.`,
|
}
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Step 6: Background tasks
|
// Step 6: Background tasks
|
||||||
@@ -701,6 +702,22 @@ export class Shade {
|
|||||||
this.decryptChains.delete(oldLabel);
|
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
|
* Accept a peer's rotated identity. Bumps the per-peer identity-version
|
||||||
* counter so any earlier verification automatically goes stale, then
|
* counter so any earlier verification automatically goes stale, then
|
||||||
@@ -726,6 +743,10 @@ export class Shade {
|
|||||||
async rotate(): Promise<void> {
|
async rotate(): Promise<void> {
|
||||||
if (!this.initialized) throw new Error('Not initialized');
|
if (!this.initialized) throw new Error('Not initialized');
|
||||||
|
|
||||||
|
// The initial registration's retry would publish the identity we are
|
||||||
|
// about to replace; this rotation registers the new one itself.
|
||||||
|
this.cancelRegistrationRetry();
|
||||||
|
|
||||||
// Rotate locally first
|
// Rotate locally first
|
||||||
const newBundle = await this.manager.rotateIdentity();
|
const newBundle = await this.manager.rotateIdentity();
|
||||||
|
|
||||||
@@ -733,11 +754,7 @@ export class Shade {
|
|||||||
// signed operations (replenish, delete, register) work
|
// signed operations (replenish, delete, register) work
|
||||||
const identity = await this.storage.getIdentityKeyPair();
|
const identity = await this.storage.getIdentityKeyPair();
|
||||||
if (!identity) throw new Error('Identity missing after rotate');
|
if (!identity) throw new Error('Identity missing after rotate');
|
||||||
this.transport = new ShadeFetchTransport({
|
this.transport = this.makeTransport(identity.signingPrivateKey);
|
||||||
baseUrl: this.config.prekeyServer,
|
|
||||||
crypto: this.crypto,
|
|
||||||
signingPrivateKey: identity.signingPrivateKey,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Re-upload the new bundle
|
// Re-upload the new bundle
|
||||||
await this.transport.register(
|
await this.transport.register(
|
||||||
@@ -806,17 +823,79 @@ export class Shade {
|
|||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
await this.manager.initialize();
|
await this.manager.initialize();
|
||||||
this.transport = new ShadeFetchTransport({
|
// Same reason as in rotate(): the pending retry is for the old identity.
|
||||||
|
this.cancelRegistrationRetry();
|
||||||
|
this.transport = this.makeTransport(restored.signingPrivateKey);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private makeTransport(
|
||||||
|
signingPrivateKey: Uint8Array,
|
||||||
|
keyTransparency?: KTVerifierOptions,
|
||||||
|
): ShadeFetchTransport {
|
||||||
|
return new ShadeFetchTransport({
|
||||||
baseUrl: this.config.prekeyServer,
|
baseUrl: this.config.prekeyServer,
|
||||||
crypto: this.crypto,
|
crypto: this.crypto,
|
||||||
signingPrivateKey: restored.signingPrivateKey,
|
signingPrivateKey,
|
||||||
|
requestTimeoutMs: this.config.requestTimeoutMs,
|
||||||
|
...(this.config.fetch ? { fetch: this.config.fetch } : {}),
|
||||||
|
...(keyTransparency ? { keyTransparency } : {}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Register with the prekey server, retrying with backoff until it works,
|
||||||
|
* the identity changes, or the instance shuts down.
|
||||||
|
*
|
||||||
|
* This used to be one attempt whose failure promised "will retry on next
|
||||||
|
* replenish" — but replenish never registers, so an identity that came
|
||||||
|
* up while the server was unreachable stayed unregistered until the next
|
||||||
|
* restart.
|
||||||
|
*
|
||||||
|
* `attempt` 0 is the first try (no delay unless `delayMs` says so); each
|
||||||
|
* failure moves one step along [REGISTRATION_RETRY_MS].
|
||||||
|
*/
|
||||||
|
private retryRegistration(
|
||||||
|
register: () => Promise<void>,
|
||||||
|
attempt: number,
|
||||||
|
delayMs?: number,
|
||||||
|
lastError?: Error,
|
||||||
|
): void {
|
||||||
|
if (this.shutDown) return;
|
||||||
|
const steps = REGISTRATION_RETRY_MS;
|
||||||
|
const delay = delayMs ?? steps[Math.min(Math.max(attempt - 1, 0), steps.length - 1)] ?? 60_000;
|
||||||
|
if (lastError) {
|
||||||
|
console.warn(
|
||||||
|
`[Shade] Failed to register with prekey server at ${this.config.prekeyServer}: ${lastError.message}. Retrying in ${Math.round(delay / 1000)} s.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.registrationRetry = setTimeout(() => {
|
||||||
|
this.registrationRetry = null;
|
||||||
|
if (this.shutDown) return;
|
||||||
|
register().then(
|
||||||
|
() => {
|
||||||
|
if (attempt > 0) {
|
||||||
|
console.warn(`[Shade] Registered with prekey server at ${this.config.prekeyServer}.`);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
(err: Error) => this.retryRegistration(register, attempt + 1, undefined, err),
|
||||||
|
);
|
||||||
|
}, delay);
|
||||||
|
(this.registrationRetry as unknown as { unref?: () => void }).unref?.();
|
||||||
|
}
|
||||||
|
|
||||||
|
private cancelRegistrationRetry(): void {
|
||||||
|
if (this.registrationRetry !== null) {
|
||||||
|
clearTimeout(this.registrationRetry);
|
||||||
|
this.registrationRetry = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Clean shutdown: stop timers, close storage if it supports it */
|
/** Clean shutdown: stop timers, close storage if it supports it */
|
||||||
async shutdown(): Promise<void> {
|
async shutdown(): Promise<void> {
|
||||||
this._background?.stop();
|
this._background?.stop();
|
||||||
|
this.cancelRegistrationRetry();
|
||||||
|
this.shutDown = true;
|
||||||
if (this.transferEngine !== null) this.transferEngine.destroy();
|
if (this.transferEngine !== null) this.transferEngine.destroy();
|
||||||
if (this.controlChannel !== null) this.controlChannel.destroy();
|
if (this.controlChannel !== null) this.controlChannel.destroy();
|
||||||
if (this.webrtcRuntime !== null) {
|
if (this.webrtcRuntime !== null) {
|
||||||
|
|||||||
@@ -14,8 +14,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
store: new MemoryPrekeyStore(),
|
store: new MemoryPrekeyStore(),
|
||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
});
|
});
|
||||||
const port = 19500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -12,8 +12,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
store: new MemoryPrekeyStore(),
|
store: new MemoryPrekeyStore(),
|
||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
});
|
});
|
||||||
const port = 19500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -36,8 +36,12 @@ async function startServer(): Promise<ServerHandle> {
|
|||||||
blobStore: new MemoryBlobStore(),
|
blobStore: new MemoryBlobStore(),
|
||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
});
|
});
|
||||||
const port = 19000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: app.fetch });
|
// 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 {
|
return {
|
||||||
url: `http://localhost:${port}`,
|
url: `http://localhost:${port}`,
|
||||||
stop: () => handle.stop(true),
|
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,
|
disableRateLimit: true,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
const port = 19500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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 {
|
return {
|
||||||
url: `http://localhost:${port}`,
|
url: `http://localhost:${port}`,
|
||||||
stop: () => handle.stop(),
|
stop: () => handle.stop(),
|
||||||
@@ -162,10 +166,15 @@ describe('createShade — happy path', () => {
|
|||||||
const env3 = await alice.send('bob', 'reply 2');
|
const env3 = await alice.send('bob', 'reply 2');
|
||||||
expect(await bob.receive('alice', env3)).toBe('reply 2');
|
expect(await bob.receive('alice', env3)).toBe('reply 2');
|
||||||
|
|
||||||
// The old fp-label has no session — receive under it would now
|
// V4.12: the fp-label is no longer a dead end. `aliasSession` leaves
|
||||||
// fail. (We don't assert the error shape, only that the label is
|
// a durable binding behind, so a peer that keeps sending under the
|
||||||
// gone.)
|
// first-contact label — which is exactly what a fingerprint-hinted
|
||||||
await expect(alice.receive(fpLabel, env3)).rejects.toThrow();
|
// 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 () => {
|
test('aliasSession refuses to overwrite an existing session', async () => {
|
||||||
|
|||||||
@@ -26,8 +26,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
const port = 21000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,8 +50,12 @@ async function setupRig(): Promise<TestRig> {
|
|||||||
|
|
||||||
// Spin up Bob's HTTP transfer endpoint.
|
// Spin up Bob's HTTP transfer endpoint.
|
||||||
const bobApp = await bob.transferRoute();
|
const bobApp = await bob.transferRoute();
|
||||||
const port = 21500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const bobServer = Bun.serve({ port, fetch: bobApp.fetch });
|
// 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}`;
|
const bobBaseUrl = `http://localhost:${port}`;
|
||||||
|
|
||||||
// Wire up Alice's outgoing transfer routing.
|
// Wire up Alice's outgoing transfer routing.
|
||||||
|
|||||||
@@ -33,8 +33,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
const port = 22000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,8 +53,12 @@ async function setupRig(): Promise<TestRig> {
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
const bobApp = await bob.transferRoute();
|
const bobApp = await bob.transferRoute();
|
||||||
const port = 22500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const bobServer = Bun.serve({ port, fetch: bobApp.fetch });
|
// 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}`;
|
const bobBaseUrl = `http://localhost:${port}`;
|
||||||
|
|
||||||
alice.configureTransfers({
|
alice.configureTransfers({
|
||||||
|
|||||||
@@ -103,8 +103,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
const port = 23000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -127,13 +131,21 @@ async function setupRig(connectTimeoutMs: number): Promise<Rig> {
|
|||||||
bob.configureWebRTC({ factory: broken, connectTimeoutMs });
|
bob.configureWebRTC({ factory: broken, connectTimeoutMs });
|
||||||
|
|
||||||
const bobApp = await bob.transferRoute();
|
const bobApp = await bob.transferRoute();
|
||||||
const bobPort = 23500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const bobServer = Bun.serve({ port: bobPort, fetch: bobApp.fetch });
|
// 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}`);
|
baseUrls.set('bob', `http://localhost:${bobPort}`);
|
||||||
|
|
||||||
const aliceApp = await alice.transferRoute();
|
const aliceApp = await alice.transferRoute();
|
||||||
const alicePort = 24000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const aliceServer = Bun.serve({ port: alicePort, fetch: aliceApp.fetch });
|
// 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}`);
|
baseUrls.set('alice', `http://localhost:${alicePort}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -145,12 +157,18 @@ async function setupRig(connectTimeoutMs: number): Promise<Rig> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
async function teardownRig(rig: Rig): Promise<void> {
|
async function teardownRig(rig: Rig | undefined): Promise<void> {
|
||||||
await rig.alice.shutdown();
|
// Tolerates a rig that never finished being built. When setupRig threw —
|
||||||
await rig.bob.shutdown();
|
// EADDRINUSE, before ports stopped being guessed — this ran anyway and died
|
||||||
rig.bobServerStop();
|
// on `rig.alice`, so one failure became two and the second one, a TypeError
|
||||||
rig.aliceServerStop();
|
// in teardown, is what you saw first. Cleanup must never be the loudest
|
||||||
rig.prekeyStop();
|
// 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 {
|
function hex(b: Uint8Array): string {
|
||||||
|
|||||||
@@ -40,8 +40,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
const port = 22000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -70,13 +74,21 @@ async function setupRig(): Promise<Rig> {
|
|||||||
bob.configureWebRTC({ factory, connectTimeoutMs: 10_000 });
|
bob.configureWebRTC({ factory, connectTimeoutMs: 10_000 });
|
||||||
|
|
||||||
const bobApp = await bob.transferRoute();
|
const bobApp = await bob.transferRoute();
|
||||||
const bobPort = 22500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const bobServer = Bun.serve({ port: bobPort, fetch: bobApp.fetch });
|
// 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 bobBaseUrl = `http://localhost:${bobPort}`;
|
||||||
|
|
||||||
const aliceApp = await alice.transferRoute();
|
const aliceApp = await alice.transferRoute();
|
||||||
const alicePort = 22000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const aliceServer = Bun.serve({ port: alicePort, fetch: aliceApp.fetch });
|
// 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}`;
|
const aliceBaseUrl = `http://localhost:${alicePort}`;
|
||||||
|
|
||||||
baseUrls.set('alice', aliceBaseUrl);
|
baseUrls.set('alice', aliceBaseUrl);
|
||||||
|
|||||||
@@ -44,8 +44,12 @@ async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|||||||
disableRateLimit: true,
|
disableRateLimit: true,
|
||||||
events,
|
events,
|
||||||
});
|
});
|
||||||
const port = 24500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const handle = Bun.serve({ port, fetch: server.fetch });
|
// 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() };
|
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 bobApp = await bob.transferRoute();
|
||||||
const bobPort = 25000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const bobServer = Bun.serve({ port: bobPort, fetch: bobApp.fetch });
|
// 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}`);
|
baseUrls.set('bob', `http://localhost:${bobPort}`);
|
||||||
|
|
||||||
const aliceApp = await alice.transferRoute();
|
const aliceApp = await alice.transferRoute();
|
||||||
const alicePort = 25500 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const aliceServer = Bun.serve({ port: alicePort, fetch: aliceApp.fetch });
|
// 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}`);
|
baseUrls.set('alice', `http://localhost:${alicePort}`);
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -9,10 +9,15 @@ COPY package.json bun.lock tsconfig.json ./
|
|||||||
# Copy all packages the server + observer + dashboard need
|
# Copy all packages the server + observer + dashboard need
|
||||||
COPY packages ./packages
|
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/
|
# 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 ───────────────────────────────────────
|
# ─── Production stage ───────────────────────────────────────
|
||||||
FROM oven/bun:1-alpine
|
FROM oven/bun:1-alpine
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/server",
|
"name": "@shade/server",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
@@ -9,6 +9,8 @@
|
|||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/key-transparency": "workspace:*",
|
"@shade/key-transparency": "workspace:*",
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
|
"@shade/storage-sqlite": "workspace:*",
|
||||||
|
"@shade/vault": "workspace:*",
|
||||||
"hono": "^4.12.12"
|
"hono": "^4.12.12"
|
||||||
},
|
},
|
||||||
"optionalDependencies": {
|
"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` —
|
* also opt the blob store *off* entirely via `SHADE_DISABLE_BLOB=1` —
|
||||||
* useful for relays that only want the inbox surface.
|
* 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> }> {
|
async function createBlobStore(): Promise<BlobStore & { close?: () => void | Promise<void> }> {
|
||||||
const sqlitePath = process.env.SHADE_BLOB_DB_PATH;
|
const sqlitePath = process.env.SHADE_BLOB_DB_PATH;
|
||||||
const pgUrl = process.env.SHADE_BLOB_PG_URL ?? process.env.SHADE_PREKEY_PG_URL;
|
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' });
|
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 ──────────────────────────
|
// ─── Optional: Observer + Dashboard ──────────────────────────
|
||||||
|
|
||||||
const observerToken = process.env.SHADE_OBSERVER_TOKEN;
|
const observerToken = process.env.SHADE_OBSERVER_TOKEN;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-encrypted",
|
"name": "@shade/storage-encrypted",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -34,12 +34,16 @@ export {
|
|||||||
deriveBlobSlotId,
|
deriveBlobSlotId,
|
||||||
deriveBlobKey,
|
deriveBlobKey,
|
||||||
deriveBlobSigningSeed,
|
deriveBlobSigningSeed,
|
||||||
|
deriveVaultId,
|
||||||
|
deriveVaultContentKey,
|
||||||
|
deriveVaultSigningSeed,
|
||||||
} from './crypto/kdf.js';
|
} from './crypto/kdf.js';
|
||||||
export {
|
export {
|
||||||
AEAD_NONCE_LEN,
|
AEAD_NONCE_LEN,
|
||||||
AEAD_TAG_LEN,
|
AEAD_TAG_LEN,
|
||||||
aeadSeal,
|
aeadSeal,
|
||||||
aeadOpen,
|
aeadOpen,
|
||||||
|
randomNonce,
|
||||||
} from './crypto/aead.js';
|
} from './crypto/aead.js';
|
||||||
export {
|
export {
|
||||||
COL,
|
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.
|
* A fresh random 12-byte nonce.
|
||||||
* Returns `nonce || ct||tag` as a single Uint8Array suitable for direct
|
*
|
||||||
* BLOB storage.
|
* 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(
|
export async function aeadSeal(
|
||||||
key: Uint8Array,
|
key: Uint8Array,
|
||||||
@@ -58,9 +81,19 @@ export async function aeadSeal(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypt a `nonce || ct||tag` blob. The expected nonce is verified against
|
* Decrypt a `nonce || ct||tag` blob.
|
||||||
* the prefix to detect tampering before we even reach the AEAD; if the
|
*
|
||||||
* caller passes a `expectedNonce`, mismatch throws before SubtleCrypto runs.
|
* 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(
|
export async function aeadOpen(
|
||||||
key: Uint8Array,
|
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
|
* Derive a deterministic 12-byte AEAD nonce from a row key plus (table, pk).
|
||||||
* field key) plus (table, pk) binding. With per-field keys, deterministic
|
*
|
||||||
* nonces are safe because each (key, plaintext) pair appears at most once
|
* @deprecated Unsafe for anything that can be written twice, which is every
|
||||||
* — re-saving the same row reuses the (nonce, key) pair only because the
|
* mutable row. The original rationale held that re-saving a row was fine
|
||||||
* plaintext also changes (chain ratchet, prekey state, etc.). The AAD
|
* "because the plaintext also changes" — but that is precisely the case
|
||||||
* also binds (table, column, pk) so swapping is rejected on decrypt.
|
* 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 {
|
export function deriveNonce(rowKey: Uint8Array, table: string, pk: string): Uint8Array {
|
||||||
const out = hkdfDerive(rowKey, `shade-row-nonce-v1:${table}:${pk}`, 12);
|
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 {
|
export function deriveBlobSigningSeed(masterKey: Uint8Array, app: string): Uint8Array {
|
||||||
return hkdfDerive(masterKey, `shade-blob-sig-v1:${app}`, 32);
|
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,
|
serializeSignedPreKey, deserializeSignedPreKey,
|
||||||
toBase64, fromBase64,
|
toBase64, fromBase64,
|
||||||
} from '@shade/core';
|
} from '@shade/core';
|
||||||
import { aeadOpen, aeadSeal } from './aead.js';
|
import { aeadOpen, aeadSeal, randomNonce } from './aead.js';
|
||||||
import { buildAad, deriveNonce } from './kdf.js';
|
import { buildAad } from './kdf.js';
|
||||||
import type { KeyManager } from './key-manager.js';
|
import type { KeyManager } from './key-manager.js';
|
||||||
|
|
||||||
const TEXT_ENCODER = new TextEncoder();
|
const TEXT_ENCODER = new TextEncoder();
|
||||||
@@ -64,9 +64,8 @@ export async function sealString(
|
|||||||
plaintext: string,
|
plaintext: string,
|
||||||
): Promise<Uint8Array> {
|
): Promise<Uint8Array> {
|
||||||
const key = km.fieldKey(table, column);
|
const key = km.fieldKey(table, column);
|
||||||
const nonce = deriveNonce(key, table, pk);
|
|
||||||
const aad = buildAad(table, column, 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). */
|
/** Decrypt a blob into a string, reconstructing AAD from (table, column, pk). */
|
||||||
@@ -78,9 +77,8 @@ export async function openString(
|
|||||||
blob: Uint8Array,
|
blob: Uint8Array,
|
||||||
): Promise<string> {
|
): Promise<string> {
|
||||||
const key = km.fieldKey(table, column);
|
const key = km.fieldKey(table, column);
|
||||||
const expectedNonce = deriveNonce(key, table, pk);
|
|
||||||
const aad = buildAad(table, column, 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);
|
return TEXT_DECODER.decode(pt);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,9 +91,8 @@ export async function sealBytes(
|
|||||||
plaintext: Uint8Array,
|
plaintext: Uint8Array,
|
||||||
): Promise<Uint8Array> {
|
): Promise<Uint8Array> {
|
||||||
const key = km.fieldKey(table, column);
|
const key = km.fieldKey(table, column);
|
||||||
const nonce = deriveNonce(key, table, pk);
|
|
||||||
const aad = buildAad(table, column, pk);
|
const aad = buildAad(table, column, pk);
|
||||||
return aeadSeal(key, nonce, plaintext, aad);
|
return aeadSeal(key, randomNonce(), plaintext, aad);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Decrypt arbitrary bytes payload. */
|
/** Decrypt arbitrary bytes payload. */
|
||||||
@@ -107,9 +104,8 @@ export async function openBytes(
|
|||||||
blob: Uint8Array,
|
blob: Uint8Array,
|
||||||
): Promise<Uint8Array> {
|
): Promise<Uint8Array> {
|
||||||
const key = km.fieldKey(table, column);
|
const key = km.fieldKey(table, column);
|
||||||
const expectedNonce = deriveNonce(key, table, pk);
|
|
||||||
const aad = buildAad(table, column, pk);
|
const aad = buildAad(table, column, pk);
|
||||||
return aeadOpen(key, blob, aad, expectedNonce);
|
return aeadOpen(key, blob, aad);
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── Typed encoders for each StorageProvider entity ──────────────────────
|
// ─── Typed encoders for each StorageProvider entity ──────────────────────
|
||||||
|
|||||||
@@ -19,12 +19,16 @@ export {
|
|||||||
deriveBlobSlotId,
|
deriveBlobSlotId,
|
||||||
deriveBlobKey,
|
deriveBlobKey,
|
||||||
deriveBlobSigningSeed,
|
deriveBlobSigningSeed,
|
||||||
|
deriveVaultId,
|
||||||
|
deriveVaultContentKey,
|
||||||
|
deriveVaultSigningSeed,
|
||||||
} from './crypto/kdf.js';
|
} from './crypto/kdf.js';
|
||||||
export {
|
export {
|
||||||
AEAD_NONCE_LEN,
|
AEAD_NONCE_LEN,
|
||||||
AEAD_TAG_LEN,
|
AEAD_TAG_LEN,
|
||||||
aeadSeal,
|
aeadSeal,
|
||||||
aeadOpen,
|
aeadOpen,
|
||||||
|
randomNonce,
|
||||||
} from './crypto/aead.js';
|
} from './crypto/aead.js';
|
||||||
export { EncryptedSQLiteStorage } from './storage/encrypted-sqlite.js';
|
export { EncryptedSQLiteStorage } from './storage/encrypted-sqlite.js';
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -100,6 +100,10 @@ export class EncryptedIndexedDBStorage implements StorageProvider {
|
|||||||
});
|
});
|
||||||
members.createIndex('byChannelId', 'channelId');
|
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);
|
const store = new EncryptedIndexedDBStorage(db, opts.keyManager);
|
||||||
@@ -212,6 +216,27 @@ export class EncryptedIndexedDBStorage implements StorageProvider {
|
|||||||
await this.db.delete('sessions_enc', address);
|
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 ─────────────────────────────────────────────────
|
// ─── Trust ─────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||||
@@ -466,7 +491,7 @@ export class EncryptedIndexedDBStorage implements StorageProvider {
|
|||||||
|
|
||||||
// ─── Schema ────────────────────────────────────────────────
|
// ─── Schema ────────────────────────────────────────────────
|
||||||
|
|
||||||
const SCHEMA_VERSION = 2;
|
const SCHEMA_VERSION = 3;
|
||||||
|
|
||||||
interface MetaRow { key: string; value: string }
|
interface MetaRow { key: string; value: string }
|
||||||
interface IdentityRow { id: 1; ciphertext: Uint8Array }
|
interface IdentityRow { id: 1; ciphertext: Uint8Array }
|
||||||
@@ -522,6 +547,11 @@ interface EncryptedShadeSchema extends DBSchema {
|
|||||||
signed_prekeys_enc: { key: number; value: SignedPreKeyRow };
|
signed_prekeys_enc: { key: number; value: SignedPreKeyRow };
|
||||||
one_time_prekeys_enc: { key: number; value: OneTimePreKeyRow };
|
one_time_prekeys_enc: { key: number; value: OneTimePreKeyRow };
|
||||||
sessions_enc: { key: string; value: SessionRow };
|
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 };
|
trusted_identities_enc: { key: string; value: TrustedIdentityRow };
|
||||||
retired_identities_enc: {
|
retired_identities_enc: {
|
||||||
key: number;
|
key: number;
|
||||||
|
|||||||
@@ -183,6 +183,30 @@ export class EncryptedPostgresStorage implements StorageProvider {
|
|||||||
await this.sql`DELETE FROM shade_sessions_enc WHERE address = ${address}`;
|
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 ─────────────────────────────────────────────────
|
// ─── Trust ─────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||||
@@ -515,6 +539,16 @@ export async function ensureEncryptedClientTables(sql: Sql): Promise<void> {
|
|||||||
ciphertext BYTEA NOT NULL
|
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`
|
await sql`
|
||||||
CREATE TABLE IF NOT EXISTS shade_trusted_identities_enc (
|
CREATE TABLE IF NOT EXISTS shade_trusted_identities_enc (
|
||||||
address TEXT PRIMARY KEY,
|
address TEXT PRIMARY KEY,
|
||||||
|
|||||||
@@ -52,6 +52,9 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
|||||||
getSession: ReturnType<Database['prepare']>;
|
getSession: ReturnType<Database['prepare']>;
|
||||||
saveSession: ReturnType<Database['prepare']>;
|
saveSession: ReturnType<Database['prepare']>;
|
||||||
removeSession: ReturnType<Database['prepare']>;
|
removeSession: ReturnType<Database['prepare']>;
|
||||||
|
getSessionAlias: ReturnType<Database['prepare']>;
|
||||||
|
saveSessionAlias: ReturnType<Database['prepare']>;
|
||||||
|
removeAliasesFor: ReturnType<Database['prepare']>;
|
||||||
getTrust: ReturnType<Database['prepare']>;
|
getTrust: ReturnType<Database['prepare']>;
|
||||||
saveTrust: ReturnType<Database['prepare']>;
|
saveTrust: ReturnType<Database['prepare']>;
|
||||||
addRetired: ReturnType<Database['prepare']>;
|
addRetired: ReturnType<Database['prepare']>;
|
||||||
@@ -134,6 +137,15 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
|||||||
address TEXT PRIMARY KEY,
|
address TEXT PRIMARY KEY,
|
||||||
ciphertext BLOB NOT NULL
|
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 (
|
CREATE TABLE IF NOT EXISTS trusted_identities_enc (
|
||||||
address TEXT PRIMARY KEY,
|
address TEXT PRIMARY KEY,
|
||||||
ciphertext BLOB NOT NULL
|
ciphertext BLOB NOT NULL
|
||||||
@@ -203,6 +215,9 @@ export class EncryptedSQLiteStorage implements StorageProvider {
|
|||||||
getSession: this.db.prepare('SELECT ciphertext FROM sessions_enc WHERE address = ?'),
|
getSession: this.db.prepare('SELECT ciphertext FROM sessions_enc WHERE address = ?'),
|
||||||
saveSession: this.db.prepare('INSERT OR REPLACE INTO sessions_enc (address, ciphertext) VALUES (?, ?)'),
|
saveSession: this.db.prepare('INSERT OR REPLACE INTO sessions_enc (address, ciphertext) VALUES (?, ?)'),
|
||||||
removeSession: this.db.prepare('DELETE FROM sessions_enc WHERE address = ?'),
|
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 = ?'),
|
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 (?, ?)'),
|
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 (?, ?)'),
|
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);
|
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 ─────────────────────────────────────────────────
|
// ─── Trust ─────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
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",
|
"name": "@shade/storage-indexeddb",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -74,6 +74,10 @@ export class IndexedDBStorage implements StorageProvider {
|
|||||||
const members = db.createObjectStore('broadcastMembers', { keyPath: ['channelId', 'peerAddress'] });
|
const members = db.createObjectStore('broadcastMembers', { keyPath: ['channelId', 'peerAddress'] });
|
||||||
members.createIndex('byChannelId', 'channelId');
|
members.createIndex('byChannelId', 'channelId');
|
||||||
}
|
}
|
||||||
|
if (oldVersion < 3) {
|
||||||
|
const aliases = db.createObjectStore('sessionAliases', { keyPath: 'alias' });
|
||||||
|
aliases.createIndex('byCanonical', 'canonical');
|
||||||
|
}
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
return new IndexedDBStorage(db);
|
return new IndexedDBStorage(db);
|
||||||
@@ -174,6 +178,24 @@ export class IndexedDBStorage implements StorageProvider {
|
|||||||
await this.db.delete('sessions', address);
|
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 ────────────────────────────────────────────────
|
// ─── Trust ────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||||
@@ -360,7 +382,7 @@ export class IndexedDBStorage implements StorageProvider {
|
|||||||
|
|
||||||
// ─── Schema ────────────────────────────────────────────────
|
// ─── Schema ────────────────────────────────────────────────
|
||||||
|
|
||||||
const SCHEMA_VERSION = 2;
|
const SCHEMA_VERSION = 3;
|
||||||
|
|
||||||
interface IdentityRow {
|
interface IdentityRow {
|
||||||
id: 1;
|
id: 1;
|
||||||
@@ -390,6 +412,11 @@ interface SessionRow {
|
|||||||
stateJson: string;
|
stateJson: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface SessionAliasRow {
|
||||||
|
alias: string;
|
||||||
|
canonical: string;
|
||||||
|
}
|
||||||
|
|
||||||
interface TrustedIdentityRow {
|
interface TrustedIdentityRow {
|
||||||
address: string;
|
address: string;
|
||||||
identityKey: string;
|
identityKey: string;
|
||||||
@@ -457,6 +484,11 @@ interface ShadeSchema extends DBSchema {
|
|||||||
signedPreKeys: { key: number; value: SignedPreKeyRow };
|
signedPreKeys: { key: number; value: SignedPreKeyRow };
|
||||||
oneTimePreKeys: { key: number; value: OneTimePreKeyRow };
|
oneTimePreKeys: { key: number; value: OneTimePreKeyRow };
|
||||||
sessions: { key: string; value: SessionRow };
|
sessions: { key: string; value: SessionRow };
|
||||||
|
sessionAliases: {
|
||||||
|
key: string;
|
||||||
|
value: SessionAliasRow;
|
||||||
|
indexes: { byCanonical: string };
|
||||||
|
};
|
||||||
trustedIdentities: { key: string; value: TrustedIdentityRow };
|
trustedIdentities: { key: string; value: TrustedIdentityRow };
|
||||||
retiredIdentities: {
|
retiredIdentities: {
|
||||||
key: number;
|
key: number;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-postgres",
|
"name": "@shade/storage-postgres",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -43,6 +43,16 @@ export async function ensureClientTables(sql: Sql): Promise<void> {
|
|||||||
state_json TEXT NOT NULL
|
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`
|
await sql`
|
||||||
CREATE TABLE IF NOT EXISTS shade_trusted_identities (
|
CREATE TABLE IF NOT EXISTS shade_trusted_identities (
|
||||||
address TEXT PRIMARY KEY,
|
address TEXT PRIMARY KEY,
|
||||||
|
|||||||
@@ -160,6 +160,27 @@ export class PostgresStorage implements StorageProvider {
|
|||||||
await this.sql`DELETE FROM shade_sessions WHERE address = ${address}`;
|
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 ────────────────────────────────────────────────
|
// ─── Trust ────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/storage-sqlite",
|
"name": "@shade/storage-sqlite",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
@@ -9,5 +9,8 @@
|
|||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/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 { SqlitePrekeyStore } from './sqlite-prekey-store.js';
|
||||||
export { SqliteInboxStore } from './sqlite-inbox-store.js';
|
export { SqliteInboxStore } from './sqlite-inbox-store.js';
|
||||||
export { SqliteBlobStore } from './sqlite-blob-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']>;
|
getSession: ReturnType<Database['prepare']>;
|
||||||
saveSession: ReturnType<Database['prepare']>;
|
saveSession: ReturnType<Database['prepare']>;
|
||||||
removeSession: ReturnType<Database['prepare']>;
|
removeSession: ReturnType<Database['prepare']>;
|
||||||
|
getSessionAlias: ReturnType<Database['prepare']>;
|
||||||
|
saveSessionAlias: ReturnType<Database['prepare']>;
|
||||||
|
removeAliasesFor: ReturnType<Database['prepare']>;
|
||||||
getTrust: ReturnType<Database['prepare']>;
|
getTrust: ReturnType<Database['prepare']>;
|
||||||
saveTrust: ReturnType<Database['prepare']>;
|
saveTrust: ReturnType<Database['prepare']>;
|
||||||
addRetired: ReturnType<Database['prepare']>;
|
addRetired: ReturnType<Database['prepare']>;
|
||||||
@@ -100,6 +103,12 @@ export class SQLiteStorage implements StorageProvider {
|
|||||||
address TEXT PRIMARY KEY,
|
address TEXT PRIMARY KEY,
|
||||||
state_json TEXT NOT NULL
|
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 (
|
CREATE TABLE IF NOT EXISTS trusted_identities (
|
||||||
address TEXT PRIMARY KEY,
|
address TEXT PRIMARY KEY,
|
||||||
identity_key TEXT NOT NULL
|
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 = ?'),
|
getSession: this.db.prepare('SELECT state_json FROM sessions WHERE address = ?'),
|
||||||
saveSession: this.db.prepare('INSERT OR REPLACE INTO sessions (address, state_json) VALUES (?, ?)'),
|
saveSession: this.db.prepare('INSERT OR REPLACE INTO sessions (address, state_json) VALUES (?, ?)'),
|
||||||
removeSession: this.db.prepare('DELETE FROM sessions WHERE address = ?'),
|
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 = ?'),
|
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 (?, ?)'),
|
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 (?, ?)'),
|
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);
|
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 ────────────────────────────────────────────────
|
// ─── Trust ────────────────────────────────────────────────
|
||||||
|
|
||||||
async isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean> {
|
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",
|
"name": "@shade/streams",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transfer",
|
"name": "@shade/transfer",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -451,7 +451,7 @@ export class TransferEngine {
|
|||||||
for (const q of queues.values()) q.abort(err);
|
for (const q of queues.values()) q.abort(err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
await Promise.all(workers);
|
await settleWorkers(workers);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runRoundRobinUploadResumed(
|
private async runRoundRobinUploadResumed(
|
||||||
@@ -518,7 +518,7 @@ export class TransferEngine {
|
|||||||
for (const q of queues.values()) q.abort(err);
|
for (const q of queues.values()) q.abort(err);
|
||||||
throw 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);
|
for (const q of queues.values()) q.abort(err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
await Promise.all(workers);
|
await settleWorkers(workers);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runRoundRobinUpload(state: OutgoingState): Promise<void> {
|
private async runRoundRobinUpload(state: OutgoingState): Promise<void> {
|
||||||
@@ -851,7 +851,7 @@ export class TransferEngine {
|
|||||||
for (const q of queues.values()) q.abort(err);
|
for (const q of queues.values()) q.abort(err);
|
||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
await Promise.all(workers);
|
await settleWorkers(workers);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async runLaneWorker(
|
private async runLaneWorker(
|
||||||
@@ -1596,3 +1596,25 @@ function snapshotIncomingLanes(
|
|||||||
}
|
}
|
||||||
return out;
|
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',
|
myAddress: 'bob',
|
||||||
});
|
});
|
||||||
const receiverApp = await createTransferRoutes(receiverEngine);
|
const receiverApp = await createTransferRoutes(receiverEngine);
|
||||||
const port = 22000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const server = Bun.serve({ port, fetch: receiverApp.fetch });
|
// 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}`;
|
const baseUrl = `http://localhost:${port}`;
|
||||||
|
|
||||||
// Receiver accepts incoming.
|
// Receiver accepts incoming.
|
||||||
|
|||||||
@@ -39,8 +39,12 @@ describe('WS opt-in transport with HTTP fallback', () => {
|
|||||||
myAddress: 'bob',
|
myAddress: 'bob',
|
||||||
});
|
});
|
||||||
const httpApp = await createTransferRoutes(receiverEngine);
|
const httpApp = await createTransferRoutes(receiverEngine);
|
||||||
const httpPort = 23000 + Math.floor(Math.random() * 500);
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
||||||
const httpServer = Bun.serve({ port: httpPort, fetch: httpApp.fetch });
|
// 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}`;
|
const httpBaseUrl = `http://localhost:${httpPort}`;
|
||||||
cleanups.push(() => httpServer.stop());
|
cleanups.push(() => httpServer.stop());
|
||||||
|
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transport-bridge",
|
"name": "@shade/transport-bridge",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transport-webrtc",
|
"name": "@shade/transport-webrtc",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/transport",
|
"name": "@shade/transport",
|
||||||
"version": "4.11.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -14,6 +14,9 @@ import {
|
|||||||
KTVerificationError,
|
KTVerificationError,
|
||||||
} from '@shade/key-transparency';
|
} from '@shade/key-transparency';
|
||||||
|
|
||||||
|
/** How long any prekey-server request may go unanswered. */
|
||||||
|
export const DEFAULT_REQUEST_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* HTTP transport client for the Shade Prekey Server.
|
* HTTP transport client for the Shade Prekey Server.
|
||||||
*
|
*
|
||||||
@@ -67,15 +70,31 @@ export class ShadeFetchTransport {
|
|||||||
private readonly crypto: CryptoProvider;
|
private readonly crypto: CryptoProvider;
|
||||||
private readonly signingPrivateKey?: Uint8Array;
|
private readonly signingPrivateKey?: Uint8Array;
|
||||||
private readonly kt?: KTVerifierOptions;
|
private readonly kt?: KTVerifierOptions;
|
||||||
|
private readonly fetchImpl: (url: string, init: RequestInit) => Promise<Response>;
|
||||||
|
private readonly requestTimeoutMs: number;
|
||||||
|
|
||||||
constructor(options: {
|
constructor(options: {
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
crypto: CryptoProvider;
|
crypto: CryptoProvider;
|
||||||
signingPrivateKey?: Uint8Array;
|
signingPrivateKey?: Uint8Array;
|
||||||
keyTransparency?: KTVerifierOptions;
|
keyTransparency?: KTVerifierOptions;
|
||||||
|
/**
|
||||||
|
* Fetch for every request. Lets an app observe its server's
|
||||||
|
* reachability, or tests stub the network. Default: global fetch.
|
||||||
|
*/
|
||||||
|
fetch?: typeof fetch;
|
||||||
|
/**
|
||||||
|
* A request with no response by then fails with a `NetworkError`.
|
||||||
|
* Default 15 000. Without it an unreachable server (packets dropped,
|
||||||
|
* not refused) held each call until the kernel gave up on the TCP
|
||||||
|
* handshake — about two minutes on Linux.
|
||||||
|
*/
|
||||||
|
requestTimeoutMs?: number;
|
||||||
}) {
|
}) {
|
||||||
this.baseUrl = options.baseUrl;
|
this.baseUrl = options.baseUrl;
|
||||||
this.crypto = options.crypto;
|
this.crypto = options.crypto;
|
||||||
|
this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
|
||||||
|
this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
||||||
if (options.signingPrivateKey !== undefined) {
|
if (options.signingPrivateKey !== undefined) {
|
||||||
this.signingPrivateKey = options.signingPrivateKey;
|
this.signingPrivateKey = options.signingPrivateKey;
|
||||||
}
|
}
|
||||||
@@ -84,6 +103,22 @@ export class ShadeFetchTransport {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Every request goes through here, so every request has a deadline. */
|
||||||
|
private async request(url: string, init: RequestInit = {}): Promise<Response> {
|
||||||
|
const timeout = AbortSignal.timeout(this.requestTimeoutMs);
|
||||||
|
const signal = init.signal ? AbortSignal.any([init.signal, timeout]) : timeout;
|
||||||
|
try {
|
||||||
|
return await this.fetchImpl(url, { ...init, signal });
|
||||||
|
} catch (err) {
|
||||||
|
if (timeout.aborted && !init.signal?.aborted) {
|
||||||
|
throw new NetworkError(
|
||||||
|
`No response from ${new URL(url).host} within ${this.requestTimeoutMs} ms`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private headers(): Record<string, string> {
|
private headers(): Record<string, string> {
|
||||||
return { 'Content-Type': 'application/json' };
|
return { 'Content-Type': 'application/json' };
|
||||||
}
|
}
|
||||||
@@ -133,7 +168,7 @@ export class ShadeFetchTransport {
|
|||||||
|
|
||||||
const signed = await this.sign(body);
|
const signed = await this.sign(body);
|
||||||
|
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/register`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/register`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
body: JSON.stringify(signed),
|
body: JSON.stringify(signed),
|
||||||
@@ -159,7 +194,7 @@ export class ShadeFetchTransport {
|
|||||||
* direct access to the proof side-channel.
|
* direct access to the proof side-channel.
|
||||||
*/
|
*/
|
||||||
async fetchBundleVerified(address: string): Promise<FetchBundleResult> {
|
async fetchBundleVerified(address: string): Promise<FetchBundleResult> {
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/bundle/${encodeURIComponent(address)}`, {
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
});
|
});
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
@@ -283,7 +318,7 @@ export class ShadeFetchTransport {
|
|||||||
};
|
};
|
||||||
const signed = await this.sign(body);
|
const signed = await this.sign(body);
|
||||||
|
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/replenish`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/replenish`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
body: JSON.stringify(signed),
|
body: JSON.stringify(signed),
|
||||||
@@ -295,7 +330,7 @@ export class ShadeFetchTransport {
|
|||||||
|
|
||||||
/** Get remaining one-time prekey count (anonymous) */
|
/** Get remaining one-time prekey count (anonymous) */
|
||||||
async getKeyCount(address: string): Promise<number> {
|
async getKeyCount(address: string): Promise<number> {
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/count/${encodeURIComponent(address)}`, {
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
});
|
});
|
||||||
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
|
if (!res.ok) throw new NetworkError(`Count failed: ${res.status}`, res.status);
|
||||||
@@ -306,7 +341,7 @@ export class ShadeFetchTransport {
|
|||||||
/** Delete all keys for this identity (signed) */
|
/** Delete all keys for this identity (signed) */
|
||||||
async unregister(address: string): Promise<void> {
|
async unregister(address: string): Promise<void> {
|
||||||
const signed = await this.sign({ address });
|
const signed = await this.sign({ address });
|
||||||
const res = await fetch(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
const res = await this.request(`${this.baseUrl}/v1/keys/${encodeURIComponent(address)}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: this.headers(),
|
headers: this.headers(),
|
||||||
body: JSON.stringify(signed),
|
body: JSON.stringify(signed),
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
export { ShadeFetchTransport } from './fetch-transport.js';
|
export { ShadeFetchTransport, DEFAULT_REQUEST_TIMEOUT_MS } from './fetch-transport.js';
|
||||||
export type { FetchBundleResult, KTVerifierOptions } from './fetch-transport.js';
|
export type { FetchBundleResult, KTVerifierOptions } from './fetch-transport.js';
|
||||||
export { ShadeWebSocket } from './ws-adapter.js';
|
export { ShadeWebSocket } from './ws-adapter.js';
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user