Compare commits
45 Commits
v4.0.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 | |||
| 037f994572 | |||
| 188c3db56a | |||
| 1bd7037a6d | |||
| 80c410f518 | |||
| 3c0db14904 | |||
| a98ea8a1bd | |||
| d47774ef1c | |||
| 8c606ad498 | |||
| 680d6386f3 | |||
| 1fb59a7076 | |||
| 594992a183 | |||
| 8746571d2a | |||
| 2c400d7094 | |||
| 2b1b4d6630 | |||
| dbb3a090d8 | |||
| f5f42fe557 | |||
| b77b7e771c | |||
| 7520b11b25 | |||
| da93b97cce | |||
| 0bdf9e859c | |||
| 70e319fef8 | |||
| f301b391a5 | |||
| 40766c60f4 | |||
| de25b19033 |
@@ -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
|
||||||
|
|||||||
6
.gitignore
vendored
6
.gitignore
vendored
@@ -2,3 +2,9 @@ node_modules/
|
|||||||
dist/
|
dist/
|
||||||
*.tsbuildinfo
|
*.tsbuildinfo
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
**/.tmp-*.db
|
||||||
|
**/.tmp-*.db-shm
|
||||||
|
**/.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
|
||||||
1763
CHANGELOG.md
1763
CHANGELOG.md
File diff suppressed because it is too large
Load Diff
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.
|
||||||
322
README.md
322
README.md
@@ -3,37 +3,82 @@
|
|||||||
End-to-end encryption library implementing the Signal Protocol (X3DH + Double Ratchet) for TypeScript/Bun. Drop into any project — frontend, backend, mobile — to get forward secrecy, post-compromise recovery, and self-healing security.
|
End-to-end encryption library implementing the Signal Protocol (X3DH + Double Ratchet) for TypeScript/Bun. Drop into any project — frontend, backend, mobile — to get forward secrecy, post-compromise recovery, and self-healing security.
|
||||||
|
|
||||||
> **4.0.0 — General Availability.** All V3.1 → V3.12 work is merged,
|
> **4.0.0 — General Availability.** All V3.1 → V3.12 work is merged,
|
||||||
> the cross-platform vector suite is green on TS + Kotlin, the threat
|
> the cross-platform vector suite is green on TS + Kotlin (1000 / 1000
|
||||||
> model has been refreshed for every new surface, and the core stack
|
> + 11 / 11), the threat model has been refreshed for every new
|
||||||
> (X3DH, ratchet, storage encryption, recovery, WebRTC P2P, Key
|
> surface, and the core stack (X3DH, ratchet, storage encryption,
|
||||||
> Transparency) has been packaged for external review. The wire
|
> recovery, WebRTC P2P, Key Transparency) has been packaged for
|
||||||
> format is **unchanged from 0.4.x** — 4.0 peers interoperate with
|
> external review. The wire format is **unchanged from 0.4.x** — 4.0
|
||||||
> 0.4.x peers byte-for-byte. See
|
> peers interoperate with 0.4.x peers byte-for-byte. See
|
||||||
> [MIGRATION.md § 0.3.x → 4.0](./MIGRATION.md#migrating-from-03x-to-40-ga)
|
> [MIGRATION.md § 0.3.x → 4.0](./MIGRATION.md#migrating-from-03x-to-40-ga)
|
||||||
> for the upgrade path and [CHANGELOG.md § 4.0.0](./CHANGELOG.md) for
|
> for the upgrade path and [CHANGELOG.md § 4.0.0](./CHANGELOG.md) for
|
||||||
> the consolidated release notes. Voice / Video have been moved to
|
> the consolidated release notes. Voice / Video have been moved to
|
||||||
> [V5.0](./docs/V5.0.md), to be built on top of the frozen 4.0
|
> [V5.0](./docs/V5.0.md), to be built on top of the frozen 4.0
|
||||||
> baseline.
|
> baseline.
|
||||||
|
|
||||||
|
## Status
|
||||||
|
|
||||||
|
| Area | 4.0 status | Pointers |
|
||||||
|
|------|-----------|----------|
|
||||||
|
| Protocol core (X3DH + ratchet + sender keys) | ✅ Done — frozen | [`packages/shade-core`](./packages/shade-core) |
|
||||||
|
| Storage encryption (V3.2) | ✅ Done — opt-in `EncryptedSQLiteStorage` / `EncryptedPostgresStorage`, key sources: passphrase / OS keychain / app-injected | [`docs/storage-encryption.md`](./docs/storage-encryption.md) |
|
||||||
|
| Fingerprint gates & trust UX (V3.3) | ✅ Done — `Shade.beforeFirstLargeFile / beforeBackupImport / beforeNewDeviceTrust` | [`docs/trust-ux.md`](./docs/trust-ux.md) |
|
||||||
|
| Observability v2 (V3.4) | ✅ Done — OpenTelemetry-shaped events, `/metrics`, observer dashboard | [`docs/observability.md`](./docs/observability.md) |
|
||||||
|
| Android parity & cross-platform CI (V3.5) | ✅ Done — TS + Kotlin vector-gate live; Android `KeystoreStorage` is post-GA | [`android/shade-android/README.md`](./android/shade-android/README.md), [`docs/cross-platform.md`](./docs/cross-platform.md) |
|
||||||
|
| Async store-and-forward (V3.6) | ✅ Done — `@shade/inbox` + `@shade/inbox-server` | [`docs/inbox.md`](./docs/inbox.md) |
|
||||||
|
| Transport bridge (V3.7) | ✅ Done — SSE / long-poll / WS adapters | [`docs/transport.md`](./docs/transport.md) |
|
||||||
|
| Web Workers crypto (V3.8) | ✅ Done — lane keys never cross the thread boundary | [`docs/web-workers.md`](./docs/web-workers.md) |
|
||||||
|
| Rich file metadata + thumbnails (V3.9) | ✅ Done — in `@shade/files` | [`docs/files.md`](./docs/files.md) |
|
||||||
|
| Social key recovery (V3.10) | ✅ Done — Shamir + AEAD-gated reconstruction + guardian widgets | [`docs/recovery.md`](./docs/recovery.md) |
|
||||||
|
| WebRTC P2P transport (V3.11) | ✅ Done — `RTCDataChannel` with `MultiTransportFallback([webrtc, http])` | [`docs/webrtc.md`](./docs/webrtc.md) |
|
||||||
|
| Key Transparency (V3.12) | ✅ Done — opt-in Merkle log, signed STH, witness gossip | [`docs/key-transparency.md`](./docs/key-transparency.md) |
|
||||||
|
| External crypto review | 🟡 Bundle ready — review window open after tag | [`docs/audit/REVIEW-BUNDLE.md`](./docs/audit/REVIEW-BUNDLE.md) |
|
||||||
|
| Soak (≥ 2 weeks under load) | 🟡 Harness shipped — operator runs it | [`scripts/soak.ts`](./scripts/soak.ts) (`bun run soak --hours 336`) |
|
||||||
|
| Voice / Video / Broadcast | 🔜 V5.0 — built on top of frozen 4.0 stack | [`docs/V5.0.md`](./docs/V5.0.md) |
|
||||||
|
|
||||||
## What you get
|
## What you get
|
||||||
|
|
||||||
|
**Protocol core**
|
||||||
- **X3DH** initial key agreement (works asynchronously via prekey bundles)
|
- **X3DH** initial key agreement (works asynchronously via prekey bundles)
|
||||||
- **Double Ratchet** for per-message forward secrecy and post-compromise security
|
- **Double Ratchet** for per-message forward secrecy and post-compromise security
|
||||||
- **Self-authenticated prekey server** (Hono, Docker-ready) with rate limiting, metrics, health checks
|
- **Sender keys** for group ratchet (1:N broadcast key derivation)
|
||||||
- **Persistent storage backends**: SQLite (zero-config) and PostgreSQL (Drizzle)
|
|
||||||
- **Identity rotation** with grace period for old sessions
|
- **Identity rotation** with grace period for old sessions
|
||||||
- **Safety numbers** (Signal-style fingerprints) for out-of-band verification
|
- **Safety numbers** (Signal-style fingerprints) for out-of-band verification
|
||||||
- **Constant-time comparisons** and **memory zeroization** for hardened operation
|
- **Constant-time comparisons** and **memory zeroization** for hardened operation
|
||||||
- **Binary wire format** that's significantly smaller than JSON
|
- **Binary wire format** (`@shade/proto`) — significantly smaller than JSON
|
||||||
|
|
||||||
|
**Storage**
|
||||||
|
- **Persistent backends**: SQLite (zero-config, `bun:sqlite`) and PostgreSQL (Drizzle, FOR UPDATE SKIP LOCKED)
|
||||||
- **Crash-safe** — sessions survive container restarts, power outages, SIGKILL
|
- **Crash-safe** — sessions survive container restarts, power outages, SIGKILL
|
||||||
- **Live observability** — bundled dashboard SPA + embeddable React widgets to see what's happening between every step
|
- **At-rest encryption (V3.2, opt-in)** — AES-256-GCM under per-(table,column) DEKs; key sources: passphrase (scrypt), OS keychain (`@shade/keychain`), or app-injected. Online re-key, no downtime.
|
||||||
- **E2EE file transfers** — multi-lane chunked uploads/downloads with resume, integrity checks, and HTTP/WS fallback (`@shade/streams` + `@shade/transfer`)
|
|
||||||
- **WebRTC P2P transport (V3.11)** — opt-in `RTCDataChannel` upload path with public-STUN defaults, TURN-relay support, glare-safe peer pool, and automatic `MultiTransportFallback` back to HTTP when NAT traversal fails (`@shade/transport-webrtc`, [docs/webrtc.md](./docs/webrtc.md))
|
**Servers**
|
||||||
- **Web Workers crypto** — AEAD, HKDF, HMAC, X25519, Ed25519 and per-lane stream state run in a dedicated worker. 100 MB+ uploads stay smooth without frame drops, lane keys never cross the thread boundary (`@shade/crypto-web/worker`, [docs/web-workers.md](./docs/web-workers.md))
|
- **Self-authenticated prekey server** (`@shade/server`, Hono, Docker-ready) with rate limiting, metrics, health checks
|
||||||
- **E2EE filesystem RPC** — typed `list/stat/mkdir/delete/move/read/write/getThumbnail` + custom ops between peers, with rate-limit, retention, and fingerprint-gate hooks (`@shade/files`)
|
- **Async store-and-forward relay** (`@shade/inbox-server`) — TTL-bound ciphertext blobs, signed PUT/FETCH/ACK, idempotent on `(address, msgId)`, per-recipient quota
|
||||||
- **Async store-and-forward** — deliver to offline recipients via a relay that holds ciphertext-only blobs with TTL, idempotent PUT, signed fetch/ack, and an `onMessageQueued` push-trigger hook (`@shade/inbox` + `@shade/inbox-server`)
|
- **Bridge transports** (`@shade/transport-bridge`) — WS → SSE → long-poll fallback chain for clients that can't keep a WebSocket open. Same `IncomingMessage` shape across all three.
|
||||||
- **Social key recovery** — Shamir-split your identity to `n` guardians; any threshold-many `k` together restore it on a new device. No centralized recovery agent; OOB-fingerprint gate on every guardian release; AES-GCM authenticates the reconstruction (`@shade/recovery` + `<RecoverySetup />` / `<RecoveryRequest />` / `<RecoveryApprove />` widgets, [docs/recovery.md](./docs/recovery.md))
|
- **Standalone container** — one image bundles prekey + inbox + bridge + transfer + KT + observer
|
||||||
- **Key Transparency (V3.12)** — opt-in append-only Merkle log over the prekey server. Every `register` / `delete` becomes a signed leaf; every bundle-fetch carries an inclusion proof; an Ed25519-signed Tree Head ties roots to a fixed `log_id`. A `LightWitness` cross-checks STHs across clients so a malicious server that splits its view or rewrites history is caught (`@shade/key-transparency`, [docs/key-transparency.md](./docs/key-transparency.md))
|
|
||||||
|
**Trust UX**
|
||||||
|
- **Fingerprint gates (V3.3)** — `Shade.beforeFirstLargeFile(threshold, handler)`, `beforeBackupImport`, `beforeNewDeviceTrust`. Gates raise `FingerprintNotVerifiedError` on the operations that matter, default-warn TOFU otherwise.
|
||||||
|
- **`<FingerprintCompare />` / `<FingerprintGate />`** widgets for the matching UI side.
|
||||||
|
|
||||||
|
**File transfer & filesystem**
|
||||||
|
- **E2EE file transfers** (`@shade/streams` + `@shade/transfer`) — multi-lane chunked uploads/downloads with resume, integrity checks (per-lane sha256 + overall sha256), HTTP/WS fallback, `MultiTransportFallback` for N-ary demotion
|
||||||
|
- **WebRTC P2P transport (V3.11, opt-in)** — `RTCDataChannel` chunk path with public-STUN defaults, TURN-relay support, glare-safe peer pool, automatic fallback to HTTP when NAT traversal fails (`@shade/transport-webrtc`)
|
||||||
|
- **Web Workers crypto (V3.8, opt-in)** — AEAD, HKDF, HMAC, X25519, Ed25519 and per-lane stream state run in a dedicated worker. 100 MB+ uploads stay smooth without frame drops; lane keys never cross the thread boundary (`@shade/crypto-web/worker`)
|
||||||
|
- **E2EE filesystem RPC** (`@shade/files`) — typed `list/stat/mkdir/delete/move/read/write/getThumbnail` + custom ops, with rate-limit, retention, fingerprint-gate, and metrics hooks. React hooks under `@shade/files/react`.
|
||||||
|
|
||||||
|
**Recovery**
|
||||||
|
- **Social key recovery (V3.10)** — Shamir-split your identity to `n` guardians; any threshold-many `k` together restore it on a new device. No centralized recovery agent; OOB-fingerprint gate per guardian release; AES-GCM-authenticated reconstruction (`@shade/recovery` + `<RecoverySetup />` / `<RecoveryRequest />` / `<RecoveryApprove />`)
|
||||||
|
|
||||||
|
**Verifiable distribution**
|
||||||
|
- **Key Transparency (V3.12, opt-in)** — append-only Merkle log over the prekey server. Every `register` / `delete` becomes a signed leaf; every bundle-fetch carries an inclusion proof; an Ed25519-signed Tree Head ties roots to a fixed `log_id`. A `LightWitness` cross-checks STHs across clients so a malicious server that splits its view or rewrites history is caught (`@shade/key-transparency`).
|
||||||
|
|
||||||
|
**Observability**
|
||||||
|
- **Live observability** — OpenTelemetry-shaped events, bundled dashboard SPA + embeddable React widgets to see what's happening between every step (`@shade/observability` + `@shade/observer` + `@shade/dashboard`)
|
||||||
|
|
||||||
|
**Tooling**
|
||||||
|
- **CLI** — `shade init` scaffolder, `shade migrate-storage` (V3.2), `shade rotate-storage-key`, `shade fingerprint`, `shade rotate`, `shade peer`, `shade dashboard`, `shade doctor`, `shade backup` (`@shade/cli`)
|
||||||
|
- **Soak harness** — `bun run soak --hours 336` for the 2-week GA-stable window (`scripts/soak.ts`)
|
||||||
|
|
||||||
## Quick start
|
## Quick start
|
||||||
|
|
||||||
@@ -84,7 +129,38 @@ const plaintext = await shade.receive('alice@example.com', incomingEnvelope);
|
|||||||
console.log(await shade.fingerprint);
|
console.log(await shade.fingerprint);
|
||||||
```
|
```
|
||||||
|
|
||||||
Need to ship a file or expose a filesystem to a peer? `Shade.files` is the high-level entrypoint:
|
### Opt-in surfaces (V3.x → 4.0 GA)
|
||||||
|
|
||||||
|
All of these are off by default. Wire them only where you need them.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// V3.3 — Fingerprint gates: enforce verification on the operations that matter
|
||||||
|
shade.beforeFirstLargeFile(10 * 1024 * 1024, async ({ peer, fingerprint }) => {
|
||||||
|
return await ui.confirmSafetyNumberMatches(peer, fingerprint);
|
||||||
|
});
|
||||||
|
shade.beforeBackupImport(async ({ embeddedFingerprint }) => { /* ... */ });
|
||||||
|
shade.beforeNewDeviceTrust(async ({ peer, oldFp, newFp }) => { /* ... */ });
|
||||||
|
|
||||||
|
// V3.8 — Web Workers crypto: opt-in, lane keys stay off the main thread
|
||||||
|
shade.configureWorkerCrypto({
|
||||||
|
workerUrl: new URL('@shade/crypto-web/worker', import.meta.url),
|
||||||
|
});
|
||||||
|
|
||||||
|
// V3.11 — WebRTC P2P transport: file transfers ride RTCDataChannel where NAT allows
|
||||||
|
import { nativeRtcFactory } from '@shade/transport-webrtc';
|
||||||
|
shade.configureWebRTC({
|
||||||
|
factory: nativeRtcFactory(),
|
||||||
|
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
|
||||||
|
});
|
||||||
|
|
||||||
|
// V3.12 — Key Transparency: detect server-side bundle swaps
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://shade.example.com',
|
||||||
|
keyTransparency: { mode: 'observe-strict', logPublicKey: PINNED_KEY_BYTES_32 },
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Files RPC (`@shade/files`)
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
// Server side — Bob exposes a virtual filesystem
|
// Server side — Bob exposes a virtual filesystem
|
||||||
@@ -97,13 +173,13 @@ const stop = await shade.files.serve({
|
|||||||
|
|
||||||
// Client side — Alice consumes Bob's filesystem
|
// Client side — Alice consumes Bob's filesystem
|
||||||
const fs = await shade.files.client('bob');
|
const fs = await shade.files.client('bob');
|
||||||
await fs.write('/photos/cover.png', new Uint8Array(...)); // auto inline/streams
|
await fs.write('/photos/cover.png', new Uint8Array([/* ... */])); // auto inline/streams
|
||||||
const result = await fs.read('/photos/cover.png');
|
const result = await fs.read('/photos/cover.png');
|
||||||
```
|
```
|
||||||
|
|
||||||
Files ≤ 256 KiB ride inline in the RPC envelope; larger files automatically promote to multi-lane `@shade/transfer` streams with sha256 integrity. See [`docs/files.md`](./docs/files.md) for the full API.
|
Files ≤ 256 KiB ride inline in the RPC envelope; larger files automatically promote to multi-lane `@shade/transfer` streams with sha256 integrity. See [`docs/files.md`](./docs/files.md) for the full API.
|
||||||
|
|
||||||
Or use the lower-level packages directly if you need full control:
|
### Lower-level access
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { ShadeSessionManager } from '@shade/core';
|
import { ShadeSessionManager } from '@shade/core';
|
||||||
@@ -117,20 +193,43 @@ const manager = new ShadeSessionManager(
|
|||||||
await manager.initialize();
|
await manager.initialize();
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### At-rest encryption (V3.2)
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { KeyManager, EncryptedSQLiteStorage } from '@shade/storage-encrypted';
|
||||||
|
|
||||||
|
const km = await KeyManager.open({
|
||||||
|
kind: 'passphrase',
|
||||||
|
passphrase: process.env.SHADE_STORAGE_PASSPHRASE!,
|
||||||
|
salt: loadSaltFromDisk(),
|
||||||
|
});
|
||||||
|
const storage = await EncryptedSQLiteStorage.open({
|
||||||
|
dbPath: '/data/shade-client.db',
|
||||||
|
keyManager: km,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
To migrate an existing 0.3.x SQLite DB in place:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
shade migrate-storage \
|
||||||
|
--key-source passphrase \
|
||||||
|
--passphrase "$SHADE_STORAGE_PASSPHRASE" \
|
||||||
|
--salt-file /data/shade-client.db.salt
|
||||||
|
```
|
||||||
|
|
||||||
## Architecture — keys vs. payloads
|
## Architecture — keys vs. payloads
|
||||||
|
|
||||||
Shade splits the network into two planes. The **prekey server** only
|
Shade splits the network into a **public-key plane** (the prekey
|
||||||
sees public keys; **everything else** rides the encrypted Double
|
server) and an **encrypted plane** (everything else). The prekey
|
||||||
Ratchet between peers. If you remember nothing else from this README,
|
server only sees public key material. If you remember nothing else
|
||||||
remember this picture:
|
from this README, remember this picture:
|
||||||
|
|
||||||
```
|
```
|
||||||
Shade Prekey Server (Hono, public keys only)
|
Shade Prekey Container (Hono — public keys only)
|
||||||
│
|
│
|
||||||
POST /v1/keys/register (signed)
|
/v1/keys/* /v1/inbox/* /v1/bridge/* /v1/transfer/*
|
||||||
GET /v1/keys/bundle/:address
|
/v1/kt/* /metrics /healthz /ready
|
||||||
POST /v1/keys/replenish (signed)
|
|
||||||
DELETE /v1/keys/:address (signed)
|
|
||||||
│
|
│
|
||||||
┌──────────────────┴──────────────────┐
|
┌──────────────────┴──────────────────┐
|
||||||
│ │
|
│ │
|
||||||
@@ -142,11 +241,20 @@ remember this picture:
|
|||||||
│◄── Double Ratchet messages ────────►│ ← end-to-end,
|
│◄── Double Ratchet messages ────────►│ ← end-to-end,
|
||||||
│ (ratchet 0x02 / chunks 0x11) │ never on the
|
│ (ratchet 0x02 / chunks 0x11) │ never on the
|
||||||
│ │ prekey server
|
│ │ prekey server
|
||||||
│◄── @shade/transfer chunks ─────────►│
|
│
|
||||||
│ POST /v1/transfer/:id/chunk │ ← peer-to-peer
|
│◄── @shade/transfer chunks ─────────►│ ← peer-to-peer
|
||||||
│ GET /v1/transfer/:id/state │ HTTP, opaque
|
│ POST /v1/transfer/:id/chunk │ HTTP, opaque
|
||||||
│ │ ciphertext
|
│ GET /v1/transfer/:id/state │ ciphertext
|
||||||
|
│
|
||||||
|
│◄── @shade/inbox blobs (offline) ───►│ ← TTL-bound
|
||||||
|
│ POST /v1/inbox/:address │ ciphertext-only
|
||||||
|
│ POST /v1/inbox/:address/fetch │ relay
|
||||||
|
│
|
||||||
|
│◄── @shade/transport-webrtc ────────►│ ← optional P2P
|
||||||
|
│ RTCDataChannel `shade-transfer/v1` │ `MultiTransportFallback`
|
||||||
|
│ │ auto-demotes to HTTP
|
||||||
SQLiteStorage / PostgresStorage SQLiteStorage / PostgresStorage
|
SQLiteStorage / PostgresStorage SQLiteStorage / PostgresStorage
|
||||||
|
+ EncryptedSQLiteStorage (V3.2) + EncryptedSQLiteStorage (V3.2)
|
||||||
(private keys + sessions) (private keys + sessions)
|
(private keys + sessions) (private keys + sessions)
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -155,17 +263,23 @@ remember this picture:
|
|||||||
- Identity public keys (Ed25519 + X25519)
|
- Identity public keys (Ed25519 + X25519)
|
||||||
- Signed prekeys + one-time prekey bundles
|
- Signed prekeys + one-time prekey bundles
|
||||||
- Registration / replenish / delete writes, all Ed25519-signed
|
- Registration / replenish / delete writes, all Ed25519-signed
|
||||||
- Operator-only metrics, `/health`, and the optional observer
|
- (V3.6) Inbox ciphertext blobs with TTL — same container, separate
|
||||||
dashboard
|
routes; the relay only sees `address || msgId || ciphertext-bytes`
|
||||||
|
- (V3.7) Bridge transports (SSE / long-poll / WS) — also delivered by
|
||||||
|
the same Hono app for clients that can't hold a WebSocket
|
||||||
|
- (V3.12, opt-in) KT inclusion proofs + signed tree heads on
|
||||||
|
`/v1/kt/*` — verifiable distribution
|
||||||
|
- Operator-only metrics and the optional observer dashboard
|
||||||
|
|
||||||
### What does **not** go via the prekey server
|
### What does **not** go via the prekey server
|
||||||
|
|
||||||
- **Message plaintext, ever.** Encrypted ratchet envelopes flow peer-
|
- **Message plaintext, ever.** Encrypted ratchet envelopes flow peer-
|
||||||
to-peer over whatever transport you choose (HTTP, WebSocket, your
|
to-peer over whatever transport you choose (HTTP, WebSocket, your
|
||||||
own broker).
|
own broker, or the inbox relay above — which carries ciphertext only).
|
||||||
- **File chunks.** `@shade/transfer` POSTs ciphertext directly to the
|
- **File chunks.** `@shade/transfer` POSTs ciphertext directly to the
|
||||||
receiver's `/v1/transfer/:streamId/chunk` route — the prekey server
|
receiver's `/v1/transfer/:streamId/chunk` route — the prekey server
|
||||||
is not involved.
|
is not involved. With V3.11 + `configureWebRTC()`, chunks ride
|
||||||
|
`RTCDataChannel` peer-to-peer; the relay is bypassed entirely.
|
||||||
- **Identity private keys.** They never leave the device's storage.
|
- **Identity private keys.** They never leave the device's storage.
|
||||||
- **Filesystem RPC.** `@shade/files` rides the Double Ratchet for
|
- **Filesystem RPC.** `@shade/files` rides the Double Ratchet for
|
||||||
control + small payloads, then promotes to direct `@shade/transfer`
|
control + small payloads, then promotes to direct `@shade/transfer`
|
||||||
@@ -176,6 +290,8 @@ remember this picture:
|
|||||||
The prekey server is metadata-bearing (see `THREAT-MODEL.md § 2`):
|
The prekey server is metadata-bearing (see `THREAT-MODEL.md § 2`):
|
||||||
it sees who registers, who fetches whose bundle, and when. It does
|
it sees who registers, who fetches whose bundle, and when. It does
|
||||||
**not** see message contents, transfer contents, or session state.
|
**not** see message contents, transfer contents, or session state.
|
||||||
|
**V3.12 Key Transparency** (opt-in) makes its bundle distribution
|
||||||
|
*verifiable* so a malicious server that swaps a bundle is caught.
|
||||||
|
|
||||||
For the full threat model and mitigations, read
|
For the full threat model and mitigations, read
|
||||||
[THREAT-MODEL.md](./THREAT-MODEL.md). For deployment-time guarantees,
|
[THREAT-MODEL.md](./THREAT-MODEL.md). For deployment-time guarantees,
|
||||||
@@ -183,53 +299,84 @@ read [docs/PRODUCTION-CHECKLIST.md](./docs/PRODUCTION-CHECKLIST.md).
|
|||||||
|
|
||||||
## Packages
|
## Packages
|
||||||
|
|
||||||
|
All packages publish in lockstep at `4.0.0`.
|
||||||
|
|
||||||
| Package | Purpose |
|
| Package | Purpose |
|
||||||
|---------|---------|
|
|---------|---------|
|
||||||
| `@shade/core` | Protocol logic (X3DH, Double Ratchet, session manager, errors, events) |
|
| `@shade/core` | Protocol logic (X3DH, Double Ratchet, sender keys, session manager, errors, events) |
|
||||||
|
| `@shade/proto` | Compact binary wire format (`0x01` PreKeyMessage, `0x02` RatchetMessage, `0x11` StreamChunk) |
|
||||||
| `@shade/crypto-web` | SubtleCrypto + @noble/curves provider, in-memory storage. Includes the V3.8 Web Workers entrypoint (`@shade/crypto-web/worker`) — drop-in `WorkerCryptoProvider` plus `createEncryptStream` / `createDecryptStream` TransformStream factories |
|
| `@shade/crypto-web` | SubtleCrypto + @noble/curves provider, in-memory storage. Includes the V3.8 Web Workers entrypoint (`@shade/crypto-web/worker`) — drop-in `WorkerCryptoProvider` plus `createEncryptStream` / `createDecryptStream` TransformStream factories |
|
||||||
| `@shade/storage-sqlite` | Persistent SQLite storage (zero-config, bun:sqlite) |
|
| `@shade/observability` | OpenTelemetry-shaped event bus consumed by `@shade/observer`, server hooks, and the dashboard |
|
||||||
| `@shade/storage-postgres` | PostgreSQL storage with Drizzle for shared databases |
|
| `@shade/keychain` | OS keychain bindings (libsecret / Keychain / Credential Manager) used by `@shade/storage-encrypted` and the CLI |
|
||||||
| `@shade/server` | Prekey server (Hono routes, auth, rate limit, health, metrics) |
|
| `@shade/key-transparency` | Key Transparency (V3.12) — RFC 6962-style append-only Merkle log, address-index commitment, signed tree heads, and a `LightWitness` for split-view detection. Opt-in on both server and client. |
|
||||||
| `@shade/transport` | HTTP + WebSocket transport wrappers with auto-encryption |
|
| `@shade/storage-sqlite` | Persistent SQLite storage (zero-config, `bun:sqlite`); also ships `SqliteInboxStore` |
|
||||||
|
| `@shade/storage-postgres` | PostgreSQL storage with Drizzle for shared databases; also ships `PostgresInboxStore` + `PostgresKTLogStore` |
|
||||||
|
| `@shade/storage-encrypted` | At-rest encryption (V3.2) — `EncryptedSQLiteStorage` / `EncryptedPostgresStorage`, `KeyManager`, online re-key |
|
||||||
|
| `@shade/streams` | Multi-lane chunk encryption — HKDF-derived per-lane keys, deterministic AES-GCM nonces, streaming SHA-256, file metadata + thumbnails (V3.9) |
|
||||||
|
| `@shade/transport` | HTTP + WebSocket transport wrappers with auto-encryption; KT-verifying `fetchBundleVerified` |
|
||||||
| `@shade/transport-bridge` | WS → SSE → long-poll fallback chain (V3.7) — single `IncomingMessage` shape across transports for clients that can't keep a WebSocket open |
|
| `@shade/transport-bridge` | WS → SSE → long-poll fallback chain (V3.7) — single `IncomingMessage` shape across transports for clients that can't keep a WebSocket open |
|
||||||
| `@shade/transport-webrtc` | V3.11 P2P chunk transport via `RTCDataChannel`. Plugs into `@shade/transfer` as an `ITransferTransport`; signaling rides Shade's own ratchet. Memory factory + native (`globalThis.RTCPeerConnection`) factory included; `MultiTransportFallback([webrtc, http])` wired automatically when `shade.configureWebRTC()` is called. |
|
| `@shade/transport-webrtc` | V3.11 P2P chunk transport via `RTCDataChannel`. Plugs into `@shade/transfer` as an `ITransferTransport`; signaling rides Shade's own ratchet. Memory factory + native (`globalThis.RTCPeerConnection`) factory included; `MultiTransportFallback([webrtc, http])` wired automatically when `shade.configureWebRTC()` is called. |
|
||||||
| `@shade/proto` | Compact binary wire format (smaller than JSON) |
|
| `@shade/server` | Prekey server (Hono routes, auth, rate limit, health, metrics). `createPrekeyServerWithKT(...)` opts into V3.12 KT mode |
|
||||||
| `@shade/streams` | Multi-lane chunk encryption — HKDF-derived per-lane keys, deterministic AES-GCM nonces, streaming SHA-256 |
|
|
||||||
| `@shade/transfer` | Transfer engine on top of streams: parallel lanes, resume, HTTP + WS transport with auto-fallback, integrity verification |
|
|
||||||
| `@shade/files` | Typed E2EE filesystem RPC — list/stat/mkdir/delete/move/read/write/getThumbnail + custom ops, auto inline/streams routing, production hooks (rate limit, retention, fingerprint gate, metrics), React hooks |
|
|
||||||
| `@shade/recovery` | Social key recovery (V3.10) — Shamir-split identity to `n` guardians; threshold-many `k` reconstruct on a new device. AES-GCM-authenticated reconstruction; OOB-fingerprint gate per guardian release |
|
|
||||||
| `@shade/key-transparency` | Key Transparency (V3.12) — RFC 6962-style append-only Merkle log, address-index commitment, signed tree heads, and a `LightWitness` for split-view detection. Opt-in on both server and client. See [docs/key-transparency.md](./docs/key-transparency.md) |
|
|
||||||
| `@shade/inbox-server` | Async store-and-forward relay (V3.6) — Hono routes, signed PUT/FETCH/DELETE, per-recipient TTL + quota, idempotent on `(address, msgId)`. Bundles into the same standalone container as the prekey server |
|
| `@shade/inbox-server` | Async store-and-forward relay (V3.6) — Hono routes, signed PUT/FETCH/DELETE, per-recipient TTL + quota, idempotent on `(address, msgId)`. Bundles into the same standalone container as the prekey server |
|
||||||
| `@shade/inbox` | Inbox client + durable outgoing queue + receive cursor + push-trigger hook (`onMessageQueued`); composes on top of `Shade.send`/`Shade.receive` for offline-recipient delivery |
|
| `@shade/inbox` | Inbox client + durable outgoing queue + receive cursor + push-trigger hook (`onMessageQueued`); composes on top of `Shade.send`/`Shade.receive` for offline-recipient delivery |
|
||||||
|
| `@shade/transfer` | Transfer engine on top of streams: parallel lanes, resume, HTTP + WS transport with auto-fallback, `MultiTransportFallback` (N-ary demotion), integrity verification |
|
||||||
|
| `@shade/files` | Typed E2EE filesystem RPC — list/stat/mkdir/delete/move/read/write/getThumbnail + custom ops, auto inline/streams routing, production hooks (rate limit, retention, fingerprint gate, metrics), React hooks under `@shade/files/react` |
|
||||||
|
| `@shade/recovery` | Social key recovery (V3.10) — Shamir-split identity to `n` guardians; threshold-many `k` reconstruct on a new device. AES-GCM-authenticated reconstruction; OOB-fingerprint gate per guardian release |
|
||||||
| `@shade/observer` | Live debugger backend (snapshot, SSE, dashboard) — see [README](./packages/shade-observer/README.md) |
|
| `@shade/observer` | Live debugger backend (snapshot, SSE, dashboard) — see [README](./packages/shade-observer/README.md) |
|
||||||
| `@shade/widgets` | Embeddable React widgets including transfer uploader/downloader — see [README](./packages/shade-widgets/README.md) |
|
|
||||||
| `@shade/dashboard` | Standalone dashboard SPA bundled into the observer |
|
| `@shade/dashboard` | Standalone dashboard SPA bundled into the observer |
|
||||||
| `@shade/sdk` | High-level wrapper with `createShade()` one-liner, auto-publish, auto-establish, auto-replenish, `Shade.files` namespace |
|
| `@shade/sdk` | High-level wrapper with `createShade()` one-liner, auto-publish, auto-establish, auto-replenish, `Shade.files` namespace, fingerprint gates, KT integration, WebRTC opt-in |
|
||||||
| `@shade/cli` | `shade init` scaffolder + utilities (fingerprint, rotate, peer, dashboard, doctor) |
|
| `@shade/widgets` | Embeddable React widgets — fingerprint compare/gate, recovery setup/request/approve, transfer uploader/downloader, observer panels |
|
||||||
|
| `@shade/cli` | `shade init` scaffolder + utilities (fingerprint, rotate, peer, dashboard, doctor, backup, migrate-storage, rotate-storage-key) |
|
||||||
|
|
||||||
## Shade as a modular toolkit
|
## Shade as a modular toolkit
|
||||||
|
|
||||||
Shade is split into packages so each project can depend on **only what it needs**—encrypted messaging, file transfer, prekey hosting, or lower-level building blocks. You do not need one giant stack for every use case.
|
Shade is split into packages so each project can depend on **only what it needs**—encrypted messaging, file transfer, prekey hosting, social recovery, KT verification, or lower-level building blocks. You do not need one giant stack for every use case.
|
||||||
|
|
||||||
For a **plain-language map** (which packages to add, what the prekey server does vs your own wiring, and where to start in code), see **[docs/SHADE-BY-SCENARIO.md](./docs/SHADE-BY-SCENARIO.md)**.
|
For a **plain-language map** (which packages to add, what the prekey server does vs your own wiring, and where to start in code), see **[docs/SHADE-BY-SCENARIO.md](./docs/SHADE-BY-SCENARIO.md)**.
|
||||||
|
|
||||||
## Publishing
|
## Publishing
|
||||||
|
|
||||||
All packages publish to a self-hosted Gitea npm registry on `gt.zyon.no`.
|
All packages publish to a self-hosted Gitea npm registry on `gt.zyon.no`. The Docker image of the standalone container ships at `gt.zyon.no/stian/shade-prekey:<tag>`.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
# Bump all packages in lockstep
|
# Bump all packages in lockstep
|
||||||
bun run version 1.1.0
|
bun run version 4.0.1
|
||||||
|
|
||||||
# Dry-run (pack all tarballs without publishing)
|
# Dry-run (pack all tarballs without publishing) — no token required
|
||||||
bun run publish:dry
|
bun run publish:dry
|
||||||
|
|
||||||
# Real publish (requires GITEA_TOKEN env var)
|
# Real publish — interactive (prompts for GITEA_TOKEN, checks
|
||||||
|
# registry for conflicts, publishes via scripts/publish-all.ts)
|
||||||
bun run publish:all
|
bun run publish:all
|
||||||
|
|
||||||
# Or via CI: push a git tag v1.1.0 and .gitea/workflows/publish.yml runs
|
# Build + push the standalone Docker image
|
||||||
|
bun run scripts/build-docker.ts -- --tag 4.0.1 --push
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The interactive `scripts/publish-shade.sh` is the human entrypoint;
|
||||||
|
`scripts/publish-all.ts` is the headless variant used by CI and
|
||||||
|
`publish:dry`. They share a single `PACKAGES` list (24 entries at
|
||||||
|
4.0.0) so the two flows can never drift.
|
||||||
|
|
||||||
|
## Soak / GA-stable
|
||||||
|
|
||||||
|
Before tagging `4.0.0` as `latest` and recommending production
|
||||||
|
upgrades, run the combined soak harness for ≥ 2 weeks:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Full GA window (V4.0 §Soak): 14 days × 24 hours
|
||||||
|
bun run soak --hours 336
|
||||||
|
|
||||||
|
# Smoke (~3 minutes — ratchet ping-pong, integrity check)
|
||||||
|
bun run soak:smoke
|
||||||
|
```
|
||||||
|
|
||||||
|
The harness fans out N concurrent ratchet pairs, ping-pongs at
|
||||||
|
~400 ops/sec/pair, and reports cumulative counters every minute.
|
||||||
|
Any exception in any pair is captured and re-raised at shutdown so
|
||||||
|
silent failures cannot hide. Wrap it in `systemd-run --user`,
|
||||||
|
`nohup`, or a Gitea scheduled job for the actual 2-week window.
|
||||||
|
|
||||||
## Security properties
|
## Security properties
|
||||||
|
|
||||||
| Property | Description |
|
| Property | Description |
|
||||||
@@ -242,27 +389,57 @@ bun run publish:all
|
|||||||
| **Memory zeroization** | Key material is zeroed after use (best-effort in JS) |
|
| **Memory zeroization** | Key material is zeroed after use (best-effort in JS) |
|
||||||
| **Identity verification** | Safety numbers (60 digits) for out-of-band comparison |
|
| **Identity verification** | Safety numbers (60 digits) for out-of-band comparison |
|
||||||
| **Identity rotation** | 7-day grace period for old sessions during rotation |
|
| **Identity rotation** | 7-day grace period for old sessions during rotation |
|
||||||
|
| **At-rest encryption** *(V3.2, opt-in)* | AES-256-GCM under per-(table, column) DEKs; AAD binds `(table, column, pk)`; passphrase / OS keychain / app-injected master key; online re-key |
|
||||||
|
| **Fingerprint gates** *(V3.3)* | `Shade.beforeFirstLargeFile / beforeBackupImport / beforeNewDeviceTrust` raise `FingerprintNotVerifiedError` on the operations that matter; defaults to TOFU + warning when no gate is registered |
|
||||||
|
| **Async store-and-forward** *(V3.6)* | Relay only sees `address || msgId || ciphertext`; idempotent PUT; signed FETCH/ACK; TTL-bounded |
|
||||||
|
| **Web-Worker key isolation** *(V3.8)* | Lane keys, identity keys, and ratchet chain keys live inside a dedicated worker; main thread only ferries plaintext via transferable buffers; idle terminate releases worker memory |
|
||||||
|
| **Social key recovery** *(V3.10)* | Shamir over GF(2^8); AEAD-authenticated reconstruction (forged shares fail); guardian-side fingerprint gate before share release |
|
||||||
|
| **WebRTC P2P transport** *(V3.11)* | Same Double Ratchet authenticates SDP/ICE signaling; chunk frames AEAD-bound to `streamId/laneId/seq`; deterministic glare resolution; `MultiTransportFallback` auto-demotes to HTTP |
|
||||||
| **Key Transparency** *(V3.12, opt-in)* | Append-only Merkle log + signed tree heads + witness gossip — split-view and history-rewrite are detected by clients |
|
| **Key Transparency** *(V3.12, opt-in)* | Append-only Merkle log + signed tree heads + witness gossip — split-view and history-rewrite are detected by clients |
|
||||||
|
|
||||||
## Documentation
|
## Documentation
|
||||||
|
|
||||||
|
**Operator + integrator**
|
||||||
|
|
||||||
- [docs/SHADE-BY-SCENARIO.md](./docs/SHADE-BY-SCENARIO.md) — **Modular toolkit**: pick packages by scenario (messages, files, browser, ops)
|
- [docs/SHADE-BY-SCENARIO.md](./docs/SHADE-BY-SCENARIO.md) — **Modular toolkit**: pick packages by scenario (messages, files, browser, ops)
|
||||||
- [docs/PRODUCTION-CHECKLIST.md](./docs/PRODUCTION-CHECKLIST.md) — Pre-flight gates for going to production
|
- [docs/PRODUCTION-CHECKLIST.md](./docs/PRODUCTION-CHECKLIST.md) — Pre-flight gates for going to production
|
||||||
|
- [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md) — Full deployment guide (Docker, env vars, PostgreSQL, backup, Dokploy)
|
||||||
|
- [docs/ROADMAP.md](./docs/ROADMAP.md) — V3.x → 4.0 GA → V5.0 trajectory
|
||||||
|
|
||||||
|
**Per-surface deep-dives**
|
||||||
|
|
||||||
- [docs/files.md](./docs/files.md) — `@shade/files` API + design (filesystem RPC, custom ops, hooks, React)
|
- [docs/files.md](./docs/files.md) — `@shade/files` API + design (filesystem RPC, custom ops, hooks, React)
|
||||||
- [docs/recovery.md](./docs/recovery.md) — `@shade/recovery` social key recovery (V3.10): Shamir setup, guardian-side gates, threshold tuning
|
|
||||||
- [docs/streams.md](./docs/streams.md) — `@shade/streams` + `@shade/transfer` deep dive (incl. hardening + retention)
|
- [docs/streams.md](./docs/streams.md) — `@shade/streams` + `@shade/transfer` deep dive (incl. hardening + retention)
|
||||||
- [docs/inbox.md](./docs/inbox.md) — `@shade/inbox` + `@shade/inbox-server` async store-and-forward relay (V3.6)
|
- [docs/inbox.md](./docs/inbox.md) — `@shade/inbox` + `@shade/inbox-server` async store-and-forward relay (V3.6)
|
||||||
- [docs/transport.md](./docs/transport.md) — `@shade/transport-bridge` SSE / long-poll / WS bridge layer (V3.7)
|
- [docs/transport.md](./docs/transport.md) — `@shade/transport-bridge` SSE / long-poll / WS bridge layer (V3.7)
|
||||||
|
- [docs/web-workers.md](./docs/web-workers.md) — V3.8 Web Workers crypto: setup, bundler recipes (Vite/Webpack/Rollup), Safari notes, lifecycle, threat-model
|
||||||
|
- [docs/recovery.md](./docs/recovery.md) — `@shade/recovery` social key recovery (V3.10): Shamir setup, guardian-side gates, threshold tuning
|
||||||
- [docs/webrtc.md](./docs/webrtc.md) — `@shade/transport-webrtc` P2P transport (V3.11): NAT-traversal, TURN config, glare resolution, wire format, multi-fallback wiring
|
- [docs/webrtc.md](./docs/webrtc.md) — `@shade/transport-webrtc` P2P transport (V3.11): NAT-traversal, TURN config, glare resolution, wire format, multi-fallback wiring
|
||||||
- [docs/key-transparency.md](./docs/key-transparency.md) — `@shade/key-transparency` (V3.12): operator + client onboarding, witness role, recovery procedures
|
- [docs/key-transparency.md](./docs/key-transparency.md) — `@shade/key-transparency` (V3.12): operator + client onboarding, witness role, recovery procedures
|
||||||
- [docs/V3.12-DESIGN.md](./docs/V3.12-DESIGN.md) — V3.12 design notat (threat model, RFC 6962 vs CONIKS choice, freshness model, open-questions resolution)
|
- [docs/storage-encryption.md](./docs/storage-encryption.md) — V3.2 at-rest encryption: design, key sources, rotation
|
||||||
- [docs/web-workers.md](./docs/web-workers.md) — V3.8 Web Workers crypto: setup, bundler recipes (Vite/Webpack/Rollup), Safari notes, lifecycle, threat-model
|
- [docs/trust-ux.md](./docs/trust-ux.md) — V3.3 fingerprint gates: when each fires, handler patterns, widget integration
|
||||||
|
- [docs/observability.md](./docs/observability.md) — V3.4 event bus + dashboard
|
||||||
|
- [docs/cross-platform.md](./docs/cross-platform.md) — V3.5 Android parity + cross-platform vector regime
|
||||||
|
|
||||||
|
**Threat model + audit**
|
||||||
|
|
||||||
- [SECURITY.md](./SECURITY.md) — Reporting vulnerabilities, security policy, threat-/test-matrix
|
- [SECURITY.md](./SECURITY.md) — Reporting vulnerabilities, security policy, threat-/test-matrix
|
||||||
- [THREAT-MODEL.md](./THREAT-MODEL.md) — Honest threat model and assumptions
|
- [THREAT-MODEL.md](./THREAT-MODEL.md) — Honest threat model and assumptions (12 numbered sections + residual-risks table)
|
||||||
|
- [docs/audit/REVIEW-BUNDLE.md](./docs/audit/REVIEW-BUNDLE.md) — External crypto-review entrypoint (scope, build instructions, reporting)
|
||||||
|
- [docs/audit/SCOPE.md](./docs/audit/SCOPE.md) — One-page audit-scope summary
|
||||||
|
|
||||||
|
**Migration + history**
|
||||||
|
|
||||||
|
- [MIGRATION.md](./MIGRATION.md) — How to replace existing crypto with Shade + the [0.3.x → 4.0 upgrade path](./MIGRATION.md#migrating-from-03x-to-40-ga)
|
||||||
|
- [CHANGELOG.md](./CHANGELOG.md) — `4.0.0` GA section + every prior release
|
||||||
|
- [docs/archive/](./docs/archive/) — V2.1 / V2.2 / V2.3 backlog and V3.1 → V3.12 implementation plans (all `Status: Done`)
|
||||||
|
- [docs/V5.0.md](./docs/V5.0.md) — Voice / Video / Broadcast (post-GA, built on the frozen 4.0 stack)
|
||||||
|
|
||||||
|
**Examples**
|
||||||
|
|
||||||
- [examples/](./examples/) — Runnable example applications, including
|
- [examples/](./examples/) — Runnable example applications, including
|
||||||
[`07-streams-upload`](./examples/07-streams-upload) (multi-lane file transfer)
|
[`07-streams-upload`](./examples/07-streams-upload) (multi-lane file transfer)
|
||||||
and [`08-files-browser`](./examples/08-files-browser) (filesystem RPC)
|
and [`08-files-browser`](./examples/08-files-browser) (filesystem RPC)
|
||||||
- [MIGRATION.md](./MIGRATION.md) — How to replace existing crypto with Shade
|
|
||||||
|
|
||||||
## Deployment — one container per project
|
## Deployment — one container per project
|
||||||
|
|
||||||
@@ -274,15 +451,30 @@ docker run -d \
|
|||||||
-v my-project-shade:/data \
|
-v my-project-shade:/data \
|
||||||
-p 3900:3900 \
|
-p 3900:3900 \
|
||||||
-e SHADE_OBSERVER_TOKEN=change-me-to-at-least-16-chars \
|
-e SHADE_OBSERVER_TOKEN=change-me-to-at-least-16-chars \
|
||||||
gt.zyon.no/stian/shade-prekey:latest
|
gt.zyon.no/stian/shade-prekey:4.0.0
|
||||||
```
|
```
|
||||||
|
|
||||||
The container includes:
|
The container includes:
|
||||||
|
|
||||||
- **Prekey server** — `/v1/keys/*` REST API
|
- **Prekey server** — `/v1/keys/*` REST API
|
||||||
- **Observer dashboard** — `/shade-observer/dashboard/` (off unless token is set)
|
- **Inbox relay (V3.6)** — `/v1/inbox/*` async store-and-forward; enable
|
||||||
|
with `SHADE_INBOX_DB_PATH=/data/inbox.db` (or `SHADE_INBOX_PG_URL`).
|
||||||
|
`SHADE_INBOX_PRUNE_INTERVAL_MINUTES` controls TTL prune cadence.
|
||||||
|
- **Bridge transports (V3.7)** — `/v1/bridge/{stream,poll,ws}` SSE +
|
||||||
|
long-poll + WS adapters for clients that can't keep a WebSocket open.
|
||||||
|
- **Transfer routes** — `/v1/transfer/*` chunk + state + control routes
|
||||||
|
for `@shade/transfer`.
|
||||||
|
- **Key Transparency (V3.12)** — `/v1/kt/*` exposes `log_id`, latest +
|
||||||
|
historical STH, and consistency proofs. Enable with
|
||||||
|
`SHADE_KT_*` env vars; off by default.
|
||||||
|
- **Observer dashboard** — `/shade-observer/dashboard/` (off unless
|
||||||
|
`SHADE_OBSERVER_TOKEN` is set)
|
||||||
- **OpenAPI spec** — `/openapi.yaml` and interactive `/docs` viewer
|
- **OpenAPI spec** — `/openapi.yaml` and interactive `/docs` viewer
|
||||||
|
(covers all 27 routes — prekey, inbox, bridge, transfer, KT,
|
||||||
|
observer, `/metrics`, `/healthz`, `/ready`)
|
||||||
- **Prometheus metrics** — `/metrics`
|
- **Prometheus metrics** — `/metrics`
|
||||||
- **Health check** — `/health`
|
- **Health probes** — `/health` (full), `/healthz` (liveness),
|
||||||
|
`/ready` (readiness)
|
||||||
- **Stale cleanup** — purges inactive identities automatically
|
- **Stale cleanup** — purges inactive identities automatically
|
||||||
|
|
||||||
See [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md) for the full deployment guide, environment variables, PostgreSQL config, backup strategy, and Dokploy instructions.
|
See [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md) for the full deployment guide, environment variables, PostgreSQL config, backup strategy, and Dokploy instructions.
|
||||||
|
|||||||
@@ -100,6 +100,9 @@ matrix row in the same change.
|
|||||||
| § 1 Network attacker — replay window | ±5 min `signedAt` enforcement | `packages/shade-server/tests/server.test.ts` (`"rejects registration with stale signedAt"`) |
|
| § 1 Network attacker — replay window | ±5 min `signedAt` enforcement | `packages/shade-server/tests/server.test.ts` (`"rejects registration with stale signedAt"`) |
|
||||||
| § 1 Network attacker — header AAD | Ratchet headers bound to ciphertext | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-streams/tests/tamper.test.ts`, `packages/shade-streams/tests/aead.test.ts` |
|
| § 1 Network attacker — header AAD | Ratchet headers bound to ciphertext | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-streams/tests/tamper.test.ts`, `packages/shade-streams/tests/aead.test.ts` |
|
||||||
| § 1 Network attacker — forward secrecy | DH ratchet step + chain-key zeroize | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-crypto-web/tests/hardening.test.ts` |
|
| § 1 Network attacker — forward secrecy | DH ratchet step + chain-key zeroize | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-crypto-web/tests/hardening.test.ts` |
|
||||||
|
| § 1 Network attacker — streaming sub-session FS/replay (V4.11) | Per-frame Double-Ratchet `seal`/`open`; counter-rewind & replay rejected; in-memory-only (never persisted) | `packages/shade-core/tests/stream.test.ts` (`"R1: replayed / rewound frame is rejected"`, `"R2/R3: long one-directional burst stays correct and memory-bounded"`) |
|
||||||
|
| § 1 Network attacker — streaming handshake auth (V4.11) | Identity-bound 3-DH against parent-session-pinned identities | `packages/shade-core/tests/stream.test.ts` (`"handshake is mutually authenticated against pinned identities"`) |
|
||||||
|
| § 3 Endpoint compromise — streaming sub-session isolation (V4.11) | Stream ratchet derived without touching the stored parent session; zeroized on close | `packages/shade-core/tests/stream.test.ts` (`"R5: opening/using/closing a stream never touches the parent session"`, `"close() zeroizes and blocks further use; idempotent"`) |
|
||||||
| § 2 Compromised prekey server — public-only storage | Prekey store never accepts a private key | `packages/shade-server/tests/server.test.ts`, `packages/shade-storage-sqlite/tests/sqlite-prekey-store.test.ts` |
|
| § 2 Compromised prekey server — public-only storage | Prekey store never accepts a private key | `packages/shade-server/tests/server.test.ts`, `packages/shade-storage-sqlite/tests/sqlite-prekey-store.test.ts` |
|
||||||
| § 2 Compromised prekey server — signed replenish/delete | Per-identity Ed25519 signature | `packages/shade-server/tests/server.test.ts` |
|
| § 2 Compromised prekey server — signed replenish/delete | Per-identity Ed25519 signature | `packages/shade-server/tests/server.test.ts` |
|
||||||
| § 2 Compromised prekey server — fake-bundle detection | Out-of-band fingerprint comparison | `packages/shade-core/tests/fingerprint-session.test.ts` |
|
| § 2 Compromised prekey server — fake-bundle detection | Out-of-band fingerprint comparison | `packages/shade-core/tests/fingerprint-session.test.ts` |
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
plugins {
|
plugins {
|
||||||
kotlin("jvm") version "2.0.20" apply false
|
kotlin("jvm") version "2.0.20" apply false
|
||||||
|
kotlin("android") version "2.0.20" apply false
|
||||||
|
id("com.android.library") version "8.7.3" apply false
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,3 +2,5 @@ org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
|
|||||||
org.gradle.parallel=true
|
org.gradle.parallel=true
|
||||||
org.gradle.caching=true
|
org.gradle.caching=true
|
||||||
kotlin.code.style=official
|
kotlin.code.style=official
|
||||||
|
android.useAndroidX=true
|
||||||
|
android.nonTransitiveRClass=true
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ pluginManagement {
|
|||||||
repositories {
|
repositories {
|
||||||
gradlePluginPortal()
|
gradlePluginPortal()
|
||||||
mavenCentral()
|
mavenCentral()
|
||||||
|
google()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -17,3 +18,6 @@ dependencyResolutionManagement {
|
|||||||
|
|
||||||
include(":shade-android")
|
include(":shade-android")
|
||||||
project(":shade-android").projectDir = file("shade-android")
|
project(":shade-android").projectDir = file("shade-android")
|
||||||
|
|
||||||
|
include(":shade-android-keystore")
|
||||||
|
project(":shade-android-keystore").projectDir = file("shade-android-keystore")
|
||||||
|
|||||||
68
android/shade-android-keystore/README.md
Normal file
68
android/shade-android-keystore/README.md
Normal file
@@ -0,0 +1,68 @@
|
|||||||
|
# shade-android-keystore
|
||||||
|
|
||||||
|
Android-specific bindings for `shade-android`. Lives as a sibling Gradle module so the JVM-only protocol code can keep running in CI without an Android SDK install.
|
||||||
|
|
||||||
|
Provides:
|
||||||
|
|
||||||
|
- **`KeystoreMasterKey`** — hardware-backed AES-256-GCM master key in the Android Keystore. Optionally biometric-gated (BIOMETRIC_STRONG only — Class 3 assurance), StrongBox-backed when available, invalidated on new biometric enrollment.
|
||||||
|
- **`BiometricUnlock`** — coroutine wrapper around `BiometricPrompt` for unlocking a `Cipher` instance bound to the keystore key. Throws `BiometricCancelledException` / `BiometricFailedException` so callers can handle the auth flow without writing custom callbacks.
|
||||||
|
- **`KeystoreStorage`** — `StorageProvider` implementation that persists session/identity/prekey state to `SharedPreferences`, each row encrypted under the keystore key with the row's preference key bound as AAD.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```kotlin
|
||||||
|
import androidx.fragment.app.FragmentActivity
|
||||||
|
import no.zyon.shade.ShadeSessionManager
|
||||||
|
import no.zyon.shade.crypto.TinkProvider
|
||||||
|
import no.zyon.shade.keystore.BiometricUnlock
|
||||||
|
import no.zyon.shade.keystore.KeystoreStorage
|
||||||
|
|
||||||
|
class MyActivity : FragmentActivity() {
|
||||||
|
private val crypto = TinkProvider()
|
||||||
|
private lateinit var storage: KeystoreStorage
|
||||||
|
private lateinit var manager: ShadeSessionManager
|
||||||
|
|
||||||
|
override fun onCreate(savedInstanceState: Bundle?) {
|
||||||
|
super.onCreate(savedInstanceState)
|
||||||
|
|
||||||
|
storage = KeystoreStorage(this, crypto)
|
||||||
|
|
||||||
|
lifecycleScope.launch {
|
||||||
|
val unlock = BiometricUnlock(
|
||||||
|
activity = this@MyActivity,
|
||||||
|
title = "Unlock Shade",
|
||||||
|
subtitle = "Tap your fingerprint to access your messages",
|
||||||
|
)
|
||||||
|
try {
|
||||||
|
storage.unlock(unlock)
|
||||||
|
} catch (e: BiometricCancelledException) {
|
||||||
|
// user backed out — show a "tap to retry" UI
|
||||||
|
return@launch
|
||||||
|
}
|
||||||
|
|
||||||
|
manager = ShadeSessionManager(crypto, storage)
|
||||||
|
manager.initialize()
|
||||||
|
// ... use manager normally
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
For credential-driven bootstrap (V4.9 profile + V4.10 approval), pair this with `no.zyon.shade.blob.createProfileNamespace` and `no.zyon.shade.approval.signProxyApproval` — both pure-JVM (in `:shade-android`).
|
||||||
|
|
||||||
|
## Threat model
|
||||||
|
|
||||||
|
- **Compromised app process**: cannot read the AES key (it's in the secure environment). Can attempt to use the cipher only after the user has authenticated; biometric re-prompts are required after each biometric event.
|
||||||
|
- **Stolen device with known PIN**: cannot unlock — `setUserAuthenticationParameters(0, BIOMETRIC_STRONG)` excludes `DEVICE_CREDENTIAL`.
|
||||||
|
- **Attacker enrolls own biometric**: `setInvalidatedByBiometricEnrollment(true)` invalidates the key on enrollment, forcing a credential rebootstrap (which would need username + password + PIN).
|
||||||
|
- **Catastrophic recovery**: `forgetEverything()` deletes the master key and clears the SharedPreferences. Pair with `Profile.delete()` for full account erasure.
|
||||||
|
|
||||||
|
## Build
|
||||||
|
|
||||||
|
Requires an Android SDK. The Gradle build uses Android Gradle Plugin 8.7+, AGP minSdk 28 (Pie+ for BiometricPrompt baseline), targetSdk 35.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
JAVA_HOME=/path/to/jdk-21 ./gradlew :shade-android-keystore:assembleDebug
|
||||||
|
```
|
||||||
|
|
||||||
|
Unit tests: none yet — `KeystoreStorage` requires Android runtime. Robolectric or instrumented tests against an emulator are tracked as a follow-up. The pure-JVM `SessionStateJson` round-trip serializer is tested in `:shade-android` (`SessionStateJsonTest`).
|
||||||
59
android/shade-android-keystore/build.gradle.kts
Normal file
59
android/shade-android-keystore/build.gradle.kts
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
plugins {
|
||||||
|
id("com.android.library")
|
||||||
|
kotlin("android")
|
||||||
|
}
|
||||||
|
|
||||||
|
// V4.10 — Android-specific KeystoreStorage adapter.
|
||||||
|
//
|
||||||
|
// Lives as a sibling module to `:shade-android` so the JVM-only
|
||||||
|
// protocol code can keep running in CI without an Android SDK.
|
||||||
|
// This module pulls in `:shade-android` for `StorageProvider`,
|
||||||
|
// `IdentityKeyPair`, etc., and binds those types to a hardware-
|
||||||
|
// backed Android Keystore master key with biometric gating.
|
||||||
|
|
||||||
|
android {
|
||||||
|
namespace = "no.zyon.shade.keystore"
|
||||||
|
compileSdk = 35
|
||||||
|
|
||||||
|
defaultConfig {
|
||||||
|
minSdk = 28 // BiometricPrompt + StrongBox baseline
|
||||||
|
}
|
||||||
|
|
||||||
|
compileOptions {
|
||||||
|
sourceCompatibility = JavaVersion.VERSION_17
|
||||||
|
targetCompatibility = JavaVersion.VERSION_17
|
||||||
|
}
|
||||||
|
|
||||||
|
kotlinOptions {
|
||||||
|
jvmTarget = "17"
|
||||||
|
}
|
||||||
|
|
||||||
|
buildTypes {
|
||||||
|
release {
|
||||||
|
isMinifyEnabled = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
testOptions {
|
||||||
|
unitTests.isReturnDefaultValues = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
dependencies {
|
||||||
|
// Sibling: protocol types + StorageProvider interface.
|
||||||
|
api(project(":shade-android"))
|
||||||
|
|
||||||
|
// androidx.biometric — fragment-safe BiometricPrompt wrapper.
|
||||||
|
// 1.2.0-alpha05 is the latest with stable BiometricPrompt API.
|
||||||
|
implementation("androidx.biometric:biometric:1.2.0-alpha05")
|
||||||
|
|
||||||
|
// androidx.fragment — BiometricPrompt requires FragmentActivity.
|
||||||
|
implementation("androidx.fragment:fragment-ktx:1.8.5")
|
||||||
|
|
||||||
|
// Coroutines for the suspend-function StorageProvider implementation.
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
|
||||||
|
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
|
||||||
|
|
||||||
|
testImplementation("junit:junit:4.13.2")
|
||||||
|
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
|
||||||
|
}
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
<?xml version="1.0" encoding="utf-8"?>
|
||||||
|
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />
|
||||||
@@ -0,0 +1,112 @@
|
|||||||
|
package no.zyon.shade.keystore
|
||||||
|
|
||||||
|
import androidx.biometric.BiometricManager
|
||||||
|
import androidx.biometric.BiometricPrompt
|
||||||
|
import androidx.fragment.app.FragmentActivity
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import kotlin.coroutines.resume
|
||||||
|
import kotlin.coroutines.resumeWithException
|
||||||
|
import kotlinx.coroutines.suspendCancellableCoroutine
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Biometric unlock for a `KeystoreMasterKey`-bound `Cipher`.
|
||||||
|
*
|
||||||
|
* The Android keystore enforces that any operation on a
|
||||||
|
* user-authentication-required key must happen via a
|
||||||
|
* `BiometricPrompt.CryptoObject`-wrapped `Cipher`. The user sees a
|
||||||
|
* system biometric prompt; on success the same `Cipher` instance is
|
||||||
|
* usable for one operation (or one streaming session) before
|
||||||
|
* needing to re-prompt.
|
||||||
|
*
|
||||||
|
* This is a thin coroutine wrapper around `BiometricPrompt` that
|
||||||
|
* resolves to the authenticated cipher or throws on user
|
||||||
|
* cancellation. Callers typically run it once at app start to
|
||||||
|
* unlock the master key for the lifetime of the foreground session.
|
||||||
|
*/
|
||||||
|
class BiometricUnlock(
|
||||||
|
private val activity: FragmentActivity,
|
||||||
|
private val title: String,
|
||||||
|
private val subtitle: String? = null,
|
||||||
|
private val negativeButton: String = "Cancel",
|
||||||
|
) {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True if BIOMETRIC_STRONG is currently usable on this device.
|
||||||
|
* False means the user has no enrolled fingerprint/face that
|
||||||
|
* meets the class-3 assurance level — fall back to a credential
|
||||||
|
* recovery flow rather than crashing.
|
||||||
|
*/
|
||||||
|
fun canAuthenticate(): Boolean {
|
||||||
|
val mgr = BiometricManager.from(activity)
|
||||||
|
return mgr.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) ==
|
||||||
|
BiometricManager.BIOMETRIC_SUCCESS
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Show the biometric prompt and return the authenticated cipher.
|
||||||
|
*
|
||||||
|
* Cancellation paths:
|
||||||
|
* - User taps the negative button → throws `BiometricCancelledException`.
|
||||||
|
* - System errors out (e.g. too many failures) → throws
|
||||||
|
* `BiometricFailedException` with the system error code.
|
||||||
|
*/
|
||||||
|
suspend fun unlock(cipher: Cipher): Cipher = suspendCancellableCoroutine { cont ->
|
||||||
|
val callback = object : BiometricPrompt.AuthenticationCallback() {
|
||||||
|
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
|
||||||
|
val authedCipher = result.cryptoObject?.cipher
|
||||||
|
if (authedCipher == null) {
|
||||||
|
cont.resumeWithException(
|
||||||
|
BiometricFailedException(-1, "BiometricPrompt returned no cipher"),
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
cont.resume(authedCipher)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
|
||||||
|
if (errorCode == BiometricPrompt.ERROR_USER_CANCELED ||
|
||||||
|
errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
|
||||||
|
errorCode == BiometricPrompt.ERROR_CANCELED
|
||||||
|
) {
|
||||||
|
cont.resumeWithException(BiometricCancelledException(errString.toString()))
|
||||||
|
} else {
|
||||||
|
cont.resumeWithException(
|
||||||
|
BiometricFailedException(errorCode, errString.toString()),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
override fun onAuthenticationFailed() {
|
||||||
|
// A single failed attempt — the prompt stays open and
|
||||||
|
// gives the user another try. Don't resume the
|
||||||
|
// continuation; let the system flow continue.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
val prompt = BiometricPrompt(
|
||||||
|
activity,
|
||||||
|
activity.mainExecutor,
|
||||||
|
callback,
|
||||||
|
)
|
||||||
|
val info = BiometricPrompt.PromptInfo.Builder()
|
||||||
|
.setTitle(title)
|
||||||
|
.apply { if (subtitle != null) setSubtitle(subtitle) }
|
||||||
|
.setNegativeButtonText(negativeButton)
|
||||||
|
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
|
||||||
|
.build()
|
||||||
|
|
||||||
|
cont.invokeOnCancellation { prompt.cancelAuthentication() }
|
||||||
|
prompt.authenticate(info, BiometricPrompt.CryptoObject(cipher))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** User cancelled the biometric prompt. */
|
||||||
|
class BiometricCancelledException(message: String) : RuntimeException(message)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* BiometricPrompt returned a non-cancellation error (lockout, hardware
|
||||||
|
* unavailable, no enrolled biometrics, etc.). Inspect `errorCode`
|
||||||
|
* against `BiometricPrompt.ERROR_*` constants to decide UX response.
|
||||||
|
*/
|
||||||
|
class BiometricFailedException(val errorCode: Int, message: String) :
|
||||||
|
RuntimeException("[$errorCode] $message")
|
||||||
@@ -0,0 +1,172 @@
|
|||||||
|
package no.zyon.shade.keystore
|
||||||
|
|
||||||
|
import android.os.Build
|
||||||
|
import android.security.keystore.KeyGenParameterSpec
|
||||||
|
import android.security.keystore.KeyProperties
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.KeyGenerator
|
||||||
|
import javax.crypto.SecretKey
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
import java.security.KeyStore
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hardware-backed AES-256-GCM master key in the Android Keystore.
|
||||||
|
*
|
||||||
|
* The key never leaves the secure environment — Android's keystore
|
||||||
|
* implementation enforces that all encrypt/decrypt operations
|
||||||
|
* happen inside the TEE (or StrongBox if present), and the raw
|
||||||
|
* key bytes are never returned to userspace.
|
||||||
|
*
|
||||||
|
* The key is created on first use with these properties:
|
||||||
|
*
|
||||||
|
* - AES-256-GCM, no padding
|
||||||
|
* - User authentication required: opt-in via the `requireBiometric`
|
||||||
|
* flag. When true, every encrypt/decrypt operation must be wrapped
|
||||||
|
* in a `BiometricPrompt.authenticate(CryptoObject(cipher))` call
|
||||||
|
* that succeeds within the same `Cipher` instance.
|
||||||
|
* - StrongBox-backed if available (Pixel 3+, most Samsung flagships).
|
||||||
|
* Falls back to TEE on devices without StrongBox.
|
||||||
|
* - InvalidatedByBiometricEnrollment(true): a newly enrolled
|
||||||
|
* fingerprint/face invalidates the key, forcing the user to
|
||||||
|
* re-bootstrap from credentials. Defends against a thief who
|
||||||
|
* enrolls their own biometric.
|
||||||
|
*
|
||||||
|
* Mirrors the role `KeyManager` plays in `@shade/storage-encrypted`'s
|
||||||
|
* V4.5 KDF chain: this is the *encryption-at-rest* master key, not
|
||||||
|
* the X3DH identity key. The Shade protocol's identity keys are
|
||||||
|
* stored encrypted under THIS key.
|
||||||
|
*/
|
||||||
|
class KeystoreMasterKey(
|
||||||
|
private val alias: String,
|
||||||
|
private val requireBiometric: Boolean = true,
|
||||||
|
) {
|
||||||
|
|
||||||
|
init {
|
||||||
|
require(alias.isNotEmpty()) { "alias must be non-empty" }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a `Cipher` initialized for encryption with the master key.
|
||||||
|
*
|
||||||
|
* If the key requires user auth, the returned cipher is *not yet
|
||||||
|
* usable* — the caller MUST wrap it in a
|
||||||
|
* `BiometricPrompt.authenticate(CryptoObject(cipher))` and use
|
||||||
|
* the cipher exposed by the auth-success callback. Calling
|
||||||
|
* `cipher.doFinal(...)` before authentication throws
|
||||||
|
* `UserNotAuthenticatedException`.
|
||||||
|
*/
|
||||||
|
fun cipherForEncrypt(): Cipher {
|
||||||
|
val key = getOrCreateKey()
|
||||||
|
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, key)
|
||||||
|
return cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a `Cipher` initialized for decryption with the master key
|
||||||
|
* and a previously-stored 12-byte nonce. Same authentication
|
||||||
|
* requirement as `cipherForEncrypt`.
|
||||||
|
*/
|
||||||
|
fun cipherForDecrypt(nonce: ByteArray): Cipher {
|
||||||
|
require(nonce.size == 12) { "GCM nonce must be 12 bytes" }
|
||||||
|
val key = getOrCreateKey()
|
||||||
|
val cipher = Cipher.getInstance(TRANSFORMATION)
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, nonce))
|
||||||
|
return cipher
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True if the key already exists in the Android Keystore. */
|
||||||
|
fun exists(): Boolean {
|
||||||
|
val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||||
|
return ks.containsAlias(alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete the master key. Catastrophic — all data encrypted under
|
||||||
|
* it becomes unrecoverable. Used by the "forget everything" flow
|
||||||
|
* (paired with `Profile.delete()` in the V4.9 namespace).
|
||||||
|
*/
|
||||||
|
fun deleteKey() {
|
||||||
|
val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||||
|
if (ks.containsAlias(alias)) ks.deleteEntry(alias)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun getOrCreateKey(): SecretKey {
|
||||||
|
val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
|
||||||
|
ks.getEntry(alias, null)?.let { entry ->
|
||||||
|
return (entry as KeyStore.SecretKeyEntry).secretKey
|
||||||
|
}
|
||||||
|
return generateKey()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun generateKey(): SecretKey {
|
||||||
|
val builder = KeyGenParameterSpec.Builder(
|
||||||
|
alias,
|
||||||
|
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||||
|
)
|
||||||
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||||
|
.setKeySize(256)
|
||||||
|
// Each encrypt operation generates a fresh IV in the secure
|
||||||
|
// env; we read it back via `cipher.iv` after init.
|
||||||
|
.setRandomizedEncryptionRequired(true)
|
||||||
|
|
||||||
|
if (requireBiometric) {
|
||||||
|
builder.setUserAuthenticationRequired(true)
|
||||||
|
// BIOMETRIC_STRONG only — class 3, the highest assurance
|
||||||
|
// level (Class 3 = false-accept rate < 1/50 000 per BiometricPrompt).
|
||||||
|
// DEVICE_CREDENTIAL is intentionally NOT included: a stolen
|
||||||
|
// device with a known PIN should not unlock Shade.
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
|
||||||
|
builder.setUserAuthenticationParameters(
|
||||||
|
/* timeout = */ 0,
|
||||||
|
KeyProperties.AUTH_BIOMETRIC_STRONG,
|
||||||
|
)
|
||||||
|
} else {
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
builder.setUserAuthenticationValidityDurationSeconds(-1)
|
||||||
|
}
|
||||||
|
builder.setInvalidatedByBiometricEnrollment(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
// StrongBox if available — bumps key storage to a dedicated
|
||||||
|
// tamper-resistant chip on Pixel 3+ / most Samsung flagships.
|
||||||
|
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
|
||||||
|
builder.setIsStrongBoxBacked(true)
|
||||||
|
}
|
||||||
|
|
||||||
|
val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
|
||||||
|
return try {
|
||||||
|
gen.init(builder.build())
|
||||||
|
gen.generateKey()
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// StrongBox not present or full → retry without StrongBox.
|
||||||
|
// Same for older devices that don't honor
|
||||||
|
// setUserAuthenticationParameters.
|
||||||
|
val fallback = KeyGenParameterSpec.Builder(
|
||||||
|
alias,
|
||||||
|
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
|
||||||
|
)
|
||||||
|
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
|
||||||
|
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
|
||||||
|
.setKeySize(256)
|
||||||
|
.setRandomizedEncryptionRequired(true)
|
||||||
|
.apply {
|
||||||
|
if (requireBiometric) {
|
||||||
|
setUserAuthenticationRequired(true)
|
||||||
|
@Suppress("DEPRECATION")
|
||||||
|
setUserAuthenticationValidityDurationSeconds(-1)
|
||||||
|
setInvalidatedByBiometricEnrollment(true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.build()
|
||||||
|
gen.init(fallback)
|
||||||
|
gen.generateKey()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
private const val ANDROID_KEYSTORE = "AndroidKeyStore"
|
||||||
|
private const val TRANSFORMATION = "AES/GCM/NoPadding"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
package no.zyon.shade.keystore
|
||||||
|
|
||||||
|
import android.content.Context
|
||||||
|
import android.content.SharedPreferences
|
||||||
|
import android.util.Base64
|
||||||
|
import kotlinx.coroutines.sync.Mutex
|
||||||
|
import kotlinx.coroutines.sync.withLock
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import no.zyon.shade.serialization.SessionStateJson
|
||||||
|
import no.zyon.shade.storage.StorageProvider
|
||||||
|
import no.zyon.shade.types.IdentityKeyPair
|
||||||
|
import no.zyon.shade.types.OneTimePreKey
|
||||||
|
import no.zyon.shade.types.SessionState
|
||||||
|
import no.zyon.shade.types.SignedPreKey
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `StorageProvider` implementation that gates all reads/writes through
|
||||||
|
* a biometric-locked `KeystoreMasterKey`. Mirrors `MemoryStorage` for
|
||||||
|
* the API surface but persists state to `SharedPreferences` with each
|
||||||
|
* row encrypted under the keystore key.
|
||||||
|
*
|
||||||
|
* Lifecycle:
|
||||||
|
*
|
||||||
|
* 1. App start → construct `KeystoreStorage(context, alias)`.
|
||||||
|
* 2. `unlock(BiometricUnlock)` runs the system biometric prompt.
|
||||||
|
* The Android keystore caches the auth state under the key's
|
||||||
|
* `setUserAuthenticationParameters(0, BIOMETRIC_STRONG)` policy
|
||||||
|
* until the next biometric event (re-enrollment, etc.).
|
||||||
|
* 3. While unlocked, `getSession`/`saveSession` etc. work normally.
|
||||||
|
* 4. `lock()` clears the in-memory unlocked flag so a future
|
||||||
|
* operation triggers another biometric prompt.
|
||||||
|
*
|
||||||
|
* Wire layout per row:
|
||||||
|
* `<base64(nonce(12))>:<base64(ct||tag)>`
|
||||||
|
*
|
||||||
|
* Stored as `String` SharedPreferences entries. AAD = the row's
|
||||||
|
* preference key (`session:<address>`, `signedPreKey:<id>`, etc.) so
|
||||||
|
* a substituted-prefs swap fails to open.
|
||||||
|
*/
|
||||||
|
class KeystoreStorage(
|
||||||
|
context: Context,
|
||||||
|
private val crypto: CryptoProvider,
|
||||||
|
keyAlias: String = DEFAULT_KEY_ALIAS,
|
||||||
|
prefsName: String = DEFAULT_PREFS_NAME,
|
||||||
|
requireBiometric: Boolean = true,
|
||||||
|
) : StorageProvider {
|
||||||
|
|
||||||
|
private val prefs: SharedPreferences =
|
||||||
|
context.applicationContext.getSharedPreferences(prefsName, Context.MODE_PRIVATE)
|
||||||
|
private val masterKey = KeystoreMasterKey(keyAlias, requireBiometric = requireBiometric)
|
||||||
|
private val writeMutex = Mutex()
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
private var unlocked: Boolean = false
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unlock the keystore via biometric prompt. Idempotent — calling
|
||||||
|
* twice without a `lock()` between is a no-op.
|
||||||
|
*/
|
||||||
|
suspend fun unlock(unlock: BiometricUnlock) {
|
||||||
|
if (unlocked) return
|
||||||
|
// The biometric flow returns an authenticated *encrypt*
|
||||||
|
// cipher; we discard it after a one-shot probe to confirm
|
||||||
|
// the master key is reachable. The actual encrypt/decrypt
|
||||||
|
// ciphers in the I/O path use the authentication state
|
||||||
|
// established here (Android Keystore caches the auth for
|
||||||
|
// the user-authentication-required key under the
|
||||||
|
// `setUserAuthenticationParameters(0, BIOMETRIC_STRONG)`
|
||||||
|
// policy until the next biometric event).
|
||||||
|
val probe = masterKey.cipherForEncrypt()
|
||||||
|
unlock.unlock(probe)
|
||||||
|
unlocked = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Unlock without biometric — only valid for keys constructed with `requireBiometric=false`. */
|
||||||
|
fun unlockNoBiometric() {
|
||||||
|
unlocked = true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wipe in-memory unlock state. The key itself stays in the keystore. */
|
||||||
|
fun lock() {
|
||||||
|
unlocked = false
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Catastrophic reset: deletes the master key + all encrypted
|
||||||
|
* preferences. Used by the "forget everything" / 3-strikes-wipe
|
||||||
|
* path. The next bootstrap rebuilds from credentials.
|
||||||
|
*/
|
||||||
|
fun forgetEverything() {
|
||||||
|
masterKey.deleteKey()
|
||||||
|
prefs.edit().clear().apply()
|
||||||
|
unlocked = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Identity ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
override suspend fun getIdentityKeyPair(): IdentityKeyPair? {
|
||||||
|
val json = readDecrypted(KEY_IDENTITY) ?: return null
|
||||||
|
return SessionStateJson.deserializeIdentityKeyPair(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveIdentityKeyPair(keyPair: IdentityKeyPair) {
|
||||||
|
writeEncrypted(KEY_IDENTITY, SessionStateJson.serializeIdentityKeyPair(keyPair))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getLocalRegistrationId(): Int {
|
||||||
|
return readDecrypted(KEY_REGISTRATION_ID)?.toIntOrNull() ?: 0
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveLocalRegistrationId(id: Int) {
|
||||||
|
writeEncrypted(KEY_REGISTRATION_ID, id.toString())
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Signed prekeys ────────────────────────────────────────
|
||||||
|
|
||||||
|
override suspend fun getSignedPreKey(keyId: Int): SignedPreKey? {
|
||||||
|
val json = readDecrypted("$KEY_SIGNED_PREKEY:$keyId") ?: return null
|
||||||
|
return SessionStateJson.deserializeSignedPreKey(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveSignedPreKey(key: SignedPreKey) {
|
||||||
|
writeEncrypted(
|
||||||
|
"$KEY_SIGNED_PREKEY:${key.keyId}",
|
||||||
|
SessionStateJson.serializeSignedPreKey(key),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeSignedPreKey(keyId: Int) {
|
||||||
|
writeMutex.withLock { prefs.edit().remove("$KEY_SIGNED_PREKEY:$keyId").apply() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── One-time prekeys ──────────────────────────────────────
|
||||||
|
|
||||||
|
override suspend fun getOneTimePreKey(keyId: Int): OneTimePreKey? {
|
||||||
|
val json = readDecrypted("$KEY_ONETIME_PREKEY:$keyId") ?: return null
|
||||||
|
return SessionStateJson.deserializeOneTimePreKey(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveOneTimePreKey(key: OneTimePreKey) {
|
||||||
|
writeEncrypted(
|
||||||
|
"$KEY_ONETIME_PREKEY:${key.keyId}",
|
||||||
|
SessionStateJson.serializeOneTimePreKey(key),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeOneTimePreKey(keyId: Int) {
|
||||||
|
writeMutex.withLock { prefs.edit().remove("$KEY_ONETIME_PREKEY:$keyId").apply() }
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun getOneTimePreKeyCount(): Int {
|
||||||
|
return prefs.all.keys.count { it.startsWith("$KEY_ONETIME_PREKEY:") }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Sessions ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
override suspend fun getSession(address: String): SessionState? {
|
||||||
|
val json = readDecrypted("$KEY_SESSION:$address") ?: return null
|
||||||
|
return SessionStateJson.deserialize(json)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveSession(address: String, state: SessionState) {
|
||||||
|
writeEncrypted("$KEY_SESSION:$address", SessionStateJson.serialize(state))
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun removeSession(address: String) {
|
||||||
|
writeMutex.withLock { prefs.edit().remove("$KEY_SESSION:$address").apply() }
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Trust ─────────────────────────────────────────────────
|
||||||
|
|
||||||
|
override suspend fun isTrustedIdentity(address: String, identityKey: ByteArray): Boolean {
|
||||||
|
val stored = readDecrypted("$KEY_TRUSTED:$address") ?: return true // TOFU
|
||||||
|
val storedBytes = Base64.decode(stored, Base64.NO_WRAP)
|
||||||
|
return crypto.constantTimeEqual(storedBytes, identityKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
override suspend fun saveTrustedIdentity(address: String, identityKey: ByteArray) {
|
||||||
|
writeEncrypted(
|
||||||
|
"$KEY_TRUSTED:$address",
|
||||||
|
Base64.encodeToString(identityKey, Base64.NO_WRAP),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Encrypted-row plumbing ────────────────────────────────
|
||||||
|
|
||||||
|
private fun ensureUnlocked() {
|
||||||
|
check(unlocked) {
|
||||||
|
"KeystoreStorage is locked — call unlock(BiometricUnlock) first"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun readDecrypted(prefKey: String): String? {
|
||||||
|
ensureUnlocked()
|
||||||
|
val raw = prefs.getString(prefKey, null) ?: return null
|
||||||
|
val parts = raw.split(":", limit = 2)
|
||||||
|
require(parts.size == 2) { "malformed encrypted row at $prefKey" }
|
||||||
|
val nonce = Base64.decode(parts[0], Base64.NO_WRAP)
|
||||||
|
val ct = Base64.decode(parts[1], Base64.NO_WRAP)
|
||||||
|
val cipher = masterKey.cipherForDecrypt(nonce)
|
||||||
|
cipher.updateAAD(prefKey.toByteArray(Charsets.UTF_8))
|
||||||
|
return cipher.doFinal(ct).toString(Charsets.UTF_8)
|
||||||
|
}
|
||||||
|
|
||||||
|
private suspend fun writeEncrypted(prefKey: String, plaintext: String) {
|
||||||
|
ensureUnlocked()
|
||||||
|
writeMutex.withLock {
|
||||||
|
val cipher = masterKey.cipherForEncrypt()
|
||||||
|
cipher.updateAAD(prefKey.toByteArray(Charsets.UTF_8))
|
||||||
|
val ct = cipher.doFinal(plaintext.toByteArray(Charsets.UTF_8))
|
||||||
|
val nonce = cipher.iv
|
||||||
|
val nonceB64 = Base64.encodeToString(nonce, Base64.NO_WRAP)
|
||||||
|
val ctB64 = Base64.encodeToString(ct, Base64.NO_WRAP)
|
||||||
|
prefs.edit().putString(prefKey, "$nonceB64:$ctB64").apply()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
companion object {
|
||||||
|
const val DEFAULT_KEY_ALIAS = "shade-master-v1"
|
||||||
|
const val DEFAULT_PREFS_NAME = "shade-keystore-storage-v1"
|
||||||
|
|
||||||
|
private const val KEY_IDENTITY = "identity"
|
||||||
|
private const val KEY_REGISTRATION_ID = "registrationId"
|
||||||
|
private const val KEY_SIGNED_PREKEY = "signedPreKey"
|
||||||
|
private const val KEY_ONETIME_PREKEY = "oneTimePreKey"
|
||||||
|
private const val KEY_SESSION = "session"
|
||||||
|
private const val KEY_TRUSTED = "trusted"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -7,7 +7,11 @@ Kotlin implementation of the Shade E2EE protocol for Android apps. Byte-for-byte
|
|||||||
**M-Cross 1 ✅** — keys + HKDF + X3DH + fingerprint.
|
**M-Cross 1 ✅** — keys + HKDF + X3DH + fingerprint.
|
||||||
**M-Cross 2 ✅** — full ratchet step (encrypt + decrypt roundtrip) + wire 0x02 (RatchetMessage and PreKeyMessage with/without OTPK).
|
**M-Cross 2 ✅** — full ratchet step (encrypt + decrypt roundtrip) + wire 0x02 (RatchetMessage and PreKeyMessage with/without OTPK).
|
||||||
**M-Cross 3 ✅** — streams 0x11 (KDF labels with embedded NULs, deterministic chunk nonce/AAD, wire 0x11 encode/decode).
|
**M-Cross 3 ✅** — streams 0x11 (KDF labels with embedded NULs, deterministic chunk nonce/AAD, wire 0x11 encode/decode).
|
||||||
**M-Cross 4 ✅** — backup-key HKDF + AES-GCM, group sender-key step (`kdfChainKey` + Ed25519 sign over `aad ‖ ct`), storage HKDF (storageKey/fieldKey/rowNonce). Pending: scrypt master-key, argon2id swap, Android KeystoreStorage (sibling module).
|
**M-Cross 4 ✅** — backup-key HKDF + AES-GCM, group sender-key step (`kdfChainKey` + Ed25519 sign over `aad ‖ ct`), storage HKDF (storageKey/fieldKey/rowNonce).
|
||||||
|
**M-Cross 5 ✅** — V4.9 blob KDF + AEAD (`deriveBlobSlotId / deriveBlobKey / deriveBlobSigningSeed`, AAD-bound seal/open), `BlobClient` HTTP, `Profile` namespace. Cross-platform vectors in `blob.json`.
|
||||||
|
**M-Cross 6 ✅** — V4.10 cross-host approval routing: canonical profile-blob schema (`hosts[]` / `clients[]` / `trustedApproverFingerprints[]`), build/sign/verify proxy approvals via `canonicalApprovalSigningBytes` (length-prefixed u16 BE UTF-8). Cross-platform vectors in `approval.json`, including a TS-signed Ed25519 signature that the Kotlin port verifies.
|
||||||
|
**M-Cross 7 ✅** — scrypt + argon2id password-KDF wrappers (Bouncy Castle), NFKC-normalized inputs.
|
||||||
|
**M-Cross 8 ✅** — `:shade-android-keystore` sibling module: `KeystoreMasterKey` (StrongBox-backed AES-256-GCM, BIOMETRIC_STRONG-gated, invalidated on biometric enrollment), `BiometricUnlock`, `KeystoreStorage` (`StorageProvider` over biometric-gated AES-encrypted SharedPreferences).
|
||||||
|
|
||||||
Cross-platform test vectors in `/test-vectors/` are loaded by both the TS
|
Cross-platform test vectors in `/test-vectors/` are loaded by both the TS
|
||||||
and Kotlin test suites; any byte-divergence fails CI within 60 s. See
|
and Kotlin test suites; any byte-divergence fails CI within 60 s. See
|
||||||
|
|||||||
@@ -29,6 +29,11 @@ dependencies {
|
|||||||
// The same `subtle.*` API as `tink-android` so the source compiles unchanged.
|
// The same `subtle.*` API as `tink-android` so the source compiles unchanged.
|
||||||
implementation("com.google.crypto.tink:tink:1.15.0")
|
implementation("com.google.crypto.tink:tink:1.15.0")
|
||||||
|
|
||||||
|
// Bouncy Castle for scrypt + argon2id. Tink doesn't ship password
|
||||||
|
// KDFs; @shade/storage-encrypted uses @noble/hashes for both. We
|
||||||
|
// pin to the JDK18-on artifact so it works on JVM 17 + Android.
|
||||||
|
implementation("org.bouncycastle:bcprov-jdk18on:1.78.1")
|
||||||
|
|
||||||
// JSON serialization (session state + test-vector loader on JVM).
|
// JSON serialization (session state + test-vector loader on JVM).
|
||||||
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
|
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
|
||||||
|
|
||||||
@@ -44,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
|
||||||
|
|||||||
@@ -0,0 +1,273 @@
|
|||||||
|
package no.zyon.shade.approval
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import java.nio.ByteBuffer
|
||||||
|
import java.nio.ByteOrder
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V4.10 — cross-host approval routing helpers. Mirror
|
||||||
|
* `@shade/sdk/approval.ts` byte-for-byte.
|
||||||
|
*
|
||||||
|
* The frames themselves (`approvalNeeded` / `linkApproveByProxy`) are
|
||||||
|
* app-defined payloads sent over the existing Shade bilateral E2EE
|
||||||
|
* channel. This file ships the canonical signing-payload layout, the
|
||||||
|
* Ed25519 sign step a phone runs after biometric unlock, and the
|
||||||
|
* verify step a host runs against the freshest profile blob.
|
||||||
|
*
|
||||||
|
* The signing payload is length-prefixed binary (u16 BE) so any
|
||||||
|
* platform — Kotlin, Swift, Go — can produce byte-identical input
|
||||||
|
* without needing a JSON canonicalizer. Cross-platform parity is
|
||||||
|
* gated by `test-vectors/blob-storage.json` (signing payload
|
||||||
|
* fixtures) plus a Kotlin↔TS round-trip in `CrossPlatformVectorTest`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Default domain separator. Apps with their own canonical name (e.g. Prism) override. */
|
||||||
|
const val DEFAULT_APPROVAL_DOMAIN = "shade-link-approve-v1"
|
||||||
|
|
||||||
|
/** Default expiry: 5 minutes after the host issues the request. */
|
||||||
|
const val DEFAULT_APPROVAL_EXPIRES_IN_MS = 5L * 60 * 1000
|
||||||
|
|
||||||
|
/** Information about the device the host received a `linkRequest` from. */
|
||||||
|
data class ApprovalRequestingDevice(
|
||||||
|
val fingerprint: String,
|
||||||
|
val deviceName: String? = null,
|
||||||
|
val userAgent: String? = null,
|
||||||
|
val ipHint: String? = null,
|
||||||
|
val receivedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ApprovalRequestFrame(
|
||||||
|
val kind: String = "approvalNeeded",
|
||||||
|
/** 128-bit hex (32 chars) random idempotency key. */
|
||||||
|
val requestId: String,
|
||||||
|
val hostAddress: String,
|
||||||
|
val hostFingerprint: String,
|
||||||
|
val requestingDevice: ApprovalRequestingDevice,
|
||||||
|
val expiresAt: Long,
|
||||||
|
val domain: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class ProxyApprovalFrame(
|
||||||
|
val kind: String = "linkApproveByProxy",
|
||||||
|
val requestId: String,
|
||||||
|
val decision: String,
|
||||||
|
val approverFingerprint: String,
|
||||||
|
/** 64-byte Ed25519 signature, lowercase hex (128 chars). */
|
||||||
|
val signature: String,
|
||||||
|
val domain: String,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a fresh `approvalNeeded` frame with a 128-bit random
|
||||||
|
* `requestId`. Hosts SHOULD persist the requestId in a pending-set
|
||||||
|
* keyed by `expiresAt` so a returning `linkApproveByProxy` can be
|
||||||
|
* matched up — that's app state, the SDK doesn't track it.
|
||||||
|
*/
|
||||||
|
fun buildApprovalRequest(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
hostAddress: String,
|
||||||
|
hostFingerprint: String,
|
||||||
|
requestingDeviceFingerprint: String,
|
||||||
|
deviceName: String? = null,
|
||||||
|
userAgent: String? = null,
|
||||||
|
ipHint: String? = null,
|
||||||
|
expiresInMs: Long = DEFAULT_APPROVAL_EXPIRES_IN_MS,
|
||||||
|
domain: String = DEFAULT_APPROVAL_DOMAIN,
|
||||||
|
now: Long = System.currentTimeMillis(),
|
||||||
|
): ApprovalRequestFrame {
|
||||||
|
val requestId = crypto.randomBytes(16).joinToString("") { "%02x".format(it) }
|
||||||
|
return ApprovalRequestFrame(
|
||||||
|
requestId = requestId,
|
||||||
|
hostAddress = hostAddress,
|
||||||
|
hostFingerprint = hostFingerprint,
|
||||||
|
requestingDevice = ApprovalRequestingDevice(
|
||||||
|
fingerprint = requestingDeviceFingerprint,
|
||||||
|
deviceName = deviceName,
|
||||||
|
userAgent = userAgent,
|
||||||
|
ipHint = ipHint,
|
||||||
|
receivedAt = now,
|
||||||
|
),
|
||||||
|
expiresAt = now + expiresInMs,
|
||||||
|
domain = domain,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign a `linkApproveByProxy` frame with the approver's long-term
|
||||||
|
* Ed25519 identity key. The seed is the 32-byte Ed25519 private key
|
||||||
|
* (Tink's `Ed25519Sign(seed)` consumes it directly).
|
||||||
|
*/
|
||||||
|
fun signProxyApproval(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
request: ApprovalRequestFrame,
|
||||||
|
decision: String,
|
||||||
|
approverFingerprint: String,
|
||||||
|
approverSigningKey: ByteArray,
|
||||||
|
): ProxyApprovalFrame {
|
||||||
|
require(decision == "approve" || decision == "reject") {
|
||||||
|
"decision must be 'approve' or 'reject'"
|
||||||
|
}
|
||||||
|
require(approverSigningKey.size == 32) {
|
||||||
|
"approverSigningKey must be 32 bytes (Ed25519 seed)"
|
||||||
|
}
|
||||||
|
val payload = canonicalApprovalSigningBytes(
|
||||||
|
domain = request.domain,
|
||||||
|
requestId = request.requestId,
|
||||||
|
hostFingerprint = request.hostFingerprint,
|
||||||
|
requestingDeviceFingerprint = request.requestingDevice.fingerprint,
|
||||||
|
decision = decision,
|
||||||
|
)
|
||||||
|
val sig = crypto.sign(approverSigningKey, payload)
|
||||||
|
return ProxyApprovalFrame(
|
||||||
|
requestId = request.requestId,
|
||||||
|
decision = decision,
|
||||||
|
approverFingerprint = approverFingerprint,
|
||||||
|
signature = sig.joinToString("") { "%02x".format(it) },
|
||||||
|
domain = request.domain,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Tagged result of `verifyProxyApproval`. */
|
||||||
|
sealed class VerifyProxyApprovalResult {
|
||||||
|
data class Ok(val approver: ProfileClientEntry) : VerifyProxyApprovalResult()
|
||||||
|
data class Failed(val reason: Reason) : VerifyProxyApprovalResult()
|
||||||
|
|
||||||
|
enum class Reason {
|
||||||
|
REQUEST_ID_MISMATCH,
|
||||||
|
DOMAIN_MISMATCH,
|
||||||
|
UNKNOWN_APPROVER,
|
||||||
|
NOT_TRUSTED,
|
||||||
|
BAD_SIGNATURE,
|
||||||
|
EXPIRED,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a `linkApproveByProxy` against the originating
|
||||||
|
* `approvalNeeded` and the host's freshest profile blob. Returns a
|
||||||
|
* tagged result rather than throwing — callers usually want to log
|
||||||
|
* the reason before deciding what to surface to the user.
|
||||||
|
*
|
||||||
|
* Order of checks:
|
||||||
|
*
|
||||||
|
* 1. requestId match (replay defense)
|
||||||
|
* 2. domain match (cross-app confusion defense)
|
||||||
|
* 3. approver resolves to a `clients[]` entry
|
||||||
|
* 4. approver is in `trustedApproverFingerprints[]` AND has the
|
||||||
|
* `trustedApprover` flag (cross-checked via `isTrustedApprover`)
|
||||||
|
* 5. expiresAt in the future
|
||||||
|
* 6. Ed25519 signature verifies against `clients[].identityPublicKey`
|
||||||
|
*
|
||||||
|
* Hosts MUST refetch the profile blob fresh before calling this — see
|
||||||
|
* the FR §5 "approver-revocation propagation" rationale.
|
||||||
|
*/
|
||||||
|
fun verifyProxyApproval(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
request: ApprovalRequestFrame,
|
||||||
|
approval: ProxyApprovalFrame,
|
||||||
|
profile: CanonicalProfileBlob,
|
||||||
|
now: Long = System.currentTimeMillis(),
|
||||||
|
): VerifyProxyApprovalResult {
|
||||||
|
if (approval.requestId != request.requestId) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(
|
||||||
|
VerifyProxyApprovalResult.Reason.REQUEST_ID_MISMATCH,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (approval.domain != request.domain) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(
|
||||||
|
VerifyProxyApprovalResult.Reason.DOMAIN_MISMATCH,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
val approver = findClientByFingerprint(profile, approval.approverFingerprint)
|
||||||
|
?: return VerifyProxyApprovalResult.Failed(
|
||||||
|
VerifyProxyApprovalResult.Reason.UNKNOWN_APPROVER,
|
||||||
|
)
|
||||||
|
|
||||||
|
if (!isTrustedApprover(profile, approval.approverFingerprint)) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(
|
||||||
|
VerifyProxyApprovalResult.Reason.NOT_TRUSTED,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (now > request.expiresAt) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.EXPIRED)
|
||||||
|
}
|
||||||
|
|
||||||
|
val pubkey = try {
|
||||||
|
hexToBytes(approver.identityPublicKey)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
|
||||||
|
}
|
||||||
|
val sig = try {
|
||||||
|
hexToBytes(approval.signature)
|
||||||
|
} catch (_: Exception) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
|
||||||
|
}
|
||||||
|
if (pubkey.size != 32 || sig.size != 64) {
|
||||||
|
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
|
||||||
|
}
|
||||||
|
|
||||||
|
val payload = canonicalApprovalSigningBytes(
|
||||||
|
domain = approval.domain,
|
||||||
|
requestId = approval.requestId,
|
||||||
|
hostFingerprint = request.hostFingerprint,
|
||||||
|
requestingDeviceFingerprint = request.requestingDevice.fingerprint,
|
||||||
|
decision = approval.decision,
|
||||||
|
)
|
||||||
|
val ok = crypto.verify(pubkey, payload, sig)
|
||||||
|
return if (ok) VerifyProxyApprovalResult.Ok(approver)
|
||||||
|
else VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the canonical signing payload bytes for a proxy approval.
|
||||||
|
*
|
||||||
|
* Format (length-prefixed UTF-8, big-endian u16 lengths):
|
||||||
|
*
|
||||||
|
* u16(len(domain)) || domain
|
||||||
|
* u16(len(requestId)) || requestId
|
||||||
|
* u16(len(hostFp)) || hostFingerprint
|
||||||
|
* u16(len(requestFp)) || requestingDeviceFingerprint
|
||||||
|
* u16(len(decision)) || decision
|
||||||
|
*
|
||||||
|
* This is the EXACT byte layout `@shade/sdk`'s
|
||||||
|
* `canonicalApprovalSigningBytes` produces, ensuring an Android-signed
|
||||||
|
* approval verifies on a TS host and vice versa.
|
||||||
|
*/
|
||||||
|
fun canonicalApprovalSigningBytes(
|
||||||
|
domain: String,
|
||||||
|
requestId: String,
|
||||||
|
hostFingerprint: String,
|
||||||
|
requestingDeviceFingerprint: String,
|
||||||
|
decision: String,
|
||||||
|
): ByteArray {
|
||||||
|
val fields = listOf(
|
||||||
|
domain.toByteArray(Charsets.UTF_8),
|
||||||
|
requestId.toByteArray(Charsets.UTF_8),
|
||||||
|
hostFingerprint.toByteArray(Charsets.UTF_8),
|
||||||
|
requestingDeviceFingerprint.toByteArray(Charsets.UTF_8),
|
||||||
|
decision.toByteArray(Charsets.UTF_8),
|
||||||
|
)
|
||||||
|
for (f in fields) {
|
||||||
|
require(f.size <= 0xFFFF) { "signing field too long: ${f.size} bytes (max 65535)" }
|
||||||
|
}
|
||||||
|
val total = fields.sumOf { 2 + it.size }
|
||||||
|
val buf = ByteBuffer.allocate(total).order(ByteOrder.BIG_ENDIAN)
|
||||||
|
for (f in fields) {
|
||||||
|
buf.putShort(f.size.toShort())
|
||||||
|
buf.put(f)
|
||||||
|
}
|
||||||
|
return buf.array()
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hexToBytes(hex: String): ByteArray {
|
||||||
|
require(hex.length % 2 == 0) { "hex length must be even" }
|
||||||
|
require(hex.all { it.isDigit() || it in 'a'..'f' }) { "hex must be lowercase 0-9a-f" }
|
||||||
|
val out = ByteArray(hex.length / 2)
|
||||||
|
for (i in out.indices) {
|
||||||
|
out[i] = ((Character.digit(hex[i * 2], 16) shl 4) +
|
||||||
|
Character.digit(hex[i * 2 + 1], 16)).toByte()
|
||||||
|
}
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
package no.zyon.shade.approval
|
||||||
|
|
||||||
|
import org.json.JSONArray
|
||||||
|
import org.json.JSONObject
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V4.10 — canonical profile-blob schema. Mirror
|
||||||
|
* `@shade/sdk/approval.ts` byte-for-byte: same field names, same
|
||||||
|
* JSON shape, same denormalization invariants.
|
||||||
|
*
|
||||||
|
* The blob is the AEAD plaintext stored in the V4.9 profile slot. It
|
||||||
|
* holds the user's list of paired hosts + clients; cross-host
|
||||||
|
* approval routing reads `clients[]` to find trusted approvers when
|
||||||
|
* a headless host needs to dispatch a `linkRequest` to a phone.
|
||||||
|
*
|
||||||
|
* Mutators (`upsertHost`, `setTrustedApprover`, ...) are immutable —
|
||||||
|
* they return a new blob and never modify the input. The denormalized
|
||||||
|
* `trustedApproverFingerprints[]` is rederived on every mutation so it
|
||||||
|
* can never drift from the per-client `trustedApprover` flag.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** A host: a device that receives `linkRequest` frames and runs pairing. */
|
||||||
|
data class ProfileHostEntry(
|
||||||
|
val address: String,
|
||||||
|
val name: String,
|
||||||
|
/** Open enum: `"desktop" | "server" | "laptop" | ...`. */
|
||||||
|
val kind: String,
|
||||||
|
val addedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A client: a device that initiates link/approval flows and may
|
||||||
|
* proxy-approve when `trustedApprover == true`. Stores both the
|
||||||
|
* 32-byte Ed25519 identity public key (hex) and the safety-number
|
||||||
|
* fingerprint — the public key is what `verifyProxyApproval` checks
|
||||||
|
* signatures against; the fingerprint is what UIs display.
|
||||||
|
*/
|
||||||
|
data class ProfileClientEntry(
|
||||||
|
val address: String,
|
||||||
|
/** 32-byte Ed25519 long-term identity public key, lowercase hex (64 chars). */
|
||||||
|
val identityPublicKey: String,
|
||||||
|
/** Safety-number fingerprint of the identity key (computeFingerprint output). */
|
||||||
|
val identityFingerprint: String,
|
||||||
|
val name: String,
|
||||||
|
/** Open enum: `"mobile" | "tablet" | "browser" | ...`. */
|
||||||
|
val kind: String,
|
||||||
|
val addedAt: Long,
|
||||||
|
val trustedApprover: Boolean = false,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Canonical profile blob. `version=1` is the only currently-supported
|
||||||
|
* shape; bump when an incompatible field is added. Unknown top-level
|
||||||
|
* fields are dropped on parse — additive changes need a coordinated
|
||||||
|
* schema bump on both platforms.
|
||||||
|
*/
|
||||||
|
data class CanonicalProfileBlob(
|
||||||
|
val version: Int = 1,
|
||||||
|
val hosts: List<ProfileHostEntry> = emptyList(),
|
||||||
|
val clients: List<ProfileClientEntry> = emptyList(),
|
||||||
|
/** Denormalized list of trusted-approver fingerprints. Rederived on mutate. */
|
||||||
|
val trustedApproverFingerprints: List<String> = emptyList(),
|
||||||
|
val updatedAt: Long = 0,
|
||||||
|
/** Optional hex-encoded pubkey of the writer; informational only. */
|
||||||
|
val signedBy: String? = null,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Build a fresh empty profile blob with `updatedAt = now ?? System.currentTimeMillis()`. */
|
||||||
|
fun emptyCanonicalProfile(now: Long? = null): CanonicalProfileBlob =
|
||||||
|
CanonicalProfileBlob(updatedAt = now ?: System.currentTimeMillis())
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decode a profile-blob plaintext (the AEAD-opened bytes) into the
|
||||||
|
* canonical shape. Throws `IllegalArgumentException` on malformed JSON
|
||||||
|
* or wrong shape.
|
||||||
|
*/
|
||||||
|
fun parseCanonicalProfile(plaintext: ByteArray): CanonicalProfileBlob =
|
||||||
|
parseCanonicalProfile(plaintext.toString(Charsets.UTF_8))
|
||||||
|
|
||||||
|
fun parseCanonicalProfile(plaintext: String): CanonicalProfileBlob {
|
||||||
|
val obj = try {
|
||||||
|
JSONObject(plaintext)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw IllegalArgumentException("profile blob is not valid JSON: ${e.message}")
|
||||||
|
}
|
||||||
|
val version = obj.optInt("version", -1)
|
||||||
|
require(version == 1) { "unsupported profile blob version: $version" }
|
||||||
|
|
||||||
|
val hosts = parseArray(obj.optJSONArray("hosts"), "hosts", ::parseHostEntry)
|
||||||
|
val clients = parseArray(obj.optJSONArray("clients"), "clients", ::parseClientEntry)
|
||||||
|
val trustedApproverFingerprints = parseStringArray(
|
||||||
|
obj.optJSONArray("trustedApproverFingerprints"),
|
||||||
|
"trustedApproverFingerprints",
|
||||||
|
)
|
||||||
|
val updatedAt = if (obj.has("updatedAt") && !obj.isNull("updatedAt"))
|
||||||
|
obj.getLong("updatedAt") else 0L
|
||||||
|
val signedBy = obj.optString("signedBy", "").takeIf { it.isNotEmpty() }
|
||||||
|
|
||||||
|
return CanonicalProfileBlob(
|
||||||
|
version = 1,
|
||||||
|
hosts = hosts,
|
||||||
|
clients = clients,
|
||||||
|
trustedApproverFingerprints = trustedApproverFingerprints,
|
||||||
|
updatedAt = updatedAt,
|
||||||
|
signedBy = signedBy,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Serialize a profile blob to UTF-8 JSON ready for `Profile.put`. */
|
||||||
|
fun serializeCanonicalProfile(blob: CanonicalProfileBlob): ByteArray {
|
||||||
|
val json = JSONObject()
|
||||||
|
json.put("version", blob.version)
|
||||||
|
json.put("hosts", JSONArray().apply {
|
||||||
|
blob.hosts.forEach { put(hostEntryToJson(it)) }
|
||||||
|
})
|
||||||
|
json.put("clients", JSONArray().apply {
|
||||||
|
blob.clients.forEach { put(clientEntryToJson(it)) }
|
||||||
|
})
|
||||||
|
json.put("trustedApproverFingerprints", JSONArray(blob.trustedApproverFingerprints))
|
||||||
|
json.put("updatedAt", blob.updatedAt)
|
||||||
|
if (blob.signedBy != null) json.put("signedBy", blob.signedBy)
|
||||||
|
return json.toString().toByteArray(Charsets.UTF_8)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseHostEntry(o: JSONObject): ProfileHostEntry =
|
||||||
|
ProfileHostEntry(
|
||||||
|
address = o.requireString("address", "hosts"),
|
||||||
|
name = o.requireString("name", "hosts"),
|
||||||
|
kind = o.requireString("kind", "hosts"),
|
||||||
|
addedAt = o.requireLong("addedAt", "hosts"),
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun parseClientEntry(o: JSONObject): ProfileClientEntry {
|
||||||
|
val identityPublicKey = o.requireString("identityPublicKey", "clients")
|
||||||
|
require(identityPublicKey.matches(Regex("^[0-9a-f]{64}$"))) {
|
||||||
|
"clients[].identityPublicKey must be 64 lowercase hex chars"
|
||||||
|
}
|
||||||
|
return ProfileClientEntry(
|
||||||
|
address = o.requireString("address", "clients"),
|
||||||
|
identityPublicKey = identityPublicKey,
|
||||||
|
identityFingerprint = o.requireString("identityFingerprint", "clients"),
|
||||||
|
name = o.requireString("name", "clients"),
|
||||||
|
kind = o.requireString("kind", "clients"),
|
||||||
|
addedAt = o.requireLong("addedAt", "clients"),
|
||||||
|
trustedApprover = o.optBoolean("trustedApprover", false),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun hostEntryToJson(e: ProfileHostEntry): JSONObject = JSONObject().apply {
|
||||||
|
put("address", e.address)
|
||||||
|
put("name", e.name)
|
||||||
|
put("kind", e.kind)
|
||||||
|
put("addedAt", e.addedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun clientEntryToJson(e: ProfileClientEntry): JSONObject = JSONObject().apply {
|
||||||
|
put("address", e.address)
|
||||||
|
put("identityPublicKey", e.identityPublicKey)
|
||||||
|
put("identityFingerprint", e.identityFingerprint)
|
||||||
|
put("name", e.name)
|
||||||
|
put("kind", e.kind)
|
||||||
|
put("addedAt", e.addedAt)
|
||||||
|
if (e.trustedApprover) put("trustedApprover", true)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun <T> parseArray(
|
||||||
|
arr: JSONArray?,
|
||||||
|
field: String,
|
||||||
|
parse: (JSONObject) -> T,
|
||||||
|
): List<T> {
|
||||||
|
if (arr == null) return emptyList()
|
||||||
|
return (0 until arr.length()).map { i ->
|
||||||
|
val item = arr.opt(i)
|
||||||
|
require(item is JSONObject) { "$field[$i] must be an object" }
|
||||||
|
parse(item)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseStringArray(arr: JSONArray?, field: String): List<String> {
|
||||||
|
if (arr == null) return emptyList()
|
||||||
|
return (0 until arr.length()).map { i ->
|
||||||
|
val item = arr.opt(i)
|
||||||
|
require(item is String) { "$field[$i] must be a string" }
|
||||||
|
item
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.requireString(key: String, ctx: String): String {
|
||||||
|
require(has(key) && !isNull(key)) { "$ctx[].$key is required" }
|
||||||
|
val v = get(key)
|
||||||
|
require(v is String) { "$ctx[].$key must be a string" }
|
||||||
|
return v
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun JSONObject.requireLong(key: String, ctx: String): Long {
|
||||||
|
require(has(key) && !isNull(key)) { "$ctx[].$key is required" }
|
||||||
|
return when (val v = get(key)) {
|
||||||
|
is Number -> v.toLong()
|
||||||
|
else -> throw IllegalArgumentException("$ctx[].$key must be a number")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Mutators (immutable; return new blob, never mutate input) ──
|
||||||
|
|
||||||
|
/** Insert or replace a host entry by address. Bumps `updatedAt`. */
|
||||||
|
fun upsertHost(
|
||||||
|
blob: CanonicalProfileBlob,
|
||||||
|
host: ProfileHostEntry,
|
||||||
|
now: Long? = null,
|
||||||
|
): CanonicalProfileBlob {
|
||||||
|
val hosts = blob.hosts.filter { it.address != host.address } + host
|
||||||
|
return blob.copy(hosts = hosts, updatedAt = now ?: System.currentTimeMillis())
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the host with the given address, if any. */
|
||||||
|
fun removeHost(
|
||||||
|
blob: CanonicalProfileBlob,
|
||||||
|
address: String,
|
||||||
|
now: Long? = null,
|
||||||
|
): CanonicalProfileBlob {
|
||||||
|
val hosts = blob.hosts.filter { it.address != address }
|
||||||
|
if (hosts.size == blob.hosts.size) return blob
|
||||||
|
return blob.copy(hosts = hosts, updatedAt = now ?: System.currentTimeMillis())
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Insert or replace a client entry by `identityFingerprint`. Re-derives
|
||||||
|
* `trustedApproverFingerprints` from the resulting `clients[]` so the
|
||||||
|
* denormalized list never drifts.
|
||||||
|
*/
|
||||||
|
fun upsertClient(
|
||||||
|
blob: CanonicalProfileBlob,
|
||||||
|
client: ProfileClientEntry,
|
||||||
|
now: Long? = null,
|
||||||
|
): CanonicalProfileBlob {
|
||||||
|
val clients = blob.clients
|
||||||
|
.filter { it.identityFingerprint != client.identityFingerprint } + client
|
||||||
|
return blob.copy(
|
||||||
|
clients = clients,
|
||||||
|
trustedApproverFingerprints = deriveTrustedApprovers(clients),
|
||||||
|
updatedAt = now ?: System.currentTimeMillis(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Remove the client with the given identityFingerprint, if any. */
|
||||||
|
fun removeClient(
|
||||||
|
blob: CanonicalProfileBlob,
|
||||||
|
identityFingerprint: String,
|
||||||
|
now: Long? = null,
|
||||||
|
): CanonicalProfileBlob {
|
||||||
|
val clients = blob.clients.filter { it.identityFingerprint != identityFingerprint }
|
||||||
|
if (clients.size == blob.clients.size) return blob
|
||||||
|
return blob.copy(
|
||||||
|
clients = clients,
|
||||||
|
trustedApproverFingerprints = deriveTrustedApprovers(clients),
|
||||||
|
updatedAt = now ?: System.currentTimeMillis(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Toggle the `trustedApprover` flag on a client by fingerprint.
|
||||||
|
* Returns the input unchanged if fingerprint isn't found OR the
|
||||||
|
* desired state already matches (no spurious updatedAt bump).
|
||||||
|
*/
|
||||||
|
fun setTrustedApprover(
|
||||||
|
blob: CanonicalProfileBlob,
|
||||||
|
identityFingerprint: String,
|
||||||
|
trusted: Boolean,
|
||||||
|
now: Long? = null,
|
||||||
|
): CanonicalProfileBlob {
|
||||||
|
var touched = false
|
||||||
|
val clients = blob.clients.map { c ->
|
||||||
|
if (c.identityFingerprint != identityFingerprint) c
|
||||||
|
else if (c.trustedApprover == trusted) c
|
||||||
|
else {
|
||||||
|
touched = true
|
||||||
|
c.copy(trustedApprover = trusted)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!touched) return blob
|
||||||
|
return blob.copy(
|
||||||
|
clients = clients,
|
||||||
|
trustedApproverFingerprints = deriveTrustedApprovers(clients),
|
||||||
|
updatedAt = now ?: System.currentTimeMillis(),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* True iff the given fingerprint resolves to a client with both
|
||||||
|
* `trustedApprover == true` AND an entry in `trustedApproverFingerprints[]`.
|
||||||
|
*/
|
||||||
|
fun isTrustedApprover(blob: CanonicalProfileBlob, identityFingerprint: String): Boolean {
|
||||||
|
if (!blob.trustedApproverFingerprints.contains(identityFingerprint)) return false
|
||||||
|
val c = findClientByFingerprint(blob, identityFingerprint) ?: return false
|
||||||
|
return c.trustedApprover
|
||||||
|
}
|
||||||
|
|
||||||
|
fun findClientByFingerprint(
|
||||||
|
blob: CanonicalProfileBlob,
|
||||||
|
identityFingerprint: String,
|
||||||
|
): ProfileClientEntry? = blob.clients.firstOrNull { it.identityFingerprint == identityFingerprint }
|
||||||
|
|
||||||
|
fun findClientByAddress(blob: CanonicalProfileBlob, address: String): ProfileClientEntry? =
|
||||||
|
blob.clients.firstOrNull { it.address == address }
|
||||||
|
|
||||||
|
private fun deriveTrustedApprovers(clients: List<ProfileClientEntry>): List<String> =
|
||||||
|
clients.filter { it.trustedApprover }.map { it.identityFingerprint }
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
package no.zyon.shade.blob
|
||||||
|
|
||||||
|
import javax.crypto.Cipher
|
||||||
|
import javax.crypto.spec.GCMParameterSpec
|
||||||
|
import javax.crypto.spec.SecretKeySpec
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AEAD wrapper for the V4.9 profile blob.
|
||||||
|
*
|
||||||
|
* Wire format for one ciphertext blob:
|
||||||
|
* `nonce(12) || ciphertext(N) || tag(16)`
|
||||||
|
*
|
||||||
|
* Mirror `@shade/storage-encrypted/crypto/aead.ts` byte-for-byte. The
|
||||||
|
* relay stores this as a single opaque BLOB column; AAD is reconstructed
|
||||||
|
* at read-time as `"shade-profile-aad-v1:" + slotIdHex` and is NOT
|
||||||
|
* stored on the relay.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const val BLOB_AEAD_NONCE_LEN = 12
|
||||||
|
const val BLOB_AEAD_TAG_LEN = 16
|
||||||
|
|
||||||
|
private const val MIN_CIPHERTEXT_LEN = BLOB_AEAD_NONCE_LEN + BLOB_AEAD_TAG_LEN
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seal a plaintext blob. Returns `nonce || ct||tag` ready for direct
|
||||||
|
* blob storage. The caller supplies the nonce so this function is
|
||||||
|
* deterministic — the high-level Profile namespace generates a fresh
|
||||||
|
* 12-byte random nonce per write to keep (key, nonce, plaintext)
|
||||||
|
* unique across re-uploads.
|
||||||
|
*/
|
||||||
|
fun aeadSeal(
|
||||||
|
key: ByteArray,
|
||||||
|
nonce: ByteArray,
|
||||||
|
plaintext: ByteArray,
|
||||||
|
aad: ByteArray,
|
||||||
|
): ByteArray {
|
||||||
|
require(key.size == 32) { "AES-256-GCM key must be 32 bytes" }
|
||||||
|
require(nonce.size == BLOB_AEAD_NONCE_LEN) {
|
||||||
|
"nonce must be $BLOB_AEAD_NONCE_LEN bytes"
|
||||||
|
}
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
val spec = GCMParameterSpec(128, nonce)
|
||||||
|
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), spec)
|
||||||
|
cipher.updateAAD(aad)
|
||||||
|
val ctTag = cipher.doFinal(plaintext)
|
||||||
|
val out = ByteArray(BLOB_AEAD_NONCE_LEN + ctTag.size)
|
||||||
|
System.arraycopy(nonce, 0, out, 0, BLOB_AEAD_NONCE_LEN)
|
||||||
|
System.arraycopy(ctTag, 0, out, BLOB_AEAD_NONCE_LEN, ctTag.size)
|
||||||
|
return out
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Open a `nonce || ct||tag` blob and return the plaintext. Throws on
|
||||||
|
* tamper (AEAD tag mismatch) or short input. The caller may pass an
|
||||||
|
* `expectedNonce` to enforce a deterministic nonce — mismatch throws
|
||||||
|
* before the AEAD even runs (defense-in-depth against a relay returning
|
||||||
|
* the wrong slot's blob).
|
||||||
|
*/
|
||||||
|
fun aeadOpen(
|
||||||
|
key: ByteArray,
|
||||||
|
blob: ByteArray,
|
||||||
|
aad: ByteArray,
|
||||||
|
expectedNonce: ByteArray? = null,
|
||||||
|
): ByteArray {
|
||||||
|
require(key.size == 32) { "AES-256-GCM key must be 32 bytes" }
|
||||||
|
require(blob.size >= MIN_CIPHERTEXT_LEN) { "ciphertext blob too short" }
|
||||||
|
val nonce = blob.copyOfRange(0, BLOB_AEAD_NONCE_LEN)
|
||||||
|
if (expectedNonce != null && !ctEqual(nonce, expectedNonce)) {
|
||||||
|
throw IllegalArgumentException(
|
||||||
|
"nonce mismatch — ciphertext blob has been tampered or row identity changed",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
val ctTag = blob.copyOfRange(BLOB_AEAD_NONCE_LEN, blob.size)
|
||||||
|
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
|
||||||
|
val spec = GCMParameterSpec(128, nonce)
|
||||||
|
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), spec)
|
||||||
|
cipher.updateAAD(aad)
|
||||||
|
return cipher.doFinal(ctTag)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun ctEqual(a: ByteArray, b: ByteArray): Boolean {
|
||||||
|
if (a.size != b.size) return false
|
||||||
|
var diff = 0
|
||||||
|
for (i in a.indices) {
|
||||||
|
diff = diff or (a[i].toInt() xor b[i].toInt())
|
||||||
|
}
|
||||||
|
return diff == 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Build the AAD for a given slotId hex string. */
|
||||||
|
fun blobAadForSlot(slotIdHex: String): ByteArray {
|
||||||
|
require(slotIdHex.length == 64) { "slotIdHex must be 64 hex chars" }
|
||||||
|
return "shade-profile-aad-v1:$slotIdHex".toByteArray(Charsets.UTF_8)
|
||||||
|
}
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
package no.zyon.shade.blob
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
import no.zyon.shade.serialization.canonicalJson
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.net.URI
|
||||||
|
import java.net.http.HttpClient
|
||||||
|
import java.net.http.HttpRequest
|
||||||
|
import java.net.http.HttpResponse
|
||||||
|
import java.time.Duration
|
||||||
|
import java.util.Base64
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Low-level HTTP client for the V4.9 encrypted-blob primitive
|
||||||
|
* (`/v1/blob/<slotId>`). Mirror `@shade/inbox`'s `BlobClient` —
|
||||||
|
* stateless, reusable, and protocol-compatible with the TypeScript
|
||||||
|
* relay endpoints.
|
||||||
|
*
|
||||||
|
* The client doesn't care what the blob bytes mean — it just
|
||||||
|
* transports them. Higher-level wrappers (e.g. `Profile`) compose
|
||||||
|
* this client with AEAD-sealing of the actual payload.
|
||||||
|
*
|
||||||
|
* Auth model: every PUT/DELETE carries a detached Ed25519 signature
|
||||||
|
* (base64) over a canonical-JSON form of the request body. The
|
||||||
|
* canonicalization is deterministic — sorted keys, compact JSON, no
|
||||||
|
* trailing whitespace — so signatures generated on Kotlin verify on
|
||||||
|
* the TS server.
|
||||||
|
*/
|
||||||
|
class BlobClient(
|
||||||
|
private val baseUrl: String,
|
||||||
|
private val crypto: CryptoProvider,
|
||||||
|
private val httpClient: HttpClient = HttpClient.newBuilder()
|
||||||
|
.connectTimeout(Duration.ofSeconds(15))
|
||||||
|
.build(),
|
||||||
|
) {
|
||||||
|
|
||||||
|
data class GetResult(
|
||||||
|
val blob: ByteArray,
|
||||||
|
val etag: String,
|
||||||
|
val updatedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class PutResult(
|
||||||
|
val created: Boolean,
|
||||||
|
val etag: String,
|
||||||
|
val updatedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a slot. Returns null if no blob has ever been written there
|
||||||
|
* (or if it was DELETE'd). GET is unauthenticated by design — the
|
||||||
|
* slotId is itself a 256-bit secret derived from the master key.
|
||||||
|
*/
|
||||||
|
fun get(slotIdHex: String): GetResult? {
|
||||||
|
validateSlotIdHex(slotIdHex)
|
||||||
|
val req = HttpRequest.newBuilder(URI.create(joinUrl(baseUrl, "/v1/blob/$slotIdHex")))
|
||||||
|
.GET()
|
||||||
|
.build()
|
||||||
|
val res = httpClient.send(req, HttpResponse.BodyHandlers.ofString())
|
||||||
|
if (res.statusCode() == 404) return null
|
||||||
|
val json = parseJson(res, "GET")
|
||||||
|
val blob = Base64.getDecoder().decode(json.getString("blob"))
|
||||||
|
return GetResult(
|
||||||
|
blob = blob,
|
||||||
|
etag = json.getString("etag"),
|
||||||
|
updatedAt = json.getLong("updatedAt"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update a slot.
|
||||||
|
*
|
||||||
|
* `ifMatch` semantics:
|
||||||
|
* - `null`: create-only. Slot must be empty (else 409).
|
||||||
|
* - `<etag-string>`: compare-and-swap. Must match (else 412).
|
||||||
|
* - `"*"`: unconditional overwrite. Slot must already exist (else 412).
|
||||||
|
*/
|
||||||
|
fun put(
|
||||||
|
slotIdHex: String,
|
||||||
|
blob: ByteArray,
|
||||||
|
signingSeed: ByteArray,
|
||||||
|
ownerPubkey: ByteArray,
|
||||||
|
ifMatch: String? = null,
|
||||||
|
): PutResult {
|
||||||
|
validateSlotIdHex(slotIdHex)
|
||||||
|
require(blob.isNotEmpty()) { "Empty blob" }
|
||||||
|
require(ownerPubkey.size == 32) { "ownerPubkey must be 32 bytes (Ed25519)" }
|
||||||
|
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
|
||||||
|
|
||||||
|
// Canonical form for signing: sorted keys, slotId included,
|
||||||
|
// signature field absent. The wire body strips slotId (it's
|
||||||
|
// in the URL) but the signature is computed over the
|
||||||
|
// slotId-bearing form.
|
||||||
|
val signedAt = System.currentTimeMillis()
|
||||||
|
val canonical = sortedMapOf<String, Any>().apply {
|
||||||
|
put("blob", Base64.getEncoder().encodeToString(blob))
|
||||||
|
if (ifMatch != null) put("ifMatch", ifMatch)
|
||||||
|
put("ownerPubkey", Base64.getEncoder().encodeToString(ownerPubkey))
|
||||||
|
put("signedAt", signedAt)
|
||||||
|
put("slotId", slotIdHex)
|
||||||
|
}
|
||||||
|
val canonicalBytes = canonicalJson(canonical).toByteArray(Charsets.UTF_8)
|
||||||
|
val sig = crypto.sign(signingSeed, canonicalBytes)
|
||||||
|
|
||||||
|
// Wire body: same as canonical minus slotId, plus signature.
|
||||||
|
val wire = JSONObject()
|
||||||
|
wire.put("blob", Base64.getEncoder().encodeToString(blob))
|
||||||
|
if (ifMatch != null) wire.put("ifMatch", ifMatch)
|
||||||
|
wire.put("ownerPubkey", Base64.getEncoder().encodeToString(ownerPubkey))
|
||||||
|
wire.put("signedAt", signedAt)
|
||||||
|
wire.put("signature", Base64.getEncoder().encodeToString(sig))
|
||||||
|
|
||||||
|
val req = HttpRequest.newBuilder(URI.create(joinUrl(baseUrl, "/v1/blob/$slotIdHex")))
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.PUT(HttpRequest.BodyPublishers.ofString(wire.toString()))
|
||||||
|
.build()
|
||||||
|
val res = httpClient.send(req, HttpResponse.BodyHandlers.ofString())
|
||||||
|
val json = parseJson(res, "PUT")
|
||||||
|
return PutResult(
|
||||||
|
created = json.optBoolean("created"),
|
||||||
|
etag = json.getString("etag"),
|
||||||
|
updatedAt = json.getLong("updatedAt"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a slot. The next PUT TOFU-claims it again, possibly under
|
||||||
|
* a fresh signing key (e.g. after rotation). Used by "forget
|
||||||
|
* everything" flows.
|
||||||
|
*/
|
||||||
|
fun delete(slotIdHex: String, signingSeed: ByteArray): Boolean {
|
||||||
|
validateSlotIdHex(slotIdHex)
|
||||||
|
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
|
||||||
|
|
||||||
|
val signedAt = System.currentTimeMillis()
|
||||||
|
val canonical = sortedMapOf<String, Any>().apply {
|
||||||
|
put("signedAt", signedAt)
|
||||||
|
put("slotId", slotIdHex)
|
||||||
|
}
|
||||||
|
val canonicalBytes = canonicalJson(canonical).toByteArray(Charsets.UTF_8)
|
||||||
|
val sig = crypto.sign(signingSeed, canonicalBytes)
|
||||||
|
|
||||||
|
val wire = JSONObject()
|
||||||
|
wire.put("signedAt", signedAt)
|
||||||
|
wire.put("signature", Base64.getEncoder().encodeToString(sig))
|
||||||
|
|
||||||
|
val req = HttpRequest.newBuilder(URI.create(joinUrl(baseUrl, "/v1/blob/$slotIdHex")))
|
||||||
|
.header("content-type", "application/json")
|
||||||
|
.method("DELETE", HttpRequest.BodyPublishers.ofString(wire.toString()))
|
||||||
|
.build()
|
||||||
|
val res = httpClient.send(req, HttpResponse.BodyHandlers.ofString())
|
||||||
|
val json = parseJson(res, "DELETE")
|
||||||
|
return json.optBoolean("ok", false)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun parseJson(res: HttpResponse<String>, op: String): JSONObject {
|
||||||
|
val text = res.body() ?: ""
|
||||||
|
val json = if (text.isEmpty()) JSONObject() else try {
|
||||||
|
JSONObject(text)
|
||||||
|
} catch (e: Exception) {
|
||||||
|
throw BlobClientException(
|
||||||
|
code = "SHADE_NETWORK",
|
||||||
|
statusCode = res.statusCode(),
|
||||||
|
message = "Blob $op response not JSON: ${text.take(200)}",
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if (res.statusCode() !in 200..299) {
|
||||||
|
throw BlobClientException(
|
||||||
|
code = json.optString("code", "SHADE_NETWORK"),
|
||||||
|
statusCode = res.statusCode(),
|
||||||
|
message = json.optString("message", text),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return json
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun validateSlotIdHex(s: String) {
|
||||||
|
require(s.matches(Regex("^[0-9a-f]{64}$"))) {
|
||||||
|
"slotIdHex must be 64 lowercase hex chars (32 bytes)"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun joinUrl(base: String, path: String): String =
|
||||||
|
when {
|
||||||
|
base.endsWith("/") && path.startsWith("/") -> base + path.substring(1)
|
||||||
|
!base.endsWith("/") && !path.startsWith("/") -> "$base/$path"
|
||||||
|
else -> base + path
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
class BlobClientException(
|
||||||
|
val code: String,
|
||||||
|
val statusCode: Int,
|
||||||
|
message: String,
|
||||||
|
) : RuntimeException("[$code @ $statusCode] $message")
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
package no.zyon.shade.blob
|
||||||
|
|
||||||
|
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V4.9 — relay-side encrypted blob primitive: deterministic
|
||||||
|
* derivations from a 32-byte master key + per-app namespace string.
|
||||||
|
*
|
||||||
|
* Mirror `@shade/storage-encrypted/crypto/kdf.ts` byte-for-byte.
|
||||||
|
* Reference vectors: `test-vectors/blob-storage.json`.
|
||||||
|
*
|
||||||
|
* Three independent 32-byte derivations:
|
||||||
|
*
|
||||||
|
* slotId = HKDF(masterKey, info=`shade-blob-slot-v1:<app>`) // relay-visible opaque ID
|
||||||
|
* blobKey = HKDF(masterKey, info=`shade-blob-key-v1:<app>`) // AEAD key for the blob
|
||||||
|
* sigSeed = HKDF(masterKey, info=`shade-blob-sig-v1:<app>`) // Ed25519 owner signing seed
|
||||||
|
*
|
||||||
|
* `app` is a caller-supplied namespace string — distinct apps under
|
||||||
|
* the same master MUST pass different values (e.g. `prism-profile-v1`)
|
||||||
|
* so they don't collide on the same slot.
|
||||||
|
*
|
||||||
|
* The signing seed is an Ed25519 *seed* in the @noble/curves convention:
|
||||||
|
* `pubkey = Ed25519.publicFromSeed(seed)` is what the relay TOFU-stores
|
||||||
|
* on the first PUT and verifies subsequent writes against.
|
||||||
|
*/
|
||||||
|
|
||||||
|
private const val SLOT_INFO_PREFIX = "shade-blob-slot-v1:"
|
||||||
|
private const val BLOB_KEY_INFO_PREFIX = "shade-blob-key-v1:"
|
||||||
|
private const val SIG_SEED_INFO_PREFIX = "shade-blob-sig-v1:"
|
||||||
|
|
||||||
|
private const val DERIVED_LEN = 32
|
||||||
|
|
||||||
|
/** Lower-hex 64-char slotId derived deterministically from the master key. */
|
||||||
|
fun deriveBlobSlotId(crypto: CryptoProvider, masterKey: ByteArray, app: String): ByteArray {
|
||||||
|
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
|
||||||
|
require(app.isNotEmpty()) { "app namespace must be non-empty" }
|
||||||
|
return crypto.hkdf(
|
||||||
|
masterKey,
|
||||||
|
ByteArray(0),
|
||||||
|
(SLOT_INFO_PREFIX + app).toByteArray(Charsets.UTF_8),
|
||||||
|
DERIVED_LEN,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** AEAD key for sealing/opening the blob. The slotId hex is bound as AAD. */
|
||||||
|
fun deriveBlobKey(crypto: CryptoProvider, masterKey: ByteArray, app: String): ByteArray {
|
||||||
|
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
|
||||||
|
require(app.isNotEmpty()) { "app namespace must be non-empty" }
|
||||||
|
return crypto.hkdf(
|
||||||
|
masterKey,
|
||||||
|
ByteArray(0),
|
||||||
|
(BLOB_KEY_INFO_PREFIX + app).toByteArray(Charsets.UTF_8),
|
||||||
|
DERIVED_LEN,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 32-byte Ed25519 signing seed. The pubkey, derived deterministically
|
||||||
|
* from the seed, is what the relay TOFU-stores on the first PUT.
|
||||||
|
*/
|
||||||
|
fun deriveBlobSigningSeed(crypto: CryptoProvider, masterKey: ByteArray, app: String): ByteArray {
|
||||||
|
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
|
||||||
|
require(app.isNotEmpty()) { "app namespace must be non-empty" }
|
||||||
|
return crypto.hkdf(
|
||||||
|
masterKey,
|
||||||
|
ByteArray(0),
|
||||||
|
(SIG_SEED_INFO_PREFIX + app).toByteArray(Charsets.UTF_8),
|
||||||
|
DERIVED_LEN,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Recover the Ed25519 public key from a 32-byte seed. Mirrors
|
||||||
|
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`.
|
||||||
|
*
|
||||||
|
* 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 {
|
||||||
|
require(seed.size == 32) { "Ed25519 seed must be 32 bytes" }
|
||||||
|
return Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */
|
||||||
|
fun slotIdToHex(slotId: ByteArray): String {
|
||||||
|
require(slotId.size == 32) { "slotId must be 32 bytes" }
|
||||||
|
return slotId.joinToString("") { "%02x".format(it) }
|
||||||
|
}
|
||||||
@@ -0,0 +1,118 @@
|
|||||||
|
package no.zyon.shade.blob
|
||||||
|
|
||||||
|
import no.zyon.shade.crypto.CryptoProvider
|
||||||
|
|
||||||
|
/**
|
||||||
|
* V4.9 — high-level profile namespace. Mirror
|
||||||
|
* `@shade/sdk`'s `createProfileNamespace`. The relay never sees
|
||||||
|
* plaintext; AAD binds the slotId so a relay returning the wrong
|
||||||
|
* slot's blob fails to open.
|
||||||
|
*
|
||||||
|
* Usage:
|
||||||
|
*
|
||||||
|
* val crypto = TinkProvider()
|
||||||
|
* val masterKey = deriveMasterKey("password", salt) // V4.5 KDF chain
|
||||||
|
* val profile = createProfileNamespace(
|
||||||
|
* baseUrl = "https://shade.example/",
|
||||||
|
* crypto = crypto,
|
||||||
|
* masterKey = masterKey,
|
||||||
|
* app = "prism-profile-v1",
|
||||||
|
* )
|
||||||
|
*
|
||||||
|
* val current = profile.get() // null if no blob yet
|
||||||
|
* profile.put(serializeCanonicalProfile(...), ifMatch = current?.etag)
|
||||||
|
* profile.delete()
|
||||||
|
*
|
||||||
|
* Apps with the same master key + app namespace converge on the same
|
||||||
|
* slot — that's the whole point: a brand new device with the right
|
||||||
|
* credentials can locate, decrypt, and update the blob.
|
||||||
|
*/
|
||||||
|
class ProfileNamespace internal constructor(
|
||||||
|
/** Lower-hex 64-char slotId. Stable per (master, app). */
|
||||||
|
val slotIdHex: String,
|
||||||
|
private val blobKey: ByteArray,
|
||||||
|
private val signingSeed: ByteArray,
|
||||||
|
private val ownerPubkey: ByteArray,
|
||||||
|
private val aad: ByteArray,
|
||||||
|
private val client: BlobClient,
|
||||||
|
private val crypto: CryptoProvider,
|
||||||
|
) {
|
||||||
|
|
||||||
|
data class GetResult(
|
||||||
|
val plaintext: ByteArray,
|
||||||
|
val etag: String,
|
||||||
|
val updatedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
data class PutResult(
|
||||||
|
val created: Boolean,
|
||||||
|
val etag: String,
|
||||||
|
val updatedAt: Long,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Returns null when the slot has never been written (or was deleted). */
|
||||||
|
fun get(): GetResult? {
|
||||||
|
val raw = client.get(slotIdHex) ?: return null
|
||||||
|
val plaintext = aeadOpen(blobKey, raw.blob, aad)
|
||||||
|
return GetResult(plaintext = plaintext, etag = raw.etag, updatedAt = raw.updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update. `ifMatch`:
|
||||||
|
* - null: create-only (fails with 409 if slot populated).
|
||||||
|
* - "<etag>": CAS (fails with 412 on stale).
|
||||||
|
* - "*": unconditional overwrite.
|
||||||
|
*/
|
||||||
|
fun put(plaintext: ByteArray, ifMatch: String? = null): PutResult {
|
||||||
|
// Fresh random nonce per write — see `BlobAead`. Re-uploading
|
||||||
|
// the same plaintext after a transient error reuses neither
|
||||||
|
// (key, nonce, plaintext) nor (key, nonce).
|
||||||
|
val nonce = crypto.randomBytes(BLOB_AEAD_NONCE_LEN)
|
||||||
|
val sealed = aeadSeal(blobKey, nonce, plaintext, aad)
|
||||||
|
val r = client.put(
|
||||||
|
slotIdHex = slotIdHex,
|
||||||
|
blob = sealed,
|
||||||
|
signingSeed = signingSeed,
|
||||||
|
ownerPubkey = ownerPubkey,
|
||||||
|
ifMatch = ifMatch,
|
||||||
|
)
|
||||||
|
return PutResult(created = r.created, etag = r.etag, updatedAt = r.updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
/** "Forget everything" path — the next PUT TOFU-claims it again. */
|
||||||
|
fun delete(): Boolean = client.delete(slotIdHex, signingSeed)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a Profile namespace bound to a (master key, app) pair. The
|
||||||
|
* derivations are deterministic: any device with the same master
|
||||||
|
* key + app namespace produces the same slot, so a fresh device
|
||||||
|
* after credential entry can locate the existing profile blob.
|
||||||
|
*/
|
||||||
|
fun createProfileNamespace(
|
||||||
|
baseUrl: String,
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
masterKey: ByteArray,
|
||||||
|
app: String,
|
||||||
|
): ProfileNamespace {
|
||||||
|
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
|
||||||
|
require(app.isNotEmpty()) { "app namespace must be non-empty" }
|
||||||
|
|
||||||
|
val slotIdBytes = deriveBlobSlotId(crypto, masterKey, app)
|
||||||
|
val slotIdHex = slotIdToHex(slotIdBytes)
|
||||||
|
val blobKey = deriveBlobKey(crypto, masterKey, app)
|
||||||
|
val signingSeed = deriveBlobSigningSeed(crypto, masterKey, app)
|
||||||
|
val ownerPubkey = ed25519PublicKeyFromSeed(signingSeed)
|
||||||
|
val aad = blobAadForSlot(slotIdHex)
|
||||||
|
|
||||||
|
val client = BlobClient(baseUrl = baseUrl, crypto = crypto)
|
||||||
|
return ProfileNamespace(
|
||||||
|
slotIdHex = slotIdHex,
|
||||||
|
blobKey = blobKey,
|
||||||
|
signingSeed = signingSeed,
|
||||||
|
ownerPubkey = ownerPubkey,
|
||||||
|
aad = aad,
|
||||||
|
client = client,
|
||||||
|
crypto = crypto,
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -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,133 @@
|
|||||||
|
package no.zyon.shade.serialization
|
||||||
|
|
||||||
|
import no.zyon.shade.types.ChainState
|
||||||
|
import no.zyon.shade.types.IdentityKeyPair
|
||||||
|
import no.zyon.shade.types.KeyPair
|
||||||
|
import no.zyon.shade.types.OneTimePreKey
|
||||||
|
import no.zyon.shade.types.SessionState
|
||||||
|
import no.zyon.shade.types.SignedPreKey
|
||||||
|
import org.json.JSONObject
|
||||||
|
import java.util.Base64 as JdkBase64
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Plain-JSON serialization for the persisted protocol state types
|
||||||
|
* (`IdentityKeyPair`, `SignedPreKey`, `OneTimePreKey`, `SessionState`).
|
||||||
|
*
|
||||||
|
* The on-disk shape is for at-rest storage only — it does NOT need
|
||||||
|
* to round-trip across platforms (TS uses its own JSON shape via
|
||||||
|
* `@shade/core/serialization`). What matters is that the Kotlin
|
||||||
|
* round-trip (`serialize` then `deserialize`) preserves every byte.
|
||||||
|
*
|
||||||
|
* Both Android-targeted (`shade-android-keystore`) and pure-JVM
|
||||||
|
* (`shade-android` tests) callers use this — the function works
|
||||||
|
* without any `android.*` imports so it compiles in both.
|
||||||
|
*/
|
||||||
|
object SessionStateJson {
|
||||||
|
|
||||||
|
fun serialize(state: SessionState): String {
|
||||||
|
val o = JSONObject()
|
||||||
|
o.put("remoteIdentityKey", b64(state.remoteIdentityKey))
|
||||||
|
o.put("rootKey", b64(state.rootKey))
|
||||||
|
o.put("sendChain", chainToJson(state.sendChain))
|
||||||
|
if (state.receiveChain != null) o.put("receiveChain", chainToJson(state.receiveChain!!))
|
||||||
|
o.put("dhSend", keyPairToJson(state.dhSend))
|
||||||
|
if (state.dhReceive != null) o.put("dhReceive", b64(state.dhReceive!!))
|
||||||
|
o.put("previousSendCounter", state.previousSendCounter)
|
||||||
|
val skipped = JSONObject()
|
||||||
|
for ((k, v) in state.skippedKeys) skipped.put(k, b64(v))
|
||||||
|
o.put("skippedKeys", skipped)
|
||||||
|
return o.toString()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun deserialize(s: String): SessionState {
|
||||||
|
val o = JSONObject(s)
|
||||||
|
val skipped = mutableMapOf<String, ByteArray>()
|
||||||
|
val skJson = o.optJSONObject("skippedKeys")
|
||||||
|
if (skJson != null) {
|
||||||
|
val it = skJson.keys()
|
||||||
|
while (it.hasNext()) {
|
||||||
|
val k = it.next()
|
||||||
|
skipped[k] = fb64(skJson.getString(k))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SessionState(
|
||||||
|
remoteIdentityKey = fb64(o.getString("remoteIdentityKey")),
|
||||||
|
rootKey = fb64(o.getString("rootKey")),
|
||||||
|
sendChain = chainFromJson(o.getJSONObject("sendChain")),
|
||||||
|
receiveChain = if (o.has("receiveChain"))
|
||||||
|
chainFromJson(o.getJSONObject("receiveChain")) else null,
|
||||||
|
dhSend = keyPairFromJson(o.getJSONObject("dhSend")),
|
||||||
|
dhReceive = if (o.has("dhReceive")) fb64(o.getString("dhReceive")) else null,
|
||||||
|
previousSendCounter = o.getInt("previousSendCounter"),
|
||||||
|
skippedKeys = skipped,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun serializeIdentityKeyPair(k: IdentityKeyPair): String = JSONObject().apply {
|
||||||
|
put("signingPublicKey", b64(k.signingPublicKey))
|
||||||
|
put("signingPrivateKey", b64(k.signingPrivateKey))
|
||||||
|
put("dhPublicKey", b64(k.dhPublicKey))
|
||||||
|
put("dhPrivateKey", b64(k.dhPrivateKey))
|
||||||
|
}.toString()
|
||||||
|
|
||||||
|
fun deserializeIdentityKeyPair(s: String): IdentityKeyPair = JSONObject(s).run {
|
||||||
|
IdentityKeyPair(
|
||||||
|
signingPublicKey = fb64(getString("signingPublicKey")),
|
||||||
|
signingPrivateKey = fb64(getString("signingPrivateKey")),
|
||||||
|
dhPublicKey = fb64(getString("dhPublicKey")),
|
||||||
|
dhPrivateKey = fb64(getString("dhPrivateKey")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun serializeSignedPreKey(k: SignedPreKey): String = JSONObject().apply {
|
||||||
|
put("keyId", k.keyId)
|
||||||
|
put("keyPair", keyPairToJson(k.keyPair))
|
||||||
|
put("signature", b64(k.signature))
|
||||||
|
put("timestamp", k.timestamp)
|
||||||
|
}.toString()
|
||||||
|
|
||||||
|
fun deserializeSignedPreKey(s: String): SignedPreKey = JSONObject(s).run {
|
||||||
|
SignedPreKey(
|
||||||
|
keyId = getInt("keyId"),
|
||||||
|
keyPair = keyPairFromJson(getJSONObject("keyPair")),
|
||||||
|
signature = fb64(getString("signature")),
|
||||||
|
timestamp = getLong("timestamp"),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fun serializeOneTimePreKey(k: OneTimePreKey): String = JSONObject().apply {
|
||||||
|
put("keyId", k.keyId)
|
||||||
|
put("keyPair", keyPairToJson(k.keyPair))
|
||||||
|
}.toString()
|
||||||
|
|
||||||
|
fun deserializeOneTimePreKey(s: String): OneTimePreKey = JSONObject(s).run {
|
||||||
|
OneTimePreKey(
|
||||||
|
keyId = getInt("keyId"),
|
||||||
|
keyPair = keyPairFromJson(getJSONObject("keyPair")),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun chainToJson(c: ChainState): JSONObject = JSONObject().apply {
|
||||||
|
put("chainKey", b64(c.chainKey))
|
||||||
|
put("counter", c.counter)
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun chainFromJson(o: JSONObject): ChainState =
|
||||||
|
ChainState(chainKey = fb64(o.getString("chainKey")), counter = o.getInt("counter"))
|
||||||
|
|
||||||
|
private fun keyPairToJson(k: KeyPair): JSONObject = JSONObject().apply {
|
||||||
|
put("publicKey", b64(k.publicKey))
|
||||||
|
put("privateKey", b64(k.privateKey))
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun keyPairFromJson(o: JSONObject): KeyPair = KeyPair(
|
||||||
|
publicKey = fb64(o.getString("publicKey")),
|
||||||
|
privateKey = fb64(o.getString("privateKey")),
|
||||||
|
)
|
||||||
|
|
||||||
|
// android.util.Base64 isn't on the JVM classpath; java.util.Base64
|
||||||
|
// is available on both modern JVM and Android API 26+. Use JDK
|
||||||
|
// Base64 throughout — it's present on both targets.
|
||||||
|
private fun b64(b: ByteArray): String = JdkBase64.getEncoder().encodeToString(b)
|
||||||
|
private fun fb64(s: String): ByteArray = JdkBase64.getDecoder().decode(s)
|
||||||
|
}
|
||||||
@@ -0,0 +1,107 @@
|
|||||||
|
package no.zyon.shade.storage
|
||||||
|
|
||||||
|
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
|
||||||
|
import org.bouncycastle.crypto.generators.SCrypt
|
||||||
|
import org.bouncycastle.crypto.params.Argon2Parameters
|
||||||
|
import java.text.Normalizer
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Password / PIN key-derivation primitives. Mirror
|
||||||
|
* `@shade/storage-encrypted/crypto/kdf` (`deriveMasterKey` /
|
||||||
|
* `deriveMasterKeyArgon2id`) byte-for-byte — Tink doesn't ship password
|
||||||
|
* KDFs so we wrap Bouncy Castle.
|
||||||
|
*
|
||||||
|
* Both functions normalize string passphrases to NFKC before hashing,
|
||||||
|
* matching the TS implementation's `passphrase.normalize('NFKC')`.
|
||||||
|
* This ensures the same password typed on different OSes/keyboards
|
||||||
|
* produces the same master key regardless of which compatibility-form
|
||||||
|
* the input arrived in.
|
||||||
|
*
|
||||||
|
* The reference test-vector lives in `test-vectors/storage-encryption.json`
|
||||||
|
* and `test-vectors/blob-storage.json`. Cross-platform parity is gated
|
||||||
|
* by `CrossPlatformVectorTest`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** scrypt parameters. Defaults match `DEFAULT_SCRYPT` in TS. */
|
||||||
|
data class ScryptParams(
|
||||||
|
/** CPU/memory cost. Must be a power of 2. */
|
||||||
|
val n: Int = 1 shl 17,
|
||||||
|
/** Block size. */
|
||||||
|
val r: Int = 8,
|
||||||
|
/** Parallelization. */
|
||||||
|
val p: Int = 1,
|
||||||
|
/** Output length in bytes. */
|
||||||
|
val dkLen: Int = 32,
|
||||||
|
)
|
||||||
|
|
||||||
|
/** Argon2id parameters. Defaults match `DEFAULT_ARGON2ID` in TS. */
|
||||||
|
data class Argon2idParams(
|
||||||
|
/** Memory cost in KiB. Default 64 MiB. */
|
||||||
|
val m: Int = 64 * 1024,
|
||||||
|
/** Time cost (iterations). Default 3. */
|
||||||
|
val t: Int = 3,
|
||||||
|
/** Parallelism. Default 1. */
|
||||||
|
val p: Int = 1,
|
||||||
|
/** Output length in bytes. Default 32. */
|
||||||
|
val dkLen: Int = 32,
|
||||||
|
)
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive a 32-byte master key from a passphrase + salt via scrypt.
|
||||||
|
* Salt MUST be at least 16 bytes and persisted alongside the
|
||||||
|
* encrypted database. Throws on empty passphrase.
|
||||||
|
*/
|
||||||
|
fun deriveMasterKey(
|
||||||
|
passphrase: String,
|
||||||
|
salt: ByteArray,
|
||||||
|
params: ScryptParams = ScryptParams(),
|
||||||
|
): ByteArray {
|
||||||
|
require(passphrase.isNotEmpty()) { "passphrase must be non-empty" }
|
||||||
|
require(salt.size >= 16) { "salt must be at least 16 bytes" }
|
||||||
|
val nfkc = Normalizer.normalize(passphrase, Normalizer.Form.NFKC)
|
||||||
|
val pwBytes = nfkc.toByteArray(Charsets.UTF_8)
|
||||||
|
return SCrypt.generate(pwBytes, salt, params.n, params.r, params.p, params.dkLen)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive a 32-byte master key from a low-entropy secret (PIN) + salt
|
||||||
|
* via argon2id. Salt MUST be at least 16 bytes. The Bouncy Castle
|
||||||
|
* `Argon2BytesGenerator` parameters mirror RFC 9106's argon2id mode
|
||||||
|
* with version 1.3 (`Argon2Parameters.ARGON2_VERSION_13`), which is
|
||||||
|
* what `@noble/hashes/argon2` produces — keeping cross-platform parity.
|
||||||
|
*/
|
||||||
|
fun deriveMasterKeyArgon2id(
|
||||||
|
secret: String,
|
||||||
|
salt: ByteArray,
|
||||||
|
params: Argon2idParams = Argon2idParams(),
|
||||||
|
): ByteArray {
|
||||||
|
require(secret.isNotEmpty()) { "argon2id secret must be non-empty" }
|
||||||
|
require(salt.size >= 16) { "salt must be at least 16 bytes" }
|
||||||
|
val nfkc = Normalizer.normalize(secret, Normalizer.Form.NFKC)
|
||||||
|
return deriveMasterKeyArgon2id(nfkc.toByteArray(Charsets.UTF_8), salt, params)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Byte-array overload — useful when the secret is already binary
|
||||||
|
* (e.g. derived from a hardware token rather than typed) and
|
||||||
|
* shouldn't be NFKC-normalized as text.
|
||||||
|
*/
|
||||||
|
fun deriveMasterKeyArgon2id(
|
||||||
|
secret: ByteArray,
|
||||||
|
salt: ByteArray,
|
||||||
|
params: Argon2idParams = Argon2idParams(),
|
||||||
|
): ByteArray {
|
||||||
|
require(secret.isNotEmpty()) { "argon2id secret must be non-empty" }
|
||||||
|
require(salt.size >= 16) { "salt must be at least 16 bytes" }
|
||||||
|
val builder = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
|
||||||
|
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
|
||||||
|
.withIterations(params.t)
|
||||||
|
.withMemoryAsKB(params.m)
|
||||||
|
.withParallelism(params.p)
|
||||||
|
.withSalt(salt)
|
||||||
|
val gen = Argon2BytesGenerator()
|
||||||
|
gen.init(builder.build())
|
||||||
|
val out = ByteArray(params.dkLen)
|
||||||
|
gen.generateBytes(secret, out)
|
||||||
|
return out
|
||||||
|
}
|
||||||
@@ -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,593 @@
|
|||||||
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import no.zyon.shade.approval.ApprovalRequestFrame
|
||||||
|
import no.zyon.shade.approval.ApprovalRequestingDevice
|
||||||
|
import no.zyon.shade.approval.CanonicalProfileBlob
|
||||||
|
import no.zyon.shade.approval.DEFAULT_APPROVAL_DOMAIN
|
||||||
|
import no.zyon.shade.approval.ProfileClientEntry
|
||||||
|
import no.zyon.shade.approval.ProfileHostEntry
|
||||||
|
import no.zyon.shade.approval.ProxyApprovalFrame
|
||||||
|
import no.zyon.shade.approval.VerifyProxyApprovalResult
|
||||||
|
import no.zyon.shade.approval.buildApprovalRequest
|
||||||
|
import no.zyon.shade.approval.canonicalApprovalSigningBytes
|
||||||
|
import no.zyon.shade.approval.emptyCanonicalProfile
|
||||||
|
import no.zyon.shade.approval.findClientByAddress
|
||||||
|
import no.zyon.shade.approval.findClientByFingerprint
|
||||||
|
import no.zyon.shade.approval.isTrustedApprover
|
||||||
|
import no.zyon.shade.approval.parseCanonicalProfile
|
||||||
|
import no.zyon.shade.approval.removeClient
|
||||||
|
import no.zyon.shade.approval.serializeCanonicalProfile
|
||||||
|
import no.zyon.shade.approval.setTrustedApprover
|
||||||
|
import no.zyon.shade.approval.signProxyApproval
|
||||||
|
import no.zyon.shade.approval.upsertClient
|
||||||
|
import no.zyon.shade.approval.upsertHost
|
||||||
|
import no.zyon.shade.approval.verifyProxyApproval
|
||||||
|
import no.zyon.shade.blob.aeadOpen
|
||||||
|
import no.zyon.shade.blob.aeadSeal
|
||||||
|
import no.zyon.shade.blob.blobAadForSlot
|
||||||
|
import no.zyon.shade.blob.deriveBlobKey
|
||||||
|
import no.zyon.shade.blob.deriveBlobSigningSeed
|
||||||
|
import no.zyon.shade.blob.deriveBlobSlotId
|
||||||
|
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
|
||||||
|
import no.zyon.shade.blob.slotIdToHex
|
||||||
|
import no.zyon.shade.crypto.TinkProvider
|
||||||
|
import no.zyon.shade.storage.Argon2idParams
|
||||||
|
import no.zyon.shade.storage.ScryptParams
|
||||||
|
import no.zyon.shade.storage.deriveMasterKey
|
||||||
|
import no.zyon.shade.storage.deriveMasterKeyArgon2id
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Assert.assertNotEquals
|
||||||
|
import org.junit.Assert.assertTrue
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unit tests for the V4.9 blob primitive ports + V4.10 approval
|
||||||
|
* helpers + scrypt/argon2id wrappers. Cross-platform vector parity
|
||||||
|
* lives in `CrossPlatformVectorTest`; this file tests Kotlin-side
|
||||||
|
* round-trip behavior independent of the TS reference.
|
||||||
|
*/
|
||||||
|
class BlobAndApprovalTest {
|
||||||
|
|
||||||
|
private val crypto = TinkProvider()
|
||||||
|
|
||||||
|
private fun hex(bytes: ByteArray): String =
|
||||||
|
bytes.joinToString("") { "%02x".format(it) }
|
||||||
|
|
||||||
|
// ─── V4.9 blob KDF ─────────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun deriveBlobSlotIdIsDeterministicPerMasterAndApp() {
|
||||||
|
val km = ByteArray(32) { it.toByte() }
|
||||||
|
val a1 = deriveBlobSlotId(crypto, km, "foo")
|
||||||
|
val a2 = deriveBlobSlotId(crypto, km, "foo")
|
||||||
|
assertArrayEquals(a1, a2)
|
||||||
|
|
||||||
|
val b = deriveBlobSlotId(crypto, km, "bar")
|
||||||
|
assertFalse(a1.contentEquals(b))
|
||||||
|
|
||||||
|
val km2 = ByteArray(32) { (it + 1).toByte() }
|
||||||
|
val c = deriveBlobSlotId(crypto, km2, "foo")
|
||||||
|
assertFalse(a1.contentEquals(c))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun blobKdfHelpersAreIndependent() {
|
||||||
|
val km = ByteArray(32) { it.toByte() }
|
||||||
|
val slot = deriveBlobSlotId(crypto, km, "x")
|
||||||
|
val key = deriveBlobKey(crypto, km, "x")
|
||||||
|
val seed = deriveBlobSigningSeed(crypto, km, "x")
|
||||||
|
assertFalse(slot.contentEquals(key))
|
||||||
|
assertFalse(slot.contentEquals(seed))
|
||||||
|
assertFalse(key.contentEquals(seed))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun ed25519PublicKeyFromSeedIsDeterministic() {
|
||||||
|
val seed = ByteArray(32) { it.toByte() }
|
||||||
|
val pk1 = ed25519PublicKeyFromSeed(seed)
|
||||||
|
val pk2 = ed25519PublicKeyFromSeed(seed)
|
||||||
|
assertArrayEquals(pk1, pk2)
|
||||||
|
assertEquals(32, pk1.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun slotIdToHexProducesLowercase64Chars() {
|
||||||
|
val s = ByteArray(32) { 0xab.toByte() }
|
||||||
|
val hex = slotIdToHex(s)
|
||||||
|
assertEquals(64, hex.length)
|
||||||
|
assertEquals("a".repeat(0) + "ab".repeat(32), hex)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── V4.9 AEAD round-trip ──────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aeadSealOpenRoundTrip() {
|
||||||
|
val key = crypto.randomBytes(32)
|
||||||
|
val nonce = crypto.randomBytes(12)
|
||||||
|
val pt = "hello".toByteArray()
|
||||||
|
val aad = blobAadForSlot("00".repeat(32))
|
||||||
|
val sealed = aeadSeal(key, nonce, pt, aad)
|
||||||
|
val opened = aeadOpen(key, sealed, aad)
|
||||||
|
assertArrayEquals(pt, opened)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aeadOpenWithWrongAadFails() {
|
||||||
|
val key = crypto.randomBytes(32)
|
||||||
|
val nonce = crypto.randomBytes(12)
|
||||||
|
val pt = "hello".toByteArray()
|
||||||
|
val aad1 = blobAadForSlot("00".repeat(32))
|
||||||
|
val aad2 = blobAadForSlot("ff".repeat(32))
|
||||||
|
val sealed = aeadSeal(key, nonce, pt, aad1)
|
||||||
|
try {
|
||||||
|
aeadOpen(key, sealed, aad2)
|
||||||
|
org.junit.Assert.fail("expected AEAD to reject wrong AAD")
|
||||||
|
} catch (_: Exception) {
|
||||||
|
// expected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun aeadOpenWithExpectedNonceMismatchFails() {
|
||||||
|
val key = crypto.randomBytes(32)
|
||||||
|
val nonce = crypto.randomBytes(12)
|
||||||
|
val wrongNonce = crypto.randomBytes(12)
|
||||||
|
val pt = "hello".toByteArray()
|
||||||
|
val aad = blobAadForSlot("00".repeat(32))
|
||||||
|
val sealed = aeadSeal(key, nonce, pt, aad)
|
||||||
|
try {
|
||||||
|
aeadOpen(key, sealed, aad, expectedNonce = wrongNonce)
|
||||||
|
org.junit.Assert.fail("expected expectedNonce check to reject")
|
||||||
|
} catch (_: IllegalArgumentException) {
|
||||||
|
// expected
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Password KDFs ─────────────────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun scryptDerivesDeterministically() {
|
||||||
|
val pw = "correct-horse-battery-staple"
|
||||||
|
val salt = ByteArray(16) { 0x42.toByte() }
|
||||||
|
val k1 = deriveMasterKey(pw, salt, ScryptParams(n = 1024))
|
||||||
|
val k2 = deriveMasterKey(pw, salt, ScryptParams(n = 1024))
|
||||||
|
assertArrayEquals(k1, k2)
|
||||||
|
assertEquals(32, k1.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun argon2idDerivesDeterministically() {
|
||||||
|
val pw = "1234"
|
||||||
|
val salt = ByteArray(16) { 0x55.toByte() }
|
||||||
|
val k1 = deriveMasterKeyArgon2id(pw, salt, Argon2idParams(m = 256, t = 2))
|
||||||
|
val k2 = deriveMasterKeyArgon2id(pw, salt, Argon2idParams(m = 256, t = 2))
|
||||||
|
assertArrayEquals(k1, k2)
|
||||||
|
assertEquals(32, k1.size)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun nfkcNormalizationMakesEquivalentInputsConverge() {
|
||||||
|
// "café" can be encoded either as 'c','a','f','é' (NFC) or
|
||||||
|
// 'c','a','f','e','́' (NFD). NFKC normalization on both
|
||||||
|
// should converge to the same bytes.
|
||||||
|
val nfc = "café"
|
||||||
|
val nfd = "café"
|
||||||
|
assertNotEquals(nfc, nfd)
|
||||||
|
val salt = ByteArray(16) { 1.toByte() }
|
||||||
|
val k1 = deriveMasterKey(nfc, salt, ScryptParams(n = 1024))
|
||||||
|
val k2 = deriveMasterKey(nfd, salt, ScryptParams(n = 1024))
|
||||||
|
assertArrayEquals(k1, k2)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Canonical profile schema ──────────────────────────────
|
||||||
|
|
||||||
|
private fun makeClient(name: String, trusted: Boolean = false): Pair<ProfileClientEntry, ByteArray> {
|
||||||
|
val seed = crypto.randomBytes(32)
|
||||||
|
val pubkey = ed25519PublicKeyFromSeed(seed)
|
||||||
|
val fp = "fp-$name-${hex(pubkey).take(8)}"
|
||||||
|
return ProfileClientEntry(
|
||||||
|
address = "device:$name",
|
||||||
|
identityPublicKey = hex(pubkey),
|
||||||
|
identityFingerprint = fp,
|
||||||
|
name = name,
|
||||||
|
kind = "mobile",
|
||||||
|
addedAt = 1_700_000_000_000L,
|
||||||
|
trustedApprover = trusted,
|
||||||
|
) to seed
|
||||||
|
}
|
||||||
|
|
||||||
|
private fun makeHost(): ProfileHostEntry = ProfileHostEntry(
|
||||||
|
address = "device:host-server",
|
||||||
|
name = "Server",
|
||||||
|
kind = "server",
|
||||||
|
addedAt = 1_700_000_000_000L,
|
||||||
|
)
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun emptyCanonicalProfileRoundTrips() {
|
||||||
|
val blob = emptyCanonicalProfile(now = 123L)
|
||||||
|
val bytes = serializeCanonicalProfile(blob)
|
||||||
|
val parsed = parseCanonicalProfile(bytes)
|
||||||
|
assertEquals(1, parsed.version)
|
||||||
|
assertTrue(parsed.hosts.isEmpty())
|
||||||
|
assertTrue(parsed.clients.isEmpty())
|
||||||
|
assertTrue(parsed.trustedApproverFingerprints.isEmpty())
|
||||||
|
assertEquals(123L, parsed.updatedAt)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun upsertClientDenormalizesTrustedApprovers() {
|
||||||
|
var blob = emptyCanonicalProfile(0)
|
||||||
|
val (a, _) = makeClient("phone-a", trusted = true)
|
||||||
|
val (b, _) = makeClient("phone-b", trusted = false)
|
||||||
|
blob = upsertClient(blob, a)
|
||||||
|
blob = upsertClient(blob, b)
|
||||||
|
assertEquals(2, blob.clients.size)
|
||||||
|
assertEquals(listOf(a.identityFingerprint), blob.trustedApproverFingerprints)
|
||||||
|
assertTrue(isTrustedApprover(blob, a.identityFingerprint))
|
||||||
|
assertFalse(isTrustedApprover(blob, b.identityFingerprint))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun setTrustedApproverIsIdempotentNoOpReturnsSameInstance() {
|
||||||
|
var blob = emptyCanonicalProfile(0)
|
||||||
|
val (c, _) = makeClient("phone", trusted = false)
|
||||||
|
blob = upsertClient(blob, c)
|
||||||
|
val before = blob
|
||||||
|
blob = setTrustedApprover(blob, c.identityFingerprint, false, now = 999L)
|
||||||
|
assertTrue(blob === before)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun setTrustedApproverFlipsFlagAndDenormalizedList() {
|
||||||
|
var blob = emptyCanonicalProfile(0)
|
||||||
|
val (c, _) = makeClient("phone", trusted = false)
|
||||||
|
blob = upsertClient(blob, c)
|
||||||
|
blob = setTrustedApprover(blob, c.identityFingerprint, true, now = 100L)
|
||||||
|
assertEquals(listOf(c.identityFingerprint), blob.trustedApproverFingerprints)
|
||||||
|
assertEquals(true, blob.clients[0].trustedApprover)
|
||||||
|
|
||||||
|
blob = setTrustedApprover(blob, c.identityFingerprint, false, now = 200L)
|
||||||
|
assertTrue(blob.trustedApproverFingerprints.isEmpty())
|
||||||
|
assertEquals(false, blob.clients[0].trustedApprover)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun removeClientCleansUpDenormalizedList() {
|
||||||
|
var blob = emptyCanonicalProfile(0)
|
||||||
|
val (c, _) = makeClient("phone", trusted = true)
|
||||||
|
blob = upsertClient(blob, c)
|
||||||
|
blob = removeClient(blob, c.identityFingerprint)
|
||||||
|
assertTrue(blob.clients.isEmpty())
|
||||||
|
assertTrue(blob.trustedApproverFingerprints.isEmpty())
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun findClientByFingerprintAndAddress() {
|
||||||
|
var blob = emptyCanonicalProfile(0)
|
||||||
|
val (c, _) = makeClient("phone")
|
||||||
|
blob = upsertClient(blob, c)
|
||||||
|
assertEquals(c.address, findClientByFingerprint(blob, c.identityFingerprint)?.address)
|
||||||
|
assertEquals(
|
||||||
|
c.identityFingerprint,
|
||||||
|
findClientByAddress(blob, c.address)?.identityFingerprint,
|
||||||
|
)
|
||||||
|
assertNull(findClientByFingerprint(blob, "unknown"))
|
||||||
|
assertNull(findClientByAddress(blob, "unknown"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun parseRejectsMalformedProfile() {
|
||||||
|
try {
|
||||||
|
parseCanonicalProfile("not json")
|
||||||
|
org.junit.Assert.fail("expected throw")
|
||||||
|
} catch (_: IllegalArgumentException) {}
|
||||||
|
try {
|
||||||
|
parseCanonicalProfile("""{"version":2}""")
|
||||||
|
org.junit.Assert.fail("expected throw")
|
||||||
|
} catch (_: IllegalArgumentException) {}
|
||||||
|
try {
|
||||||
|
parseCanonicalProfile(
|
||||||
|
"""{"version":1,"clients":[{"address":"x","name":"x","kind":"m","addedAt":0}]}""",
|
||||||
|
)
|
||||||
|
org.junit.Assert.fail("expected throw — missing identityPublicKey")
|
||||||
|
} catch (_: IllegalArgumentException) {}
|
||||||
|
try {
|
||||||
|
parseCanonicalProfile(
|
||||||
|
"""{"version":1,"clients":[{"address":"x","identityPublicKey":"NOTHEX","identityFingerprint":"x","name":"x","kind":"m","addedAt":0}]}""",
|
||||||
|
)
|
||||||
|
org.junit.Assert.fail("expected throw — bad pubkey hex")
|
||||||
|
} catch (_: IllegalArgumentException) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun fullProfileSerializeParsePreservesAllFields() {
|
||||||
|
var blob = emptyCanonicalProfile(1L)
|
||||||
|
blob = upsertHost(blob, makeHost(), now = 2L)
|
||||||
|
val (c, _) = makeClient("phone", trusted = true)
|
||||||
|
blob = upsertClient(blob, c, now = 3L)
|
||||||
|
blob = blob.copy(signedBy = "aabbccdd")
|
||||||
|
|
||||||
|
val bytes = serializeCanonicalProfile(blob)
|
||||||
|
val parsed = parseCanonicalProfile(bytes)
|
||||||
|
assertEquals(blob, parsed)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Approval signing payload ──────────────────────────────
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun canonicalApprovalSigningBytesIsDeterministic() {
|
||||||
|
val a = canonicalApprovalSigningBytes(
|
||||||
|
domain = DEFAULT_APPROVAL_DOMAIN,
|
||||||
|
requestId = "aabbccddeeff00112233445566778899",
|
||||||
|
hostFingerprint = "11111 22222 33333 44444",
|
||||||
|
requestingDeviceFingerprint = "55555 66666 77777 88888",
|
||||||
|
decision = "approve",
|
||||||
|
)
|
||||||
|
val b = canonicalApprovalSigningBytes(
|
||||||
|
domain = DEFAULT_APPROVAL_DOMAIN,
|
||||||
|
requestId = "aabbccddeeff00112233445566778899",
|
||||||
|
hostFingerprint = "11111 22222 33333 44444",
|
||||||
|
requestingDeviceFingerprint = "55555 66666 77777 88888",
|
||||||
|
decision = "approve",
|
||||||
|
)
|
||||||
|
assertArrayEquals(a, b)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun differentDecisionProducesDifferentSigningBytes() {
|
||||||
|
val approve = canonicalApprovalSigningBytes(
|
||||||
|
DEFAULT_APPROVAL_DOMAIN, "r", "h", "d", "approve",
|
||||||
|
)
|
||||||
|
val reject = canonicalApprovalSigningBytes(
|
||||||
|
DEFAULT_APPROVAL_DOMAIN, "r", "h", "d", "reject",
|
||||||
|
)
|
||||||
|
assertFalse(approve.contentEquals(reject))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun differentDomainProducesDifferentSigningBytes() {
|
||||||
|
val a = canonicalApprovalSigningBytes("shade-link-approve-v1", "r", "h", "d", "approve")
|
||||||
|
val b = canonicalApprovalSigningBytes("prism-link-approve-v1", "r", "h", "d", "approve")
|
||||||
|
assertFalse(a.contentEquals(b))
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Build / sign / verify ─────────────────────────────────
|
||||||
|
|
||||||
|
private data class Scenario(
|
||||||
|
val phone: ProfileClientEntry,
|
||||||
|
val phoneSeed: ByteArray,
|
||||||
|
val profile: CanonicalProfileBlob,
|
||||||
|
val request: ApprovalRequestFrame,
|
||||||
|
)
|
||||||
|
|
||||||
|
private fun buildScenario(): Scenario {
|
||||||
|
val (phone, seed) = makeClient("phone", trusted = true)
|
||||||
|
var profile = emptyCanonicalProfile(0)
|
||||||
|
profile = upsertHost(profile, makeHost())
|
||||||
|
profile = upsertClient(profile, phone)
|
||||||
|
|
||||||
|
val request = buildApprovalRequest(
|
||||||
|
crypto = crypto,
|
||||||
|
hostAddress = "device:host-server",
|
||||||
|
hostFingerprint = "host-fp-12345",
|
||||||
|
requestingDeviceFingerprint = "cafe-laptop-fp-67890",
|
||||||
|
deviceName = "cafe-laptop",
|
||||||
|
userAgent = "Mozilla/5.0",
|
||||||
|
ipHint = "203.0.113.7",
|
||||||
|
)
|
||||||
|
return Scenario(phone, seed, profile, request)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun happyPathApproveVerifies() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request,
|
||||||
|
decision = "approve",
|
||||||
|
approverFingerprint = s.phone.identityFingerprint,
|
||||||
|
approverSigningKey = s.phoneSeed,
|
||||||
|
)
|
||||||
|
assertEquals("linkApproveByProxy", approval.kind)
|
||||||
|
assertEquals(s.request.requestId, approval.requestId)
|
||||||
|
assertEquals(128, approval.signature.length)
|
||||||
|
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, approval, s.profile)
|
||||||
|
assertTrue(r is VerifyProxyApprovalResult.Ok)
|
||||||
|
assertEquals(s.phone.address, (r as VerifyProxyApprovalResult.Ok).approver.address)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun happyPathRejectVerifies() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "reject",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, approval, s.profile)
|
||||||
|
assertTrue(r is VerifyProxyApprovalResult.Ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun replayAgainstDifferentRequestFails() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val other = s.request.copy(requestId = "f".repeat(32))
|
||||||
|
val r = verifyProxyApproval(crypto, other, approval, s.profile)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.REQUEST_ID_MISMATCH,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun decisionTamperingFails() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val tampered = approval.copy(decision = "reject")
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, tampered, s.profile)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.BAD_SIGNATURE,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun hostFingerprintSwapFails() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val swapped = s.request.copy(hostFingerprint = "evil-host-fp")
|
||||||
|
val r = verifyProxyApproval(crypto, swapped, approval, s.profile)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.BAD_SIGNATURE,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun domainMismatchIsRejectedBeforeSignature() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val r = verifyProxyApproval(
|
||||||
|
crypto, s.request, approval.copy(domain = "prism-link-approve-v1"), s.profile,
|
||||||
|
)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.DOMAIN_MISMATCH,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun unknownApproverFails() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val lying = approval.copy(approverFingerprint = "no-such-fingerprint")
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, lying, s.profile)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.UNKNOWN_APPROVER,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun revokedApproverFailsWithNotTrusted() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val revoked = setTrustedApprover(s.profile, s.phone.identityFingerprint, false)
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, approval, revoked)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.NOT_TRUSTED,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun expiredRequestIsRejected() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, approval, s.profile, now = s.request.expiresAt + 1)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.EXPIRED,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun signatureWithWrongKeyFails() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val wrongSeed = crypto.randomBytes(32)
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, s.request, "approve",
|
||||||
|
approverFingerprint = s.phone.identityFingerprint, // claim phone
|
||||||
|
approverSigningKey = wrongSeed, // sign with different key
|
||||||
|
)
|
||||||
|
val r = verifyProxyApproval(crypto, s.request, approval, s.profile)
|
||||||
|
assertEquals(
|
||||||
|
VerifyProxyApprovalResult.Reason.BAD_SIGNATURE,
|
||||||
|
(r as VerifyProxyApprovalResult.Failed).reason,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun customDomainSurvivesRoundTrip() {
|
||||||
|
val s = buildScenario()
|
||||||
|
val request = s.request.copy(domain = "prism-link-approve-v1")
|
||||||
|
val approval = signProxyApproval(
|
||||||
|
crypto, request, "approve",
|
||||||
|
s.phone.identityFingerprint, s.phoneSeed,
|
||||||
|
)
|
||||||
|
assertEquals("prism-link-approve-v1", approval.domain)
|
||||||
|
val r = verifyProxyApproval(crypto, request, approval, s.profile)
|
||||||
|
assertTrue(r is VerifyProxyApprovalResult.Ok)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun requestIdIs32LowercaseHexChars() {
|
||||||
|
val r = buildApprovalRequest(
|
||||||
|
crypto, "device:h", "h", "r",
|
||||||
|
)
|
||||||
|
assertTrue(r.requestId.matches(Regex("^[0-9a-f]{32}$")))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun consecutiveBuildsProduceDistinctRequestIds() {
|
||||||
|
val a = buildApprovalRequest(crypto, "device:h", "h", "r")
|
||||||
|
val b = buildApprovalRequest(crypto, "device:h", "h", "r")
|
||||||
|
assertNotEquals(a.requestId, b.requestId)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── Sanity glue: TS-side reference frame parses on Kotlin ──
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun tsStyleProxyApprovalFrameParsesAndStructurallyMatches() {
|
||||||
|
// Construct a frame the way @shade/sdk would emit it via JSON,
|
||||||
|
// and check our Kotlin types accept the same field names.
|
||||||
|
val expected = ProxyApprovalFrame(
|
||||||
|
requestId = "00112233445566778899aabbccddeeff",
|
||||||
|
decision = "approve",
|
||||||
|
approverFingerprint = "fp",
|
||||||
|
signature = "ab".repeat(64),
|
||||||
|
domain = DEFAULT_APPROVAL_DOMAIN,
|
||||||
|
)
|
||||||
|
assertEquals("linkApproveByProxy", expected.kind)
|
||||||
|
assertEquals("approve", expected.decision)
|
||||||
|
|
||||||
|
val req = ApprovalRequestFrame(
|
||||||
|
requestId = "00112233445566778899aabbccddeeff",
|
||||||
|
hostAddress = "device:h",
|
||||||
|
hostFingerprint = "host-fp",
|
||||||
|
requestingDevice = ApprovalRequestingDevice(
|
||||||
|
fingerprint = "req-fp",
|
||||||
|
receivedAt = 1L,
|
||||||
|
),
|
||||||
|
expiresAt = 2L,
|
||||||
|
domain = DEFAULT_APPROVAL_DOMAIN,
|
||||||
|
)
|
||||||
|
assertNotNull(req)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,6 +1,13 @@
|
|||||||
package no.zyon.shade
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import no.zyon.shade.approval.canonicalApprovalSigningBytes
|
||||||
import no.zyon.shade.backup.deriveBackupKey
|
import no.zyon.shade.backup.deriveBackupKey
|
||||||
|
import no.zyon.shade.blob.aeadOpen
|
||||||
|
import no.zyon.shade.blob.blobAadForSlot
|
||||||
|
import no.zyon.shade.blob.deriveBlobKey
|
||||||
|
import no.zyon.shade.blob.deriveBlobSigningSeed
|
||||||
|
import no.zyon.shade.blob.deriveBlobSlotId
|
||||||
|
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
|
||||||
import no.zyon.shade.crypto.TinkProvider
|
import no.zyon.shade.crypto.TinkProvider
|
||||||
import no.zyon.shade.fingerprint.computeFingerprint
|
import no.zyon.shade.fingerprint.computeFingerprint
|
||||||
import no.zyon.shade.group.encodeSenderHeader
|
import no.zyon.shade.group.encodeSenderHeader
|
||||||
@@ -447,6 +454,92 @@ class CrossPlatformVectorTest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun blobKdfAndAeadVectorsMatch() {
|
||||||
|
val vectors = loadVectors("blob.json")
|
||||||
|
var kdfMatched = 0
|
||||||
|
var aeadMatched = 0
|
||||||
|
for (i in 0 until vectors.length()) {
|
||||||
|
val v = vectors.getJSONObject(i)
|
||||||
|
val desc = v.getString("description")
|
||||||
|
if (desc.startsWith("V4.9 blob KDF")) {
|
||||||
|
kdfMatched++
|
||||||
|
val masterKey = fromHex(v.getString("masterKey"))
|
||||||
|
val app = v.getString("app")
|
||||||
|
val slotId = deriveBlobSlotId(crypto, masterKey, app)
|
||||||
|
assertEquals(v.getString("slotId"), hex(slotId))
|
||||||
|
assertEquals(v.getString("blobKey"), hex(deriveBlobKey(crypto, masterKey, app)))
|
||||||
|
val seed = deriveBlobSigningSeed(crypto, masterKey, app)
|
||||||
|
assertEquals(v.getString("signingSeed"), hex(seed))
|
||||||
|
assertEquals(v.getString("ownerPubkey"), hex(ed25519PublicKeyFromSeed(seed)))
|
||||||
|
} else if (desc.startsWith("V4.9 blob AEAD")) {
|
||||||
|
aeadMatched++
|
||||||
|
val key = fromHex(v.getString("key"))
|
||||||
|
val slotIdHex = v.getString("slotIdHex")
|
||||||
|
val expectedPlaintext = fromHex(v.getString("plaintext"))
|
||||||
|
val wire = fromHex(v.getString("wire"))
|
||||||
|
val aad = blobAadForSlot(slotIdHex)
|
||||||
|
val opened = aeadOpen(key, wire, aad)
|
||||||
|
assertEquals(hex(expectedPlaintext), hex(opened))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue("KDF vectors expected", kdfMatched >= 3)
|
||||||
|
assertTrue("AEAD vectors expected", aeadMatched >= 2)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun approvalSigningPayloadVectorsMatch() {
|
||||||
|
val vectors = loadVectors("approval.json")
|
||||||
|
var payloadMatched = 0
|
||||||
|
var e2eMatched = 0
|
||||||
|
for (i in 0 until vectors.length()) {
|
||||||
|
val v = vectors.getJSONObject(i)
|
||||||
|
val desc = v.getString("description")
|
||||||
|
if (desc.startsWith("V4.10 approval signing payload")) {
|
||||||
|
payloadMatched++
|
||||||
|
val out = canonicalApprovalSigningBytes(
|
||||||
|
domain = v.getString("domain"),
|
||||||
|
requestId = v.getString("requestId"),
|
||||||
|
hostFingerprint = v.getString("hostFingerprint"),
|
||||||
|
requestingDeviceFingerprint = v.getString("requestingDeviceFingerprint"),
|
||||||
|
decision = v.getString("decision"),
|
||||||
|
)
|
||||||
|
assertEquals(v.getString("signingPayload"), hex(out))
|
||||||
|
} else if (desc.startsWith("V4.10 approval Ed25519 sign/verify")) {
|
||||||
|
e2eMatched++
|
||||||
|
val seed = fromHex(v.getString("seed"))
|
||||||
|
val pubkey = fromHex(v.getString("publicKey"))
|
||||||
|
assertEquals(hex(pubkey), hex(ed25519PublicKeyFromSeed(seed)))
|
||||||
|
|
||||||
|
val req = v.getJSONObject("request")
|
||||||
|
val payload = canonicalApprovalSigningBytes(
|
||||||
|
domain = req.getString("domain"),
|
||||||
|
requestId = req.getString("requestId"),
|
||||||
|
hostFingerprint = req.getString("hostFingerprint"),
|
||||||
|
requestingDeviceFingerprint = req.getString("requestingDeviceFingerprint"),
|
||||||
|
decision = req.getString("decision"),
|
||||||
|
)
|
||||||
|
assertEquals(v.getString("signingPayload"), hex(payload))
|
||||||
|
|
||||||
|
// Verify the TS-generated signature against our pubkey + payload.
|
||||||
|
// This is the load-bearing parity check: a Kotlin-implemented
|
||||||
|
// verifyProxyApproval running against a TS-signed approval
|
||||||
|
// succeeds.
|
||||||
|
val sig = fromHex(v.getString("signature"))
|
||||||
|
val ok = crypto.verify(pubkey, payload, sig)
|
||||||
|
assertTrue("Ed25519 verify of TS-signed approval failed", ok)
|
||||||
|
|
||||||
|
// And: Kotlin signs the same payload with the same seed and
|
||||||
|
// produces a sig the TS pubkey verifies. Ed25519 is
|
||||||
|
// deterministic, so the sig bytes also match exactly.
|
||||||
|
val mySig = crypto.sign(seed, payload)
|
||||||
|
assertEquals(v.getString("signature"), hex(mySig))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assertTrue("payload vectors expected", payloadMatched >= 3)
|
||||||
|
assertTrue("e2e sign/verify vector expected", e2eMatched >= 1)
|
||||||
|
}
|
||||||
|
|
||||||
@Test
|
@Test
|
||||||
fun ratchetStepRoundtripMatches() {
|
fun ratchetStepRoundtripMatches() {
|
||||||
val vectors = loadVectors("ratchet-step.json")
|
val vectors = loadVectors("ratchet-step.json")
|
||||||
|
|||||||
@@ -0,0 +1,123 @@
|
|||||||
|
package no.zyon.shade
|
||||||
|
|
||||||
|
import no.zyon.shade.serialization.SessionStateJson
|
||||||
|
import no.zyon.shade.types.ChainState
|
||||||
|
import no.zyon.shade.types.IdentityKeyPair
|
||||||
|
import no.zyon.shade.types.KeyPair
|
||||||
|
import no.zyon.shade.types.OneTimePreKey
|
||||||
|
import no.zyon.shade.types.SessionState
|
||||||
|
import no.zyon.shade.types.SignedPreKey
|
||||||
|
import org.junit.Assert.assertArrayEquals
|
||||||
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertNotNull
|
||||||
|
import org.junit.Assert.assertNull
|
||||||
|
import org.junit.Test
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Round-trip tests for the at-rest JSON serialization used by
|
||||||
|
* `KeystoreStorage`. The format isn't cross-platform (TS uses its
|
||||||
|
* own shape) — what matters is `serialize → deserialize` preserves
|
||||||
|
* every byte of every key.
|
||||||
|
*/
|
||||||
|
class SessionStateJsonTest {
|
||||||
|
|
||||||
|
private fun bytes(n: Int, fill: Byte): ByteArray = ByteArray(n) { fill }
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun identityKeyPairRoundTrip() {
|
||||||
|
val k = IdentityKeyPair(
|
||||||
|
signingPublicKey = bytes(32, 0x11),
|
||||||
|
signingPrivateKey = bytes(32, 0x22),
|
||||||
|
dhPublicKey = bytes(32, 0x33),
|
||||||
|
dhPrivateKey = bytes(32, 0x44),
|
||||||
|
)
|
||||||
|
val s = SessionStateJson.serializeIdentityKeyPair(k)
|
||||||
|
val d = SessionStateJson.deserializeIdentityKeyPair(s)
|
||||||
|
assertArrayEquals(k.signingPublicKey, d.signingPublicKey)
|
||||||
|
assertArrayEquals(k.signingPrivateKey, d.signingPrivateKey)
|
||||||
|
assertArrayEquals(k.dhPublicKey, d.dhPublicKey)
|
||||||
|
assertArrayEquals(k.dhPrivateKey, d.dhPrivateKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun signedPreKeyRoundTrip() {
|
||||||
|
val k = SignedPreKey(
|
||||||
|
keyId = 42,
|
||||||
|
keyPair = KeyPair(publicKey = bytes(32, 0x55), privateKey = bytes(32, 0x66)),
|
||||||
|
signature = bytes(64, 0x77),
|
||||||
|
timestamp = 1_700_000_000_000L,
|
||||||
|
)
|
||||||
|
val s = SessionStateJson.serializeSignedPreKey(k)
|
||||||
|
val d = SessionStateJson.deserializeSignedPreKey(s)
|
||||||
|
assertEquals(k.keyId, d.keyId)
|
||||||
|
assertArrayEquals(k.keyPair.publicKey, d.keyPair.publicKey)
|
||||||
|
assertArrayEquals(k.keyPair.privateKey, d.keyPair.privateKey)
|
||||||
|
assertArrayEquals(k.signature, d.signature)
|
||||||
|
assertEquals(k.timestamp, d.timestamp)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun oneTimePreKeyRoundTrip() {
|
||||||
|
val k = OneTimePreKey(
|
||||||
|
keyId = 7,
|
||||||
|
keyPair = KeyPair(publicKey = bytes(32, 0x88.toByte()), privateKey = bytes(32, 0x99.toByte())),
|
||||||
|
)
|
||||||
|
val s = SessionStateJson.serializeOneTimePreKey(k)
|
||||||
|
val d = SessionStateJson.deserializeOneTimePreKey(s)
|
||||||
|
assertEquals(k.keyId, d.keyId)
|
||||||
|
assertArrayEquals(k.keyPair.publicKey, d.keyPair.publicKey)
|
||||||
|
assertArrayEquals(k.keyPair.privateKey, d.keyPair.privateKey)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sessionStateRoundTripFullPopulated() {
|
||||||
|
val state = SessionState(
|
||||||
|
remoteIdentityKey = bytes(32, 0x01),
|
||||||
|
rootKey = bytes(32, 0x02),
|
||||||
|
sendChain = ChainState(chainKey = bytes(32, 0x03), counter = 5),
|
||||||
|
receiveChain = ChainState(chainKey = bytes(32, 0x04), counter = 3),
|
||||||
|
dhSend = KeyPair(publicKey = bytes(32, 0x05), privateKey = bytes(32, 0x06)),
|
||||||
|
dhReceive = bytes(32, 0x07),
|
||||||
|
previousSendCounter = 9,
|
||||||
|
skippedKeys = mutableMapOf(
|
||||||
|
"remote:1" to bytes(32, 0x0A),
|
||||||
|
"remote:2" to bytes(32, 0x0B),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
val s = SessionStateJson.serialize(state)
|
||||||
|
val d = SessionStateJson.deserialize(s)
|
||||||
|
assertArrayEquals(state.remoteIdentityKey, d.remoteIdentityKey)
|
||||||
|
assertArrayEquals(state.rootKey, d.rootKey)
|
||||||
|
assertArrayEquals(state.sendChain.chainKey, d.sendChain.chainKey)
|
||||||
|
assertEquals(state.sendChain.counter, d.sendChain.counter)
|
||||||
|
assertNotNull(d.receiveChain)
|
||||||
|
assertArrayEquals(state.receiveChain!!.chainKey, d.receiveChain!!.chainKey)
|
||||||
|
assertArrayEquals(state.dhSend.publicKey, d.dhSend.publicKey)
|
||||||
|
assertArrayEquals(state.dhSend.privateKey, d.dhSend.privateKey)
|
||||||
|
assertArrayEquals(state.dhReceive, d.dhReceive)
|
||||||
|
assertEquals(state.previousSendCounter, d.previousSendCounter)
|
||||||
|
assertEquals(state.skippedKeys.size, d.skippedKeys.size)
|
||||||
|
for ((k, v) in state.skippedKeys) {
|
||||||
|
assertArrayEquals(v, d.skippedKeys[k])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
fun sessionStateRoundTripWithNullableFields() {
|
||||||
|
val state = SessionState(
|
||||||
|
remoteIdentityKey = bytes(32, 0x01),
|
||||||
|
rootKey = bytes(32, 0x02),
|
||||||
|
sendChain = ChainState(chainKey = bytes(32, 0x03), counter = 0),
|
||||||
|
receiveChain = null,
|
||||||
|
dhSend = KeyPair(publicKey = bytes(32, 0x05), privateKey = bytes(32, 0x06)),
|
||||||
|
dhReceive = null,
|
||||||
|
previousSendCounter = 0,
|
||||||
|
skippedKeys = mutableMapOf(),
|
||||||
|
)
|
||||||
|
val s = SessionStateJson.serialize(state)
|
||||||
|
val d = SessionStateJson.deserialize(s)
|
||||||
|
assertNull(d.receiveChain)
|
||||||
|
assertNull(d.dhReceive)
|
||||||
|
assertEquals(0, d.skippedKeys.size)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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))
|
||||||
|
}
|
||||||
|
}
|
||||||
146
bun.lock
146
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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"version": "4.13.0",
|
||||||
},
|
},
|
||||||
"packages/shade-observability": {
|
"packages/shade-observability": {
|
||||||
"name": "@shade/observability",
|
"name": "@shade/observability",
|
||||||
"version": "0.1.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"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": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -198,22 +199,25 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-sdk": {
|
"packages/shade-sdk": {
|
||||||
"name": "@shade/sdk",
|
"name": "@shade/sdk",
|
||||||
"version": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
"@shade/files": "workspace:*",
|
"@shade/files": "workspace:*",
|
||||||
|
"@shade/inbox": "workspace:*",
|
||||||
"@shade/key-transparency": "workspace:*",
|
"@shade/key-transparency": "workspace:*",
|
||||||
"@shade/observability": "workspace:*",
|
"@shade/observability": "workspace:*",
|
||||||
"@shade/observer": "workspace:*",
|
"@shade/observer": "workspace:*",
|
||||||
"@shade/proto": "workspace:*",
|
"@shade/proto": "workspace:*",
|
||||||
"@shade/server": "workspace:*",
|
"@shade/server": "workspace:*",
|
||||||
|
"@shade/storage-encrypted": "workspace:*",
|
||||||
"@shade/storage-sqlite": "workspace:*",
|
"@shade/storage-sqlite": "workspace:*",
|
||||||
"@shade/streams": "workspace:*",
|
"@shade/streams": "workspace:*",
|
||||||
"@shade/transfer": "workspace:*",
|
"@shade/transfer": "workspace:*",
|
||||||
"@shade/transport": "workspace:*",
|
"@shade/transport": "workspace:*",
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@shade/inbox-server": "workspace:*",
|
||||||
"@shade/transport-webrtc": "workspace:*",
|
"@shade/transport-webrtc": "workspace:*",
|
||||||
},
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
@@ -225,12 +229,14 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-server": {
|
"packages/shade-server": {
|
||||||
"name": "@shade/server",
|
"name": "@shade/server",
|
||||||
"version": "0.4.0",
|
"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": {
|
||||||
@@ -245,15 +251,19 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-storage-encrypted": {
|
"packages/shade-storage-encrypted": {
|
||||||
"name": "@shade/storage-encrypted",
|
"name": "@shade/storage-encrypted",
|
||||||
"version": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
"@shade/storage-postgres": "workspace:*",
|
"@shade/storage-postgres": "workspace:*",
|
||||||
"@shade/storage-sqlite": "workspace:*",
|
"@shade/storage-sqlite": "workspace:*",
|
||||||
|
"idb": "^8.0.3",
|
||||||
"postgres": "^3.4.9",
|
"postgres": "^3.4.9",
|
||||||
},
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"fake-indexeddb": "^6.0.0",
|
||||||
|
},
|
||||||
"peerDependencies": {
|
"peerDependencies": {
|
||||||
"@shade/keychain": "workspace:*",
|
"@shade/keychain": "workspace:*",
|
||||||
},
|
},
|
||||||
@@ -261,9 +271,21 @@
|
|||||||
"@shade/keychain",
|
"@shade/keychain",
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
|
"packages/shade-storage-indexeddb": {
|
||||||
|
"name": "@shade/storage-indexeddb",
|
||||||
|
"version": "4.13.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@shade/core": "workspace:*",
|
||||||
|
"idb": "^8.0.3",
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@shade/crypto-web": "workspace:*",
|
||||||
|
"fake-indexeddb": "^6.0.0",
|
||||||
|
},
|
||||||
|
},
|
||||||
"packages/shade-storage-postgres": {
|
"packages/shade-storage-postgres": {
|
||||||
"name": "@shade/storage-postgres",
|
"name": "@shade/storage-postgres",
|
||||||
"version": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/inbox-server": "workspace:*",
|
"@shade/inbox-server": "workspace:*",
|
||||||
@@ -278,17 +300,20 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-storage-sqlite": {
|
"packages/shade-storage-sqlite": {
|
||||||
"name": "@shade/storage-sqlite",
|
"name": "@shade/storage-sqlite",
|
||||||
"version": "0.4.0",
|
"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": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/hashes": "^2.0.1",
|
"@noble/hashes": "^2.0.1",
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
@@ -300,7 +325,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transfer": {
|
"packages/shade-transfer": {
|
||||||
"name": "@shade/transfer",
|
"name": "@shade/transfer",
|
||||||
"version": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -317,7 +342,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transport": {
|
"packages/shade-transport": {
|
||||||
"name": "@shade/transport",
|
"name": "@shade/transport",
|
||||||
"version": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/crypto-web": "workspace:*",
|
"@shade/crypto-web": "workspace:*",
|
||||||
@@ -328,7 +353,7 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transport-bridge": {
|
"packages/shade-transport-bridge": {
|
||||||
"name": "@shade/transport-bridge",
|
"name": "@shade/transport-bridge",
|
||||||
"version": "0.1.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/core": "workspace:*",
|
"@shade/core": "workspace:*",
|
||||||
"@shade/server": "workspace:*",
|
"@shade/server": "workspace:*",
|
||||||
@@ -350,16 +375,29 @@
|
|||||||
},
|
},
|
||||||
"packages/shade-transport-webrtc": {
|
"packages/shade-transport-webrtc": {
|
||||||
"name": "@shade/transport-webrtc",
|
"name": "@shade/transport-webrtc",
|
||||||
"version": "0.4.0",
|
"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": "0.4.0",
|
"version": "4.13.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@shade/recovery": "workspace:*",
|
"@shade/recovery": "workspace:*",
|
||||||
"@shade/sdk": "workspace:*",
|
"@shade/sdk": "workspace:*",
|
||||||
@@ -568,6 +606,8 @@
|
|||||||
|
|
||||||
"@shade/storage-encrypted": ["@shade/storage-encrypted@workspace:packages/shade-storage-encrypted"],
|
"@shade/storage-encrypted": ["@shade/storage-encrypted@workspace:packages/shade-storage-encrypted"],
|
||||||
|
|
||||||
|
"@shade/storage-indexeddb": ["@shade/storage-indexeddb@workspace:packages/shade-storage-indexeddb"],
|
||||||
|
|
||||||
"@shade/storage-postgres": ["@shade/storage-postgres@workspace:packages/shade-storage-postgres"],
|
"@shade/storage-postgres": ["@shade/storage-postgres@workspace:packages/shade-storage-postgres"],
|
||||||
|
|
||||||
"@shade/storage-sqlite": ["@shade/storage-sqlite@workspace:packages/shade-storage-sqlite"],
|
"@shade/storage-sqlite": ["@shade/storage-sqlite@workspace:packages/shade-storage-sqlite"],
|
||||||
@@ -582,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=="],
|
||||||
@@ -600,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=="],
|
||||||
@@ -626,6 +708,8 @@
|
|||||||
|
|
||||||
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
|
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
|
||||||
|
|
||||||
|
"fake-indexeddb": ["fake-indexeddb@6.2.5", "", {}, "sha512-CGnyrvbhPlWYMngksqrSSUT1BAVP49dZocrHuK0SvtR0D5TMs5wP0o3j7jexDJW01KSadjBp1M/71o/KR3nD1w=="],
|
||||||
|
|
||||||
"fast-check": ["fast-check@3.23.2", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
"fast-check": ["fast-check@3.23.2", "", { "dependencies": { "pure-rand": "^6.1.0" } }, "sha512-h5+1OzzfCC3Ef7VbtKdcv7zsstUQwUDlYpUTvjeUsJAssPgLn7QzbboPtL5ro04Mq0rPOsMzl7q5hIbRs2wD1A=="],
|
||||||
|
|
||||||
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
|
||||||
@@ -638,6 +722,8 @@
|
|||||||
|
|
||||||
"hono": ["hono@4.12.12", "", {}, "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q=="],
|
"hono": ["hono@4.12.12", "", {}, "sha512-p1JfQMKaceuCbpJKAPKVqyqviZdS0eUxH9v82oWo1kb9xjQ5wA6iP3FNVAPDFlz5/p7d45lO+BpSk1tuSZMF4Q=="],
|
||||||
|
|
||||||
|
"idb": ["idb@8.0.3", "", {}, "sha512-LtwtVyVYO5BqRvcsKuB2iUMnHwPVByPCXFXOpuU96IZPPoPN6xjOGxZQ74pgSVVLQWtUOYgyeL4GE98BY5D3wg=="],
|
||||||
|
|
||||||
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
"js-tokens": ["js-tokens@4.0.0", "", {}, "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ=="],
|
||||||
|
|
||||||
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
"jsesc": ["jsesc@3.1.0", "", { "bin": { "jsesc": "bin/jsesc" } }, "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA=="],
|
||||||
@@ -678,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=="],
|
||||||
@@ -691,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=="],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -81,6 +81,7 @@ Tables will be created automatically with the `shade_server_*` prefix, so they c
|
|||||||
| `SHADE_CLEANUP_INTERVAL_HOURS` | `24` | Cleanup cycle interval |
|
| `SHADE_CLEANUP_INTERVAL_HOURS` | `24` | Cleanup cycle interval |
|
||||||
| `SHADE_LOG_LEVEL` | `info` | `debug` / `info` / `warn` / `error` |
|
| `SHADE_LOG_LEVEL` | `info` | `debug` / `info` / `warn` / `error` |
|
||||||
| `SHADE_OTEL_ENABLED` | unset | Set to `1`/`true` to enable OpenTelemetry tracing on `withTracer()`-configured deployments. See [`observability.md`](./observability.md). |
|
| `SHADE_OTEL_ENABLED` | unset | Set to `1`/`true` to enable OpenTelemetry tracing on `withTracer()`-configured deployments. See [`observability.md`](./observability.md). |
|
||||||
|
| `SHADE_DISABLE_RATE_LIMIT` | unset | Set to `1` to disable IP rate-limits on every prekey + inbox route. **Single-tenant deployments only** — multi-tenant relays must leave this unset to keep the abuse defenses on. |
|
||||||
|
|
||||||
## Health and observability
|
## Health and observability
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,11 @@
|
|||||||
# Shade V2.1 — Improvements (infrastructure, storage, operations, security)
|
# Shade V2.1 — Improvements (infrastructure, storage, operations, security)
|
||||||
|
|
||||||
This document describes **improvements** agreed for next-generation work on Shade: clearer product story, stronger storage, mobile parity, operational hardening, transfer abuse, and a formal security narrative.
|
**Status:** Done — superseded by the V3.1 → V3.12 plans, all of which
|
||||||
|
landed in the 4.0 GA release. This document is preserved as historical
|
||||||
|
context for the original V2.1 backlog; the concrete deliverables live
|
||||||
|
under [`docs/archive/V3.*.md`](./).
|
||||||
|
|
||||||
**Audience:** **Maintainers and contributors** implementing the changes. Add status fields as items land in code/docs.
|
This document describes **improvements** agreed for next-generation work on Shade: clearer product story, stronger storage, mobile parity, operational hardening, transfer abuse, and a formal security narrative.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
# Shade V2.2 — Feature plan: product, platform, and developer experience
|
# Shade V2.2 — Feature plan: product, platform, and developer experience
|
||||||
|
|
||||||
This document gathers **planned features** that extend Shade beyond today’s core (X3DH + Double Ratchet + Streams/transfer): groups, asynchronous delivery, richer file UX, web workers, CLI, API docs, and scaffolding.
|
**Status:** Done — superseded by V3.6 (inbox), V3.7 (bridge), V3.8
|
||||||
|
(workers), V3.9 (file metadata), V3.10 (recovery), V3.12 (KT). All
|
||||||
|
landed in the 4.0 GA release; see [`docs/ROADMAP.md`](../ROADMAP.md).
|
||||||
|
|
||||||
Add optional per-feature status (Idea / Design / IMP / Done).
|
This document gathers **planned features** that extend Shade beyond today’s core (X3DH + Double Ratchet + Streams/transfer): groups, asynchronous delivery, richer file UX, web workers, CLI, API docs, and scaffolding.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
# Shade V2.3 — Tillit, retention, integrasjon og observability
|
# Shade V2.3 — Tillit, retention, integrasjon og observability
|
||||||
|
|
||||||
|
**Status:** Done — superseded by V3.3 (trust UX), V3.4 (observability),
|
||||||
|
V3.10 (recovery), V3.12 (KT). Alt levert i 4.0 GA — se
|
||||||
|
[`docs/ROADMAP.md`](../ROADMAP.md).
|
||||||
|
|
||||||
Dette dokumentet beskriver **høyere ambisjonsnivå** og **plattformkryssende** arbeid: brukertilfeller der tillit må være **eksplisitt**, data må **utkrympes**/ryddes automatisk, apper må **enkelt koble seg på** kjente transportmønstre, og drift må **observere** uten å lekke innhold.
|
Dette dokumentet beskriver **høyere ambisjonsnivå** og **plattformkryssende** arbeid: brukertilfeller der tillit må være **eksplisitt**, data må **utkrympes**/ryddes automatisk, apper må **enkelt koble seg på** kjente transportmønstre, og drift må **observere** uten å lekke innhold.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# V3.12 — Key Transparency: Designnotat
|
# V3.12 — Key Transparency: Designnotat
|
||||||
|
|
||||||
**Status:** Approved (in-tree review — markeres `Design` i ROADMAP)
|
**Status:** Done — implementert i `@shade/key-transparency` 0.4.0, frosset i 4.0 GA.
|
||||||
**Forfatter:** Shade-teamet
|
**Forfatter:** Shade-teamet
|
||||||
**Reviewer-mål:** ekstern crypto-orientert reviewer før produksjons-deploy.
|
**Reviewer-mål:** ekstern crypto-orientert reviewer før produksjons-deploy.
|
||||||
**Implementasjons-target:** `@shade/key-transparency` + utvidelser i
|
**Implementasjons-target:** `@shade/key-transparency` + utvidelser i
|
||||||
|
|||||||
105
docs/files.md
105
docs/files.md
@@ -53,6 +53,111 @@ if (result.kind === 'inline') console.log(result.bytes.byteLength);
|
|||||||
else for await (const _chunk of /* result.stream */) { /* ... */ }
|
else for await (const _chunk of /* result.stream */) { /* ... */ }
|
||||||
```
|
```
|
||||||
|
|
||||||
|
## HTTP RPC — browser-friendly request-response (4.1+)
|
||||||
|
|
||||||
|
The default `shade.files.client(peer)` requires both peers to be mutually
|
||||||
|
addressable over HTTP — the response to a `list`/`read` etc. round-trips
|
||||||
|
through `Shade.deliverControlEnvelope`, which POSTs to the peer's
|
||||||
|
`/v1/transfer/control` endpoint. **That doesn't work for browsers** —
|
||||||
|
a tab can't host an HTTP server, so the server cannot call back outbound.
|
||||||
|
|
||||||
|
`@shade/files` 4.1 ships a parallel **request-response** transport that
|
||||||
|
lets browser-style clients fully consume the file-RPC surface without
|
||||||
|
any inbound channel. It mirrors the way `@shade/server`'s
|
||||||
|
`shade-auth-middleware` works: one POST per RPC, encrypted envelope in
|
||||||
|
the request body, encrypted response in the same HTTP response.
|
||||||
|
|
||||||
|
### Server side — mount the RPC route
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// 1. Register the file handler. `inlineOnly: true` skips the
|
||||||
|
// streams-bridge (which would require @shade/transfer).
|
||||||
|
await shade.files.serve(handlerConfig, { inlineOnly: true });
|
||||||
|
|
||||||
|
// 2. Mount the route on your Hono app under any base path.
|
||||||
|
app.route('/api/v1/shade-files', shade.files.rpcRoute());
|
||||||
|
// ^^^^^^^^^^^^^^
|
||||||
|
// POST <base>/rpc
|
||||||
|
```
|
||||||
|
|
||||||
|
`rpcRoute()` accepts:
|
||||||
|
|
||||||
|
| Option | Default | Purpose |
|
||||||
|
|---------------------|---------|----------------------------------------------------------------------------------------------------|
|
||||||
|
| `maxBodyBytes` | 1 MiB | Max request body. The protocol caps inline payloads at 256 KiB; the headroom is for base64 inflation + custom-op envelopes. |
|
||||||
|
| `acceptFirstMessage`| `false` | Accept `0x01` PreKeyMessage envelopes — required when the RPC route also doubles as the X3DH handshake (browser's first-ever request). |
|
||||||
|
|
||||||
|
### Browser client
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { createShade } from '@shade/sdk';
|
||||||
|
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://shade.example.com',
|
||||||
|
storage: 'memory',
|
||||||
|
address: 'alice@example.com',
|
||||||
|
});
|
||||||
|
|
||||||
|
const fs = shade.files.httpClient('bob@example.com', {
|
||||||
|
rpcUrl: 'https://dispatch.example.com/api/v1/shade-files/rpc',
|
||||||
|
// Optional: thread CSRF / auth tokens, override fetch, etc.
|
||||||
|
headers: { 'X-CSRF-Token': csrfToken },
|
||||||
|
});
|
||||||
|
|
||||||
|
await fs.mkdir('/photos');
|
||||||
|
await fs.write('/photos/cover.png', new Uint8Array([/* ... */]), {
|
||||||
|
contentType: 'image/png',
|
||||||
|
});
|
||||||
|
const result = await fs.read('/photos/cover.png');
|
||||||
|
```
|
||||||
|
|
||||||
|
### What works in HTTP-RPC mode
|
||||||
|
|
||||||
|
- `list`, `stat`, `mkdir`, `delete`, `move`, `getThumbnail`, `custom<K>` — full parity.
|
||||||
|
- `write` — **inline only** (≤ 256 KiB plaintext). Larger inputs throw `ConflictError`.
|
||||||
|
- `read` — **inline only**. If the server returns a streamed `read` result, the client throws `InternalFileError` directing callers to the stateful pathway.
|
||||||
|
|
||||||
|
### Wire contract
|
||||||
|
|
||||||
|
```
|
||||||
|
POST /rpc HTTP/1.1
|
||||||
|
Content-Type: application/octet-stream
|
||||||
|
X-Shade-Sender-Address: alice@example.com
|
||||||
|
|
||||||
|
<wire-encoded ShadeEnvelope (0x01 first-time, 0x02 after) wrapping
|
||||||
|
JSON-encoded RpcRequest>
|
||||||
|
|
||||||
|
────
|
||||||
|
|
||||||
|
200 OK
|
||||||
|
Content-Type: application/octet-stream
|
||||||
|
|
||||||
|
<wire-encoded ShadeEnvelope (0x02) wrapping JSON-encoded RpcResponse | RpcError>
|
||||||
|
```
|
||||||
|
|
||||||
|
Transport-level failures (no session, undecryptable envelope, body too
|
||||||
|
big) return JSON `{ "error": "..." }` with appropriate 4xx status.
|
||||||
|
Application-level failures (file not found, permission denied) ship
|
||||||
|
encrypted `RpcError` envelopes — the client maps them back to typed
|
||||||
|
`FileError` subclasses (`NotFoundError`, `ConflictError`, etc.).
|
||||||
|
|
||||||
|
### Symmetry with `@shade/server`
|
||||||
|
|
||||||
|
The shape mirrors `@shade/server`'s shade-auth-middleware: encrypted
|
||||||
|
envelope rides the request body, server decrypts via the existing
|
||||||
|
ratchet session, performs the protected operation, returns an encrypted
|
||||||
|
envelope in the response. No bidirectional channel required, no
|
||||||
|
WebSocket, no SSE.
|
||||||
|
|
||||||
|
### When to use which
|
||||||
|
|
||||||
|
| Setup | Use |
|
||||||
|
|-----------------------------------------------|-----------------------------------------------|
|
||||||
|
| Browser client ↔ Bun/Hono server | `httpClient()` + `rpcRoute()` |
|
||||||
|
| Server ↔ server (both can host HTTP) | `client()` (default) — supports streams |
|
||||||
|
| Service-worker / extension ↔ server | `httpClient()` (no inbound listener) |
|
||||||
|
| CLI / daemon ↔ daemon | Either; `client()` if you need streams |
|
||||||
|
|
||||||
## Op surface
|
## Op surface
|
||||||
|
|
||||||
| Op | Args | Result |
|
| Op | Args | Result |
|
||||||
|
|||||||
173
docs/shade-identity-public-key-accessor.md
Normal file
173
docs/shade-identity-public-key-accessor.md
Normal file
@@ -0,0 +1,173 @@
|
|||||||
|
# Feature Request — Public accessor for the device's identity public key
|
||||||
|
|
||||||
|
**To**: Shade SDK team
|
||||||
|
**From**: Dispatch (browser-based Shade consumer)
|
||||||
|
**Target**: Shade SDK 4.4.x (or whichever release vehicle fits)
|
||||||
|
**Priority**: medium — unblocks real per-device fingerprint binding at
|
||||||
|
enrollment time; consumers ship with placeholder keys until then
|
||||||
|
|
||||||
|
Thanks for shipping `@shade/storage-indexeddb` so quickly — that unblocked
|
||||||
|
Dispatch's Slice 2.5 (persistent browser identity). During integration we
|
||||||
|
hit one more gap that's worth raising as a separate FR.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Expose the local device's Ed25519 identity public key as a public accessor
|
||||||
|
on `Shade`, so applications can hand it to their own backend at enrollment
|
||||||
|
time for per-device verification, audit, or peer-fingerprint computation.
|
||||||
|
|
||||||
|
Today the SDK exposes `myAddress` and `fingerprint`, but the underlying
|
||||||
|
identity public key — the cryptographic root that everything else binds
|
||||||
|
to — is reachable only via the private `this.storage.getIdentityKeyPair()`
|
||||||
|
call inside `Shade`. Consumers building enrollment flows have no way to
|
||||||
|
hand the real key over.
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
A common pattern in Shade-using apps is:
|
||||||
|
|
||||||
|
1. Browser device generates Shade identity (via `createShade`)
|
||||||
|
2. User enters an enrollment token
|
||||||
|
3. Browser POSTs to its backend: `{ token, address, identityPublicKey, ... }`
|
||||||
|
4. Backend records the device, computes/stores a safety number from the
|
||||||
|
identity key, opens a Shade session
|
||||||
|
|
||||||
|
Step 3 today has nowhere to get a real `identityPublicKey` from. Dispatch
|
||||||
|
currently sends `crypto.getRandomValues(new Uint8Array(32))` formatted as
|
||||||
|
hex, with this comment in the source:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
/**
|
||||||
|
* The browser submits a hex public-key field at enroll time so the schema
|
||||||
|
* stays stable. Wiring this to the SDK-generated identity key requires a
|
||||||
|
* Shade SDK addition (no public accessor for the raw identity key today).
|
||||||
|
*/
|
||||||
|
export function generatePlaceholderIdentityPublicKey(): string { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
The backend stores this placeholder but cannot verify anything against it,
|
||||||
|
because it's not actually the device's key. Real cryptographic binding is
|
||||||
|
deferred until the SDK exposes the underlying key.
|
||||||
|
|
||||||
|
## Why `fingerprint` isn't sufficient
|
||||||
|
|
||||||
|
`Shade.fingerprint` returns a 12-groups-of-5-digits safety-number string
|
||||||
|
designed for human side-channel comparison. That's the right output for a
|
||||||
|
"compare these digits with your friend" UX, but it's a derived format, not
|
||||||
|
the raw key. Backends that want to:
|
||||||
|
|
||||||
|
- Store the key for later signature verification
|
||||||
|
- Compute their own safety-number representation (Dispatch uses
|
||||||
|
`deterministicSafetyNumber(localAddr, peerAddr)` based on the raw bytes)
|
||||||
|
- Re-derive the fingerprint after an identity rotation
|
||||||
|
|
||||||
|
…all need access to the raw 32-byte Ed25519 public key.
|
||||||
|
|
||||||
|
## Proposed API
|
||||||
|
|
||||||
|
Add a single async accessor on `Shade`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
class Shade {
|
||||||
|
/**
|
||||||
|
* The local device's Ed25519 identity public key (32 bytes).
|
||||||
|
*
|
||||||
|
* Stable for the lifetime of the identity. After `rotateIdentity()`
|
||||||
|
* this returns the new key; the old key is preserved in retired-
|
||||||
|
* identities storage for the configured grace period.
|
||||||
|
*/
|
||||||
|
get identityPublicKey(): Promise<Uint8Array>;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Internally:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
get identityPublicKey(): Promise<Uint8Array> {
|
||||||
|
if (!this.initialized) throw new Error('Not initialized');
|
||||||
|
return this.storage.getIdentityKeyPair().then((kp) => {
|
||||||
|
if (!kp) throw new Error('Identity not yet generated');
|
||||||
|
return kp.publicKey;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
If returning a getter that produces a Promise feels off, the equivalent
|
||||||
|
method form is fine:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
async getIdentityPublicKey(): Promise<Uint8Array> { ... }
|
||||||
|
```
|
||||||
|
|
||||||
|
Either shape works for consumers — pick whichever matches existing SDK
|
||||||
|
conventions.
|
||||||
|
|
||||||
|
## Alternative considered: object accessor
|
||||||
|
|
||||||
|
Returning an object would leave room to expose other identity-related
|
||||||
|
fields later without a breaking change:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
get identity(): Promise<{
|
||||||
|
address: string;
|
||||||
|
publicKey: Uint8Array;
|
||||||
|
fingerprint: string;
|
||||||
|
// future: registrationId, createdAt, etc.
|
||||||
|
}>;
|
||||||
|
```
|
||||||
|
|
||||||
|
This would mildly duplicate `myAddress` + `fingerprint`, but consolidates
|
||||||
|
identity-related accessors. Not a blocker for shipping the simpler
|
||||||
|
single-purpose accessor — just flagging the option in case the SDK is
|
||||||
|
considering broader API ergonomics.
|
||||||
|
|
||||||
|
## What this unblocks
|
||||||
|
|
||||||
|
For Dispatch specifically:
|
||||||
|
|
||||||
|
- Real device identity binding at enrollment (replaces the placeholder
|
||||||
|
`crypto.randomUUID()`-derived hex bytes the backend currently stores)
|
||||||
|
- Server-side `computePeerSafetyNumber()` can use the real key instead of
|
||||||
|
the deterministic-from-address stand-in (`shade-identity-provider.ts:151`)
|
||||||
|
- Future signature-based device authentication (sign a challenge with the
|
||||||
|
device's identity key during enrollment) becomes possible without
|
||||||
|
another SDK round
|
||||||
|
|
||||||
|
For other Shade consumers:
|
||||||
|
|
||||||
|
- Any app that hands a device key to its own backend for enrollment —
|
||||||
|
multi-device pairing flows, contact verification UIs, push-notification
|
||||||
|
targeting — gets an actual key to work with
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
1. New accessor exposed on `Shade` (getter or async method, SDK's
|
||||||
|
preference)
|
||||||
|
2. Returns the 32-byte Ed25519 identity public key
|
||||||
|
3. Returns the **current** key after `rotateIdentity()`
|
||||||
|
4. Throws (or resolves to a clear error) when called before
|
||||||
|
`initialize()` completes
|
||||||
|
5. Documented alongside `myAddress` and `fingerprint` in the SDK reference
|
||||||
|
6. One unit test in `shade-sdk` confirming the returned bytes match what
|
||||||
|
`storage.getIdentityKeyPair()` holds
|
||||||
|
7. Mentioned in the changelog under the next release
|
||||||
|
|
||||||
|
## Out of scope
|
||||||
|
|
||||||
|
- **Private key access** — consumers should never need it; signature
|
||||||
|
operations go through `shade.send()` etc. Don't expose the secret half.
|
||||||
|
- **Cross-peer key lookup** — getting *another* peer's identity key is a
|
||||||
|
separate concern (related to peer-verification storage), not what this
|
||||||
|
FR is about. This is strictly the local device's own key.
|
||||||
|
- **Format conversions** — base64/hex/PEM helpers don't belong in the SDK.
|
||||||
|
Consumers can encode the raw bytes however their wire format requires.
|
||||||
|
|
||||||
|
## Why this can't be done in consumer-land
|
||||||
|
|
||||||
|
The identity keypair is generated by `MemoryStorage` / `SQLiteStorage` /
|
||||||
|
`IndexedDBStorage` and consumed by `ShadeSessionManager`. Consumers can't
|
||||||
|
reach into either layer without breaching the SDK's encapsulation. A
|
||||||
|
public accessor is the only path that doesn't require monkey-patching
|
||||||
|
private fields.
|
||||||
191
docs/shade-storage-indexeddb.md
Normal file
191
docs/shade-storage-indexeddb.md
Normal file
@@ -0,0 +1,191 @@
|
|||||||
|
# Feature Request — `@shade/storage-indexeddb`
|
||||||
|
|
||||||
|
**To**: Shade SDK team
|
||||||
|
**From**: Dispatch (browser-based Shade consumer)
|
||||||
|
**Target**: Shade SDK 4.3.x (or whichever release vehicle fits)
|
||||||
|
**Priority**: blocks all browser-based Shade apps from achieving session
|
||||||
|
persistence across tab refresh
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## Summary
|
||||||
|
|
||||||
|
Ship an official IndexedDB-backed `StorageProvider` adapter as a new
|
||||||
|
workspace package `@shade/storage-indexeddb`, so browser-based Shade SDK
|
||||||
|
consumers can persist identity, prekeys, sessions, and peer-verification
|
||||||
|
state across tab refresh and browser restart — the same way `@shade/storage-sqlite`
|
||||||
|
does for Node and `@shade/storage-postgres` does for server deployments.
|
||||||
|
|
||||||
|
## Problem
|
||||||
|
|
||||||
|
Today the Shade SDK ships three storage paths:
|
||||||
|
|
||||||
|
| spec | adapter | environment |
|
||||||
|
| --------------------------------- | ------------------------ | ---------------- |
|
||||||
|
| `"memory"` | `MemoryStorage` (in-SDK) | tests, ephemeral |
|
||||||
|
| `"sqlite:/path"` | `@shade/storage-sqlite` | Node |
|
||||||
|
| `{ type: 'postgres', url: '…' }` | `@shade/storage-postgres`| Node servers |
|
||||||
|
|
||||||
|
There is **no browser-storage option**. The only way to run Shade in a
|
||||||
|
browser today is `storage: "memory"`, which means:
|
||||||
|
|
||||||
|
- Identity keypair regenerates on every page load
|
||||||
|
- Sessions reset → re-enrollment after every refresh
|
||||||
|
- `getLocalRegistrationId()` returns a fresh value → `device:${id}`
|
||||||
|
address changes → server-side device record orphaned every reload
|
||||||
|
|
||||||
|
This forces every browser-based Shade app to either (a) accept the broken
|
||||||
|
UX, or (b) build their own `StorageProvider` from scratch — duplicating
|
||||||
|
~25 methods × N consumers, with no shared conformance test surface.
|
||||||
|
|
||||||
|
The right place to solve this is at the SDK level, exactly mirroring how
|
||||||
|
SQLite and Postgres are handled.
|
||||||
|
|
||||||
|
## Proposed package
|
||||||
|
|
||||||
|
`packages/shade-storage-indexeddb/` — modeled directly after
|
||||||
|
`packages/shade-storage-sqlite/`. Same package shape, same test layout,
|
||||||
|
same `@shade/core`-only runtime dependency surface.
|
||||||
|
|
||||||
|
### Public API
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// @shade/storage-indexeddb
|
||||||
|
export class IndexedDBStorage implements StorageProvider {
|
||||||
|
/**
|
||||||
|
* Open (or create) the IndexedDB database. Idempotent — repeated calls
|
||||||
|
* with the same dbName return a connection sharing the same object stores.
|
||||||
|
*/
|
||||||
|
static async create(opts?: { dbName?: string }): Promise<IndexedDBStorage>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cleanly close the underlying connection. Future calls will reopen.
|
||||||
|
* Called by Shade.shutdown() when consumers register cleanup.
|
||||||
|
*/
|
||||||
|
async close(): Promise<void>;
|
||||||
|
|
||||||
|
// ─── all StorageProvider methods (identity, prekeys, sessions,
|
||||||
|
// retired identities, peer verifications, optional stream-state) ───
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
`dbName` defaults to something like `"shade"`. Consumers like Dispatch
|
||||||
|
will pass distinct names per app (`"dispatch-dashboard-shade"`,
|
||||||
|
`"dispatch-host-ui-shade"`) so DevTools' IndexedDB inspector groups them
|
||||||
|
sensibly, even though origin-isolation already makes the data isolated.
|
||||||
|
|
||||||
|
### SDK integration
|
||||||
|
|
||||||
|
`@shade/sdk` `resolveStorage()` gets a fourth branch:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
if (typeof spec === 'object' && spec.type === 'indexeddb') {
|
||||||
|
const moduleId = '@shade/storage-indexeddb';
|
||||||
|
const mod = (await import(moduleId)) as {
|
||||||
|
IndexedDBStorage: { create(opts: { dbName?: string }): Promise<StorageProvider> };
|
||||||
|
};
|
||||||
|
return mod.IndexedDBStorage.create({ dbName: spec.dbName });
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Dynamic import keeps `@shade/storage-indexeddb` an optional dependency,
|
||||||
|
matching the Postgres pattern — Node-only consumers don't need to install
|
||||||
|
a browser-only adapter.
|
||||||
|
|
||||||
|
Consumer surface:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
const shade = await createShade({
|
||||||
|
prekeyServer: 'https://…/shade-prekey',
|
||||||
|
storage: { type: 'indexeddb', dbName: 'my-app-shade' },
|
||||||
|
address: 'device:user@example.com', // optional — falls back to device:${registrationId}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Implementation guidance (non-prescriptive)
|
||||||
|
|
||||||
|
- **IDB wrapper**: suggest `idb` (Jake Archibald's thin wrapper, well-typed,
|
||||||
|
zero deps). Avoid Dexie or idb-keyval — we want full schema control to
|
||||||
|
match the SQL adapters' explicit schemas.
|
||||||
|
- **Object-store layout**: one store per StorageProvider category
|
||||||
|
(`identity`, `signedPreKeys`, `oneTimePreKeys`, `sessions`,
|
||||||
|
`trustedIdentities`, `retiredIdentities`, `peerVerifications`,
|
||||||
|
`streamStates`). Keypaths match the natural keys (`keyId`, `address`,
|
||||||
|
`streamId`).
|
||||||
|
- **Schema version**: integer, bumped on every shape change. Migrations
|
||||||
|
in `db.upgrade(...)` callback. Document schema-history alongside
|
||||||
|
the SQLite schema.
|
||||||
|
- **Concurrency**: IndexedDB transactions are auto-committing — the adapter
|
||||||
|
must keep operations within a single transaction where SQL adapters do.
|
||||||
|
Particular care for `bumpPeerIdentityVersion` (atomic read-modify-write).
|
||||||
|
- **Stream-state methods**: implement them. Browser apps will increasingly
|
||||||
|
use `@shade/transfer` for large file resume, and parity with SQLite's
|
||||||
|
capabilities matters.
|
||||||
|
|
||||||
|
## Test expectations
|
||||||
|
|
||||||
|
Mirror `packages/shade-storage-sqlite/tests/`:
|
||||||
|
|
||||||
|
- `indexeddb-storage.test.ts` — full StorageProvider surface (identity,
|
||||||
|
sessions, trusted identities, retired identities)
|
||||||
|
- `indexeddb-prekey-store.test.ts` — signed + one-time prekey lifecycle
|
||||||
|
- `peer-verifications.test.ts` — verification CRUD + identity-version
|
||||||
|
bumping invariants
|
||||||
|
- `indexeddb-stream-state.test.ts` (if stream-state is implemented)
|
||||||
|
|
||||||
|
Use **`fake-indexeddb`** for the Node test environment — it's the
|
||||||
|
established standard, supports the v3 spec, and lets us run IDB tests
|
||||||
|
in `bun test` / `vitest` / `jest` without a real browser.
|
||||||
|
|
||||||
|
If/when Shade gains a shared `StorageProvider` conformance test suite,
|
||||||
|
this adapter should consume it directly. Until then, follow the SQLite
|
||||||
|
adapter's per-method coverage style.
|
||||||
|
|
||||||
|
## Acceptance criteria
|
||||||
|
|
||||||
|
1. `@shade/storage-indexeddb` published at version 4.3.0 (or whichever
|
||||||
|
matches the next Shade release)
|
||||||
|
2. `@shade/sdk` `resolveStorage()` resolves `{ type: 'indexeddb', dbName? }`
|
||||||
|
via dynamic import
|
||||||
|
3. Full StorageProvider conformance in tests (identity, prekeys,
|
||||||
|
sessions, retired identities, peer verifications, stream-state)
|
||||||
|
4. Documented in Shade docs alongside SQLite/Postgres adapters
|
||||||
|
5. README example showing browser-app integration
|
||||||
|
6. Bundle-size note: dynamic-imported IDB module shouldn't pull crypto
|
||||||
|
dependencies — adapter should be ≤ ~10 KB minified+gzipped
|
||||||
|
|
||||||
|
## Out of scope (deferred)
|
||||||
|
|
||||||
|
- **Encryption-at-rest** for the IDB contents — separate work item; should
|
||||||
|
match the deviceKey-AES-GCM pattern Shade already uses for `secretEnc`
|
||||||
|
in `PersistedStreamState`. This adapter ships unencrypted-at-rest in v1
|
||||||
|
(consistent with SQLite), with the encryption layer added uniformly to
|
||||||
|
all adapters later.
|
||||||
|
- **Cross-tab BroadcastChannel sync** — IDB is shared across same-origin
|
||||||
|
tabs already; concurrent writes work via IDB transactions. Real-time
|
||||||
|
notification across tabs (e.g. "session was rotated in another tab") is
|
||||||
|
a separate concern, not storage-adapter scope.
|
||||||
|
- **Quota handling** — IDB quota for a Shade keystore is far below realistic
|
||||||
|
browser quotas. If it ever becomes relevant, add a `QuotaExceededError`
|
||||||
|
observability hook then.
|
||||||
|
|
||||||
|
## Why this can't be done in consumer-land
|
||||||
|
|
||||||
|
Building this in Dispatch (or any other consumer) would mean:
|
||||||
|
|
||||||
|
- 25+ method `StorageProvider` re-implementation per consumer
|
||||||
|
- No shared conformance tests
|
||||||
|
- Schema drift across consumers — each would invent its own object-store
|
||||||
|
shape, blocking any future cross-app data import/export
|
||||||
|
- Every Shade SDK update that adjusts `StorageProvider` would force every
|
||||||
|
consumer to track and patch independently
|
||||||
|
|
||||||
|
`@shade/storage-sqlite` and `@shade/storage-postgres` are part of the SDK
|
||||||
|
for the same reason. IndexedDB belongs alongside them.
|
||||||
|
|
||||||
|
## What unblocks
|
||||||
|
|
||||||
|
Shipping this unblocks Dispatch's "Slice 2.5" — persistent enrollment
|
||||||
|
across browser refresh, which today is the largest QA-friction point in
|
||||||
|
the dev loop. Any future browser-Shade consumer (web dashboard,
|
||||||
|
contact-list app, browser-extension messenger) gets persistence for free.
|
||||||
128
docs/streaming-sessions.md
Normal file
128
docs/streaming-sessions.md
Normal file
@@ -0,0 +1,128 @@
|
|||||||
|
# Streaming Double-Ratchet sub-sessions (V4.11)
|
||||||
|
|
||||||
|
`ShadeStream` wraps individual frames on a long-lived, high-frequency,
|
||||||
|
often one-directional channel (e.g. a server→client console-log
|
||||||
|
WebSocket) in an **independent** Double Ratchet derived from — but never
|
||||||
|
mutating — an already-established parent Shade session.
|
||||||
|
|
||||||
|
This is the answer to Vyvern FR `shade-ws-streaming-ratchet.md`. It is a
|
||||||
|
first-class API, *not* the "documented contract that `send`/`receive` is
|
||||||
|
safe per-frame" fallback: the Double-Ratchet crypto was already safe for
|
||||||
|
that access pattern, but the `send`/`receive` wrapper layer was not
|
||||||
|
(per-frame keystore writes; a shared per-peer mutex and a single stored
|
||||||
|
session row coupling the stream to the HTTP path). `ShadeStream` keeps
|
||||||
|
the proven ratchet and fixes the wrapper.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
Transport-agnostic, exactly like `send`/`receive`: it emits/consumes
|
||||||
|
wire bytes; you own the WebSocket.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// Initiator (the side that calls openStream)
|
||||||
|
const stream = await shade.openStream(peerAddr);
|
||||||
|
ws.send(stream.handshakeFrame()); // → STREAM_OPEN
|
||||||
|
// first inbound WS frame is the peer's STREAM_OPEN_ACK:
|
||||||
|
await stream.handleHandshake(ackBytes); // stream now usable
|
||||||
|
ws.send(await stream.seal(utf8(logLine))); // outbound frame
|
||||||
|
onLog(await stream.open(inboundBytes)); // inbound frame
|
||||||
|
await stream.close(); // on ws close/error
|
||||||
|
|
||||||
|
// Responder
|
||||||
|
const stream = await shade.acceptStream(peerAddr, openBytes); // usable now
|
||||||
|
ws.send(stream.handshakeFrame()); // → STREAM_OPEN_ACK
|
||||||
|
// open()/seal() as above
|
||||||
|
```
|
||||||
|
|
||||||
|
Route inbound bytes with `inspectEnvelopeType()`:
|
||||||
|
`'stream-open' | 'stream-open-ack' | 'stream-frame'`.
|
||||||
|
|
||||||
|
## Seeding (no prekey-server round trip)
|
||||||
|
|
||||||
|
The stream root key is derived from an identity-bound **3-DH** exchange
|
||||||
|
— the X3DH pattern minus signed/one-time prekeys, because the peer's
|
||||||
|
identity is *already* mutually pinned by the parent session's TOFU. Two
|
||||||
|
ephemerals are exchanged inside the transport (`STREAM_OPEN` /
|
||||||
|
`STREAM_OPEN_ACK`); no prekey server is involved.
|
||||||
|
|
||||||
|
```
|
||||||
|
slotA = DH(initiatorEphemeral, responderIdentity) — authenticates responder
|
||||||
|
slotB = DH(initiatorIdentity, responderEphemeral) — authenticates initiator
|
||||||
|
slotC = DH(initiatorEphemeral, responderEphemeral) — ephemeral forward secrecy
|
||||||
|
SK = HKDF(ikm = slotA‖slotB‖slotC, salt = streamId, info = "ShadeStream/v1")
|
||||||
|
```
|
||||||
|
|
||||||
|
Both peers compute the identical three scalars regardless of role.
|
||||||
|
`SK` then bootstraps a textbook Double Ratchet by handing the
|
||||||
|
responder's ephemeral to `initSenderSession`/`initReceiverSession`
|
||||||
|
exactly the way X3DH hands its signed prekey to the ratchet — so
|
||||||
|
`ratchetEncrypt`/`ratchetDecrypt` and every guarantee they carry apply
|
||||||
|
unchanged.
|
||||||
|
|
||||||
|
## Security contract (answers FR R1–R7)
|
||||||
|
|
||||||
|
- **R1 — same properties as `send`/`receive`.** Each frame is one
|
||||||
|
`ratchetEncrypt`/`ratchetDecrypt` over the *same* crypto as the HTTP
|
||||||
|
path: AES-256-GCM confidentiality, per-frame forward secrecy via the
|
||||||
|
one-way HMAC chain-key KDF with in-place zeroize of the spent chain
|
||||||
|
key, and replay/rewind rejection (a re-delivered or counter-rewound
|
||||||
|
frame fails closed). The handshake is mutually authenticated against
|
||||||
|
the identities the parent session already pinned.
|
||||||
|
- **R2 — one-directional resilience.** A long server→client burst with
|
||||||
|
no client traffic only advances the symmetric sending chain (no DH
|
||||||
|
step until the peer replies — standard Double Ratchet). Forward
|
||||||
|
secrecy holds per frame in this regime. Over an ordered transport
|
||||||
|
(WebSocket/TCP) zero keys are skipped per frame.
|
||||||
|
- **R3 — bounded memory.** Out-of-order arrivals are capped by the
|
||||||
|
ratchet's `MAX_SKIP` (1000) and `MAX_CACHED_SKIPPED_KEYS` (2000)
|
||||||
|
with oldest-key eviction. In-order delivery retains nothing. Verified
|
||||||
|
to stay at zero retained keys across a 5000-frame burst.
|
||||||
|
- **R4 — browser parity.** Identical API and guarantees in the browser
|
||||||
|
SDK: `ShadeStream` is on the same `Shade` class over the same
|
||||||
|
`CryptoProvider` (`SubtleCryptoProvider`), so the IndexedDB-backed
|
||||||
|
build behaves identically to the `sqlite:` server build. No storage
|
||||||
|
is touched at all (see R7), so the keystore backend is irrelevant.
|
||||||
|
- **R5 — independent lifecycle.** The stream ratchet is derived without
|
||||||
|
reading or writing the stored parent `SessionState`, runs on its own
|
||||||
|
private op-mutex (not the per-peer `send`/`receive` queues), and is
|
||||||
|
zeroized on `close()`. Opening, using for thousands of frames, and
|
||||||
|
closing a stream leaves the parent session byte-identical; the HTTP
|
||||||
|
path keeps working concurrently against the same peer. Each
|
||||||
|
`openStream` gets a fresh `streamId` and an independent root, so
|
||||||
|
concurrent streams to one peer never share key material.
|
||||||
|
- **R6 — wire framing.** `@shade/proto` defines `STREAM_OPEN` (0x31),
|
||||||
|
`STREAM_OPEN_ACK` (0x32), `STREAM_FRAME` (0x33). A `STREAM_FRAME`
|
||||||
|
carries one Double-Ratchet message via the exact ratchet inner codec
|
||||||
|
the HTTP path uses. One sealed logical frame ⇒ one self-delimiting
|
||||||
|
wire frame ⇒ one WS text/binary frame.
|
||||||
|
- **R7 — performance.** The ratchet lives **only in memory and is never
|
||||||
|
persisted**. There is therefore *zero* per-frame storage I/O — the
|
||||||
|
per-frame cost is exactly the symmetric KDF + one AES-GCM, the same
|
||||||
|
primitives the HTTP path runs. This is strictly better than the
|
||||||
|
"doubled CPU" the Vyvern roadmap budgeted, because the dominant cost
|
||||||
|
the naive `send`/`receive`-per-frame approach would have paid (a
|
||||||
|
`saveSession` keystore write per frame) is eliminated, not doubled.
|
||||||
|
Not persisting is also a *security* property, not a shortcut: writing
|
||||||
|
evolving per-frame ratchet secrets to disk would defeat forward
|
||||||
|
secrecy. A dropped/reconnected stream is re-opened with a fresh
|
||||||
|
handshake, never resumed.
|
||||||
|
|
||||||
|
## Double-Ratchet ordering note
|
||||||
|
|
||||||
|
A responder cannot `seal()` until it has `open()`ed at least one frame
|
||||||
|
from the initiator (standard Signal behaviour — the responder has no
|
||||||
|
sending chain until the first DH step). For a server-heavy stream
|
||||||
|
either make the bursty data sender the **initiator**, or have the
|
||||||
|
initiator send one priming frame immediately after the handshake.
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
- `packages/shade-core/tests/stream.test.ts` — handshake agreement,
|
||||||
|
frame round-trips, 5000-frame one-directional burst (bounded skipped
|
||||||
|
keys + forward-secrecy zeroize), parent-session independence (R5),
|
||||||
|
replay/rewind rejection, mutual authentication against pinned
|
||||||
|
identities, `close()` zeroize/idempotence.
|
||||||
|
- `packages/shade-proto/tests/stream-wire.test.ts` — wire round-trips
|
||||||
|
and type-tag/length rejection for all three stream frame kinds.
|
||||||
|
</content>
|
||||||
|
</invoke>
|
||||||
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.
|
||||||
13
package.json
13
package.json
@@ -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",
|
||||||
@@ -16,14 +18,17 @@
|
|||||||
"version": "bun run scripts/bump-version.ts",
|
"version": "bun run scripts/bump-version.ts",
|
||||||
"soak": "bun run scripts/soak.ts",
|
"soak": "bun run scripts/soak.ts",
|
||||||
"soak:smoke": "bun run scripts/soak.ts --hours 0.05 --pairs 4",
|
"soak:smoke": "bun run scripts/soak.ts --hours 0.05 --pairs 4",
|
||||||
"publish:dry": "DRY_RUN=1 bun run scripts/publish-all.ts",
|
"typecheck": "bun run scripts/typecheck-all.ts",
|
||||||
"publish:all": "bash scripts/publish-shade.sh",
|
"prepublish:check": "bun run typecheck",
|
||||||
|
"publish:dry": "bun run prepublish:check && DRY_RUN=1 bun run scripts/publish-all.ts",
|
||||||
|
"publish:all": "bun run prepublish:check && bash scripts/publish-shade.sh",
|
||||||
"build:docker": "bun run scripts/build-docker.ts",
|
"build:docker": "bun run scripts/build-docker.ts",
|
||||||
"publish:docker": "bun run scripts/build-docker.ts -- --push"
|
"publish:docker": "bun run scripts/build-docker.ts -- --push"
|
||||||
},
|
},
|
||||||
"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.0.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.0.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",
|
||||||
|
|||||||
@@ -107,6 +107,31 @@ export class FingerprintNotVerifiedError extends ShadeError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when `seal()` / `open()` is called on a {@link StreamRatchet}
|
||||||
|
* that has already been torn down via `close()`. The stream's ratchet
|
||||||
|
* secrets have been zeroized and cannot be revived — open a fresh
|
||||||
|
* stream instead.
|
||||||
|
*/
|
||||||
|
export class StreamClosedError extends ShadeError {
|
||||||
|
constructor(message = 'Stream is closed') {
|
||||||
|
super('SHADE_STREAM_CLOSED', message);
|
||||||
|
this.name = 'StreamClosedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Thrown when a stream handshake frame is malformed, arrives in the
|
||||||
|
* wrong order, or references a streamId that does not match the stream
|
||||||
|
* it was fed to.
|
||||||
|
*/
|
||||||
|
export class StreamHandshakeError extends ShadeError {
|
||||||
|
constructor(message = 'Stream handshake failed') {
|
||||||
|
super('SHADE_STREAM_HANDSHAKE', message);
|
||||||
|
this.name = 'StreamHandshakeError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Infrastructure Errors ───────────────────────────────────
|
// ─── Infrastructure Errors ───────────────────────────────────
|
||||||
|
|
||||||
export class NetworkError extends ShadeError {
|
export class NetworkError extends ShadeError {
|
||||||
@@ -158,6 +183,30 @@ export class UnauthorizedError extends ShadeError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 409 Conflict — caller wrote to a resource that already exists without
|
||||||
|
* supplying an If-Match precondition. V4.9: the encrypted blob primitive
|
||||||
|
* uses this to force read-then-write on already-occupied slots.
|
||||||
|
*/
|
||||||
|
export class ConflictError extends ShadeError {
|
||||||
|
constructor(message = 'Conflict') {
|
||||||
|
super('SHADE_CONFLICT', message);
|
||||||
|
this.name = 'ConflictError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 412 Precondition Failed — caller supplied an If-Match etag that does
|
||||||
|
* not match the current state. V4.9: the encrypted blob primitive uses
|
||||||
|
* this to surface stale-CAS so clients can re-read, merge, and retry.
|
||||||
|
*/
|
||||||
|
export class PreconditionFailedError extends ShadeError {
|
||||||
|
constructor(message = 'Precondition failed') {
|
||||||
|
super('SHADE_PRECONDITION_FAILED', message);
|
||||||
|
this.name = 'PreconditionFailedError';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ─── Error → HTTP Status Mapping ────────────────────────────
|
// ─── Error → HTTP Status Mapping ────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -180,7 +229,10 @@ export function errorToHttpStatus(error: unknown): number {
|
|||||||
return 400;
|
return 400;
|
||||||
case 'SHADE_REPLAY':
|
case 'SHADE_REPLAY':
|
||||||
case 'SHADE_DUPLICATE_MESSAGE':
|
case 'SHADE_DUPLICATE_MESSAGE':
|
||||||
|
case 'SHADE_CONFLICT':
|
||||||
return 409;
|
return 409;
|
||||||
|
case 'SHADE_PRECONDITION_FAILED':
|
||||||
|
return 412;
|
||||||
case 'SHADE_RATE_LIMIT':
|
case 'SHADE_RATE_LIMIT':
|
||||||
return 429;
|
return 429;
|
||||||
case 'SHADE_TIMEOUT':
|
case 'SHADE_TIMEOUT':
|
||||||
|
|||||||
@@ -26,6 +26,8 @@ export interface ShadeEventMap {
|
|||||||
'identity.rotated': { newFingerprint: string };
|
'identity.rotated': { newFingerprint: string };
|
||||||
'session.created': { address: string; remoteIdentityKeyHash: string };
|
'session.created': { address: string; remoteIdentityKeyHash: string };
|
||||||
'session.removed': { address: string };
|
'session.removed': { address: string };
|
||||||
|
/** V4.8.3 — emitted when `aliasSession` moves a peer's per-peer state. */
|
||||||
|
'session.aliased': { oldLabel: string; newLabel: string };
|
||||||
'message.encrypted': { address: string; counter: number; ciphertextSize: number };
|
'message.encrypted': { address: string; counter: number; ciphertextSize: number };
|
||||||
'message.decrypted': { address: string; counter: number; plaintextSize: number };
|
'message.decrypted': { address: string; counter: number; plaintextSize: number };
|
||||||
'ratchet.dh_step': { address: string };
|
'ratchet.dh_step': { address: string };
|
||||||
@@ -34,6 +36,10 @@ export interface ShadeEventMap {
|
|||||||
'signed_prekey.rotated': { oldKeyId: number; newKeyId: number };
|
'signed_prekey.rotated': { oldKeyId: number; newKeyId: number };
|
||||||
'trust.pinned': { address: string; identityKeyHash: string };
|
'trust.pinned': { address: string; identityKeyHash: string };
|
||||||
'trust.changed': { address: string; oldKeyHash: string; newKeyHash: string };
|
'trust.changed': { address: string; oldKeyHash: string; newKeyHash: string };
|
||||||
|
/** V4.11 — a streaming sub-ratchet handshake completed. */
|
||||||
|
'stream.opened': { address: string; role: 'initiator' | 'responder' };
|
||||||
|
/** V4.11 — a streaming sub-ratchet was torn down and zeroized. */
|
||||||
|
'stream.closed': { address: string };
|
||||||
}
|
}
|
||||||
|
|
||||||
export type ShadeEventName = keyof ShadeEventMap;
|
export type ShadeEventName = keyof ShadeEventMap;
|
||||||
|
|||||||
@@ -5,6 +5,7 @@ export * from './keys.js';
|
|||||||
export * from './errors.js';
|
export * from './errors.js';
|
||||||
export * from './x3dh.js';
|
export * from './x3dh.js';
|
||||||
export * from './ratchet.js';
|
export * from './ratchet.js';
|
||||||
|
export * from './stream.js';
|
||||||
export { ShadeSessionManager, GRACE_PERIOD_MS } from './session.js';
|
export { ShadeSessionManager, GRACE_PERIOD_MS } from './session.js';
|
||||||
export * from './serialization.js';
|
export * from './serialization.js';
|
||||||
export * from './fingerprint.js';
|
export * from './fingerprint.js';
|
||||||
|
|||||||
@@ -185,6 +185,22 @@ export async function ratchetDecrypt(
|
|||||||
if (!session.receiveChain) {
|
if (!session.receiveChain) {
|
||||||
throw new DecryptionError('No receiving chain available');
|
throw new DecryptionError('No receiving chain available');
|
||||||
}
|
}
|
||||||
|
// Defense-in-depth: a same-DH message whose counter is already
|
||||||
|
// behind the chain — and that did NOT match a cached skipped key —
|
||||||
|
// is either a duplicate we already decrypted (skipped key was
|
||||||
|
// consumed) or one whose key was evicted under cache pressure.
|
||||||
|
// Falling through would call kdfChainKey on the *current* (ahead)
|
||||||
|
// chainKey and then rewind `chain.counter = message.counter + 1`,
|
||||||
|
// permanently desyncing the chain so every subsequent decrypt
|
||||||
|
// returns wrong-key. Reject without mutating state instead.
|
||||||
|
if (
|
||||||
|
!isNewRatchet &&
|
||||||
|
message.counter < session.receiveChain.counter
|
||||||
|
) {
|
||||||
|
throw new DecryptionError(
|
||||||
|
'Failed to decrypt message — wrong key or tampered data',
|
||||||
|
);
|
||||||
|
}
|
||||||
await skipMessageKeys(crypto, session, message.dhPublicKey, session.receiveChain, message.counter);
|
await skipMessageKeys(crypto, session, message.dhPublicKey, session.receiveChain, message.counter);
|
||||||
|
|
||||||
// Advance the receiving chain one more step to get this message's key
|
// Advance the receiving chain one more step to get this message's key
|
||||||
|
|||||||
@@ -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,
|
||||||
|
|||||||
@@ -23,7 +23,14 @@ import {
|
|||||||
ratchetEncrypt,
|
ratchetEncrypt,
|
||||||
ratchetDecrypt,
|
ratchetDecrypt,
|
||||||
} from './ratchet.js';
|
} from './ratchet.js';
|
||||||
import { NoSessionError } from './errors.js';
|
import {
|
||||||
|
deriveStreamRootKey,
|
||||||
|
bootstrapStreamSession,
|
||||||
|
StreamRatchet,
|
||||||
|
STREAM_ID_BYTES,
|
||||||
|
STREAM_EPHEMERAL_BYTES,
|
||||||
|
} from './stream.js';
|
||||||
|
import { NoSessionError, StreamHandshakeError } from './errors.js';
|
||||||
import { computeFingerprint, shortFingerprint } from './fingerprint.js';
|
import { computeFingerprint, shortFingerprint } from './fingerprint.js';
|
||||||
import { ShadeEventEmitter, shortHash } from './events.js';
|
import { ShadeEventEmitter, shortHash } from './events.js';
|
||||||
import {
|
import {
|
||||||
@@ -79,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,
|
||||||
@@ -144,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;
|
||||||
@@ -261,10 +316,90 @@ 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.
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Move every per-peer storage row for `oldLabel` (session, trusted
|
||||||
|
* identity, peer-verification, identity-version counter) to
|
||||||
|
* `newLabel`. Used to canonicalize sessions when first-contact
|
||||||
|
* forces the receiver to label by sender-fingerprint hint
|
||||||
|
* (`fp:<hex>`) and a later in-band announcement reveals the peer's
|
||||||
|
* canonical address.
|
||||||
|
*
|
||||||
|
* Holds the per-peer mutex on **both** labels for the whole
|
||||||
|
* migration so concurrent encrypt/decrypt for either label can't
|
||||||
|
* observe a half-moved state. Locks are taken in lexicographic
|
||||||
|
* order to avoid deadlocks if two callers alias in opposite
|
||||||
|
* directions.
|
||||||
|
*
|
||||||
|
* Throws if no session exists for `oldLabel`. Throws (refuses to
|
||||||
|
* overwrite) if a session already exists for `newLabel`. No-ops
|
||||||
|
* when `oldLabel === newLabel`.
|
||||||
|
*
|
||||||
|
* V4.8.3 — Prism FR `session-label-asymmetry-v4.8.2.md`.
|
||||||
|
*/
|
||||||
|
async aliasSession(oldLabel: string, newLabel: string): Promise<void> {
|
||||||
|
if (oldLabel === newLabel) return;
|
||||||
|
const [first, second] = oldLabel < newLabel ? [oldLabel, newLabel] : [newLabel, oldLabel];
|
||||||
|
await this.runUnderPeerLock(first, () =>
|
||||||
|
this.runUnderPeerLock(second, () => this.aliasUnderLock(oldLabel, newLabel)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private async aliasUnderLock(oldLabel: string, newLabel: string): Promise<void> {
|
||||||
|
const session = await this.storage.getSession(oldLabel);
|
||||||
|
if (!session) throw new NoSessionError(oldLabel);
|
||||||
|
const collision = await this.storage.getSession(newLabel);
|
||||||
|
if (collision) {
|
||||||
|
throw new Error(
|
||||||
|
`aliasSession: refusing to overwrite an existing session for "${newLabel}". ` +
|
||||||
|
`If you want to replace it, call resetSession("${newLabel}") first.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Move the session.
|
||||||
|
await this.storage.saveSession(newLabel, session);
|
||||||
|
// Re-pin trust under the new label using the session's stored DH
|
||||||
|
// identity key — `saveTrustedIdentity` is the same primitive that
|
||||||
|
// the X3DH initiator/responder uses, and the DH key in `session`
|
||||||
|
// is the value that was pinned at session-establish time. The old
|
||||||
|
// pin under `oldLabel` is harmless leftover (the storage interface
|
||||||
|
// has no remove for trust pins) and would only be re-checked if a
|
||||||
|
// fresh X3DH against `oldLabel` somehow happened later.
|
||||||
|
await this.storage.saveTrustedIdentity(newLabel, session.remoteIdentityKey);
|
||||||
|
// Migrate the peer-verification record if present.
|
||||||
|
const verification = await this.storage.getPeerVerification(oldLabel);
|
||||||
|
if (verification) {
|
||||||
|
await this.storage.savePeerVerification({
|
||||||
|
...verification,
|
||||||
|
peerAddress: newLabel,
|
||||||
|
});
|
||||||
|
await this.storage.removePeerVerification(oldLabel);
|
||||||
|
}
|
||||||
|
// Carry the identity-version counter forward so peer rotation
|
||||||
|
// history is preserved.
|
||||||
|
const oldVersion = await this.storage.getPeerIdentityVersion(oldLabel);
|
||||||
|
for (let i = 1; i < oldVersion; i++) {
|
||||||
|
await this.storage.bumpPeerIdentityVersion(newLabel);
|
||||||
|
}
|
||||||
|
await this.storage.removeSession(oldLabel);
|
||||||
|
// Remember the move durably. The peer goes on sending under
|
||||||
|
// `oldLabel` — its transport derives the same first-contact label
|
||||||
|
// from our relay hint every time — so without this record every
|
||||||
|
// inbound frame after a restart resolves to a label whose session
|
||||||
|
// we just removed, and the peer (holding a valid session, never
|
||||||
|
// re-running X3DH) can never recover on its own.
|
||||||
|
await this.storage.saveSessionAlias?.(oldLabel, newLabel);
|
||||||
|
this.aliasCache.clear();
|
||||||
|
this.events?.emit('session.aliased', { oldLabel, newLabel });
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Accept a changed remote identity. This should only be called after
|
* Accept a changed remote identity. This should only be called after
|
||||||
* verifying the new identity out-of-band (e.g., comparing fingerprints).
|
* verifying the new identity out-of-band (e.g., comparing fingerprints).
|
||||||
@@ -275,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);
|
||||||
@@ -442,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,
|
||||||
});
|
});
|
||||||
@@ -458,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,
|
||||||
@@ -472,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,
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
@@ -490,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);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -559,6 +709,121 @@ export class ShadeSessionManager {
|
|||||||
|
|
||||||
return dec.decode(plaintext);
|
return dec.decode(plaintext);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Streaming sub-sessions (V4.11) ────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Resolve the peer's pinned identity X25519 key for a stream
|
||||||
|
* handshake. Requires an *already established* parent session — the
|
||||||
|
* stream is explicitly a "second channel on a known peer", never a
|
||||||
|
* first contact (so it needs no prekey-server round trip and inherits
|
||||||
|
* the parent's TOFU pin).
|
||||||
|
*/
|
||||||
|
private async streamIdentityMaterial(
|
||||||
|
address: string,
|
||||||
|
): Promise<{ selfIdentityDHPriv: Uint8Array; peerIdentityDHPub: Uint8Array }> {
|
||||||
|
if (!this.identity) throw new Error('Not initialized');
|
||||||
|
const session = await this.storage.getSession(address);
|
||||||
|
if (!session) throw new NoSessionError(address);
|
||||||
|
return {
|
||||||
|
selfIdentityDHPriv: this.identity.dhPrivateKey,
|
||||||
|
peerIdentityDHPub: session.remoteIdentityKey,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Initiator side of a stream handshake. Generates the streamId and
|
||||||
|
* this side's ephemeral, and returns a `complete` continuation that
|
||||||
|
* derives the sub-ratchet once the responder's ephemeral arrives in
|
||||||
|
* the `STREAM_OPEN_ACK`.
|
||||||
|
*
|
||||||
|
* Touches neither the stored parent session nor the per-peer op
|
||||||
|
* queues (R5).
|
||||||
|
*/
|
||||||
|
async beginStream(address: string): Promise<{
|
||||||
|
streamId: Uint8Array;
|
||||||
|
ephemeralPublicKey: Uint8Array;
|
||||||
|
complete: (peerEphemeralPub: Uint8Array) => Promise<StreamRatchet>;
|
||||||
|
}> {
|
||||||
|
const { selfIdentityDHPriv, peerIdentityDHPub } =
|
||||||
|
await this.streamIdentityMaterial(address);
|
||||||
|
const streamId = this.crypto.randomBytes(STREAM_ID_BYTES);
|
||||||
|
const ephemeral = await this.crypto.generateX25519KeyPair();
|
||||||
|
|
||||||
|
const complete = async (peerEphemeralPub: Uint8Array): Promise<StreamRatchet> => {
|
||||||
|
if (peerEphemeralPub.length !== STREAM_EPHEMERAL_BYTES) {
|
||||||
|
throw new StreamHandshakeError(
|
||||||
|
`responder ephemeral must be ${STREAM_EPHEMERAL_BYTES} bytes`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const sk = await deriveStreamRootKey(
|
||||||
|
this.crypto,
|
||||||
|
'initiator',
|
||||||
|
streamId,
|
||||||
|
selfIdentityDHPriv,
|
||||||
|
peerIdentityDHPub,
|
||||||
|
ephemeral.privateKey,
|
||||||
|
peerEphemeralPub,
|
||||||
|
);
|
||||||
|
const session = await bootstrapStreamSession(this.crypto, 'initiator', sk, peerIdentityDHPub, {
|
||||||
|
publicKey: peerEphemeralPub,
|
||||||
|
privateKey: new Uint8Array(0),
|
||||||
|
});
|
||||||
|
this.crypto.zeroize(sk);
|
||||||
|
this.crypto.zeroize(ephemeral.privateKey);
|
||||||
|
this.events?.emit('stream.opened', { address, role: 'initiator' });
|
||||||
|
return new StreamRatchet(this.crypto, session, streamId);
|
||||||
|
};
|
||||||
|
|
||||||
|
return { streamId, ephemeralPublicKey: ephemeral.publicKey, complete };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Responder side of a stream handshake. Given the initiator's
|
||||||
|
* `STREAM_OPEN` (its streamId + ephemeral), derives the sub-ratchet
|
||||||
|
* immediately and returns this side's ephemeral for the
|
||||||
|
* `STREAM_OPEN_ACK`.
|
||||||
|
*/
|
||||||
|
async acceptStream(
|
||||||
|
address: string,
|
||||||
|
streamId: Uint8Array,
|
||||||
|
initiatorEphemeralPub: Uint8Array,
|
||||||
|
): Promise<{ ephemeralPublicKey: Uint8Array; stream: StreamRatchet }> {
|
||||||
|
if (streamId.length !== STREAM_ID_BYTES) {
|
||||||
|
throw new StreamHandshakeError(`streamId must be ${STREAM_ID_BYTES} bytes`);
|
||||||
|
}
|
||||||
|
if (initiatorEphemeralPub.length !== STREAM_EPHEMERAL_BYTES) {
|
||||||
|
throw new StreamHandshakeError(
|
||||||
|
`initiator ephemeral must be ${STREAM_EPHEMERAL_BYTES} bytes`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const { selfIdentityDHPriv, peerIdentityDHPub } =
|
||||||
|
await this.streamIdentityMaterial(address);
|
||||||
|
const ephemeral = await this.crypto.generateX25519KeyPair();
|
||||||
|
|
||||||
|
const sk = await deriveStreamRootKey(
|
||||||
|
this.crypto,
|
||||||
|
'responder',
|
||||||
|
streamId,
|
||||||
|
selfIdentityDHPriv,
|
||||||
|
peerIdentityDHPub,
|
||||||
|
ephemeral.privateKey,
|
||||||
|
initiatorEphemeralPub,
|
||||||
|
);
|
||||||
|
const session = await bootstrapStreamSession(
|
||||||
|
this.crypto,
|
||||||
|
'responder',
|
||||||
|
sk,
|
||||||
|
peerIdentityDHPub,
|
||||||
|
ephemeral,
|
||||||
|
);
|
||||||
|
this.crypto.zeroize(sk);
|
||||||
|
this.events?.emit('stream.opened', { address, role: 'responder' });
|
||||||
|
return {
|
||||||
|
ephemeralPublicKey: ephemeral.publicKey,
|
||||||
|
stream: new StreamRatchet(this.crypto, session, streamId),
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function arraysEqual(a: Uint8Array, b: Uint8Array): boolean {
|
function arraysEqual(a: Uint8Array, b: Uint8Array): boolean {
|
||||||
|
|||||||
@@ -46,6 +46,50 @@ export interface PersistedStreamState {
|
|||||||
*/
|
*/
|
||||||
export type PeerVerificationSource = 'user' | 'transitive' | 'tofu-after-warning';
|
export type PeerVerificationSource = 'user' | 'transitive' | 'tofu-after-warning';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persisted broadcast-channel state (V4.6). Holds the sender-key chain that
|
||||||
|
* lets the channel owner encrypt a single ciphertext and fan it out to all
|
||||||
|
* paired members.
|
||||||
|
*
|
||||||
|
* - `ownerRole === 'sender'`: this device created the channel; the record
|
||||||
|
* carries the full chain (chainKey + iteration + signing keypair).
|
||||||
|
* - `ownerRole === 'receiver'`: this device joined a channel that
|
||||||
|
* `ownerAddress` owns; we hold a tracking copy of the chain (chainKey +
|
||||||
|
* iteration + signing public key only — no private signing key).
|
||||||
|
*
|
||||||
|
* `generation` is bumped each time `removeMember` rotates the chain. Stale
|
||||||
|
* broadcasts at lower generations are silently dropped on receive.
|
||||||
|
*/
|
||||||
|
export interface BroadcastChannelRecord {
|
||||||
|
/** Opaque, stable across restarts. UUID-style. */
|
||||||
|
channelId: string;
|
||||||
|
ownerRole: 'sender' | 'receiver';
|
||||||
|
/** The address that owns the channel (i.e. the only sender). */
|
||||||
|
ownerAddress: string;
|
||||||
|
label?: string;
|
||||||
|
/** Sender-key generation — bumped on rotation. Starts at 0. */
|
||||||
|
generation: number;
|
||||||
|
/** Current chain key (32 bytes). */
|
||||||
|
chainKey: Uint8Array;
|
||||||
|
/** Counter advanced by `senderKeyEncrypt` / `senderKeyDecrypt`. */
|
||||||
|
iteration: number;
|
||||||
|
/** Owner's Ed25519 signing public key (32 bytes). */
|
||||||
|
signingPublicKey: Uint8Array;
|
||||||
|
/** Owner's Ed25519 signing private key. Present iff `ownerRole === 'sender'`. */
|
||||||
|
signingPrivateKey?: Uint8Array;
|
||||||
|
createdAt: number;
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Membership row for a broadcast channel (sender-side only). */
|
||||||
|
export interface BroadcastMemberRecord {
|
||||||
|
channelId: string;
|
||||||
|
peerAddress: string;
|
||||||
|
joinedAt: number;
|
||||||
|
/** When this peer was revoked. `null` while still active. */
|
||||||
|
removedAt: number | null;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Persistent record that a peer's safety number was verified at a point
|
* Persistent record that a peer's safety number was verified at a point
|
||||||
* in time. `identityVersion` is the local counter for that peer's identity:
|
* in time. `identityVersion` is the local counter for that peer's identity:
|
||||||
@@ -121,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>;
|
||||||
|
|
||||||
@@ -188,4 +262,35 @@ export interface StorageProvider {
|
|||||||
|
|
||||||
/** Prune stream-state rows in `'finished' | 'aborted'` status older than `olderThan`. */
|
/** Prune stream-state rows in `'finished' | 'aborted'` status older than `olderThan`. */
|
||||||
pruneStreamStates?(olderThan: number): Promise<void>;
|
pruneStreamStates?(olderThan: number): Promise<void>;
|
||||||
|
|
||||||
|
// ─── Broadcast channels (V4.6) — optional ─────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Persist or replace the broadcast-channel record. Idempotent upsert on
|
||||||
|
* `channelId`. Backends that don't implement broadcast-channel support
|
||||||
|
* may omit this; the SDK throws a clear error when the app tries to
|
||||||
|
* call `createBroadcastChannel` on such a backend.
|
||||||
|
*/
|
||||||
|
saveBroadcastChannel?(channel: BroadcastChannelRecord): Promise<void>;
|
||||||
|
|
||||||
|
/** Look up a broadcast channel by id. */
|
||||||
|
getBroadcastChannel?(channelId: string): Promise<BroadcastChannelRecord | null>;
|
||||||
|
|
||||||
|
/** Enumerate all broadcast channels persisted on this device. */
|
||||||
|
listBroadcastChannels?(): Promise<BroadcastChannelRecord[]>;
|
||||||
|
|
||||||
|
/** Drop a broadcast channel and all its membership rows. */
|
||||||
|
removeBroadcastChannel?(channelId: string): Promise<void>;
|
||||||
|
|
||||||
|
/** Persist or replace a broadcast-membership row (sender-side only). */
|
||||||
|
saveBroadcastMember?(member: BroadcastMemberRecord): Promise<void>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* List membership rows for a channel. Includes revoked members (with
|
||||||
|
* `removedAt !== null`); callers filter as needed.
|
||||||
|
*/
|
||||||
|
getBroadcastMembers?(channelId: string): Promise<BroadcastMemberRecord[]>;
|
||||||
|
|
||||||
|
/** Hard-delete a single membership row. */
|
||||||
|
removeBroadcastMember?(channelId: string, peerAddress: string): Promise<void>;
|
||||||
}
|
}
|
||||||
|
|||||||
233
packages/shade-core/src/stream.ts
Normal file
233
packages/shade-core/src/stream.ts
Normal file
@@ -0,0 +1,233 @@
|
|||||||
|
import type { CryptoProvider } from './crypto.js';
|
||||||
|
import type { KeyPair, RatchetMessage, SessionState } from './types.js';
|
||||||
|
import {
|
||||||
|
initSenderSession,
|
||||||
|
initReceiverSession,
|
||||||
|
ratchetEncrypt,
|
||||||
|
ratchetDecrypt,
|
||||||
|
} from './ratchet.js';
|
||||||
|
import { StreamClosedError } from './errors.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Streaming Double-Ratchet sub-sessions (V4.11).
|
||||||
|
*
|
||||||
|
* Wraps a long-lived, high-frequency, often-one-directional channel
|
||||||
|
* (e.g. a server→client WebSocket log burst) in an *independent* Double
|
||||||
|
* Ratchet that is derived from — but never mutates — an already
|
||||||
|
* established parent Shade session.
|
||||||
|
*
|
||||||
|
* Why a sub-ratchet rather than reusing `ShadeSessionManager`:
|
||||||
|
*
|
||||||
|
* - **Independence (R5).** A stream gets its own root key, chains, DH
|
||||||
|
* ratchet and op-mutex. Opening/closing it never touches the stored
|
||||||
|
* parent `SessionState` nor serialises against the HTTP send/receive
|
||||||
|
* queue.
|
||||||
|
* - **Performance (R7).** The stream ratchet lives only in memory and
|
||||||
|
* is *never* written to the keystore. There is therefore zero
|
||||||
|
* per-frame storage I/O — the cost is purely the symmetric KDF +
|
||||||
|
* AES-GCM, the same primitives the HTTP path uses.
|
||||||
|
* - **Forward secrecy.** Not persisting the evolving ratchet state is
|
||||||
|
* a feature, not a shortcut: writing per-frame secrets to disk would
|
||||||
|
* actively defeat the forward-secrecy guarantee. A dropped/reconnected
|
||||||
|
* stream is re-opened with a fresh handshake, not resumed.
|
||||||
|
*
|
||||||
|
* ## Seeding (no prekey-server round trip)
|
||||||
|
*
|
||||||
|
* The stream root key is derived from an identity-bound 3-DH exchange —
|
||||||
|
* the X3DH pattern minus the signed / one-time prekeys, because the
|
||||||
|
* peer's identity is *already* mutually pinned by the parent session's
|
||||||
|
* TOFU. Two ephemeral keys are exchanged inside the transport itself
|
||||||
|
* (`STREAM_OPEN` / `STREAM_OPEN_ACK`); no prekey server is involved.
|
||||||
|
*
|
||||||
|
* slotA = DH(initiatorEphemeral, responderIdentity) — auth of responder
|
||||||
|
* slotB = DH(initiatorIdentity, responderEphemeral) — auth of initiator
|
||||||
|
* slotC = DH(initiatorEphemeral, responderEphemeral) — ephemeral FS
|
||||||
|
*
|
||||||
|
* SK = HKDF(ikm = slotA‖slotB‖slotC, salt = streamId, info = "ShadeStream/v1")
|
||||||
|
*
|
||||||
|
* Both peers compute the identical three scalars regardless of role, so
|
||||||
|
* `SK` agrees. An attacker lacking the responder's identity private key
|
||||||
|
* cannot form slotA; one lacking the initiator's cannot form slotB —
|
||||||
|
* the handshake is therefore mutually authenticated against the same
|
||||||
|
* identities the parent session already trusts.
|
||||||
|
*
|
||||||
|
* `SK` then bootstraps a textbook Double Ratchet by handing the
|
||||||
|
* responder's ephemeral to {@link initSenderSession} /
|
||||||
|
* {@link initReceiverSession} exactly the way X3DH hands its signed
|
||||||
|
* prekey to the ratchet — so `ratchetEncrypt` / `ratchetDecrypt` (and
|
||||||
|
* thus every R1–R3 guarantee they already carry) apply unchanged.
|
||||||
|
*/
|
||||||
|
|
||||||
|
export type StreamRole = 'initiator' | 'responder';
|
||||||
|
|
||||||
|
/** Stream identifier length (bytes). 128 bits of collision resistance. */
|
||||||
|
export const STREAM_ID_BYTES = 16;
|
||||||
|
|
||||||
|
/** Ephemeral X25519 public-key length carried in the handshake. */
|
||||||
|
export const STREAM_EPHEMERAL_BYTES = 32;
|
||||||
|
|
||||||
|
const STREAM_KDF_INFO = new TextEncoder().encode('ShadeStream/v1');
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Derive the stream's independent root key from the identity-bound 3-DH
|
||||||
|
* exchange. Pure: never reads or mutates any `SessionState`.
|
||||||
|
*
|
||||||
|
* @param role which end of the handshake we are
|
||||||
|
* @param streamId 16-byte stream id (HKDF salt; binds the
|
||||||
|
* derivation so two concurrent streams to the
|
||||||
|
* same peer never share a root key)
|
||||||
|
* @param selfIdentityDHPriv our long-term identity X25519 private key
|
||||||
|
* @param peerIdentityDHPub peer's pinned identity X25519 public key
|
||||||
|
* (the value the parent session pinned)
|
||||||
|
* @param selfEphemeralPriv our per-stream ephemeral X25519 private key
|
||||||
|
* @param peerEphemeralPub peer's per-stream ephemeral X25519 public key
|
||||||
|
*/
|
||||||
|
export async function deriveStreamRootKey(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
role: StreamRole,
|
||||||
|
streamId: Uint8Array,
|
||||||
|
selfIdentityDHPriv: Uint8Array,
|
||||||
|
peerIdentityDHPub: Uint8Array,
|
||||||
|
selfEphemeralPriv: Uint8Array,
|
||||||
|
peerEphemeralPub: Uint8Array,
|
||||||
|
): Promise<Uint8Array> {
|
||||||
|
// Each slot is pinned to a fixed semantic (not to local role) so both
|
||||||
|
// sides feed HKDF the identical ikm:
|
||||||
|
// slotA = DH(initiatorEphemeral, responderIdentity)
|
||||||
|
// slotB = DH(initiatorIdentity, responderEphemeral)
|
||||||
|
// slotC = DH(initiatorEphemeral, responderEphemeral)
|
||||||
|
let slotA: Uint8Array;
|
||||||
|
let slotB: Uint8Array;
|
||||||
|
let slotC: Uint8Array;
|
||||||
|
if (role === 'initiator') {
|
||||||
|
slotA = await crypto.x25519(selfEphemeralPriv, peerIdentityDHPub);
|
||||||
|
slotB = await crypto.x25519(selfIdentityDHPriv, peerEphemeralPub);
|
||||||
|
slotC = await crypto.x25519(selfEphemeralPriv, peerEphemeralPub);
|
||||||
|
} else {
|
||||||
|
slotA = await crypto.x25519(selfIdentityDHPriv, peerEphemeralPub);
|
||||||
|
slotB = await crypto.x25519(selfEphemeralPriv, peerIdentityDHPub);
|
||||||
|
slotC = await crypto.x25519(selfEphemeralPriv, peerEphemeralPub);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ikm = new Uint8Array(96);
|
||||||
|
ikm.set(slotA, 0);
|
||||||
|
ikm.set(slotB, 32);
|
||||||
|
ikm.set(slotC, 64);
|
||||||
|
const sk = await crypto.hkdf(ikm, streamId, STREAM_KDF_INFO, 32);
|
||||||
|
|
||||||
|
crypto.zeroize(slotA);
|
||||||
|
crypto.zeroize(slotB);
|
||||||
|
crypto.zeroize(slotC);
|
||||||
|
crypto.zeroize(ikm);
|
||||||
|
return sk;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bootstrap a fresh Double Ratchet `SessionState` from the derived
|
||||||
|
* stream root key. The responder's ephemeral plays exactly the role
|
||||||
|
* X3DH's signed prekey plays in {@link initSenderSession} /
|
||||||
|
* {@link initReceiverSession}, so the ratchet handoff is identical to
|
||||||
|
* the proven HTTP path.
|
||||||
|
*
|
||||||
|
* On the initiator only `responderEphemeral.publicKey` is needed; the
|
||||||
|
* responder must pass its full ephemeral keypair.
|
||||||
|
*
|
||||||
|
* `peerIdentityDHPub` is recorded as the session's `remoteIdentityKey`
|
||||||
|
* so stream fingerprints stay meaningful and consistent with the parent.
|
||||||
|
*/
|
||||||
|
export async function bootstrapStreamSession(
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
role: StreamRole,
|
||||||
|
sk: Uint8Array,
|
||||||
|
peerIdentityDHPub: Uint8Array,
|
||||||
|
responderEphemeral: KeyPair,
|
||||||
|
): Promise<SessionState> {
|
||||||
|
if (role === 'initiator') {
|
||||||
|
// initSenderSession derives a fresh root via kdfRootKey and does not
|
||||||
|
// retain `sk`, so the caller may safely zeroize it afterwards.
|
||||||
|
return initSenderSession(crypto, sk, peerIdentityDHPub, responderEphemeral.publicKey);
|
||||||
|
}
|
||||||
|
// initReceiverSession stores the root key BY REFERENCE. Hand it an
|
||||||
|
// independent copy so the caller zeroizing its `sk` scratch buffer
|
||||||
|
// can't wipe the live session root.
|
||||||
|
return initReceiverSession(new Uint8Array(sk), peerIdentityDHPub, responderEphemeral);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Zeroize every secret a stream session holds, then drop the chains. */
|
||||||
|
function zeroizeSession(crypto: CryptoProvider, s: SessionState): void {
|
||||||
|
crypto.zeroize(s.rootKey);
|
||||||
|
if (s.sendChain.chainKey.length > 0) crypto.zeroize(s.sendChain.chainKey);
|
||||||
|
if (s.receiveChain && s.receiveChain.chainKey.length > 0) {
|
||||||
|
crypto.zeroize(s.receiveChain.chainKey);
|
||||||
|
}
|
||||||
|
if (s.dhSend.privateKey.length > 0) crypto.zeroize(s.dhSend.privateKey);
|
||||||
|
for (const mk of s.skippedKeys.values()) crypto.zeroize(mk);
|
||||||
|
s.skippedKeys.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-memory holder for a stream's Double Ratchet. Serialises its own
|
||||||
|
* `seal`/`open`/`close` on a private promise chain (independent of the
|
||||||
|
* SDK's per-peer encrypt/decrypt queues — R5) so per-frame ratchet
|
||||||
|
* mutations never interleave, while staying fully concurrent with the
|
||||||
|
* parent session and with other streams.
|
||||||
|
*
|
||||||
|
* Never persisted: the ratchet exists only for the lifetime of the
|
||||||
|
* stream and is zeroized on `close()`.
|
||||||
|
*/
|
||||||
|
export class StreamRatchet {
|
||||||
|
private session: SessionState | null;
|
||||||
|
private opChain: Promise<unknown> = Promise.resolve();
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private readonly crypto: CryptoProvider,
|
||||||
|
session: SessionState,
|
||||||
|
/** 16-byte stream id this ratchet is bound to. */
|
||||||
|
public readonly streamId: Uint8Array,
|
||||||
|
) {
|
||||||
|
this.session = session;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** True once {@link close} has run; `seal`/`open` will throw. */
|
||||||
|
get closed(): boolean {
|
||||||
|
return this.session === null;
|
||||||
|
}
|
||||||
|
|
||||||
|
private run<T>(fn: (s: SessionState) => Promise<T>): Promise<T> {
|
||||||
|
const next = this.opChain.catch(() => undefined).then(() => {
|
||||||
|
if (!this.session) throw new StreamClosedError();
|
||||||
|
return fn(this.session);
|
||||||
|
});
|
||||||
|
// Keep a never-rejecting tail so a failed frame doesn't poison the
|
||||||
|
// next one (a single bad inbound frame must not wedge the stream).
|
||||||
|
this.opChain = next.catch(() => undefined);
|
||||||
|
return next;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Wrap one logical frame. Advances the sending chain by one step. */
|
||||||
|
seal(plaintext: Uint8Array): Promise<RatchetMessage> {
|
||||||
|
return this.run((s) => ratchetEncrypt(this.crypto, s, plaintext));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Unwrap one inbound frame. Correct and memory-bounded across long
|
||||||
|
* one-directional runs from the peer: ordered transport delivery
|
||||||
|
* skips zero keys per frame, and out-of-order arrivals are still
|
||||||
|
* capped by the ratchet's `MAX_SKIP` / `MAX_CACHED_SKIPPED_KEYS`.
|
||||||
|
*/
|
||||||
|
open(message: RatchetMessage): Promise<Uint8Array> {
|
||||||
|
return this.run((s) => ratchetDecrypt(this.crypto, s, message));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Zeroize and drop the ratchet. Idempotent. */
|
||||||
|
close(): Promise<void> {
|
||||||
|
return this.opChain
|
||||||
|
.catch(() => undefined)
|
||||||
|
.then(() => {
|
||||||
|
if (this.session) {
|
||||||
|
zeroizeSession(this.crypto, this.session);
|
||||||
|
this.session = null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -281,6 +281,41 @@ describe('Double Ratchet', () => {
|
|||||||
|
|
||||||
expect(ratchetDecrypt(crypto, bob, msg)).rejects.toThrow();
|
expect(ratchetDecrypt(crypto, bob, msg)).rejects.toThrow();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Regression — the v4.2.0 OutboundQueue waiter-since bug delivered
|
||||||
|
* the same envelope twice to `manager.decrypt`. The first decrypt
|
||||||
|
* succeeded via a cached skipped key; the second one fell into the
|
||||||
|
* `message.counter < chain.counter` path with no skipped key
|
||||||
|
* available, advanced the chainKey ONCE and rewound `chain.counter`
|
||||||
|
* to `message.counter + 1`, leaving the ratchet permanently
|
||||||
|
* desynced. ratchetDecrypt now rejects without mutating state when
|
||||||
|
* a same-DH message is behind the chain and not in skippedKeys, so
|
||||||
|
* a downstream replay (transport bug, retry, etc.) cannot poison
|
||||||
|
* the session for everyone else.
|
||||||
|
*/
|
||||||
|
test('same-DH stale message after consumed skipped key fails without corrupting state', async () => {
|
||||||
|
const { alice, bob } = await setupPair();
|
||||||
|
|
||||||
|
// Alice sends 3 messages on the same DH chain.
|
||||||
|
const m0 = await ratchetEncrypt(crypto, alice, enc.encode('m0'));
|
||||||
|
const m1 = await ratchetEncrypt(crypto, alice, enc.encode('m1'));
|
||||||
|
const m2 = await ratchetEncrypt(crypto, alice, enc.encode('m2'));
|
||||||
|
|
||||||
|
// Bob receives m1 first, caching m0's key. Then m0 (delivered
|
||||||
|
// via the cache). After this, m0's skipped key is consumed.
|
||||||
|
expect(dec.decode(await ratchetDecrypt(crypto, bob, m1))).toBe('m1');
|
||||||
|
expect(dec.decode(await ratchetDecrypt(crypto, bob, m0))).toBe('m0');
|
||||||
|
|
||||||
|
// Replay of m0: skippedKey is gone, chain.counter is past m0.
|
||||||
|
// Pre-fix: this would corrupt Bob's chain state; post-fix it
|
||||||
|
// throws cleanly.
|
||||||
|
await expect(ratchetDecrypt(crypto, bob, m0)).rejects.toThrow(DecryptionError);
|
||||||
|
|
||||||
|
// Bob can still decrypt the remaining valid message — chain
|
||||||
|
// state was NOT mutated by the rejected replay.
|
||||||
|
expect(dec.decode(await ratchetDecrypt(crypto, bob, m2))).toBe('m2');
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// ─── Long Conversation ────────────────────────────────────
|
// ─── Long Conversation ────────────────────────────────────
|
||||||
|
|||||||
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');
|
||||||
|
});
|
||||||
|
});
|
||||||
176
packages/shade-core/tests/stream.test.ts
Normal file
176
packages/shade-core/tests/stream.test.ts
Normal file
@@ -0,0 +1,176 @@
|
|||||||
|
import { describe, test, expect, beforeEach } from 'bun:test';
|
||||||
|
import { SubtleCryptoProvider, MemoryStorage } from '@shade/crypto-web';
|
||||||
|
import {
|
||||||
|
ShadeSessionManager,
|
||||||
|
StreamRatchet,
|
||||||
|
StreamClosedError,
|
||||||
|
DecryptionError,
|
||||||
|
} from '../src/index.js';
|
||||||
|
|
||||||
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
const dec = new TextDecoder();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Establish a *bidirectional* parent session: Alice→Bob X3DH, then one
|
||||||
|
* Alice→Bob message Bob decrypts so Bob also has a session for 'alice'.
|
||||||
|
* Both sides then hold the peer's pinned identity DH key — the input the
|
||||||
|
* stream handshake derives from.
|
||||||
|
*/
|
||||||
|
async function bidirectionalPair() {
|
||||||
|
const aliceStorage = new MemoryStorage();
|
||||||
|
const bobStorage = new MemoryStorage();
|
||||||
|
const alice = new ShadeSessionManager(crypto, aliceStorage);
|
||||||
|
const bob = new ShadeSessionManager(crypto, bobStorage);
|
||||||
|
await alice.initialize();
|
||||||
|
await bob.initialize();
|
||||||
|
|
||||||
|
const otpks = await bob.generateOneTimePreKeys(4);
|
||||||
|
const bundle = await bob.createPreKeyBundle();
|
||||||
|
bundle.oneTimePreKey = { keyId: otpks[0]!.keyId, publicKey: otpks[0]!.keyPair.publicKey };
|
||||||
|
await alice.initSessionFromBundle('bob', bundle);
|
||||||
|
|
||||||
|
const hello = await alice.encrypt('bob', 'parent-hello');
|
||||||
|
expect(await bob.decrypt('alice', hello)).toBe('parent-hello');
|
||||||
|
|
||||||
|
return { alice, bob, aliceStorage, bobStorage };
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Run the full STREAM_OPEN / STREAM_OPEN_ACK handshake between managers. */
|
||||||
|
async function openStreamPair(alice: ShadeSessionManager, bob: ShadeSessionManager) {
|
||||||
|
const begun = await alice.beginStream('bob'); // initiator
|
||||||
|
const accepted = await bob.acceptStream('alice', begun.streamId, begun.ephemeralPublicKey);
|
||||||
|
const aliceStream = await begun.complete(accepted.ephemeralPublicKey);
|
||||||
|
return { aliceStream, bobStream: accepted.stream, streamId: begun.streamId };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('streaming sub-ratchet (V4.11)', () => {
|
||||||
|
let alice: ShadeSessionManager;
|
||||||
|
let bob: ShadeSessionManager;
|
||||||
|
let aliceStorage: MemoryStorage;
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
({ alice, bob, aliceStorage } = await bidirectionalPair());
|
||||||
|
});
|
||||||
|
|
||||||
|
test('both sides derive the same stream root (round-trips frames)', async () => {
|
||||||
|
const { aliceStream, bobStream } = await openStreamPair(alice, bob);
|
||||||
|
|
||||||
|
// Initiator → responder (first frame triggers responder DH step).
|
||||||
|
const f1 = await aliceStream.seal(enc.encode('log line 1'));
|
||||||
|
expect(dec.decode(await bobStream.open(f1))).toBe('log line 1');
|
||||||
|
|
||||||
|
// Responder → initiator (now responder may seal).
|
||||||
|
const r1 = await bobStream.seal(enc.encode('command-response 1'));
|
||||||
|
expect(dec.decode(await aliceStream.open(r1))).toBe('command-response 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('two streams to the same peer get independent roots', async () => {
|
||||||
|
const s1 = await openStreamPair(alice, bob);
|
||||||
|
const s2 = await openStreamPair(alice, bob);
|
||||||
|
expect(s1.streamId).not.toEqual(s2.streamId);
|
||||||
|
|
||||||
|
const a = await s1.aliceStream.seal(enc.encode('on stream 1'));
|
||||||
|
// A frame from stream 1 must not decrypt on stream 2's ratchet.
|
||||||
|
await expect(s2.bobStream.open(a)).rejects.toBeInstanceOf(DecryptionError);
|
||||||
|
// …but does on its own.
|
||||||
|
expect(dec.decode(await s1.bobStream.open(a))).toBe('on stream 1');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('R2/R3: long one-directional burst stays correct and memory-bounded', async () => {
|
||||||
|
const { aliceStream, bobStream } = await openStreamPair(alice, bob);
|
||||||
|
const N = 5000;
|
||||||
|
|
||||||
|
// Capture a live receive-chain key buffer to prove forward secrecy:
|
||||||
|
// ratchetDecrypt zeroizes the previous chain key in place.
|
||||||
|
await bobStream.open(await aliceStream.seal(enc.encode('frame-0')));
|
||||||
|
const bobSession = (bobStream as unknown as { session: { receiveChain: { chainKey: Uint8Array }; skippedKeys: Map<string, Uint8Array> } }).session;
|
||||||
|
const staleChainKey = bobSession.receiveChain.chainKey;
|
||||||
|
const staleCopy = staleChainKey.slice();
|
||||||
|
expect(staleCopy.some((b) => b !== 0)).toBe(true);
|
||||||
|
|
||||||
|
for (let i = 1; i < N; i++) {
|
||||||
|
const wire = await aliceStream.seal(enc.encode(`frame-${i}`));
|
||||||
|
expect(dec.decode(await bobStream.open(wire))).toBe(`frame-${i}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// In-order delivery ⇒ zero skipped keys retained across 5k frames.
|
||||||
|
expect(bobSession.skippedKeys.size).toBe(0);
|
||||||
|
// The chain key in use at frame 0 was overwritten (forward secrecy).
|
||||||
|
expect(staleChainKey.every((b) => b === 0)).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('R5: opening/using/closing a stream never touches the parent session', async () => {
|
||||||
|
const before = await aliceStorage.getSession('bob');
|
||||||
|
const snapshot = JSON.stringify({
|
||||||
|
root: Array.from(before!.rootKey),
|
||||||
|
sendCtr: before!.sendChain.counter,
|
||||||
|
prevCtr: before!.previousSendCounter,
|
||||||
|
});
|
||||||
|
|
||||||
|
const { aliceStream, bobStream } = await openStreamPair(alice, bob);
|
||||||
|
for (let i = 0; i < 200; i++) {
|
||||||
|
await bobStream.open(await aliceStream.seal(enc.encode(`x${i}`)));
|
||||||
|
}
|
||||||
|
await aliceStream.close();
|
||||||
|
await bobStream.close();
|
||||||
|
|
||||||
|
const after = await aliceStorage.getSession('bob');
|
||||||
|
expect(
|
||||||
|
JSON.stringify({
|
||||||
|
root: Array.from(after!.rootKey),
|
||||||
|
sendCtr: after!.sendChain.counter,
|
||||||
|
prevCtr: after!.previousSendCounter,
|
||||||
|
}),
|
||||||
|
).toBe(snapshot);
|
||||||
|
|
||||||
|
// Parent HTTP path still works after the stream lifecycle.
|
||||||
|
const env = await alice.encrypt('bob', 'after-stream');
|
||||||
|
expect(await bob.decrypt('alice', env)).toBe('after-stream');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('R1: replayed / rewound frame is rejected', async () => {
|
||||||
|
const { aliceStream, bobStream } = await openStreamPair(alice, bob);
|
||||||
|
const f1 = await aliceStream.seal(enc.encode('once'));
|
||||||
|
expect(dec.decode(await bobStream.open(f1))).toBe('once');
|
||||||
|
// Re-delivering the exact same sealed frame must fail.
|
||||||
|
await expect(bobStream.open(f1)).rejects.toBeInstanceOf(DecryptionError);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('close() zeroizes and blocks further use; idempotent', async () => {
|
||||||
|
const { aliceStream, bobStream } = await openStreamPair(alice, bob);
|
||||||
|
await aliceStream.close();
|
||||||
|
await aliceStream.close(); // idempotent
|
||||||
|
expect(aliceStream.closed).toBe(true);
|
||||||
|
await expect(aliceStream.seal(enc.encode('nope'))).rejects.toBeInstanceOf(
|
||||||
|
StreamClosedError,
|
||||||
|
);
|
||||||
|
// The peer end is unaffected by our local close.
|
||||||
|
expect(bobStream.closed).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('handshake is mutually authenticated against pinned identities', async () => {
|
||||||
|
// A third party (mallory) with its own identity cannot stand in for
|
||||||
|
// bob: alice derives against bob's pinned identity key, so a
|
||||||
|
// handshake completed with mallory's ephemeral yields a different
|
||||||
|
// root and frames fail to open.
|
||||||
|
const mStorage = new MemoryStorage();
|
||||||
|
const mallory = new ShadeSessionManager(crypto, mStorage);
|
||||||
|
await mallory.initialize();
|
||||||
|
// Give mallory a parent session label so acceptStream has identity
|
||||||
|
// material, but pinned to the WRONG (alice) identity vs what alice
|
||||||
|
// pinned for 'bob'.
|
||||||
|
const otpks = await mallory.generateOneTimePreKeys(2);
|
||||||
|
const mb = await mallory.createPreKeyBundle();
|
||||||
|
mb.oneTimePreKey = { keyId: otpks[0]!.keyId, publicKey: otpks[0]!.keyPair.publicKey };
|
||||||
|
await alice.initSessionFromBundle('mallory', mb);
|
||||||
|
const helo = await alice.encrypt('mallory', 'hi');
|
||||||
|
await mallory.decrypt('alice', helo);
|
||||||
|
|
||||||
|
const begun = await alice.beginStream('bob');
|
||||||
|
const mAccept = await mallory.acceptStream('alice', begun.streamId, begun.ephemeralPublicKey);
|
||||||
|
const aliceStream = await begun.complete(mAccept.ephemeralPublicKey);
|
||||||
|
const frame = await aliceStream.seal(enc.encode('secret'));
|
||||||
|
await expect(mAccept.stream.open(frame)).rejects.toBeInstanceOf(DecryptionError);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/crypto-web",
|
"name": "@shade/crypto-web",
|
||||||
"version": "4.0.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",
|
||||||
|
|||||||
18
packages/shade-crypto-web/src/ed25519-derive.ts
Normal file
18
packages/shade-crypto-web/src/ed25519-derive.ts
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
import { ed25519 } from '@noble/curves/ed25519.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deterministically derive an Ed25519 public key from a 32-byte seed.
|
||||||
|
*
|
||||||
|
* In the @noble/curves convention the "private key" *is* the seed —
|
||||||
|
* `sign(seed, msg)` works directly, and `getPublicKey(seed)` recovers
|
||||||
|
* the matching public key. V4.9's encrypted-blob primitive uses this
|
||||||
|
* to mint a per-slot signing keypair from an HKDF output rooted at the
|
||||||
|
* user's master key, so the same credentials always reproduce the same
|
||||||
|
* keypair.
|
||||||
|
*/
|
||||||
|
export function ed25519PublicKeyFromSeed(seed: Uint8Array): Uint8Array {
|
||||||
|
if (seed.length !== 32) {
|
||||||
|
throw new Error(`Ed25519 seed must be 32 bytes, got ${seed.length}`);
|
||||||
|
}
|
||||||
|
return ed25519.getPublicKey(seed);
|
||||||
|
}
|
||||||
@@ -1,5 +1,6 @@
|
|||||||
export { SubtleCryptoProvider } from './provider.js';
|
export { SubtleCryptoProvider } from './provider.js';
|
||||||
export { MemoryStorage } from './memory-storage.js';
|
export { MemoryStorage } from './memory-storage.js';
|
||||||
|
export { ed25519PublicKeyFromSeed } from './ed25519-derive.js';
|
||||||
|
|
||||||
// ─── Web Workers crypto (V3.8) ────────────────────────────
|
// ─── Web Workers crypto (V3.8) ────────────────────────────
|
||||||
export {
|
export {
|
||||||
|
|||||||
@@ -1,4 +1,8 @@
|
|||||||
import type { StorageProvider, IdentityKeyPair, SignedPreKey, OneTimePreKey, SessionState, RetiredIdentity, PersistedStreamState, PeerVerification } from '@shade/core';
|
import type {
|
||||||
|
StorageProvider, IdentityKeyPair, SignedPreKey, OneTimePreKey,
|
||||||
|
SessionState, RetiredIdentity, PersistedStreamState, PeerVerification,
|
||||||
|
BroadcastChannelRecord, BroadcastMemberRecord,
|
||||||
|
} from '@shade/core';
|
||||||
import { constantTimeEqual } from '@shade/core';
|
import { constantTimeEqual } from '@shade/core';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -11,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[] = [];
|
||||||
|
|
||||||
@@ -78,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> {
|
||||||
@@ -167,4 +189,62 @@ export class MemoryStorage implements StorageProvider {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Broadcast channels (V4.6) ────────────────────────────
|
||||||
|
|
||||||
|
private broadcastChannels = new Map<string, BroadcastChannelRecord>();
|
||||||
|
private broadcastMembers = new Map<string, Map<string, BroadcastMemberRecord>>();
|
||||||
|
|
||||||
|
async saveBroadcastChannel(channel: BroadcastChannelRecord): Promise<void> {
|
||||||
|
this.broadcastChannels.set(channel.channelId, cloneChannel(channel));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getBroadcastChannel(channelId: string): Promise<BroadcastChannelRecord | null> {
|
||||||
|
const v = this.broadcastChannels.get(channelId);
|
||||||
|
return v ? cloneChannel(v) : null;
|
||||||
|
}
|
||||||
|
|
||||||
|
async listBroadcastChannels(): Promise<BroadcastChannelRecord[]> {
|
||||||
|
return [...this.broadcastChannels.values()].map(cloneChannel);
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeBroadcastChannel(channelId: string): Promise<void> {
|
||||||
|
this.broadcastChannels.delete(channelId);
|
||||||
|
this.broadcastMembers.delete(channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async saveBroadcastMember(member: BroadcastMemberRecord): Promise<void> {
|
||||||
|
let inner = this.broadcastMembers.get(member.channelId);
|
||||||
|
if (!inner) {
|
||||||
|
inner = new Map();
|
||||||
|
this.broadcastMembers.set(member.channelId, inner);
|
||||||
|
}
|
||||||
|
inner.set(member.peerAddress, { ...member });
|
||||||
|
}
|
||||||
|
|
||||||
|
async getBroadcastMembers(channelId: string): Promise<BroadcastMemberRecord[]> {
|
||||||
|
const inner = this.broadcastMembers.get(channelId);
|
||||||
|
return inner ? [...inner.values()].map((m) => ({ ...m })) : [];
|
||||||
|
}
|
||||||
|
|
||||||
|
async removeBroadcastMember(channelId: string, peerAddress: string): Promise<void> {
|
||||||
|
this.broadcastMembers.get(channelId)?.delete(peerAddress);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function cloneChannel(c: BroadcastChannelRecord): BroadcastChannelRecord {
|
||||||
|
const out: BroadcastChannelRecord = {
|
||||||
|
channelId: c.channelId,
|
||||||
|
ownerRole: c.ownerRole,
|
||||||
|
ownerAddress: c.ownerAddress,
|
||||||
|
generation: c.generation,
|
||||||
|
chainKey: new Uint8Array(c.chainKey),
|
||||||
|
iteration: c.iteration,
|
||||||
|
signingPublicKey: new Uint8Array(c.signingPublicKey),
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
updatedAt: c.updatedAt,
|
||||||
|
};
|
||||||
|
if (c.label !== undefined) out.label = c.label;
|
||||||
|
if (c.signingPrivateKey !== undefined) out.signingPrivateKey = new Uint8Array(c.signingPrivateKey);
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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.0.0",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -8,5 +8,5 @@
|
|||||||
"module": "ESNext",
|
"module": "ESNext",
|
||||||
"moduleResolution": "bundler"
|
"moduleResolution": "bundler"
|
||||||
},
|
},
|
||||||
"include": ["src", "vite.config.ts"]
|
"include": ["src"]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/files",
|
"name": "@shade/files",
|
||||||
"version": "4.0.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,4 +1,4 @@
|
|||||||
import type { Shade } from '@shade/sdk';
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
import {
|
import {
|
||||||
KIND_CUSTOM_V1,
|
KIND_CUSTOM_V1,
|
||||||
KIND_DELETE_V1,
|
KIND_DELETE_V1,
|
||||||
@@ -184,7 +184,7 @@ export interface CreateFileClientOptions {
|
|||||||
* transfers that carry the actual bytes.
|
* transfers that carry the actual bytes.
|
||||||
*/
|
*/
|
||||||
export function createFileClient(
|
export function createFileClient(
|
||||||
shade: Shade,
|
shade: ShadeBridge,
|
||||||
channel: ShadeFileRpcChannel,
|
channel: ShadeFileRpcChannel,
|
||||||
pending: PendingRpcRegistry,
|
pending: PendingRpcRegistry,
|
||||||
peerAddress: string,
|
peerAddress: string,
|
||||||
|
|||||||
597
packages/shade-files/src/client/http-client.ts
Normal file
597
packages/shade-files/src/client/http-client.ts
Normal file
@@ -0,0 +1,597 @@
|
|||||||
|
/**
|
||||||
|
* Browser-friendly request-response `FileClient` for `@shade/files`.
|
||||||
|
*
|
||||||
|
* The default `shade.files.client(peer)` ships RPC envelopes via
|
||||||
|
* `Shade.send` + `Shade.deliverControlEnvelope`, which means the
|
||||||
|
* server has to be able to call back outbound to the client. That
|
||||||
|
* doesn't work for browser tabs (no inbound HTTP listener). This
|
||||||
|
* client posts each RPC envelope to a single server endpoint and
|
||||||
|
* reads the encrypted response from the same HTTP response — pure
|
||||||
|
* request-response, no inbound channel required.
|
||||||
|
*
|
||||||
|
* Inline payloads only (≤ 256 KiB). For larger reads/writes, use the
|
||||||
|
* stateful path: `shade.files.client(peer)` server-to-server, with
|
||||||
|
* `@shade/transfer` chunk routes for content I/O.
|
||||||
|
*
|
||||||
|
* @see {@link createFilesRpcRoute} for the matching server-side route.
|
||||||
|
*/
|
||||||
|
import type { ZodTypeAny } from 'zod';
|
||||||
|
import { decodeEnvelope, encodeEnvelope as encodeWireEnvelope } from '@shade/proto';
|
||||||
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
|
import {
|
||||||
|
encodeEnvelope as encodeRpcEnvelope,
|
||||||
|
tryParseEnvelope,
|
||||||
|
} from '../protocol/envelope-codec.js';
|
||||||
|
import {
|
||||||
|
KIND_CUSTOM_V1,
|
||||||
|
KIND_DELETE_V1,
|
||||||
|
KIND_GET_THUMBNAIL_V1,
|
||||||
|
KIND_LIST_V1,
|
||||||
|
KIND_MKDIR_V1,
|
||||||
|
KIND_MOVE_V1,
|
||||||
|
KIND_READ_V1,
|
||||||
|
KIND_STAT_V1,
|
||||||
|
KIND_WRITE_V1,
|
||||||
|
} from '../protocol/kinds.js';
|
||||||
|
import {
|
||||||
|
CustomArgsSchema,
|
||||||
|
CustomResultSchema,
|
||||||
|
DeleteArgsSchema,
|
||||||
|
DeleteResultSchema,
|
||||||
|
GetThumbnailArgsSchema,
|
||||||
|
GetThumbnailResultSchema,
|
||||||
|
ListArgsSchema,
|
||||||
|
ListResultSchema,
|
||||||
|
MkdirArgsSchema,
|
||||||
|
MkdirResultSchema,
|
||||||
|
MoveArgsSchema,
|
||||||
|
MoveResultSchema,
|
||||||
|
ReadArgsSchema,
|
||||||
|
ReadResultSchema,
|
||||||
|
StatArgsSchema,
|
||||||
|
StatResultSchema,
|
||||||
|
WriteArgsSchema,
|
||||||
|
WriteResultSchema,
|
||||||
|
type ListResult,
|
||||||
|
type MkdirResult,
|
||||||
|
type DeleteResult,
|
||||||
|
type MoveResult,
|
||||||
|
type StatResult,
|
||||||
|
type ThumbnailSize,
|
||||||
|
type WriteResult,
|
||||||
|
} from '../schemas/ops.js';
|
||||||
|
import {
|
||||||
|
fileErrorFromPayload,
|
||||||
|
CancelledError,
|
||||||
|
InternalFileError,
|
||||||
|
ConflictError,
|
||||||
|
} from '../schemas/errors.js';
|
||||||
|
import { buildRpcRequest } from '../protocol/rpc-builder.js';
|
||||||
|
import { decideInline, INLINE_THRESHOLD, type WriteSource } from './inline-threshold.js';
|
||||||
|
import { base64ToBytes, bytesToBase64 } from '../protocol/canonical.js';
|
||||||
|
import { startQueueDrainer, type QueueDrainerHandle } from './queue-drainer.js';
|
||||||
|
import {
|
||||||
|
createClientStreamsBridge,
|
||||||
|
type ClientStreamsBridge,
|
||||||
|
} from './streams-bridge.js';
|
||||||
|
import type {
|
||||||
|
FileClient,
|
||||||
|
ReadOpts,
|
||||||
|
ReadOutput,
|
||||||
|
ThumbnailResult,
|
||||||
|
WriteOpts,
|
||||||
|
CreateFileClientOptions,
|
||||||
|
BaseOpts,
|
||||||
|
} from './client.js';
|
||||||
|
|
||||||
|
export interface FilesHttpClientOptions
|
||||||
|
extends Omit<CreateFileClientOptions, 'streamsBridge'> {
|
||||||
|
/**
|
||||||
|
* Server endpoint that hosts `createFilesRpcRoute(...)`. Typically:
|
||||||
|
* `https://server.example.com/api/v1/shade-files/rpc`.
|
||||||
|
*/
|
||||||
|
rpcUrl: string;
|
||||||
|
/**
|
||||||
|
* Optional `fetch` override. Defaults to `globalThis.fetch`. Wire a
|
||||||
|
* custom `fetch` to thread auth-cookies, CSRF tokens, or
|
||||||
|
* service-worker interception.
|
||||||
|
*/
|
||||||
|
fetch?: typeof globalThis.fetch;
|
||||||
|
/**
|
||||||
|
* Extra HTTP headers applied to every RPC POST. Useful for app-level
|
||||||
|
* auth (CSRF, session cookies via custom header, etc.) — these are
|
||||||
|
* orthogonal to the ratchet authentication on the envelope itself.
|
||||||
|
*/
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
/**
|
||||||
|
* Server endpoint that hosts `transferQueueRoute()`'s long-poll
|
||||||
|
* endpoint. Typically:
|
||||||
|
* `https://server.example.com/api/v1/shade-files/queue`.
|
||||||
|
*
|
||||||
|
* When supplied, the client starts a background long-poll that
|
||||||
|
* drains queued envelopes + chunks from the server and dispatches
|
||||||
|
* them via `shade.acceptTransferEnvelope`. This unlocks
|
||||||
|
* **streamed reads** (>256 KiB) for browser-style consumers.
|
||||||
|
*/
|
||||||
|
outboundQueueUrl?: string;
|
||||||
|
/**
|
||||||
|
* Base URL for outbound transfer routes (browser → server). Required
|
||||||
|
* alongside `outboundQueueUrl` to enable streamed writes. Typically:
|
||||||
|
* `https://server.example.com/api/v1/shade-files`.
|
||||||
|
*
|
||||||
|
* The client POSTs:
|
||||||
|
* - chunks to `<base>/v1/transfer/<streamId>/chunk`
|
||||||
|
* - control envelopes to `<base>/v1/transfer/control`
|
||||||
|
*/
|
||||||
|
transferBaseUrl?: string;
|
||||||
|
/**
|
||||||
|
* Long-poll block timeout, milliseconds. Default 30_000. Server
|
||||||
|
* clamps to its own `maxBlockMs` (default 55_000).
|
||||||
|
*/
|
||||||
|
queueBlockMs?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface RoundTripOpts {
|
||||||
|
signal?: AbortSignal;
|
||||||
|
timeoutMs?: number;
|
||||||
|
idempotencyKey?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create a request-response `FileClient` bound to `peerAddress` and a
|
||||||
|
* server-side RPC URL. The session must already be established
|
||||||
|
* (via `shade.initSessionFromBundle(peerAddress, bundle)` or an
|
||||||
|
* incoming first-message). Otherwise the first RPC will fail with
|
||||||
|
* "decrypt failed: no session for peer".
|
||||||
|
*
|
||||||
|
* When `outboundQueueUrl` + `transferBaseUrl` are supplied, the
|
||||||
|
* client also unlocks **streamed reads/writes** for files larger than
|
||||||
|
* the inline threshold (256 KiB). The browser polls the server's
|
||||||
|
* outbound queue for chunks/envelopes and POSTs its own outbound
|
||||||
|
* chunks to the server's transfer-receive routes.
|
||||||
|
*/
|
||||||
|
export function createFilesHttpClient(
|
||||||
|
shade: ShadeBridge,
|
||||||
|
peerAddress: string,
|
||||||
|
options: FilesHttpClientOptions,
|
||||||
|
): FileClient {
|
||||||
|
const rpcUrl = options.rpcUrl;
|
||||||
|
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
||||||
|
const extraHeaders = options.headers ?? {};
|
||||||
|
const defaultTimeoutMs = options.defaultTimeoutMs ?? 30_000;
|
||||||
|
const ioTimeoutMs = options.ioTimeoutMs ?? 60_000;
|
||||||
|
const signRequest = options.signRequest;
|
||||||
|
const senderAddress = shade.myAddress;
|
||||||
|
|
||||||
|
// ─── Streamed-mode bootstrap ─────────────────────────────────
|
||||||
|
//
|
||||||
|
// When `outboundQueueUrl` is supplied, the client:
|
||||||
|
// 1. Configures `shade.configureTransfers(...)` so outbound
|
||||||
|
// chunks POST to `<transferBaseUrl>/v1/transfer/<streamId>/chunk`
|
||||||
|
// and outbound control envelopes POST to
|
||||||
|
// `<transferBaseUrl>/v1/transfer/control`.
|
||||||
|
// 2. Spawns a streams-bridge so streamed reads can be awaited.
|
||||||
|
// 3. Starts a long-poll drainer that pulls queued envelopes +
|
||||||
|
// chunks from the server and dispatches via
|
||||||
|
// `shade.acceptTransferEnvelope`.
|
||||||
|
|
||||||
|
let drainer: QueueDrainerHandle | null = null;
|
||||||
|
let streamsBridgePromise: Promise<ClientStreamsBridge> | null = null;
|
||||||
|
let streamsBridge: ClientStreamsBridge | null = null;
|
||||||
|
|
||||||
|
if (options.outboundQueueUrl !== undefined) {
|
||||||
|
const outboundQueueUrl = options.outboundQueueUrl;
|
||||||
|
if (options.transferBaseUrl === undefined) {
|
||||||
|
throw new Error(
|
||||||
|
'createFilesHttpClient: outboundQueueUrl was supplied without transferBaseUrl. Pass `transferBaseUrl` (the server prefix that hosts /v1/transfer/...) so outbound chunks have a destination.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (shade.configureTransfers === undefined) {
|
||||||
|
throw new Error(
|
||||||
|
'createFilesHttpClient: shade.configureTransfers is required for streamed mode (the underlying ShadeBridge must surface it).',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const transferBaseUrl = options.transferBaseUrl.replace(/\/$/, '');
|
||||||
|
shade.configureTransfers({
|
||||||
|
resolveBaseUrl: async (peer) => {
|
||||||
|
if (peer !== peerAddress) {
|
||||||
|
throw new Error(
|
||||||
|
`httpClient is bound to peer "${peerAddress}" — refusing to resolve outgoing chunks for "${peer}" without a multi-peer registry. Use shade.files.client(peer) for server-to-server multi-peer.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return transferBaseUrl;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Build the streams-bridge eagerly. The engine's incoming-transfer
|
||||||
|
// subscription has to be in place BEFORE the drainer dispatches the
|
||||||
|
// first stream-init envelope, otherwise the engine emits the
|
||||||
|
// IncomingTransfer to zero handlers and the read silently never
|
||||||
|
// accepts. We kick off the drainer once the bridge has subscribed.
|
||||||
|
streamsBridgePromise = createClientStreamsBridge(shade).then((bridge) => {
|
||||||
|
streamsBridge = bridge;
|
||||||
|
drainer = startQueueDrainer(shade, {
|
||||||
|
outboundQueueUrl,
|
||||||
|
peerAddress,
|
||||||
|
senderAddress,
|
||||||
|
...(options.fetch !== undefined ? { fetch: options.fetch } : {}),
|
||||||
|
...(options.headers !== undefined ? { headers: options.headers } : {}),
|
||||||
|
...(options.queueBlockMs !== undefined ? { blockMs: options.queueBlockMs } : {}),
|
||||||
|
});
|
||||||
|
return bridge;
|
||||||
|
});
|
||||||
|
// Surface bridge-construction failures eagerly via a rejected
|
||||||
|
// promise the next read/write picks up.
|
||||||
|
streamsBridgePromise.catch(() => {
|
||||||
|
/* observed via getStreamsBridge() */
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getStreamsBridge(): Promise<ClientStreamsBridge> {
|
||||||
|
if (streamsBridge !== null) return streamsBridge;
|
||||||
|
if (streamsBridgePromise === null) {
|
||||||
|
throw new ConflictError(
|
||||||
|
`http RPC client supports inline writes/reads only (≤ ${INLINE_THRESHOLD} bytes) — pass { outboundQueueUrl, transferBaseUrl } to enable streamed transfers.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
streamsBridge = await streamsBridgePromise;
|
||||||
|
return streamsBridge;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encrypt + POST + decrypt + parse one RPC round-trip.
|
||||||
|
*
|
||||||
|
* Throws a typed `FileError` subclass when the server returns an
|
||||||
|
* encrypted `RpcError`, or `InternalFileError` for transport-level
|
||||||
|
* failures (network, 4xx/5xx, malformed body).
|
||||||
|
*/
|
||||||
|
async function roundTrip<TResult>(
|
||||||
|
kind: string,
|
||||||
|
op: 'list' | 'stat' | 'mkdir' | 'delete' | 'move' | 'read' | 'write' | 'getThumbnail' | 'custom',
|
||||||
|
args: unknown,
|
||||||
|
resultSchema: ZodTypeAny,
|
||||||
|
opts: RoundTripOpts | undefined,
|
||||||
|
): Promise<TResult> {
|
||||||
|
const requestEnv = await buildRpcRequest({
|
||||||
|
senderAddress,
|
||||||
|
kind,
|
||||||
|
op,
|
||||||
|
args,
|
||||||
|
...(opts?.idempotencyKey !== undefined ? { idempotencyKey: opts.idempotencyKey } : {}),
|
||||||
|
...(signRequest !== undefined ? { signRequest } : {}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const plaintext = encodeRpcEnvelope(requestEnv);
|
||||||
|
const ratchetEnvelope = await shade.send(peerAddress, plaintext);
|
||||||
|
const wireBytes = encodeWireEnvelope(ratchetEnvelope);
|
||||||
|
|
||||||
|
const ac = new AbortController();
|
||||||
|
const timeoutMs = opts?.timeoutMs ?? defaultTimeoutMs;
|
||||||
|
const timer = setTimeout(
|
||||||
|
() => ac.abort(new Error(`RPC timeout after ${timeoutMs}ms`)),
|
||||||
|
timeoutMs,
|
||||||
|
);
|
||||||
|
(timer as unknown as { unref?: () => void }).unref?.();
|
||||||
|
if (opts?.signal !== undefined) {
|
||||||
|
const userSignal = opts.signal;
|
||||||
|
if (userSignal.aborted) ac.abort(userSignal.reason);
|
||||||
|
else userSignal.addEventListener('abort', () => ac.abort(userSignal.reason), { once: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
// Wrap the wire bytes in a Blob so the body type satisfies the
|
||||||
|
// common-denominator `BodyInit` across DOM, Bun, and node-fetch
|
||||||
|
// (some runtimes accept `Uint8Array` directly, others don't).
|
||||||
|
// Cast through `unknown` because TS's `bun-types` and `lib.dom`
|
||||||
|
// disagree about whether `Uint8Array<ArrayBufferLike>` is itself
|
||||||
|
// a `BlobPart`; the runtime accepts it on every platform.
|
||||||
|
response = await fetchFn(rpcUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
body: new Blob([wireBytes as unknown as ArrayBuffer]),
|
||||||
|
signal: ac.signal,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/octet-stream',
|
||||||
|
'X-Shade-Sender-Address': senderAddress,
|
||||||
|
...extraHeaders,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
clearTimeout(timer);
|
||||||
|
if ((err as Error).name === 'AbortError') {
|
||||||
|
throw new CancelledError(`RPC ${kind} aborted: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
throw new InternalFileError(`RPC ${kind} fetch failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
clearTimeout(timer);
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
let body: { error?: string } | null = null;
|
||||||
|
try {
|
||||||
|
body = (await response.json()) as { error?: string };
|
||||||
|
} catch {
|
||||||
|
/* server emitted non-JSON body */
|
||||||
|
}
|
||||||
|
throw new InternalFileError(
|
||||||
|
`RPC ${kind} → ${response.status} ${response.statusText}: ${
|
||||||
|
body?.error ?? '(no error body)'
|
||||||
|
}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ab = await response.arrayBuffer();
|
||||||
|
if (ab.byteLength === 0) {
|
||||||
|
throw new InternalFileError(`RPC ${kind}: empty response body`);
|
||||||
|
}
|
||||||
|
|
||||||
|
let responseRatchet;
|
||||||
|
try {
|
||||||
|
responseRatchet = decodeEnvelope(new Uint8Array(ab));
|
||||||
|
} catch (err) {
|
||||||
|
throw new InternalFileError(
|
||||||
|
`RPC ${kind}: response body is not a valid wire envelope: ${(err as Error).message}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
let responsePlaintext: string;
|
||||||
|
try {
|
||||||
|
responsePlaintext = await shade.receive(peerAddress, responseRatchet);
|
||||||
|
} catch (err) {
|
||||||
|
throw new InternalFileError(
|
||||||
|
`RPC ${kind}: response decrypt failed: ${(err as Error).message}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const classified = tryParseEnvelope(responsePlaintext);
|
||||||
|
if (classified === null) {
|
||||||
|
throw new InternalFileError(
|
||||||
|
`RPC ${kind}: response plaintext is not a valid @shade/files envelope`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (classified.kind === 'error') {
|
||||||
|
throw fileErrorFromPayload(classified.envelope.error);
|
||||||
|
}
|
||||||
|
if (classified.kind !== 'response') {
|
||||||
|
throw new InternalFileError(
|
||||||
|
`RPC ${kind}: unexpected response envelope kind: ${classified.kind}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (classified.envelope.id !== requestEnv.id) {
|
||||||
|
throw new InternalFileError(
|
||||||
|
`RPC ${kind}: response correlation id mismatch (got ${classified.envelope.id}, expected ${requestEnv.id})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return resultSchema.parse(classified.envelope.result) as TResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
async list(path, opts): Promise<ListResult> {
|
||||||
|
const args = ListArgsSchema.parse({
|
||||||
|
path,
|
||||||
|
...(opts?.cursor !== undefined ? { cursor: opts.cursor } : {}),
|
||||||
|
...(opts?.pageSize !== undefined ? { pageSize: opts.pageSize } : {}),
|
||||||
|
...(opts?.filter !== undefined ? { filter: opts.filter } : {}),
|
||||||
|
});
|
||||||
|
return await roundTrip<ListResult>(
|
||||||
|
KIND_LIST_V1,
|
||||||
|
'list',
|
||||||
|
args,
|
||||||
|
ListResultSchema,
|
||||||
|
opts,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
async stat(path, opts): Promise<StatResult> {
|
||||||
|
const args = StatArgsSchema.parse({ path });
|
||||||
|
return await roundTrip<StatResult>(KIND_STAT_V1, 'stat', args, StatResultSchema, opts);
|
||||||
|
},
|
||||||
|
|
||||||
|
async mkdir(path, opts): Promise<MkdirResult> {
|
||||||
|
const args = MkdirArgsSchema.parse({
|
||||||
|
path,
|
||||||
|
...(opts?.recursive !== undefined ? { recursive: opts.recursive } : {}),
|
||||||
|
});
|
||||||
|
return await roundTrip<MkdirResult>(
|
||||||
|
KIND_MKDIR_V1,
|
||||||
|
'mkdir',
|
||||||
|
args,
|
||||||
|
MkdirResultSchema,
|
||||||
|
opts,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
async delete(path, opts): Promise<DeleteResult> {
|
||||||
|
const args = DeleteArgsSchema.parse({
|
||||||
|
path,
|
||||||
|
...(opts?.recursive !== undefined ? { recursive: opts.recursive } : {}),
|
||||||
|
});
|
||||||
|
return await roundTrip<DeleteResult>(
|
||||||
|
KIND_DELETE_V1,
|
||||||
|
'delete',
|
||||||
|
args,
|
||||||
|
DeleteResultSchema,
|
||||||
|
opts,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
async move(src, dst, opts): Promise<MoveResult> {
|
||||||
|
const args = MoveArgsSchema.parse({
|
||||||
|
src,
|
||||||
|
dst,
|
||||||
|
...(opts?.overwrite !== undefined ? { overwrite: opts.overwrite } : {}),
|
||||||
|
});
|
||||||
|
return await roundTrip<MoveResult>(KIND_MOVE_V1, 'move', args, MoveResultSchema, opts);
|
||||||
|
},
|
||||||
|
|
||||||
|
async read(path, opts: ReadOpts = {}): Promise<ReadOutput> {
|
||||||
|
const args = ReadArgsSchema.parse({
|
||||||
|
path,
|
||||||
|
...(opts.range !== undefined ? { range: opts.range } : {}),
|
||||||
|
...(opts.preferInline !== undefined ? { preferInline: opts.preferInline } : {}),
|
||||||
|
});
|
||||||
|
const wire = await roundTrip<import('../schemas/ops.js').ReadResult>(
|
||||||
|
KIND_READ_V1,
|
||||||
|
'read',
|
||||||
|
args,
|
||||||
|
ReadResultSchema,
|
||||||
|
opts,
|
||||||
|
);
|
||||||
|
if (wire.kind === 'inline') {
|
||||||
|
const bytes = base64ToBytes(wire.bytesB64);
|
||||||
|
const out: ReadOutput = {
|
||||||
|
kind: 'inline',
|
||||||
|
bytes,
|
||||||
|
size: wire.size,
|
||||||
|
sha256: wire.sha256,
|
||||||
|
...(wire.contentType !== undefined ? { contentType: wire.contentType } : {}),
|
||||||
|
};
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
// Streamed read — only supported when pull-mode was configured.
|
||||||
|
// `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(
|
||||||
|
`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.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const bridge = await getStreamsBridge();
|
||||||
|
const bridgeSignal = opts.signal ?? new AbortController().signal;
|
||||||
|
const parked = await bridge.awaitRead(wire.streamId, {
|
||||||
|
expectedFrom: peerAddress,
|
||||||
|
signal: bridgeSignal,
|
||||||
|
timeoutMs: ioTimeoutMs,
|
||||||
|
});
|
||||||
|
const out: ReadOutput = {
|
||||||
|
kind: 'streams',
|
||||||
|
stream: parked.readable,
|
||||||
|
size: wire.size,
|
||||||
|
sha256: wire.sha256,
|
||||||
|
...(wire.contentType !== undefined ? { contentType: wire.contentType } : {}),
|
||||||
|
done: async () => {
|
||||||
|
await parked.done;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
|
||||||
|
async write(path, input: WriteSource, opts: WriteOpts = {}): Promise<WriteResult> {
|
||||||
|
const decision = await decideInline(input);
|
||||||
|
const overwrite = opts.overwrite ?? false;
|
||||||
|
const contentType = opts.contentType ?? decision.contentType;
|
||||||
|
|
||||||
|
if (decision.kind === 'inline' || opts.forceInline === true) {
|
||||||
|
const bytes = decision.kind === 'inline' ? decision.bytes : null;
|
||||||
|
if (bytes === null) {
|
||||||
|
// forceInline === true with a streams-typed decision —
|
||||||
|
// decideInline always produced a `streams` shape because the
|
||||||
|
// input was a bare ReadableStream. We can't drain a stream
|
||||||
|
// synchronously here without a streams-bridge.
|
||||||
|
throw new ConflictError(
|
||||||
|
'http RPC client cannot forceInline a streamed input — pass a Uint8Array / Blob, or pre-buffer the stream.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (bytes.byteLength > INLINE_THRESHOLD) {
|
||||||
|
throw new ConflictError(
|
||||||
|
`inline write exceeds ${INLINE_THRESHOLD}-byte threshold (got ${bytes.byteLength}); pass forceInline=true to override`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const args = WriteArgsSchema.parse({
|
||||||
|
kind: 'inline',
|
||||||
|
path,
|
||||||
|
bytesB64: bytesToBase64(bytes),
|
||||||
|
...(contentType !== undefined ? { contentType } : {}),
|
||||||
|
overwrite,
|
||||||
|
});
|
||||||
|
return await roundTrip<WriteResult>(
|
||||||
|
KIND_WRITE_V1,
|
||||||
|
'write',
|
||||||
|
args,
|
||||||
|
WriteResultSchema,
|
||||||
|
opts,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Streamed write — requires pull-mode configuration. Do not inspect
|
||||||
|
// `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(
|
||||||
|
`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.`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const bridge = await getStreamsBridge();
|
||||||
|
const size = decision.size;
|
||||||
|
if (size === undefined) {
|
||||||
|
throw new ConflictError(
|
||||||
|
'streams write requires a known plaintext size; pass `{ stream, size }` instead of a bare ReadableStream',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const { writeId, handle } = await bridge.initiateWrite({
|
||||||
|
peer: peerAddress,
|
||||||
|
stream: decision.stream,
|
||||||
|
size,
|
||||||
|
...(contentType !== undefined ? { contentType } : {}),
|
||||||
|
name: path,
|
||||||
|
...(opts.signal !== undefined ? { signal: opts.signal } : {}),
|
||||||
|
});
|
||||||
|
const args = WriteArgsSchema.parse({
|
||||||
|
kind: 'streams',
|
||||||
|
path,
|
||||||
|
size,
|
||||||
|
...(contentType !== undefined ? { contentType } : {}),
|
||||||
|
overwrite,
|
||||||
|
writeId,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const [result] = await Promise.all([
|
||||||
|
roundTrip<WriteResult>(KIND_WRITE_V1, 'write', args, WriteResultSchema, opts),
|
||||||
|
handle.done(),
|
||||||
|
]);
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
await handle.abort('rpc-failed').catch(() => undefined);
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
async getThumbnail(path, size: ThumbnailSize, opts): Promise<ThumbnailResult> {
|
||||||
|
const args = GetThumbnailArgsSchema.parse({
|
||||||
|
path,
|
||||||
|
size,
|
||||||
|
...(opts?.format !== undefined ? { format: opts.format } : {}),
|
||||||
|
});
|
||||||
|
const raw = await roundTrip<import('../schemas/ops.js').GetThumbnailResult>(
|
||||||
|
KIND_GET_THUMBNAIL_V1,
|
||||||
|
'getThumbnail',
|
||||||
|
args,
|
||||||
|
GetThumbnailResultSchema,
|
||||||
|
opts,
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
bytes: base64ToBytes(raw.bytesB64),
|
||||||
|
format: raw.format,
|
||||||
|
width: raw.width,
|
||||||
|
height: raw.height,
|
||||||
|
sha256: raw.sha256,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
async custom(name, args, opts?: BaseOpts): Promise<unknown> {
|
||||||
|
const wireArgs = CustomArgsSchema.parse({ name, args });
|
||||||
|
return await roundTrip(KIND_CUSTOM_V1, 'custom', wireArgs, CustomResultSchema, opts);
|
||||||
|
},
|
||||||
|
|
||||||
|
close(): void {
|
||||||
|
// Stop the long-poll drainer + tear down the streams-bridge if
|
||||||
|
// we built one. Idempotent — safe to call multiple times.
|
||||||
|
drainer?.stop();
|
||||||
|
drainer = null;
|
||||||
|
if (streamsBridge !== null) {
|
||||||
|
void streamsBridge.destroy().catch(() => undefined);
|
||||||
|
streamsBridge = null;
|
||||||
|
}
|
||||||
|
streamsBridgePromise = null;
|
||||||
|
},
|
||||||
|
} as FileClient;
|
||||||
|
}
|
||||||
@@ -161,15 +161,33 @@ async function peekStream(stream: ReadableStream<Uint8Array>): Promise<InlineDec
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface MinimalReader {
|
/**
|
||||||
read(): Promise<{ value: Uint8Array | undefined; done: boolean }>;
|
* Structural mirror of WHATWG `ReadableStreamDefaultReader<Uint8Array>`.
|
||||||
|
*
|
||||||
|
* The disjoint union shape with `value?: T | undefined` is the lowest
|
||||||
|
* common denominator across every lib environment we care about:
|
||||||
|
* - `bun-types` emits `{ done: true; value?: undefined }`
|
||||||
|
* - `lib.dom` emits `{ done: true; value?: T }`
|
||||||
|
* - `node:stream/web` emits the union form
|
||||||
|
*
|
||||||
|
* `value?: T | undefined` is assignable from all three. A flat
|
||||||
|
* `{ value?: T; done: boolean }` is rejected by
|
||||||
|
* `exactOptionalPropertyTypes` because the present branches require
|
||||||
|
* `value: T`. Defining it as an explicit union avoids the trap.
|
||||||
|
*/
|
||||||
|
type MinimalReadResult<T> =
|
||||||
|
| { done: false; value: T }
|
||||||
|
| { done: true; value?: T | undefined };
|
||||||
|
|
||||||
|
interface MinimalReader<T> {
|
||||||
|
read(): Promise<MinimalReadResult<T>>;
|
||||||
cancel(reason?: unknown): Promise<void>;
|
cancel(reason?: unknown): Promise<void>;
|
||||||
releaseLock(): void;
|
releaseLock(): void;
|
||||||
}
|
}
|
||||||
|
|
||||||
function reconstructStream(
|
function reconstructStream(
|
||||||
prefix: Uint8Array[],
|
prefix: Uint8Array[],
|
||||||
reader: MinimalReader,
|
reader: MinimalReader<Uint8Array>,
|
||||||
): ReadableStream<Uint8Array> {
|
): ReadableStream<Uint8Array> {
|
||||||
let prefixIdx = 0;
|
let prefixIdx = 0;
|
||||||
return new ReadableStream<Uint8Array>({
|
return new ReadableStream<Uint8Array>({
|
||||||
|
|||||||
172
packages/shade-files/src/client/queue-drainer.ts
Normal file
172
packages/shade-files/src/client/queue-drainer.ts
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
/**
|
||||||
|
* Browser-side drainer for the pull-mode outbound queue.
|
||||||
|
*
|
||||||
|
* Background task that long-polls the server's `/queue` endpoint,
|
||||||
|
* decodes each event, and dispatches it into the consumer's Shade
|
||||||
|
* instance via `shade.acceptTransferEnvelope`. Same wire-shape as the
|
||||||
|
* server-to-server case where the engine receives chunks via direct
|
||||||
|
* HTTP POSTs — we just flip the direction so the browser pulls
|
||||||
|
* instead of accepts.
|
||||||
|
*/
|
||||||
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
|
|
||||||
|
export interface QueueDrainerOptions {
|
||||||
|
/**
|
||||||
|
* Server endpoint that hosts `transferQueueRoute()`. Typically:
|
||||||
|
* `https://server.example.com/api/v1/shade-files/queue`.
|
||||||
|
*/
|
||||||
|
outboundQueueUrl: string;
|
||||||
|
/** Peer the queue is pulled FROM (the server's address). */
|
||||||
|
peerAddress: string;
|
||||||
|
/** Address we identify ourselves with on the long-poll. */
|
||||||
|
senderAddress: string;
|
||||||
|
/** Optional `fetch` override. Default `globalThis.fetch`. */
|
||||||
|
fetch?: typeof globalThis.fetch;
|
||||||
|
/** Extra headers applied to every poll request. */
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
/**
|
||||||
|
* Long-poll request timeout (server-side block). Default 30_000.
|
||||||
|
* Server clamps to its own `maxBlockMs` (default 55_000).
|
||||||
|
*/
|
||||||
|
blockMs?: number;
|
||||||
|
/**
|
||||||
|
* Backoff after a network error before re-polling. Default 2_000.
|
||||||
|
* Doubles up to `maxBackoffMs` on consecutive failures.
|
||||||
|
*/
|
||||||
|
initialBackoffMs?: number;
|
||||||
|
maxBackoffMs?: number;
|
||||||
|
/**
|
||||||
|
* Called when a poll cycle fails. Defaults to logging via `console.error`.
|
||||||
|
* Throwing from this hook does NOT stop the drainer — it backs off
|
||||||
|
* and retries.
|
||||||
|
*/
|
||||||
|
onError?: (err: unknown) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface QueueDrainerHandle {
|
||||||
|
/** Stop the drainer. Pending fetch is aborted; the loop exits. */
|
||||||
|
stop(): void;
|
||||||
|
/** Promise that resolves once the drainer has fully stopped. */
|
||||||
|
stopped: Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PolledEvent {
|
||||||
|
id: number;
|
||||||
|
timestampMs: number;
|
||||||
|
kind: 'envelope' | 'chunk';
|
||||||
|
bytesB64: string;
|
||||||
|
meta?: { streamId: string; laneId: number; seq: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
interface PollResponseBody {
|
||||||
|
events: PolledEvent[];
|
||||||
|
nextSince: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_BLOCK_MS = 30_000;
|
||||||
|
const DEFAULT_INITIAL_BACKOFF_MS = 2_000;
|
||||||
|
const DEFAULT_MAX_BACKOFF_MS = 30_000;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Start a long-poll loop that drains queued envelopes + chunks from
|
||||||
|
* the server and dispatches them into the local Shade instance.
|
||||||
|
*
|
||||||
|
* Returns a handle the caller can use to stop the drainer when the
|
||||||
|
* `httpClient` is closed (e.g. on tab unload).
|
||||||
|
*/
|
||||||
|
export function startQueueDrainer(
|
||||||
|
shade: ShadeBridge,
|
||||||
|
options: QueueDrainerOptions,
|
||||||
|
): QueueDrainerHandle {
|
||||||
|
if (shade.acceptTransferEnvelope === undefined) {
|
||||||
|
throw new Error(
|
||||||
|
'startQueueDrainer: shade.acceptTransferEnvelope is required for pull-mode streams. The supplied ShadeBridge implementation must surface it.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const accept = shade.acceptTransferEnvelope.bind(shade);
|
||||||
|
const fetchFn = options.fetch ?? globalThis.fetch.bind(globalThis);
|
||||||
|
const blockMs = options.blockMs ?? DEFAULT_BLOCK_MS;
|
||||||
|
const onError = options.onError ?? ((err: unknown) => console.error('[shade.files queue-drainer]', err));
|
||||||
|
const initialBackoffMs = options.initialBackoffMs ?? DEFAULT_INITIAL_BACKOFF_MS;
|
||||||
|
const maxBackoffMs = options.maxBackoffMs ?? DEFAULT_MAX_BACKOFF_MS;
|
||||||
|
const ac = new AbortController();
|
||||||
|
let stopped = false;
|
||||||
|
let resolveStopped!: () => void;
|
||||||
|
const stoppedPromise = new Promise<void>((r) => {
|
||||||
|
resolveStopped = r;
|
||||||
|
});
|
||||||
|
|
||||||
|
void (async () => {
|
||||||
|
let since = 0;
|
||||||
|
let backoff = initialBackoffMs;
|
||||||
|
while (!stopped) {
|
||||||
|
try {
|
||||||
|
const response = await fetchFn(options.outboundQueueUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
signal: ac.signal,
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-Shade-Sender-Address': options.senderAddress,
|
||||||
|
...(options.headers ?? {}),
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ since, blockMs }),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`queue poll → ${response.status} ${response.statusText}`);
|
||||||
|
}
|
||||||
|
const body = (await response.json()) as PollResponseBody;
|
||||||
|
if (Array.isArray(body.events) && body.events.length > 0) {
|
||||||
|
for (const event of body.events) {
|
||||||
|
if (stopped) break;
|
||||||
|
try {
|
||||||
|
const bytes = base64ToBytes(event.bytesB64);
|
||||||
|
await accept(options.peerAddress, bytes);
|
||||||
|
} catch (err) {
|
||||||
|
// Per-event dispatch failure should not kill the loop —
|
||||||
|
// resume picks up missing chunks via @shade/transfer's
|
||||||
|
// built-in lane-resume protocol.
|
||||||
|
onError(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
since = typeof body.nextSince === 'number' ? body.nextSince : since;
|
||||||
|
backoff = initialBackoffMs;
|
||||||
|
} catch (err) {
|
||||||
|
if (stopped || ac.signal.aborted) break;
|
||||||
|
onError(err);
|
||||||
|
// Exponential backoff with jitter — caps at maxBackoffMs.
|
||||||
|
const jitter = Math.floor(Math.random() * Math.min(backoff, 1_000));
|
||||||
|
await new Promise<void>((r) => {
|
||||||
|
const t = setTimeout(r, backoff + jitter);
|
||||||
|
(t as unknown as { unref?: () => void }).unref?.();
|
||||||
|
ac.signal.addEventListener(
|
||||||
|
'abort',
|
||||||
|
() => {
|
||||||
|
clearTimeout(t);
|
||||||
|
r();
|
||||||
|
},
|
||||||
|
{ once: true },
|
||||||
|
);
|
||||||
|
});
|
||||||
|
backoff = Math.min(maxBackoffMs, backoff * 2);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
resolveStopped();
|
||||||
|
})();
|
||||||
|
|
||||||
|
return {
|
||||||
|
stop(): void {
|
||||||
|
if (stopped) return;
|
||||||
|
stopped = true;
|
||||||
|
ac.abort(new Error('queue drainer stopped'));
|
||||||
|
},
|
||||||
|
stopped: stoppedPromise,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function base64ToBytes(b64: string): Uint8Array {
|
||||||
|
const bin = atob(b64);
|
||||||
|
const out = new Uint8Array(bin.length);
|
||||||
|
for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
@@ -102,7 +102,16 @@ export async function createClientStreamsBridge(
|
|||||||
const readStreamId = incoming.metadata.userMetadata?.[META_KEY_READ_STREAM_ID];
|
const readStreamId = incoming.metadata.userMetadata?.[META_KEY_READ_STREAM_ID];
|
||||||
if (readStreamId === undefined) return;
|
if (readStreamId === undefined) return;
|
||||||
|
|
||||||
const ts = new TransformStream<Uint8Array, Uint8Array>();
|
// Generous HWM so the receiver-side write loop (drainer →
|
||||||
|
// engine.receiveChunk → sink.write) doesn't stall on backpressure
|
||||||
|
// before the consumer's reader is wired up. The reader still
|
||||||
|
// applies its own backpressure once it's consuming, but we no
|
||||||
|
// longer race fs.read's await on stream-init against the consumer
|
||||||
|
// attaching its reader.
|
||||||
|
const ts = new TransformStream<Uint8Array, Uint8Array>(undefined, undefined, {
|
||||||
|
highWaterMark: 64,
|
||||||
|
size: (chunk?: Uint8Array) => (chunk === undefined ? 0 : 1),
|
||||||
|
});
|
||||||
let handle: TransferHandle;
|
let handle: TransferHandle;
|
||||||
try {
|
try {
|
||||||
handle = await incoming.accept({
|
handle = await incoming.accept({
|
||||||
@@ -142,13 +151,14 @@ export async function createClientStreamsBridge(
|
|||||||
}
|
}
|
||||||
|
|
||||||
parked.set(readStreamId, arrival);
|
parked.set(readStreamId, arrival);
|
||||||
setTimeout(() => {
|
const t = setTimeout(() => {
|
||||||
const stale = parked.get(readStreamId);
|
const stale = parked.get(readStreamId);
|
||||||
if (stale === arrival) {
|
if (stale === arrival) {
|
||||||
parked.delete(readStreamId);
|
parked.delete(readStreamId);
|
||||||
void handle.abort('rpc-timeout').catch(() => undefined);
|
void handle.abort('rpc-timeout').catch(() => undefined);
|
||||||
}
|
}
|
||||||
}, parkedReadTtlMs).unref?.();
|
}, parkedReadTtlMs);
|
||||||
|
(t as unknown as { unref?: () => void }).unref?.();
|
||||||
});
|
});
|
||||||
|
|
||||||
function cleanupWaiter(w: PendingReadWaiter): void {
|
function cleanupWaiter(w: PendingReadWaiter): void {
|
||||||
|
|||||||
@@ -183,6 +183,24 @@ export { MAX_SIGNATURE_AGE_MS } from './server/handler.js';
|
|||||||
export { createFilesNamespace } from './integration/files-namespace.js';
|
export { createFilesNamespace } from './integration/files-namespace.js';
|
||||||
export type { FilesNamespace } from './integration/files-namespace.js';
|
export type { FilesNamespace } from './integration/files-namespace.js';
|
||||||
|
|
||||||
|
// Request-response HTTP transport — for browser-style consumers
|
||||||
|
// (one HTTP POST per RPC, no inbound channel needed). See
|
||||||
|
// `docs/files.md § HTTP RPC`.
|
||||||
|
export { createFilesRpcRoute } from './server/rpc-route.js';
|
||||||
|
export type { FilesRpcRouteOptions } from './server/rpc-route.js';
|
||||||
|
export { createFilesHttpClient } from './client/http-client.js';
|
||||||
|
export type { FilesHttpClientOptions } from './client/http-client.js';
|
||||||
|
export { startQueueDrainer } from './client/queue-drainer.js';
|
||||||
|
export type {
|
||||||
|
QueueDrainerHandle,
|
||||||
|
QueueDrainerOptions,
|
||||||
|
} from './client/queue-drainer.js';
|
||||||
|
|
||||||
|
// Shared structural surface @shade/files needs from a Shade instance —
|
||||||
|
// exposed so consumers building custom Shade-shaped bridges can verify
|
||||||
|
// they implement every required member.
|
||||||
|
export type { ShadeBridge } from './integration/shade-bridge.js';
|
||||||
|
|
||||||
// Integration helpers — wire handler + pending registry onto a channel
|
// Integration helpers — wire handler + pending registry onto a channel
|
||||||
export { attachFileHandler } from './integration/wire-server.js';
|
export { attachFileHandler } from './integration/wire-server.js';
|
||||||
export { attachClientRouting } from './integration/wire-client.js';
|
export { attachClientRouting } from './integration/wire-client.js';
|
||||||
|
|||||||
@@ -4,13 +4,16 @@
|
|||||||
* so a single Shade can simultaneously serve files AND consume them from
|
* so a single Shade can simultaneously serve files AND consume them from
|
||||||
* peers without paying the setup cost twice.
|
* peers without paying the setup cost twice.
|
||||||
*/
|
*/
|
||||||
import type { Shade } from '@shade/sdk';
|
import type { Hono } from 'hono';
|
||||||
|
import type { ShadeBridge } from './shade-bridge.js';
|
||||||
import {
|
import {
|
||||||
attachClientRouting,
|
attachClientRouting,
|
||||||
attachFileHandler,
|
attachFileHandler,
|
||||||
createClientStreamsBridge,
|
createClientStreamsBridge,
|
||||||
createFileClient,
|
createFileClient,
|
||||||
createFileHandler,
|
createFileHandler,
|
||||||
|
createFilesHttpClient,
|
||||||
|
createFilesRpcRoute,
|
||||||
createServerStreamsBridge,
|
createServerStreamsBridge,
|
||||||
PendingRpcRegistry,
|
PendingRpcRegistry,
|
||||||
ShadeFileRpcChannel,
|
ShadeFileRpcChannel,
|
||||||
@@ -19,22 +22,79 @@ import {
|
|||||||
type FileClient,
|
type FileClient,
|
||||||
type FileHandler,
|
type FileHandler,
|
||||||
type FileHandlerConfig,
|
type FileHandlerConfig,
|
||||||
|
type FilesHttpClientOptions,
|
||||||
|
type FilesRpcRouteOptions,
|
||||||
type ServerStreamsBridge,
|
type ServerStreamsBridge,
|
||||||
} from '../index.js';
|
} from '../index.js';
|
||||||
import { IdempotencyCache } from '../server/idempotency-cache.js';
|
import { IdempotencyCache } from '../server/idempotency-cache.js';
|
||||||
|
|
||||||
|
export interface ServeOptions {
|
||||||
|
/**
|
||||||
|
* Skip the streams bridge setup. Required for deployments that only
|
||||||
|
* use the HTTP RPC route ({@link FilesNamespace.rpcRoute}) — those
|
||||||
|
* deployments don't need to configure `@shade/transfer` because the
|
||||||
|
* RPC route only services inline payloads (≤ 256 KiB). Without this
|
||||||
|
* flag, `serve()` calls `createServerStreamsBridge(shade)` which
|
||||||
|
* eagerly instantiates the transfer engine and fails when
|
||||||
|
* `configureTransfers({ resolveBaseUrl })` has not been called.
|
||||||
|
*
|
||||||
|
* Default: `false` (build the streams bridge — full server-to-server
|
||||||
|
* stack with streamed reads/writes).
|
||||||
|
*/
|
||||||
|
inlineOnly?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
export interface FilesNamespace {
|
export interface FilesNamespace {
|
||||||
/**
|
/**
|
||||||
* Register a file handler. Throws if a handler is already attached on
|
* Register a file handler. Throws if a handler is already attached on
|
||||||
* this Shade — only one server per Shade. The returned function detaches
|
* this Shade — only one server per Shade. The returned function detaches
|
||||||
* the handler and tears down its idempotency / retention timers.
|
* the handler and tears down its idempotency / retention timers.
|
||||||
|
*
|
||||||
|
* Pass `{ inlineOnly: true }` for HTTP-RPC-only deployments to skip
|
||||||
|
* the streams-bridge setup (and the implied `configureTransfers`
|
||||||
|
* pre-condition).
|
||||||
*/
|
*/
|
||||||
serve(handler: FileHandlerConfig): Promise<() => Promise<void>>;
|
serve(
|
||||||
|
handler: FileHandlerConfig,
|
||||||
|
options?: ServeOptions,
|
||||||
|
): Promise<() => Promise<void>>;
|
||||||
/**
|
/**
|
||||||
* Build a typed file client for `peer`. Multiple concurrent clients to
|
* Build a typed file client for `peer`. Multiple concurrent clients to
|
||||||
* different peers share the same channel + streams bridge.
|
* different peers share the same channel + streams bridge.
|
||||||
|
*
|
||||||
|
* Use this for **server-to-server** deployments where both peers can
|
||||||
|
* receive inbound HTTP. For browser clients (no inbound listener),
|
||||||
|
* use {@link httpClient} instead.
|
||||||
*/
|
*/
|
||||||
client(peer: string, opts?: Omit<CreateFileClientOptions, 'streamsBridge'>): Promise<FileClient>;
|
client(peer: string, opts?: Omit<CreateFileClientOptions, 'streamsBridge'>): Promise<FileClient>;
|
||||||
|
/**
|
||||||
|
* Build a request-response `FileClient` for browser-style consumers.
|
||||||
|
* Each RPC is one HTTP POST to the supplied `rpcUrl`; the encrypted
|
||||||
|
* response rides back in the same response body. No inbound channel
|
||||||
|
* required on the client side.
|
||||||
|
*
|
||||||
|
* Inline payloads only (≤ 256 KiB). Streamed reads/writes throw a
|
||||||
|
* clear error directing callers to {@link client} instead.
|
||||||
|
*
|
||||||
|
* Pre-condition: the session for `peer` must already be established
|
||||||
|
* (typically via `shade.initSessionFromBundle(peer, bundle)`).
|
||||||
|
*/
|
||||||
|
httpClient(peer: string, opts: FilesHttpClientOptions): FileClient;
|
||||||
|
/**
|
||||||
|
* Mount the server-side request-response RPC route. Returns a Hono
|
||||||
|
* app exposing `POST /rpc` that accepts encrypted file-RPC envelopes
|
||||||
|
* and returns encrypted responses in the same HTTP roundtrip.
|
||||||
|
*
|
||||||
|
* Mount under any base path:
|
||||||
|
* ```ts
|
||||||
|
* app.route('/api/v1/shade-files', shade.files.rpcRoute());
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* Requires `shade.files.serve(...)` to have been called first —
|
||||||
|
* the route dispatches incoming requests through the attached
|
||||||
|
* handler.
|
||||||
|
*/
|
||||||
|
rpcRoute(opts?: FilesRpcRouteOptions): Hono;
|
||||||
/** Tear down channel + bridges. After destroy(), serve()/client() throw. */
|
/** Tear down channel + bridges. After destroy(), serve()/client() throw. */
|
||||||
destroy(): Promise<void>;
|
destroy(): Promise<void>;
|
||||||
}
|
}
|
||||||
@@ -54,7 +114,7 @@ interface NamespaceState {
|
|||||||
* Construct a `FilesNamespace` bound to a Shade instance. The SDK's
|
* Construct a `FilesNamespace` bound to a Shade instance. The SDK's
|
||||||
* `Shade.files` getter calls this lazily and memoizes the result.
|
* `Shade.files` getter calls this lazily and memoizes the result.
|
||||||
*/
|
*/
|
||||||
export function createFilesNamespace(shade: Shade): FilesNamespace {
|
export function createFilesNamespace(shade: ShadeBridge): FilesNamespace {
|
||||||
const state: NamespaceState = {
|
const state: NamespaceState = {
|
||||||
channel: new ShadeFileRpcChannel(shade),
|
channel: new ShadeFileRpcChannel(shade),
|
||||||
pending: new PendingRpcRegistry(),
|
pending: new PendingRpcRegistry(),
|
||||||
@@ -71,24 +131,39 @@ export function createFilesNamespace(shade: Shade): FilesNamespace {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
async serve(handlerConfig) {
|
async serve(handlerConfig, options = {}) {
|
||||||
ensureAlive();
|
ensureAlive();
|
||||||
if (state.serverHandler !== null) {
|
if (state.serverHandler !== null) {
|
||||||
throw new Error('FilesNamespace: a handler is already registered (one per Shade)');
|
throw new Error('FilesNamespace: a handler is already registered (one per Shade)');
|
||||||
}
|
}
|
||||||
// Lazy server-side streams bridge.
|
// Lazy server-side streams bridge — skip when the deployment is
|
||||||
if (state.serverBridge === null) {
|
// HTTP-RPC-only and does not need `@shade/transfer` wired up.
|
||||||
|
if (!options.inlineOnly && state.serverBridge === null) {
|
||||||
state.serverBridge = await createServerStreamsBridge(shade);
|
state.serverBridge = await createServerStreamsBridge(shade);
|
||||||
}
|
}
|
||||||
const inheritedObservability = shade.getObservability?.();
|
const inheritedObservability = shade.getObservability?.();
|
||||||
const handler = createFileHandler(shade, {
|
const handler = createFileHandler(shade, {
|
||||||
...handlerConfig,
|
...handlerConfig,
|
||||||
streamsBridge: state.serverBridge,
|
...(state.serverBridge !== null
|
||||||
|
? { streamsBridge: state.serverBridge }
|
||||||
|
: {}),
|
||||||
...(handlerConfig.observability === undefined && inheritedObservability !== undefined
|
...(handlerConfig.observability === undefined && inheritedObservability !== undefined
|
||||||
? { observability: inheritedObservability }
|
? { observability: inheritedObservability }
|
||||||
: {}),
|
: {}),
|
||||||
});
|
});
|
||||||
const detach = attachFileHandler(state.channel, handler);
|
// In inlineOnly mode, the rpc-route is the sole inbound path —
|
||||||
|
// do NOT also subscribe the channel's onMessage handler to this
|
||||||
|
// file handler, because that would cause every incoming request
|
||||||
|
// to be dispatched twice (once by the rpc-route's direct call,
|
||||||
|
// once by the channel's onMessage handler) and the channel-side
|
||||||
|
// response would attempt an outbound POST via
|
||||||
|
// `deliverControlEnvelope`, which is exactly the path that fails
|
||||||
|
// for browser clients.
|
||||||
|
const detach: () => void = options.inlineOnly
|
||||||
|
? () => {
|
||||||
|
/* no channel subscription to detach */
|
||||||
|
}
|
||||||
|
: attachFileHandler(state.channel, handler);
|
||||||
state.serverHandler = handler;
|
state.serverHandler = handler;
|
||||||
state.serverDetach = detach;
|
state.serverDetach = detach;
|
||||||
|
|
||||||
@@ -131,6 +206,21 @@ export function createFilesNamespace(shade: Shade): FilesNamespace {
|
|||||||
});
|
});
|
||||||
},
|
},
|
||||||
|
|
||||||
|
httpClient(peer, opts) {
|
||||||
|
ensureAlive();
|
||||||
|
return createFilesHttpClient(shade, peer, opts);
|
||||||
|
},
|
||||||
|
|
||||||
|
rpcRoute(opts = {}) {
|
||||||
|
ensureAlive();
|
||||||
|
if (state.serverHandler === null) {
|
||||||
|
throw new Error(
|
||||||
|
'FilesNamespace.rpcRoute(): no handler attached. Call shade.files.serve(...) before mounting the RPC route.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return createFilesRpcRoute(shade, state.serverHandler, opts);
|
||||||
|
},
|
||||||
|
|
||||||
async destroy() {
|
async destroy() {
|
||||||
if (state.destroyed) return;
|
if (state.destroyed) return;
|
||||||
state.destroyed = true;
|
state.destroyed = true;
|
||||||
|
|||||||
94
packages/shade-files/src/integration/shade-bridge.ts
Normal file
94
packages/shade-files/src/integration/shade-bridge.ts
Normal file
@@ -0,0 +1,94 @@
|
|||||||
|
/**
|
||||||
|
* Structural surface @shade/files needs from a Shade instance.
|
||||||
|
*
|
||||||
|
* Defining this locally — instead of `import type { Shade } from '@shade/sdk'`
|
||||||
|
* — breaks the @shade/sdk ↔ @shade/files dependency cycle. Without this
|
||||||
|
* break, a consumer that installs @shade/sdk from a registry ends up with
|
||||||
|
* two distinct `Shade` classes in `node_modules` (one from
|
||||||
|
* `@shade/sdk/node_modules/@shade/files/.../Shade`, one from
|
||||||
|
* `@shade/sdk/Shade`). TypeScript treats them as nominally different types,
|
||||||
|
* raising `this is not assignable to Shade` from inside SDK methods that
|
||||||
|
* pass `this` into `createFilesNamespace`.
|
||||||
|
*
|
||||||
|
* The Shade class structurally implements every member listed below, so
|
||||||
|
* `createFilesNamespace(this)` from the SDK side compiles regardless of
|
||||||
|
* how many copies of @shade/sdk a consumer's package manager installs.
|
||||||
|
*
|
||||||
|
* Member signatures match Shade's exactly so this is a structural
|
||||||
|
* subtype, not a parallel API.
|
||||||
|
*/
|
||||||
|
import type { ShadeEnvelope } from '@shade/core';
|
||||||
|
import type {
|
||||||
|
IncomingTransfer,
|
||||||
|
TransferHandle,
|
||||||
|
TransferOptions,
|
||||||
|
} from '@shade/transfer';
|
||||||
|
import type { ObservabilityHook } from '@shade/observability';
|
||||||
|
|
||||||
|
export interface ShadeBridge {
|
||||||
|
/** Address that names this Shade instance to peers. */
|
||||||
|
readonly myAddress: string;
|
||||||
|
|
||||||
|
/** Encrypt + send `plaintext` to `peer`; returns the wire envelope. */
|
||||||
|
send(peer: string, plaintext: string): Promise<ShadeEnvelope>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Decrypt an inbound envelope from `peer` and return the plaintext.
|
||||||
|
* Used by the request-response RPC route on the server side.
|
||||||
|
*/
|
||||||
|
receive(peer: string, envelope: ShadeEnvelope): Promise<string>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Subscribe to incoming ratchet plaintext. Returns an unsubscribe.
|
||||||
|
* Handlers may be sync or async; async handlers are awaited in
|
||||||
|
* registration order.
|
||||||
|
*/
|
||||||
|
onMessage(
|
||||||
|
handler: (from: string, plaintext: string) => void | Promise<void>,
|
||||||
|
): () => void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upload bytes via the SDK's transfer engine. Required when the bridge
|
||||||
|
* is used with `streams` content I/O (read/write > 256 KiB).
|
||||||
|
*/
|
||||||
|
upload(opts: TransferOptions): Promise<TransferHandle>;
|
||||||
|
|
||||||
|
/** Subscribe to incoming transfers initiated by a peer. */
|
||||||
|
onIncomingTransfer(
|
||||||
|
handler: (incoming: IncomingTransfer) => void | Promise<void>,
|
||||||
|
): Promise<() => void>;
|
||||||
|
|
||||||
|
/** Fingerprint accessor for the trust-gate hooks. */
|
||||||
|
getFingerprintFor(peer: string): Promise<string>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional inheritable observability bus. Files inherits the bus when
|
||||||
|
* the SDK passes one in via the namespace; otherwise files runs without
|
||||||
|
* observability hooks.
|
||||||
|
*/
|
||||||
|
getObservability?(): ObservabilityHook | undefined;
|
||||||
|
|
||||||
|
/** Optional control-envelope passthrough used by the WebRTC bridge. */
|
||||||
|
deliverControlEnvelope?(peer: string, envelope: ShadeEnvelope): Promise<void>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hand a freshly-decoded wire envelope (control or chunk) to the
|
||||||
|
* transfer engine. Required by the pull-mode HTTP client when it
|
||||||
|
* drains queued events from the server: each polled chunk / control
|
||||||
|
* envelope is dispatched here so the engine sees it just as if it
|
||||||
|
* had arrived via an HTTP POST on `/v1/transfer/...`.
|
||||||
|
*/
|
||||||
|
acceptTransferEnvelope?(from: string, env: ShadeEnvelope | Uint8Array): Promise<void>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configure the transfer stack. Called by the pull-mode HTTP client
|
||||||
|
* to point the browser's outgoing chunks + control envelopes at the
|
||||||
|
* server's transferQueueRoute mount. Optional because the
|
||||||
|
* server-to-server path uses a separate, app-driven configuration.
|
||||||
|
*/
|
||||||
|
configureTransfers?(opts: {
|
||||||
|
resolveBaseUrl?: (peerAddress: string) => Promise<string>;
|
||||||
|
transport?: unknown;
|
||||||
|
envelopeTransport?: unknown;
|
||||||
|
}): void;
|
||||||
|
}
|
||||||
126
packages/shade-files/src/protocol/rpc-builder.ts
Normal file
126
packages/shade-files/src/protocol/rpc-builder.ts
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
/**
|
||||||
|
* Shared RPC-request construction.
|
||||||
|
*
|
||||||
|
* Both the channel-based `FileClient` (`createFileClient`) and the
|
||||||
|
* HTTP-based `FilesHttpClient` build identical `RpcRequest` envelopes
|
||||||
|
* — they differ only in *transport* (channel.send → ratchet via
|
||||||
|
* Shade.send/onMessage vs HTTP POST → ratchet via single
|
||||||
|
* request-response). This module is the single source of truth for
|
||||||
|
* the wire shape so the two clients can never drift.
|
||||||
|
*/
|
||||||
|
import type { ZodTypeAny } from 'zod';
|
||||||
|
import {
|
||||||
|
KIND_DELETE_V1,
|
||||||
|
KIND_GET_THUMBNAIL_V1,
|
||||||
|
KIND_LIST_V1,
|
||||||
|
KIND_MKDIR_V1,
|
||||||
|
KIND_MOVE_V1,
|
||||||
|
KIND_READ_V1,
|
||||||
|
KIND_STAT_V1,
|
||||||
|
KIND_WRITE_V1,
|
||||||
|
MUTATION_OPS,
|
||||||
|
type StandardOp,
|
||||||
|
} from './kinds.js';
|
||||||
|
import { generateIdempotencyKey, generateRequestId } from './correlate.js';
|
||||||
|
import { canonicalRpcBytes, hashArgs } from './canonical.js';
|
||||||
|
import type { RpcRequest } from '../schemas/envelope.js';
|
||||||
|
|
||||||
|
export const KIND_BY_OP: Record<StandardOp, string> = {
|
||||||
|
list: KIND_LIST_V1,
|
||||||
|
stat: KIND_STAT_V1,
|
||||||
|
mkdir: KIND_MKDIR_V1,
|
||||||
|
delete: KIND_DELETE_V1,
|
||||||
|
move: KIND_MOVE_V1,
|
||||||
|
read: KIND_READ_V1,
|
||||||
|
write: KIND_WRITE_V1,
|
||||||
|
getThumbnail: KIND_GET_THUMBNAIL_V1,
|
||||||
|
};
|
||||||
|
|
||||||
|
export type SignRequest = (canonicalBytes: Uint8Array) => Promise<string> | string;
|
||||||
|
|
||||||
|
export interface BuildRpcRequestOptions {
|
||||||
|
/** Address that this RPC call originates from. */
|
||||||
|
senderAddress: string;
|
||||||
|
/** RPC kind — `KIND_*_V1` constants for standard ops, `KIND_CUSTOM_V1` otherwise. */
|
||||||
|
kind: string;
|
||||||
|
/** Op classifier so mutations get an auto-generated idempotency key. */
|
||||||
|
op: StandardOp | 'custom';
|
||||||
|
/** Validated args object. The caller is responsible for `Zod.parse(args)`. */
|
||||||
|
args: unknown;
|
||||||
|
/** Caller-supplied idempotency key. Mutations get one auto-generated. */
|
||||||
|
idempotencyKey?: string;
|
||||||
|
/** Optional Ed25519-style signer over the canonical bytes. */
|
||||||
|
signRequest?: SignRequest;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a single `RpcRequest` envelope. Generates `id`, `signedAt`,
|
||||||
|
* idempotency key (mutations only), and the canonical signature.
|
||||||
|
*/
|
||||||
|
export async function buildRpcRequest(
|
||||||
|
options: BuildRpcRequestOptions,
|
||||||
|
): Promise<RpcRequest> {
|
||||||
|
const { senderAddress, kind, op, args, signRequest } = options;
|
||||||
|
const requestId = generateRequestId();
|
||||||
|
const isMutation = MUTATION_OPS.has(op);
|
||||||
|
const idempotencyKey =
|
||||||
|
options.idempotencyKey ?? (isMutation ? generateIdempotencyKey() : undefined);
|
||||||
|
const signedAt = Date.now();
|
||||||
|
|
||||||
|
let sig = 'unsigned';
|
||||||
|
if (signRequest !== undefined) {
|
||||||
|
const canonical = canonicalRpcBytes({
|
||||||
|
address: senderAddress,
|
||||||
|
signedAt,
|
||||||
|
kind,
|
||||||
|
id: requestId,
|
||||||
|
argsHash: hashArgs(args),
|
||||||
|
});
|
||||||
|
sig = await signRequest(canonical);
|
||||||
|
}
|
||||||
|
|
||||||
|
const env: RpcRequest = {
|
||||||
|
kind,
|
||||||
|
id: requestId,
|
||||||
|
args,
|
||||||
|
...(idempotencyKey !== undefined ? { idempotencyKey } : {}),
|
||||||
|
sig,
|
||||||
|
signedAt,
|
||||||
|
};
|
||||||
|
return env;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper for the typed standard ops: validates args via the supplied Zod
|
||||||
|
* schema, calls {@link buildRpcRequest}, and forwards the result.
|
||||||
|
*
|
||||||
|
* The HTTP and channel clients both call this from each op-method to
|
||||||
|
* guarantee identical wire-shape. Custom ops use {@link buildRpcRequest}
|
||||||
|
* directly because they ship `KIND_CUSTOM_V1` plus runtime-validated args.
|
||||||
|
*/
|
||||||
|
export async function buildStandardRpcRequest<TArgs>(
|
||||||
|
schema: { parse(input: unknown): TArgs },
|
||||||
|
rawArgs: unknown,
|
||||||
|
options: Omit<BuildRpcRequestOptions, 'kind' | 'op' | 'args'> & {
|
||||||
|
op: StandardOp;
|
||||||
|
},
|
||||||
|
): Promise<{ request: RpcRequest; args: TArgs }> {
|
||||||
|
const args = schema.parse(rawArgs) as TArgs;
|
||||||
|
const kind = KIND_BY_OP[options.op];
|
||||||
|
const request = await buildRpcRequest({
|
||||||
|
...options,
|
||||||
|
kind,
|
||||||
|
op: options.op,
|
||||||
|
args,
|
||||||
|
});
|
||||||
|
return { request, args };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate a returned RpcResponse `result` against the supplied schema.
|
||||||
|
* Centralised so the HTTP and channel clients fail-loudly with the same
|
||||||
|
* error type when a server returns an off-spec response.
|
||||||
|
*/
|
||||||
|
export function parseResult<T>(schema: ZodTypeAny, raw: unknown): T {
|
||||||
|
return schema.parse(raw) as T;
|
||||||
|
}
|
||||||
@@ -1,17 +1,23 @@
|
|||||||
import React, { createContext, useContext, useMemo } from 'react';
|
import React, { createContext, useContext, useMemo } from 'react';
|
||||||
import type { Shade } from '@shade/sdk';
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
import type { FilesNamespace } from '../integration/files-namespace.js';
|
import type { FilesNamespace } from '../integration/files-namespace.js';
|
||||||
|
|
||||||
export interface ShadeFilesContextValue {
|
export interface ShadeFilesContextValue {
|
||||||
shade: Shade;
|
shade: ShadeBridge;
|
||||||
files: FilesNamespace;
|
files: FilesNamespace;
|
||||||
}
|
}
|
||||||
|
|
||||||
const ShadeFilesContext = createContext<ShadeFilesContextValue | null>(null);
|
const ShadeFilesContext = createContext<ShadeFilesContextValue | null>(null);
|
||||||
|
|
||||||
export interface ShadeFilesProviderProps {
|
export interface ShadeFilesProviderProps {
|
||||||
/** Initialized `Shade` instance. `files` namespace is read off it lazily. */
|
/** Initialized `Shade` instance (or any `ShadeBridge`-shaped object). */
|
||||||
shade: Shade;
|
shade: ShadeBridge;
|
||||||
|
/**
|
||||||
|
* The `FilesNamespace` to expose to children. Pass `shade.files` from
|
||||||
|
* `@shade/sdk`, or a `createFilesNamespace(...)` result for tests /
|
||||||
|
* custom bridges.
|
||||||
|
*/
|
||||||
|
files: FilesNamespace;
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -20,8 +26,8 @@ export interface ShadeFilesProviderProps {
|
|||||||
* `<ShadeRuntimeProvider>` in `@shade/widgets` so file-RPC consumers
|
* `<ShadeRuntimeProvider>` in `@shade/widgets` so file-RPC consumers
|
||||||
* don't pull in the widget tree.
|
* don't pull in the widget tree.
|
||||||
*/
|
*/
|
||||||
export function ShadeFilesProvider({ shade, children }: ShadeFilesProviderProps): React.ReactElement {
|
export function ShadeFilesProvider({ shade, files, children }: ShadeFilesProviderProps): React.ReactElement {
|
||||||
const value = useMemo<ShadeFilesContextValue>(() => ({ shade, files: shade.files }), [shade]);
|
const value = useMemo<ShadeFilesContextValue>(() => ({ shade, files }), [shade, files]);
|
||||||
return React.createElement(ShadeFilesContext.Provider, { value }, children);
|
return React.createElement(ShadeFilesContext.Provider, { value }, children);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Shade } from '@shade/sdk';
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
import {
|
import {
|
||||||
encodeEnvelope,
|
encodeEnvelope,
|
||||||
looksLikeFileEnvelope,
|
looksLikeFileEnvelope,
|
||||||
@@ -35,7 +35,7 @@ export class ShadeFileRpcChannel {
|
|||||||
private readonly unsubscribe: () => void;
|
private readonly unsubscribe: () => void;
|
||||||
private destroyed = false;
|
private destroyed = false;
|
||||||
|
|
||||||
constructor(private readonly shade: Shade) {
|
constructor(private readonly shade: ShadeBridge) {
|
||||||
this.unsubscribe = shade.onMessage(async (from, plaintext) => {
|
this.unsubscribe = shade.onMessage(async (from, plaintext) => {
|
||||||
if (!looksLikeFileEnvelope(plaintext)) return;
|
if (!looksLikeFileEnvelope(plaintext)) return;
|
||||||
const classified = tryParseEnvelope(plaintext);
|
const classified = tryParseEnvelope(plaintext);
|
||||||
@@ -72,6 +72,11 @@ export class ShadeFileRpcChannel {
|
|||||||
if (this.destroyed) throw new Error('ShadeFileRpcChannel: destroyed');
|
if (this.destroyed) throw new Error('ShadeFileRpcChannel: destroyed');
|
||||||
const plaintext = encodeEnvelope(envelope);
|
const plaintext = encodeEnvelope(envelope);
|
||||||
const ratchetEnvelope = await this.shade.send(peerAddress, plaintext);
|
const ratchetEnvelope = await this.shade.send(peerAddress, plaintext);
|
||||||
|
if (this.shade.deliverControlEnvelope === undefined) {
|
||||||
|
throw new Error(
|
||||||
|
'ShadeFileRpcChannel: shade.deliverControlEnvelope is required — call shade.configureTransfers({ resolveBaseUrl }) before using the files namespace.',
|
||||||
|
);
|
||||||
|
}
|
||||||
await this.shade.deliverControlEnvelope(peerAddress, ratchetEnvelope);
|
await this.shade.deliverControlEnvelope(peerAddress, ratchetEnvelope);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Shade } from '@shade/sdk';
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
import type { StandardOp } from '../protocol/kinds.js';
|
import type { StandardOp } from '../protocol/kinds.js';
|
||||||
|
|
||||||
export type OpKind = StandardOp | `custom:${string}`;
|
export type OpKind = StandardOp | `custom:${string}`;
|
||||||
@@ -42,7 +42,7 @@ export function buildOpContext<TArgs>(args: {
|
|||||||
signal: AbortSignal;
|
signal: AbortSignal;
|
||||||
idempotencyKey: string | undefined;
|
idempotencyKey: string | undefined;
|
||||||
attemptNumber: number;
|
attemptNumber: number;
|
||||||
shade: Shade;
|
shade: ShadeBridge;
|
||||||
}): OpContext<TArgs> {
|
}): OpContext<TArgs> {
|
||||||
return {
|
return {
|
||||||
op: args.op,
|
op: args.op,
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import type { Shade } from '@shade/sdk';
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
import type { ZodTypeAny } from 'zod';
|
import type { ZodTypeAny } from 'zod';
|
||||||
import {
|
import {
|
||||||
MUTATION_OPS,
|
MUTATION_OPS,
|
||||||
@@ -215,7 +215,7 @@ const OP_SCHEMAS: Record<StandardOp, OpSchemaPair> = {
|
|||||||
* via `Shade.files.serve(...)` in the SDK).
|
* via `Shade.files.serve(...)` in the SDK).
|
||||||
*/
|
*/
|
||||||
export function createFileHandler(
|
export function createFileHandler(
|
||||||
shade: Shade,
|
shade: ShadeBridge,
|
||||||
config: FileHandlerConfig,
|
config: FileHandlerConfig,
|
||||||
): FileHandler {
|
): FileHandler {
|
||||||
const idempotency = new IdempotencyCache(config.idempotency);
|
const idempotency = new IdempotencyCache(config.idempotency);
|
||||||
|
|||||||
218
packages/shade-files/src/server/rpc-route.ts
Normal file
218
packages/shade-files/src/server/rpc-route.ts
Normal file
@@ -0,0 +1,218 @@
|
|||||||
|
/**
|
||||||
|
* Request-response RPC route for `@shade/files`.
|
||||||
|
*
|
||||||
|
* Mounts a single `POST /rpc` Hono endpoint that accepts an encrypted
|
||||||
|
* `RpcRequest` envelope, dispatches it through the file handler, and
|
||||||
|
* returns the encrypted `RpcResponse` (or `RpcError`) envelope in the
|
||||||
|
* SAME HTTP response.
|
||||||
|
*
|
||||||
|
* This is the browser-friendly transport: the server never needs to
|
||||||
|
* make outbound calls back to the client, so a browser tab — which
|
||||||
|
* cannot host an HTTP server — can fully consume `@shade/files`.
|
||||||
|
*
|
||||||
|
* ### Wire contract
|
||||||
|
*
|
||||||
|
* Request:
|
||||||
|
* ```
|
||||||
|
* POST <mount>/rpc HTTP/1.1
|
||||||
|
* Content-Type: application/octet-stream
|
||||||
|
* X-Shade-Sender-Address: <peer address>
|
||||||
|
*
|
||||||
|
* <wire-encoded ShadeEnvelope (0x01 PreKeyMessage or 0x02 RatchetMessage)
|
||||||
|
* containing JSON-encoded RpcRequest>
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* Response (success):
|
||||||
|
* ```
|
||||||
|
* 200 OK
|
||||||
|
* Content-Type: application/octet-stream
|
||||||
|
*
|
||||||
|
* <wire-encoded ShadeEnvelope (0x02 RatchetMessage)
|
||||||
|
* containing JSON-encoded RpcResponse | RpcError>
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* Response (transport-level failure — no session, undecryptable, etc.):
|
||||||
|
* ```
|
||||||
|
* 4xx
|
||||||
|
* Content-Type: application/json
|
||||||
|
*
|
||||||
|
* { "error": "..." }
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* ### Symmetry with shade-auth-middleware
|
||||||
|
*
|
||||||
|
* The shape mirrors `@shade/server`'s shade-auth-middleware: an
|
||||||
|
* encrypted envelope rides the request body, the server decrypts via
|
||||||
|
* the existing ratchet session, performs the protected operation,
|
||||||
|
* and returns an encrypted envelope in the response. No bidirectional
|
||||||
|
* channel required.
|
||||||
|
*
|
||||||
|
* @see {@link createFilesHttpClient} for the matching browser client.
|
||||||
|
*/
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { decodeEnvelope, encodeEnvelope } from '@shade/proto';
|
||||||
|
import type { ShadeBridge } from '../integration/shade-bridge.js';
|
||||||
|
import {
|
||||||
|
encodeEnvelope as encodeRpcEnvelope,
|
||||||
|
tryParseEnvelope,
|
||||||
|
} from '../protocol/envelope-codec.js';
|
||||||
|
import type { FileHandler } from './handler.js';
|
||||||
|
import type { RpcError, RpcRequest, RpcResponse } from '../schemas/envelope.js';
|
||||||
|
import { KIND_ERROR_V1 } from '../protocol/kinds.js';
|
||||||
|
|
||||||
|
export interface FilesRpcRouteOptions {
|
||||||
|
/**
|
||||||
|
* Maximum request body size in bytes. Default 1 MiB. Inline payloads
|
||||||
|
* are capped at 256 KiB by the protocol; the headroom is for
|
||||||
|
* custom-op payloads and base64 inflation.
|
||||||
|
*/
|
||||||
|
maxBodyBytes?: number;
|
||||||
|
/**
|
||||||
|
* Allow this server to accept the very first message (PreKeyMessage,
|
||||||
|
* `0x01`) over the RPC route. Disabled by default — most browser
|
||||||
|
* clients establish a session via `shade.initSessionFromBundle`
|
||||||
|
* before the first RPC. Enable when you want the RPC route to also
|
||||||
|
* be the X3DH carrier (uncommon but supported).
|
||||||
|
*/
|
||||||
|
acceptFirstMessage?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_MAX_BODY_BYTES = 1 * 1024 * 1024;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a Hono app with a single `POST /rpc` route. Mount under any
|
||||||
|
* base path: `app.route('/api/v1/shade-files', shade.files.rpcRoute())`.
|
||||||
|
*
|
||||||
|
* The `handler` must already be attached (typically via
|
||||||
|
* `shade.files.serve(handlerConfig)`); this route only ships the
|
||||||
|
* transport — it does not register a new file handler.
|
||||||
|
*/
|
||||||
|
export function createFilesRpcRoute(
|
||||||
|
shade: ShadeBridge,
|
||||||
|
handler: FileHandler,
|
||||||
|
options: FilesRpcRouteOptions = {},
|
||||||
|
): Hono {
|
||||||
|
const maxBodyBytes = options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES;
|
||||||
|
const app = new Hono();
|
||||||
|
|
||||||
|
app.post('/rpc', async (c) => {
|
||||||
|
const senderAddress = c.req.header('X-Shade-Sender-Address');
|
||||||
|
if (senderAddress === undefined || senderAddress === '') {
|
||||||
|
return c.json({ error: 'missing X-Shade-Sender-Address header' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
const contentLengthHeader = c.req.header('Content-Length');
|
||||||
|
if (contentLengthHeader !== undefined) {
|
||||||
|
const contentLength = Number.parseInt(contentLengthHeader, 10);
|
||||||
|
if (Number.isFinite(contentLength) && contentLength > maxBodyBytes) {
|
||||||
|
return c.json(
|
||||||
|
{ error: `body exceeds maxBodyBytes (${contentLength} > ${maxBodyBytes})` },
|
||||||
|
413,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let bodyBytes: Uint8Array;
|
||||||
|
try {
|
||||||
|
const ab = await c.req.arrayBuffer();
|
||||||
|
if (ab.byteLength > maxBodyBytes) {
|
||||||
|
return c.json(
|
||||||
|
{ error: `body exceeds maxBodyBytes (${ab.byteLength} > ${maxBodyBytes})` },
|
||||||
|
413,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
bodyBytes = new Uint8Array(ab);
|
||||||
|
} catch (err) {
|
||||||
|
return c.json({ error: `failed to read request body: ${(err as Error).message}` }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bodyBytes.byteLength === 0) {
|
||||||
|
return c.json({ error: 'empty request body' }, 400);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Decode the wire envelope. `decodeEnvelope` handles both `0x01`
|
||||||
|
// PreKeyMessage and `0x02` RatchetMessage shapes.
|
||||||
|
let plaintext: string;
|
||||||
|
try {
|
||||||
|
const envelope = decodeEnvelope(bodyBytes);
|
||||||
|
// First-message gate: only allow `prekey` envelopes when the
|
||||||
|
// operator has explicitly opted in.
|
||||||
|
if (options.acceptFirstMessage !== true && envelope.type === 'prekey') {
|
||||||
|
return c.json(
|
||||||
|
{
|
||||||
|
error:
|
||||||
|
'PreKeyMessage envelopes are not accepted on this RPC route — establish the session first via shade.initSessionFromBundle, or set acceptFirstMessage: true',
|
||||||
|
},
|
||||||
|
400,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
plaintext = await shade.receive(senderAddress, envelope);
|
||||||
|
} catch (err) {
|
||||||
|
// Decryption failure — could be no session, corrupted envelope,
|
||||||
|
// or sender address mismatch. Treat as 401 since the envelope is
|
||||||
|
// self-authenticating: a valid sender would decrypt cleanly.
|
||||||
|
return c.json({ error: `decrypt failed: ${(err as Error).message}` }, 401);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the plaintext as an RpcRequest.
|
||||||
|
const classified = tryParseEnvelope(plaintext);
|
||||||
|
if (classified === null) {
|
||||||
|
return c.json({ error: 'plaintext is not a valid @shade/files envelope' }, 400);
|
||||||
|
}
|
||||||
|
if (classified.kind !== 'request') {
|
||||||
|
// Cancel envelopes are silently dropped — RPC route is request/
|
||||||
|
// response only. Cancellation across HTTP is achieved via
|
||||||
|
// AbortController on the client side, not protocol-level.
|
||||||
|
if (classified.kind === 'cancel') {
|
||||||
|
handler.handleCancel(senderAddress, classified.envelope);
|
||||||
|
// No response body — the cancel was best-effort.
|
||||||
|
return new Response(null, { status: 204 });
|
||||||
|
}
|
||||||
|
return c.json(
|
||||||
|
{ error: `unexpected envelope kind on RPC route: ${classified.kind}` },
|
||||||
|
400,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const request: RpcRequest = classified.envelope;
|
||||||
|
|
||||||
|
// Dispatch through the file handler.
|
||||||
|
let result: RpcResponse | RpcError;
|
||||||
|
try {
|
||||||
|
result = await handler.handleRequest(senderAddress, request);
|
||||||
|
} catch (err) {
|
||||||
|
// Should never happen — handler.handleRequest catches its own
|
||||||
|
// errors and returns RpcError. If it didn't, that's a bug; emit
|
||||||
|
// a generic transport-level RpcError so the client can surface
|
||||||
|
// it deterministically.
|
||||||
|
result = {
|
||||||
|
kind: KIND_ERROR_V1,
|
||||||
|
id: request.id,
|
||||||
|
error: {
|
||||||
|
code: 'INTERNAL',
|
||||||
|
message: `handler raised: ${(err as Error).message}`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Encrypt the response and return it as wire bytes.
|
||||||
|
let responseBytes: Uint8Array;
|
||||||
|
try {
|
||||||
|
const responsePlaintext = encodeRpcEnvelope(result);
|
||||||
|
const responseEnvelope = await shade.send(senderAddress, responsePlaintext);
|
||||||
|
responseBytes = encodeEnvelope(responseEnvelope);
|
||||||
|
} catch (err) {
|
||||||
|
return c.json(
|
||||||
|
{ error: `failed to encrypt response: ${(err as Error).message}` },
|
||||||
|
500,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Response(new Blob([responseBytes as unknown as ArrayBuffer]), {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'Content-Type': 'application/octet-stream' },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
@@ -168,13 +168,14 @@ export async function createServerStreamsBridge(
|
|||||||
|
|
||||||
// No waiter yet — park.
|
// No waiter yet — park.
|
||||||
parked.set(writeId, arrived);
|
parked.set(writeId, arrived);
|
||||||
setTimeout(() => {
|
const parkTimer = setTimeout(() => {
|
||||||
const stale = parked.get(writeId);
|
const stale = parked.get(writeId);
|
||||||
if (stale === arrived) {
|
if (stale === arrived) {
|
||||||
parked.delete(writeId);
|
parked.delete(writeId);
|
||||||
void handle.abort('rpc-timeout').catch(() => undefined);
|
void handle.abort('rpc-timeout').catch(() => undefined);
|
||||||
}
|
}
|
||||||
}, parkedWriteTtlMs).unref?.();
|
}, parkedWriteTtlMs);
|
||||||
|
(parkTimer as unknown as { unref?: () => void }).unref?.();
|
||||||
});
|
});
|
||||||
|
|
||||||
function cleanupWaiter(w: PendingWaiter): void {
|
function cleanupWaiter(w: PendingWaiter): void {
|
||||||
|
|||||||
@@ -0,0 +1,184 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { createShade } from '@shade/sdk';
|
||||||
|
import {
|
||||||
|
createPrekeyServer,
|
||||||
|
MemoryPrekeyStore,
|
||||||
|
PrekeyServerEvents,
|
||||||
|
} from '@shade/server';
|
||||||
|
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Concurrent-ratchet hardening tests.
|
||||||
|
*
|
||||||
|
* Reproduces the scenario described in the v4.2.0 ratchet-desync bug
|
||||||
|
* report: with the queue-drainer running on Alice and many concurrent
|
||||||
|
* `shade.send`/RPC operations against the same peer, do
|
||||||
|
* encrypt/decrypt paths share the per-peer mutex on
|
||||||
|
* `ShadeSessionManager` so that no path observes a stale ratchet
|
||||||
|
* state?
|
||||||
|
*
|
||||||
|
* If the lock coverage regresses (a future change re-introduces a
|
||||||
|
* sidekanal bypass), one of these tests will fail with
|
||||||
|
* `DecryptionError: Failed to decrypt message — wrong key or
|
||||||
|
* tampered data`.
|
||||||
|
*/
|
||||||
|
async function setupPullRig() {
|
||||||
|
const prekey = createPrekeyServer({
|
||||||
|
crypto,
|
||||||
|
store: new MemoryPrekeyStore(),
|
||||||
|
disableRateLimit: true,
|
||||||
|
events: new PrekeyServerEvents(),
|
||||||
|
});
|
||||||
|
const prekeyServer = Bun.serve({ port: 0, fetch: prekey.fetch });
|
||||||
|
const prekeyUrl = `http://localhost:${prekeyServer.port}`;
|
||||||
|
|
||||||
|
const alice = await createShade({ prekeyServer: prekeyUrl, address: 'alice' });
|
||||||
|
const bob = await createShade({ prekeyServer: prekeyUrl, address: 'bob' });
|
||||||
|
|
||||||
|
const queueRoute = await bob.transferQueueRoute({ blockMs: 500 });
|
||||||
|
await bob.files.serve({
|
||||||
|
stat: async () => ({
|
||||||
|
name: '_',
|
||||||
|
kind: 'dir' as const,
|
||||||
|
size: 0,
|
||||||
|
mtime: 0,
|
||||||
|
metadata: {},
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const rpcRoute = bob.files.rpcRoute({ acceptFirstMessage: true });
|
||||||
|
|
||||||
|
const app = new Hono();
|
||||||
|
app.route('/', queueRoute);
|
||||||
|
app.route('/', rpcRoute);
|
||||||
|
const bobServer = Bun.serve({ port: 0, fetch: app.fetch });
|
||||||
|
const baseUrl = `http://localhost:${bobServer.port}`;
|
||||||
|
|
||||||
|
const fs = alice.files.httpClient('bob', {
|
||||||
|
rpcUrl: `${baseUrl}/rpc`,
|
||||||
|
outboundQueueUrl: `${baseUrl}/queue`,
|
||||||
|
transferBaseUrl: baseUrl,
|
||||||
|
defaultTimeoutMs: 10_000,
|
||||||
|
queueBlockMs: 500,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
alice,
|
||||||
|
bob,
|
||||||
|
fs,
|
||||||
|
baseUrl,
|
||||||
|
teardown: async () => {
|
||||||
|
fs.close();
|
||||||
|
await alice.shutdown();
|
||||||
|
await bob.shutdown();
|
||||||
|
bobServer.stop();
|
||||||
|
prekeyServer.stop();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('@shade/files — concurrent ratchet under drainer', () => {
|
||||||
|
test('100 parallel httpClient RPCs while drainer runs — no DecryptionError', async () => {
|
||||||
|
const rig = await setupPullRig();
|
||||||
|
try {
|
||||||
|
// Warm-up: establishes the X3DH session (Alice → Bob first message
|
||||||
|
// is a PreKeyMessage; subsequent messages are pure ratchet).
|
||||||
|
const first = await rig.fs.stat('/');
|
||||||
|
expect(first.kind).toBe('dir');
|
||||||
|
|
||||||
|
// Fire 100 concurrent stat RPCs. Each one is a full ratchet
|
||||||
|
// round-trip: encrypt request, POST, decrypt response. They all
|
||||||
|
// contend for `manager.peerOpChains["bob"]` on Alice's side
|
||||||
|
// (encrypt + decrypt) and `manager.peerOpChains["alice"]` on
|
||||||
|
// Bob's side. Drainer is running in the background polling
|
||||||
|
// Bob's queue — its decrypt path also funnels through the same
|
||||||
|
// per-peer lock.
|
||||||
|
// 100 concurrent — minimal repro (after warm-up only).
|
||||||
|
const N = 100;
|
||||||
|
const results = await Promise.allSettled(
|
||||||
|
Array.from({ length: N }, () => rig.fs.stat('/')),
|
||||||
|
);
|
||||||
|
const failures = results.filter((s) => s.status === 'rejected') as Array<
|
||||||
|
PromiseRejectedResult
|
||||||
|
>;
|
||||||
|
if (failures.length > 0) {
|
||||||
|
const sample = failures.slice(0, 1).map((f) => String(f.reason));
|
||||||
|
throw new Error(`${failures.length}/${N} concurrent RPCs failed: ${sample[0]}`);
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 30_000);
|
||||||
|
|
||||||
|
test('parallel shade.send + drainer + RPCs — ratchet stays in sync', async () => {
|
||||||
|
const rig = await setupPullRig();
|
||||||
|
try {
|
||||||
|
// Establish session via one warm-up RPC.
|
||||||
|
await rig.fs.stat('/');
|
||||||
|
|
||||||
|
// Subscribe Bob to inbound plaintext from Alice — when Alice's
|
||||||
|
// raw `shade.send` plaintext arrives, Bob echoes a reply back
|
||||||
|
// through `shade.send` + `deliverControlEnvelope`, which the
|
||||||
|
// pull-mode envelope transport enqueues for Alice's drainer.
|
||||||
|
// This injects extra inbound traffic into Alice's drainer in
|
||||||
|
// parallel with her ongoing RPCs.
|
||||||
|
const echoes: string[] = [];
|
||||||
|
rig.bob.onMessage(async (from, plaintext) => {
|
||||||
|
if (from !== 'alice') return;
|
||||||
|
if (!plaintext.startsWith('ping:')) return;
|
||||||
|
echoes.push(plaintext);
|
||||||
|
const reply = `pong:${plaintext.slice('ping:'.length)}`;
|
||||||
|
const env = await rig.bob.send('alice', reply);
|
||||||
|
await rig.bob.deliverControlEnvelope('alice', env);
|
||||||
|
});
|
||||||
|
|
||||||
|
const inboundDrained: string[] = [];
|
||||||
|
rig.alice.onMessage((from, plaintext) => {
|
||||||
|
if (from !== 'bob') return;
|
||||||
|
if (plaintext.startsWith('pong:')) inboundDrained.push(plaintext);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mix three concurrent workloads against the same peer:
|
||||||
|
// - 50 inline file RPCs through httpClient (encrypt + decrypt)
|
||||||
|
// - 50 raw `shade.send` deliveries via control envelope
|
||||||
|
// - drainer pulling Bob's responses + echoes
|
||||||
|
const N = 50;
|
||||||
|
const rpcs = Array.from({ length: N }, () => rig.fs.stat('/'));
|
||||||
|
const sends = Array.from({ length: N }, async (_, i) => {
|
||||||
|
const env = await rig.alice.send('bob', `ping:${i}`);
|
||||||
|
await rig.alice.deliverControlEnvelope('bob', env);
|
||||||
|
});
|
||||||
|
|
||||||
|
const settled = await Promise.allSettled([...rpcs, ...sends]);
|
||||||
|
const failures = settled.filter((s) => s.status === 'rejected') as Array<
|
||||||
|
PromiseRejectedResult
|
||||||
|
>;
|
||||||
|
if (failures.length > 0) {
|
||||||
|
const sample = failures.slice(0, 3).map((f) => String(f.reason));
|
||||||
|
throw new Error(
|
||||||
|
`${failures.length}/${settled.length} concurrent ops failed: ${sample.join(' | ')}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Give Bob's queue + Alice's drainer a beat to drain pongs back.
|
||||||
|
// Echoes round-trip Alice → Bob (control envelope) → Bob's
|
||||||
|
// onMessage → Bob.send + deliver (queue) → Alice's drainer →
|
||||||
|
// Alice's onMessage. We just verify some make it back without
|
||||||
|
// any DecryptionError surfacing.
|
||||||
|
const deadline = Date.now() + 5_000;
|
||||||
|
while (inboundDrained.length < N && Date.now() < deadline) {
|
||||||
|
await new Promise((r) => setTimeout(r, 50));
|
||||||
|
}
|
||||||
|
// Don't gate on every echo arriving — the long-poll cadence and
|
||||||
|
// bun's serve/abort timing can lag a few. We only care that the
|
||||||
|
// ratchet didn't desync; if it had, every subsequent op would
|
||||||
|
// throw DecryptionError above.
|
||||||
|
expect(echoes.length).toBe(N);
|
||||||
|
expect(inboundDrained.length).toBeGreaterThan(0);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 30_000);
|
||||||
|
});
|
||||||
288
packages/shade-files/tests/integration/http-rpc-streams.test.ts
Normal file
288
packages/shade-files/tests/integration/http-rpc-streams.test.ts
Normal file
@@ -0,0 +1,288 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { createShade } from '@shade/sdk';
|
||||||
|
import {
|
||||||
|
createPrekeyServer,
|
||||||
|
MemoryPrekeyStore,
|
||||||
|
PrekeyServerEvents,
|
||||||
|
} from '@shade/server';
|
||||||
|
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { createFilesHttpClient, type FileEntry } from '../../src/index.js';
|
||||||
|
|
||||||
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
type ShadeInstance = Awaited<ReturnType<typeof createShade>>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stand up the full pull-mode rig:
|
||||||
|
* - Prekey server (for X3DH)
|
||||||
|
* - Bob: file handler + rpcRoute + transferQueueRoute, all on one server
|
||||||
|
* - Alice: httpClient with outboundQueueUrl + transferBaseUrl wired
|
||||||
|
*
|
||||||
|
* Returns Alice's `FileClient`, which speaks browser-style: ONE base URL,
|
||||||
|
* no inbound listener, streams supported via long-poll.
|
||||||
|
*/
|
||||||
|
async function setupPullRig(opts: {
|
||||||
|
bobHandler: Parameters<NonNullable<ShadeInstance['files']>['serve']>[0];
|
||||||
|
wrapClientShade?: (shade: ShadeInstance) => Parameters<typeof createFilesHttpClient>[0];
|
||||||
|
}) {
|
||||||
|
const prekey = createPrekeyServer({
|
||||||
|
crypto,
|
||||||
|
store: new MemoryPrekeyStore(),
|
||||||
|
disableRateLimit: true,
|
||||||
|
events: new PrekeyServerEvents(),
|
||||||
|
});
|
||||||
|
const prekeyServer = Bun.serve({ port: 0, fetch: prekey.fetch });
|
||||||
|
const prekeyUrl = `http://localhost:${prekeyServer.port}`;
|
||||||
|
|
||||||
|
const alice = await createShade({ prekeyServer: prekeyUrl, address: 'alice' });
|
||||||
|
const bob = await createShade({ prekeyServer: prekeyUrl, address: 'bob' });
|
||||||
|
|
||||||
|
// Bob: queue-route FIRST (configures bob's transports), then files.serve.
|
||||||
|
const queueRoute = await bob.transferQueueRoute({ blockMs: 1_500 });
|
||||||
|
await bob.files.serve(opts.bobHandler);
|
||||||
|
const rpcRoute = bob.files.rpcRoute({ acceptFirstMessage: true });
|
||||||
|
|
||||||
|
const app = new Hono();
|
||||||
|
app.route('/', queueRoute);
|
||||||
|
app.route('/', rpcRoute);
|
||||||
|
|
||||||
|
const bobServer = Bun.serve({ port: 0, fetch: app.fetch });
|
||||||
|
const baseUrl = `http://localhost:${bobServer.port}`;
|
||||||
|
|
||||||
|
const fs = createFilesHttpClient(opts.wrapClientShade?.(alice) ?? alice, 'bob', {
|
||||||
|
rpcUrl: `${baseUrl}/rpc`,
|
||||||
|
outboundQueueUrl: `${baseUrl}/queue`,
|
||||||
|
transferBaseUrl: baseUrl,
|
||||||
|
defaultTimeoutMs: 10_000,
|
||||||
|
queueBlockMs: 1_000,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
alice,
|
||||||
|
bob,
|
||||||
|
fs,
|
||||||
|
baseUrl,
|
||||||
|
teardown: async () => {
|
||||||
|
fs.close();
|
||||||
|
await alice.shutdown();
|
||||||
|
await bob.shutdown();
|
||||||
|
bobServer.stop();
|
||||||
|
prekeyServer.stop();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
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 () => {
|
||||||
|
const payload = new Uint8Array(4 * 1024 * 1024);
|
||||||
|
for (let i = 0; i < payload.length; i++) payload[i] = (i * 97) & 0xff;
|
||||||
|
|
||||||
|
const rig = await setupPullRig({
|
||||||
|
bobHandler: {
|
||||||
|
read: async () => {
|
||||||
|
// Return the payload as a streamed read so the rpc-handler
|
||||||
|
// promotes it via the streams-bridge into a transfer.
|
||||||
|
const stream = new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
const CHUNK = 256 * 1024;
|
||||||
|
for (let off = 0; off < payload.byteLength; off += CHUNK) {
|
||||||
|
controller.enqueue(payload.slice(off, Math.min(off + CHUNK, payload.byteLength)));
|
||||||
|
}
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Need a precomputed sha256 for streamed reads. Use the
|
||||||
|
// crypto provider's sha256 directly.
|
||||||
|
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', payload));
|
||||||
|
const sha256Hex = Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||||
|
return {
|
||||||
|
kind: 'streams' as const,
|
||||||
|
stream,
|
||||||
|
size: payload.byteLength,
|
||||||
|
sha256: sha256Hex,
|
||||||
|
contentType: 'application/octet-stream',
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await rig.fs.read('/big.bin');
|
||||||
|
expect(result.kind).toBe('streams');
|
||||||
|
if (result.kind !== 'streams') return;
|
||||||
|
|
||||||
|
// Drain the stream and compare.
|
||||||
|
const reader = result.stream.getReader();
|
||||||
|
const got = new Uint8Array(payload.byteLength);
|
||||||
|
let offset = 0;
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
if (value !== undefined) {
|
||||||
|
got.set(value, offset);
|
||||||
|
offset += value.byteLength;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
reader.releaseLock();
|
||||||
|
await result.done();
|
||||||
|
|
||||||
|
expect(offset).toBe(payload.byteLength);
|
||||||
|
// Compare in 64KiB strides for speed.
|
||||||
|
let mismatch = -1;
|
||||||
|
for (let i = 0; i < payload.byteLength; i++) {
|
||||||
|
if (got[i] !== payload[i]) {
|
||||||
|
mismatch = i;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
expect(mismatch).toBe(-1);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 30_000);
|
||||||
|
|
||||||
|
test('streamed read fails with clear error when outboundQueueUrl is omitted', async () => {
|
||||||
|
const rig = await setupPullRig({
|
||||||
|
bobHandler: {
|
||||||
|
read: async () => {
|
||||||
|
const stream = new ReadableStream<Uint8Array>({
|
||||||
|
start(c) {
|
||||||
|
c.enqueue(new Uint8Array(512 * 1024));
|
||||||
|
c.close();
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const digest = new Uint8Array(await globalThis.crypto.subtle.digest('SHA-256', new Uint8Array(512 * 1024)));
|
||||||
|
const sha256Hex = Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
|
||||||
|
return {
|
||||||
|
kind: 'streams' as const,
|
||||||
|
stream,
|
||||||
|
size: 512 * 1024,
|
||||||
|
sha256: sha256Hex,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
// Tear down the rig's drainer so we can construct an inline-only client
|
||||||
|
rig.fs.close();
|
||||||
|
|
||||||
|
const inlineOnly = rig.alice.files.httpClient('bob', {
|
||||||
|
rpcUrl: `${rig.baseUrl}/rpc`,
|
||||||
|
defaultTimeoutMs: 10_000,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await expect(inlineOnly.read('/big.bin')).rejects.toThrow(/streamed read/);
|
||||||
|
} finally {
|
||||||
|
inlineOnly.close();
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
|
||||||
|
test('long-poll returns empty events on idle timeout', async () => {
|
||||||
|
const rig = await setupPullRig({
|
||||||
|
bobHandler: {
|
||||||
|
stat: async () => ({
|
||||||
|
name: '_',
|
||||||
|
kind: 'dir' as const,
|
||||||
|
size: 0,
|
||||||
|
mtime: 0,
|
||||||
|
metadata: {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
// Direct poll without any pending events — should return after blockMs.
|
||||||
|
const start = Date.now();
|
||||||
|
const res = await fetch(`${rig.baseUrl}/queue`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'X-Shade-Sender-Address': 'alice',
|
||||||
|
},
|
||||||
|
body: JSON.stringify({ since: 0, blockMs: 500 }),
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { events: unknown[]; nextSince: number };
|
||||||
|
expect(body.events).toHaveLength(0);
|
||||||
|
expect(Date.now() - start).toBeGreaterThanOrEqual(400);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 10_000);
|
||||||
|
});
|
||||||
321
packages/shade-files/tests/integration/http-rpc.test.ts
Normal file
321
packages/shade-files/tests/integration/http-rpc.test.ts
Normal file
@@ -0,0 +1,321 @@
|
|||||||
|
import { describe, expect, test } from 'bun:test';
|
||||||
|
import { createShade } from '@shade/sdk';
|
||||||
|
import {
|
||||||
|
createPrekeyServer,
|
||||||
|
MemoryPrekeyStore,
|
||||||
|
PrekeyServerEvents,
|
||||||
|
} from '@shade/server';
|
||||||
|
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||||
|
|
||||||
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Stand up a prekey server + two Shades + Bob's file handler + RPC route
|
||||||
|
* mounted on Bun.serve, then return Alice's HTTP-only `FileClient`.
|
||||||
|
*
|
||||||
|
* Mirrors the request-response setup a browser client would use against a
|
||||||
|
* Bun-style server.
|
||||||
|
*/
|
||||||
|
async function setupHttpRig(opts: {
|
||||||
|
bobHandler: Parameters<NonNullable<Awaited<ReturnType<typeof createShade>>['files']>['serve']>[0];
|
||||||
|
}) {
|
||||||
|
// 1. Prekey server.
|
||||||
|
const prekeyEvents = new PrekeyServerEvents();
|
||||||
|
const prekey = createPrekeyServer({
|
||||||
|
crypto,
|
||||||
|
store: new MemoryPrekeyStore(),
|
||||||
|
disableRateLimit: true,
|
||||||
|
events: prekeyEvents,
|
||||||
|
});
|
||||||
|
const prekeyServer = Bun.serve({ port: 0, fetch: prekey.fetch });
|
||||||
|
const prekeyUrl = `http://localhost:${prekeyServer.port}`;
|
||||||
|
|
||||||
|
// 2. Two Shades. Alice plays the browser client (no transferRoute);
|
||||||
|
// Bob is the server.
|
||||||
|
const alice = await createShade({ prekeyServer: prekeyUrl, address: 'alice' });
|
||||||
|
const bob = await createShade({ prekeyServer: prekeyUrl, address: 'bob' });
|
||||||
|
|
||||||
|
// 3. Bob: register file handler (HTTP-only — no streams) + mount
|
||||||
|
// the RPC route.
|
||||||
|
await bob.files.serve(opts.bobHandler, { inlineOnly: true });
|
||||||
|
const rpcRoute = bob.files.rpcRoute({ acceptFirstMessage: true });
|
||||||
|
const bobServer = Bun.serve({ port: 0, fetch: rpcRoute.fetch });
|
||||||
|
const rpcUrl = `http://localhost:${bobServer.port}/rpc`;
|
||||||
|
|
||||||
|
// 5. Alice: build the HTTP-only file client.
|
||||||
|
const fs = alice.files.httpClient('bob', { rpcUrl, defaultTimeoutMs: 5000 });
|
||||||
|
|
||||||
|
return {
|
||||||
|
alice,
|
||||||
|
bob,
|
||||||
|
fs,
|
||||||
|
rpcUrl,
|
||||||
|
teardown: async () => {
|
||||||
|
await alice.shutdown();
|
||||||
|
await bob.shutdown();
|
||||||
|
bobServer.stop();
|
||||||
|
prekeyServer.stop();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('@shade/files HTTP RPC — round-trip', () => {
|
||||||
|
test('list → mkdir → stat → write inline → read inline → delete via httpClient', async () => {
|
||||||
|
interface VfsEntry {
|
||||||
|
kind: 'file' | 'dir';
|
||||||
|
bytes?: Uint8Array;
|
||||||
|
contentType?: string;
|
||||||
|
}
|
||||||
|
const vfs = new Map<string, VfsEntry>([
|
||||||
|
['/', { kind: 'dir' }],
|
||||||
|
['/photos', { kind: 'dir' }],
|
||||||
|
]);
|
||||||
|
|
||||||
|
const rig = await setupHttpRig({
|
||||||
|
bobHandler: {
|
||||||
|
list: async (ctx) => {
|
||||||
|
const prefix = ctx.path.endsWith('/') ? ctx.path : `${ctx.path}/`;
|
||||||
|
const entries = Array.from(vfs.entries())
|
||||||
|
.filter(([p]) => p.startsWith(prefix) && p !== ctx.path && !p.slice(prefix.length).includes('/'))
|
||||||
|
.map(([p, e]) => ({
|
||||||
|
name: p.slice(prefix.length) || p,
|
||||||
|
kind: e.kind,
|
||||||
|
size: e.bytes?.byteLength ?? 0,
|
||||||
|
mtime: 0,
|
||||||
|
metadata: {},
|
||||||
|
}));
|
||||||
|
return { entries, hasMore: false };
|
||||||
|
},
|
||||||
|
stat: async (ctx) => {
|
||||||
|
const e = vfs.get(ctx.path);
|
||||||
|
if (!e) throw new (await import('../../src/index.js')).NotFoundError(`stat ${ctx.path}`);
|
||||||
|
return {
|
||||||
|
name: ctx.path.split('/').pop() ?? ctx.path,
|
||||||
|
kind: e.kind,
|
||||||
|
size: e.bytes?.byteLength ?? 0,
|
||||||
|
mtime: 0,
|
||||||
|
metadata: {},
|
||||||
|
...(e.contentType !== undefined ? { contentType: e.contentType } : {}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
mkdir: async (ctx) => {
|
||||||
|
vfs.set(ctx.path, { kind: 'dir' });
|
||||||
|
return { entry: { name: ctx.path.split('/').pop() ?? ctx.path, kind: 'dir' as const, size: 0, mtime: 0, metadata: {} } };
|
||||||
|
},
|
||||||
|
delete: async (ctx) => {
|
||||||
|
if (!vfs.has(ctx.path)) {
|
||||||
|
throw new (await import('../../src/index.js')).NotFoundError(`delete ${ctx.path}`);
|
||||||
|
}
|
||||||
|
vfs.delete(ctx.path);
|
||||||
|
return { deletedCount: 1 };
|
||||||
|
},
|
||||||
|
read: async (ctx) => {
|
||||||
|
const e = vfs.get(ctx.path);
|
||||||
|
if (!e || e.kind !== 'file' || !e.bytes) {
|
||||||
|
throw new (await import('../../src/index.js')).NotFoundError(`read ${ctx.path}`);
|
||||||
|
}
|
||||||
|
// Omit sha256 — dispatcher computes it from the bytes.
|
||||||
|
return {
|
||||||
|
kind: 'inline' as const,
|
||||||
|
bytes: e.bytes,
|
||||||
|
...(e.contentType !== undefined ? { contentType: e.contentType } : {}),
|
||||||
|
};
|
||||||
|
},
|
||||||
|
write: async (ctx) => {
|
||||||
|
if (ctx.args.content.kind !== 'inline') {
|
||||||
|
throw new (await import('../../src/index.js')).ConflictError('streams not supported in this test handler');
|
||||||
|
}
|
||||||
|
vfs.set(ctx.args.path, {
|
||||||
|
kind: 'file',
|
||||||
|
bytes: ctx.args.content.bytes,
|
||||||
|
...(ctx.args.contentType !== undefined ? { contentType: ctx.args.contentType } : {}),
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
entry: {
|
||||||
|
name: ctx.args.path.split('/').pop() ?? ctx.args.path,
|
||||||
|
kind: 'file' as const,
|
||||||
|
size: ctx.args.content.bytes.byteLength,
|
||||||
|
mtime: 0,
|
||||||
|
metadata: {},
|
||||||
|
...(ctx.args.contentType !== undefined ? { contentType: ctx.args.contentType } : {}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// list
|
||||||
|
const listed = await rig.fs.list('/');
|
||||||
|
expect(listed.entries.map((e) => e.name).sort()).toContain('photos');
|
||||||
|
|
||||||
|
// mkdir
|
||||||
|
await rig.fs.mkdir('/docs');
|
||||||
|
const stat = await rig.fs.stat('/docs');
|
||||||
|
expect(stat.kind).toBe('dir');
|
||||||
|
|
||||||
|
// write inline
|
||||||
|
const payload = new TextEncoder().encode('hello browser-friendly world');
|
||||||
|
const writeResult = await rig.fs.write('/docs/greeting.txt', payload, {
|
||||||
|
contentType: 'text/plain',
|
||||||
|
});
|
||||||
|
expect(writeResult.entry.size).toBe(payload.byteLength);
|
||||||
|
|
||||||
|
// read inline
|
||||||
|
const readResult = await rig.fs.read('/docs/greeting.txt');
|
||||||
|
expect(readResult.kind).toBe('inline');
|
||||||
|
if (readResult.kind === 'inline') {
|
||||||
|
expect(new TextDecoder().decode(readResult.bytes)).toBe('hello browser-friendly world');
|
||||||
|
expect(readResult.contentType).toBe('text/plain');
|
||||||
|
}
|
||||||
|
|
||||||
|
// delete
|
||||||
|
const del = await rig.fs.delete('/docs/greeting.txt');
|
||||||
|
expect(del.deletedCount).toBe(1);
|
||||||
|
|
||||||
|
// stat the deleted path → typed NotFoundError
|
||||||
|
const { NotFoundError } = await import('../../src/index.js');
|
||||||
|
await expect(rig.fs.stat('/docs/greeting.txt')).rejects.toBeInstanceOf(NotFoundError);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('streamed write (> 256 KiB) is rejected with a clear error', async () => {
|
||||||
|
const rig = await setupHttpRig({
|
||||||
|
bobHandler: {
|
||||||
|
write: async () => ({
|
||||||
|
entry: { name: 'unused', kind: 'file' as const, size: 0, mtime: 0, metadata: {} },
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const big = new Uint8Array(257 * 1024);
|
||||||
|
const { ConflictError } = await import('../../src/index.js');
|
||||||
|
await expect(rig.fs.write('/big.bin', big)).rejects.toBeInstanceOf(ConflictError);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('rpcRoute() throws when no handler is attached', async () => {
|
||||||
|
// Don't call shade.files.serve(...) — rpcRoute() should refuse.
|
||||||
|
const prekeyEvents = new PrekeyServerEvents();
|
||||||
|
const prekey = createPrekeyServer({
|
||||||
|
crypto,
|
||||||
|
store: new MemoryPrekeyStore(),
|
||||||
|
disableRateLimit: true,
|
||||||
|
events: prekeyEvents,
|
||||||
|
});
|
||||||
|
const prekeyServer = Bun.serve({ port: 0, fetch: prekey.fetch });
|
||||||
|
const bob = await createShade({
|
||||||
|
prekeyServer: `http://localhost:${prekeyServer.port}`,
|
||||||
|
address: 'bob',
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
expect(() => bob.files.rpcRoute()).toThrow(/no handler attached/);
|
||||||
|
} finally {
|
||||||
|
await bob.shutdown();
|
||||||
|
prekeyServer.stop();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('missing X-Shade-Sender-Address header → 400', async () => {
|
||||||
|
const rig = await setupHttpRig({
|
||||||
|
bobHandler: {
|
||||||
|
stat: async () => ({
|
||||||
|
name: '_', kind: 'dir' as const, size: 0, mtime: 0, metadata: {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const res = await fetch(rig.rpcUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
body: new Uint8Array([0]),
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
const body = (await res.json()) as { error: string };
|
||||||
|
expect(body.error).toMatch(/X-Shade-Sender-Address/);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('empty body → 400', async () => {
|
||||||
|
const rig = await setupHttpRig({
|
||||||
|
bobHandler: {
|
||||||
|
stat: async () => ({
|
||||||
|
name: '_', kind: 'dir' as const, size: 0, mtime: 0, metadata: {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const res = await fetch(rig.rpcUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-Shade-Sender-Address': 'alice' },
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('garbage body → 401 decrypt failure', async () => {
|
||||||
|
const rig = await setupHttpRig({
|
||||||
|
bobHandler: {
|
||||||
|
stat: async () => ({
|
||||||
|
name: '_', kind: 'dir' as const, size: 0, mtime: 0, metadata: {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const res = await fetch(rig.rpcUrl, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-Shade-Sender-Address': 'alice' },
|
||||||
|
body: new Uint8Array([0x02, 0xff, 0xff, 0xff]),
|
||||||
|
});
|
||||||
|
// 400 from envelope decode failure or 401 from decrypt failure.
|
||||||
|
expect([400, 401]).toContain(res.status);
|
||||||
|
} finally {
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('body past maxBodyBytes → 413', async () => {
|
||||||
|
const prekeyEvents = new PrekeyServerEvents();
|
||||||
|
const prekey = createPrekeyServer({
|
||||||
|
crypto,
|
||||||
|
store: new MemoryPrekeyStore(),
|
||||||
|
disableRateLimit: true,
|
||||||
|
events: prekeyEvents,
|
||||||
|
});
|
||||||
|
const prekeyServer = Bun.serve({ port: 0, fetch: prekey.fetch });
|
||||||
|
const bob = await createShade({
|
||||||
|
prekeyServer: `http://localhost:${prekeyServer.port}`,
|
||||||
|
address: 'bob',
|
||||||
|
});
|
||||||
|
await bob.files.serve(
|
||||||
|
{
|
||||||
|
stat: async () => ({
|
||||||
|
name: '_', kind: 'dir' as const, size: 0, mtime: 0, metadata: {},
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
{ inlineOnly: true },
|
||||||
|
);
|
||||||
|
const route = bob.files.rpcRoute({ maxBodyBytes: 1024 });
|
||||||
|
const server = Bun.serve({ port: 0, fetch: route.fetch });
|
||||||
|
try {
|
||||||
|
const big = new Uint8Array(2048);
|
||||||
|
const res = await fetch(`http://localhost:${server.port}/rpc`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'X-Shade-Sender-Address': 'alice' },
|
||||||
|
body: big,
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(413);
|
||||||
|
} finally {
|
||||||
|
await bob.shutdown();
|
||||||
|
server.stop();
|
||||||
|
prekeyServer.stop();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user