Compare commits
37 Commits
v4.2.1
...
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 |
@@ -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
|
||||||
1329
CHANGELOG.md
1329
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.
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
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.
|
||||||
@@ -1,7 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "shade",
|
"name": "shade",
|
||||||
"private": true,
|
"private": true,
|
||||||
"workspaces": ["packages/*"],
|
"workspaces": [
|
||||||
|
"packages/*"
|
||||||
|
],
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"test": "bun test --recursive",
|
"test": "bun test --recursive",
|
||||||
"test:core": "cd packages/shade-core && bun test",
|
"test:core": "cd packages/shade-core && bun test",
|
||||||
@@ -25,7 +27,8 @@
|
|||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"bun-types": "^1.3.11",
|
"bun-types": "^1.3.11",
|
||||||
"fast-check": "^3.22.0"
|
"fast-check": "^3.22.0",
|
||||||
|
"typescript": "7.0.2"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@noble/curves": "^2.0.1",
|
"@noble/curves": "^2.0.1",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/cli",
|
"name": "@shade/cli",
|
||||||
"version": "4.2.1",
|
"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.2.1",
|
"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';
|
||||||
|
|||||||
@@ -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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
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.2.1",
|
"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.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "vite",
|
"dev": "vite",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/files",
|
"name": "@shade/files",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -444,8 +444,12 @@ export function createFilesHttpClient(
|
|||||||
};
|
};
|
||||||
return out;
|
return out;
|
||||||
}
|
}
|
||||||
// Streamed read — only supported when the queue drainer is wired.
|
// Streamed read — only supported when pull-mode was configured.
|
||||||
if (drainer === null) {
|
// `drainer` is assigned asynchronously after the streams bridge has
|
||||||
|
// subscribed, so checking it here races client construction. The
|
||||||
|
// promise itself is the synchronous configuration signal; awaiting it
|
||||||
|
// also guarantees the drainer has been installed by its `.then()`.
|
||||||
|
if (streamsBridgePromise === null) {
|
||||||
throw new InternalFileError(
|
throw new InternalFileError(
|
||||||
`http RPC client received a streamed read (size ${wire.size}) but is in inline-only mode. Pass { outboundQueueUrl, transferBaseUrl } when constructing the client to enable streamed reads.`,
|
`http RPC client received a streamed read (size ${wire.size}) but is in inline-only mode. Pass { outboundQueueUrl, transferBaseUrl } when constructing the client to enable streamed reads.`,
|
||||||
);
|
);
|
||||||
@@ -507,8 +511,11 @@ export function createFilesHttpClient(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Streamed write — requires the queue drainer + streams-bridge.
|
// Streamed write — requires pull-mode configuration. Do not inspect
|
||||||
if (drainer === null) {
|
// `drainer` as a readiness flag: bridge registration is asynchronous,
|
||||||
|
// and an immediate large write must wait for it instead of being
|
||||||
|
// misclassified as an inline-only client.
|
||||||
|
if (streamsBridgePromise === null) {
|
||||||
throw new ConflictError(
|
throw new ConflictError(
|
||||||
`http RPC client supports inline writes only (≤ ${INLINE_THRESHOLD} bytes). The supplied input was promoted to streams (size ${decision.size ?? 'unknown'}). Pass { outboundQueueUrl, transferBaseUrl } to enable streamed writes.`,
|
`http RPC client supports inline writes only (≤ ${INLINE_THRESHOLD} bytes). The supplied input was promoted to streams (size ${decision.size ?? 'unknown'}). Pass { outboundQueueUrl, transferBaseUrl } to enable streamed writes.`,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -7,8 +7,10 @@ import {
|
|||||||
} from '@shade/server';
|
} from '@shade/server';
|
||||||
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
||||||
import { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
|
import { createFilesHttpClient, type FileEntry } from '../../src/index.js';
|
||||||
|
|
||||||
const crypto = new SubtleCryptoProvider();
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
type ShadeInstance = Awaited<ReturnType<typeof createShade>>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Stand up the full pull-mode rig:
|
* Stand up the full pull-mode rig:
|
||||||
@@ -20,7 +22,8 @@ const crypto = new SubtleCryptoProvider();
|
|||||||
* no inbound listener, streams supported via long-poll.
|
* no inbound listener, streams supported via long-poll.
|
||||||
*/
|
*/
|
||||||
async function setupPullRig(opts: {
|
async function setupPullRig(opts: {
|
||||||
bobHandler: Parameters<NonNullable<Awaited<ReturnType<typeof createShade>>['files']>['serve']>[0];
|
bobHandler: Parameters<NonNullable<ShadeInstance['files']>['serve']>[0];
|
||||||
|
wrapClientShade?: (shade: ShadeInstance) => Parameters<typeof createFilesHttpClient>[0];
|
||||||
}) {
|
}) {
|
||||||
const prekey = createPrekeyServer({
|
const prekey = createPrekeyServer({
|
||||||
crypto,
|
crypto,
|
||||||
@@ -46,7 +49,7 @@ async function setupPullRig(opts: {
|
|||||||
const bobServer = Bun.serve({ port: 0, fetch: app.fetch });
|
const bobServer = Bun.serve({ port: 0, fetch: app.fetch });
|
||||||
const baseUrl = `http://localhost:${bobServer.port}`;
|
const baseUrl = `http://localhost:${bobServer.port}`;
|
||||||
|
|
||||||
const fs = alice.files.httpClient('bob', {
|
const fs = createFilesHttpClient(opts.wrapClientShade?.(alice) ?? alice, 'bob', {
|
||||||
rpcUrl: `${baseUrl}/rpc`,
|
rpcUrl: `${baseUrl}/rpc`,
|
||||||
outboundQueueUrl: `${baseUrl}/queue`,
|
outboundQueueUrl: `${baseUrl}/queue`,
|
||||||
transferBaseUrl: baseUrl,
|
transferBaseUrl: baseUrl,
|
||||||
@@ -70,6 +73,83 @@ async function setupPullRig(opts: {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe('@shade/files HTTP RPC — pull-mode streams', () => {
|
describe('@shade/files HTTP RPC — pull-mode streams', () => {
|
||||||
|
test('immediate streamed write waits for asynchronous stream-bridge registration', async () => {
|
||||||
|
const payload = new Uint8Array(512 * 1024);
|
||||||
|
for (let i = 0; i < payload.length; i++) payload[i] = (i * 53) & 0xff;
|
||||||
|
|
||||||
|
let releaseRegistration!: () => void;
|
||||||
|
const registrationGate = new Promise<void>((resolve) => {
|
||||||
|
releaseRegistration = resolve;
|
||||||
|
});
|
||||||
|
let registrationStarted!: () => void;
|
||||||
|
const started = new Promise<void>((resolve) => {
|
||||||
|
registrationStarted = resolve;
|
||||||
|
});
|
||||||
|
|
||||||
|
const rig = await setupPullRig({
|
||||||
|
wrapClientShade: (alice) =>
|
||||||
|
new Proxy(alice, {
|
||||||
|
get(target, property) {
|
||||||
|
if (property === 'onIncomingTransfer') {
|
||||||
|
return async (handler: Parameters<typeof target.onIncomingTransfer>[0]) => {
|
||||||
|
registrationStarted();
|
||||||
|
await registrationGate;
|
||||||
|
return await target.onIncomingTransfer(handler);
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const value = Reflect.get(target, property, target) as unknown;
|
||||||
|
return typeof value === 'function' ? value.bind(target) : value;
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
bobHandler: {
|
||||||
|
write: async (ctx) => {
|
||||||
|
const content = ctx.args.content;
|
||||||
|
if (content.kind !== 'streams') throw new Error('expected streamed content');
|
||||||
|
const reader = content.stream.getReader();
|
||||||
|
let received = 0;
|
||||||
|
while (true) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
received += value?.byteLength ?? 0;
|
||||||
|
}
|
||||||
|
reader.releaseLock();
|
||||||
|
await content.sha256;
|
||||||
|
const entry: FileEntry = {
|
||||||
|
name: 'immediate.bin',
|
||||||
|
kind: 'file',
|
||||||
|
size: received,
|
||||||
|
mtime: Date.now(),
|
||||||
|
metadata: {},
|
||||||
|
};
|
||||||
|
return { entry };
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
let settled = false;
|
||||||
|
const write = rig.fs.write('/immediate.bin', payload);
|
||||||
|
void write.then(
|
||||||
|
() => {
|
||||||
|
settled = true;
|
||||||
|
},
|
||||||
|
() => {
|
||||||
|
settled = true;
|
||||||
|
},
|
||||||
|
);
|
||||||
|
await started;
|
||||||
|
await Bun.sleep(10);
|
||||||
|
expect(settled).toBe(false);
|
||||||
|
|
||||||
|
releaseRegistration();
|
||||||
|
const result = await write;
|
||||||
|
expect(result.entry.size).toBe(payload.byteLength);
|
||||||
|
} finally {
|
||||||
|
releaseRegistration();
|
||||||
|
await rig.teardown();
|
||||||
|
}
|
||||||
|
}, 15_000);
|
||||||
|
|
||||||
test('streamed read (4 MiB) via long-poll queue', async () => {
|
test('streamed read (4 MiB) via long-poll queue', async () => {
|
||||||
const payload = new Uint8Array(4 * 1024 * 1024);
|
const payload = new Uint8Array(4 * 1024 * 1024);
|
||||||
for (let i = 0; i < payload.length; i++) payload[i] = (i * 97) & 0xff;
|
for (let i = 0; i < payload.length; i++) payload[i] = (i * 97) & 0xff;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/inbox-server",
|
"name": "@shade/inbox-server",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
268
packages/shade-inbox-server/src/blob-routes.ts
Normal file
268
packages/shade-inbox-server/src/blob-routes.ts
Normal file
@@ -0,0 +1,268 @@
|
|||||||
|
import { Hono } from 'hono';
|
||||||
|
import type { CryptoProvider } from '@shade/core';
|
||||||
|
import {
|
||||||
|
errorToHttpStatus,
|
||||||
|
ShadeError,
|
||||||
|
ValidationError,
|
||||||
|
UnauthorizedError,
|
||||||
|
fromBase64,
|
||||||
|
toBase64,
|
||||||
|
constantTimeEqual,
|
||||||
|
} from '@shade/core';
|
||||||
|
import {
|
||||||
|
verifyPayload,
|
||||||
|
RateLimiter,
|
||||||
|
MemoryRateLimitStore,
|
||||||
|
type RateLimitConfig,
|
||||||
|
} from '@shade/server';
|
||||||
|
import {
|
||||||
|
ATTR_ERROR_CODE,
|
||||||
|
ATTR_HTTP_STATUS,
|
||||||
|
ATTR_ROUTE,
|
||||||
|
NOOP_HOOK,
|
||||||
|
type ObservabilityHook,
|
||||||
|
} from '@shade/observability';
|
||||||
|
import type { BlobStore } from './blob-store.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Wire-level wrapper around the V4.9 BlobStore primitive.
|
||||||
|
*
|
||||||
|
* Endpoints:
|
||||||
|
* GET /v1/blob/:slotId → { blob, etag } | 404
|
||||||
|
* PUT /v1/blob/:slotId → { etag, created } | 409 | 412
|
||||||
|
* DELETE /v1/blob/:slotId → { ok }
|
||||||
|
*
|
||||||
|
* SlotId is 64 lowercase hex chars (the HKDF output, 32 bytes). Payloads
|
||||||
|
* are base64-encoded ciphertext; the relay never decrypts. Auth uses
|
||||||
|
* `signPayload` / `verifyPayload` (same canonical-JSON-and-Ed25519
|
||||||
|
* scheme as the inbox routes), keyed off the per-slot pubkey stored
|
||||||
|
* TOFU on the first PUT.
|
||||||
|
*
|
||||||
|
* Quota: a single slot holds one blob. `MAX_BLOB_BYTES` (64 KiB) is
|
||||||
|
* sized for Prism's profile use-case (a few hundred host entries) with
|
||||||
|
* plenty of headroom; future apps can override via `BlobRoutesOptions`.
|
||||||
|
*/
|
||||||
|
const SLOT_ID_REGEX = /^[0-9a-f]{64}$/;
|
||||||
|
const MAX_META_BODY_SIZE = 64 * 1024;
|
||||||
|
/** Default per-slot blob ceiling. Sized for ~500 host entries in JSON form. */
|
||||||
|
export const DEFAULT_MAX_BLOB_BYTES = 64 * 1024;
|
||||||
|
|
||||||
|
const PUT_LIMIT: RateLimitConfig = { capacity: 60, refillPerSecond: 1 };
|
||||||
|
const GET_LIMIT: RateLimitConfig = { capacity: 120, refillPerSecond: 2 };
|
||||||
|
const DELETE_LIMIT: RateLimitConfig = { capacity: 30, refillPerSecond: 1 };
|
||||||
|
|
||||||
|
export interface BlobRoutesOptions {
|
||||||
|
disableRateLimit?: boolean;
|
||||||
|
observability?: ObservabilityHook;
|
||||||
|
/** Per-blob byte ceiling. Defaults to 64 KiB. */
|
||||||
|
maxBlobBytes?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createBlobRoutes(
|
||||||
|
store: BlobStore,
|
||||||
|
crypto: CryptoProvider,
|
||||||
|
options: BlobRoutesOptions = {},
|
||||||
|
): Hono {
|
||||||
|
const app = new Hono();
|
||||||
|
const observability = options.observability ?? NOOP_HOOK;
|
||||||
|
const maxBlobBytes = options.maxBlobBytes ?? DEFAULT_MAX_BLOB_BYTES;
|
||||||
|
|
||||||
|
app.use('*', async (c, next) => {
|
||||||
|
const route = c.req.routePath ?? c.req.path ?? '<unknown>';
|
||||||
|
const span = observability.startSpan('shade.blob.request', {
|
||||||
|
[ATTR_ROUTE]: route,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
await next();
|
||||||
|
span.setAttribute(ATTR_HTTP_STATUS, c.res.status);
|
||||||
|
span.setStatus(c.res.status >= 500 ? 'error' : 'ok');
|
||||||
|
} catch (err) {
|
||||||
|
const code =
|
||||||
|
err instanceof ShadeError ? err.code ?? 'SHADE_ERROR' : 'SHADE_INTERNAL';
|
||||||
|
span.setAttribute(ATTR_ERROR_CODE, code);
|
||||||
|
span.recordException(err);
|
||||||
|
span.setStatus('error', code);
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
span.end();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const rlStore = new MemoryRateLimitStore();
|
||||||
|
const putRL = new RateLimiter(rlStore, PUT_LIMIT);
|
||||||
|
const getRL = new RateLimiter(rlStore, GET_LIMIT);
|
||||||
|
const deleteRL = new RateLimiter(rlStore, DELETE_LIMIT);
|
||||||
|
const rateLimitEnabled = !options.disableRateLimit;
|
||||||
|
|
||||||
|
const getClientIp = (c: any): string =>
|
||||||
|
c.req.header('x-forwarded-for')?.split(',')[0]?.trim() ??
|
||||||
|
c.req.header('x-real-ip') ??
|
||||||
|
'unknown';
|
||||||
|
|
||||||
|
app.onError((err, c) => {
|
||||||
|
if (err instanceof ShadeError) {
|
||||||
|
const status = errorToHttpStatus(err);
|
||||||
|
const body: any = err.toJSON();
|
||||||
|
if ((err as any).retryAfterSeconds) {
|
||||||
|
c.header('Retry-After', String((err as any).retryAfterSeconds));
|
||||||
|
}
|
||||||
|
return c.json(body, status as any);
|
||||||
|
}
|
||||||
|
console.error('[Shade] Unhandled blob error:', err);
|
||||||
|
return c.json({ error: 'Internal server error' }, 500);
|
||||||
|
});
|
||||||
|
|
||||||
|
function validateSlotId(raw: string | undefined): string {
|
||||||
|
if (typeof raw !== 'string' || !SLOT_ID_REGEX.test(raw)) {
|
||||||
|
throw new ValidationError(
|
||||||
|
'slotId must be 64 lowercase hex chars (32 bytes)',
|
||||||
|
'slotId',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── GET ─────────────────────────────────────────────────────
|
||||||
|
// Unauthenticated. SlotId is itself a 256-bit secret derived from the
|
||||||
|
// master key — knowing it implies you derived the master, which is
|
||||||
|
// equivalent to holding the credentials. The blob is AEAD-sealed, so
|
||||||
|
// a relay-side leak of slotId still cannot decrypt the contents.
|
||||||
|
app.get('/v1/blob/:slotId', async (c) => {
|
||||||
|
const slotId = validateSlotId(c.req.param('slotId'));
|
||||||
|
if (rateLimitEnabled) await getRL.consume(`blob-get:${getClientIp(c)}`);
|
||||||
|
|
||||||
|
const row = await store.get(slotId);
|
||||||
|
if (!row) {
|
||||||
|
return c.json({ error: 'Slot not found', code: 'SHADE_NOT_FOUND' }, 404);
|
||||||
|
}
|
||||||
|
return c.json({
|
||||||
|
blob: toBase64(row.blob),
|
||||||
|
etag: String(row.etag),
|
||||||
|
updatedAt: row.updatedAt,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── PUT ─────────────────────────────────────────────────────
|
||||||
|
// Body format:
|
||||||
|
// {
|
||||||
|
// ownerPubkey: b64, // Ed25519 pubkey deterministically
|
||||||
|
// // derived from the master via HKDF.
|
||||||
|
// blob: b64,
|
||||||
|
// ifMatch?: string, // "<etag>" | "*" | undefined
|
||||||
|
// signedAt: number,
|
||||||
|
// signature: b64 // over the canonical body sans signature
|
||||||
|
// }
|
||||||
|
//
|
||||||
|
// First write to a slot is TOFU: we record `ownerPubkey` and require
|
||||||
|
// any future write to verify against it. A different key trying to
|
||||||
|
// overwrite an existing slot is rejected with UnauthorizedError.
|
||||||
|
app.put('/v1/blob/:slotId', async (c) => {
|
||||||
|
const slotId = validateSlotId(c.req.param('slotId'));
|
||||||
|
if (rateLimitEnabled) await putRL.consume(`blob-put:${getClientIp(c)}`);
|
||||||
|
|
||||||
|
const rawBody = await c.req.text();
|
||||||
|
const hardLimit = Math.ceil(maxBlobBytes * 1.4) + MAX_META_BODY_SIZE;
|
||||||
|
if (rawBody.length > hardLimit) {
|
||||||
|
throw new ValidationError(`Request body too large`);
|
||||||
|
}
|
||||||
|
const body = JSON.parse(rawBody);
|
||||||
|
const { ownerPubkey, blob, ifMatch } = body;
|
||||||
|
|
||||||
|
if (typeof ownerPubkey !== 'string') {
|
||||||
|
throw new ValidationError('Missing ownerPubkey', 'ownerPubkey');
|
||||||
|
}
|
||||||
|
if (typeof blob !== 'string') {
|
||||||
|
throw new ValidationError('Missing blob', 'blob');
|
||||||
|
}
|
||||||
|
const claimedKey = fromBase64(ownerPubkey);
|
||||||
|
if (claimedKey.length !== 32) {
|
||||||
|
throw new ValidationError('ownerPubkey must be 32 bytes (Ed25519)', 'ownerPubkey');
|
||||||
|
}
|
||||||
|
const blobBytes = fromBase64(blob);
|
||||||
|
if (blobBytes.length === 0) {
|
||||||
|
throw new ValidationError('blob is empty', 'blob');
|
||||||
|
}
|
||||||
|
if (blobBytes.length > maxBlobBytes) {
|
||||||
|
throw new ValidationError(
|
||||||
|
`blob exceeds maxBlobBytes (${blobBytes.length} > ${maxBlobBytes})`,
|
||||||
|
'blob',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let expectedEtag: number | '*' | undefined;
|
||||||
|
if (ifMatch === undefined) {
|
||||||
|
expectedEtag = undefined;
|
||||||
|
} else if (typeof ifMatch !== 'string') {
|
||||||
|
throw new ValidationError('ifMatch must be a string when present', 'ifMatch');
|
||||||
|
} else if (ifMatch === '*') {
|
||||||
|
expectedEtag = '*';
|
||||||
|
} else {
|
||||||
|
const n = Number(ifMatch);
|
||||||
|
if (!Number.isFinite(n) || !Number.isInteger(n) || n < 0) {
|
||||||
|
throw new ValidationError('ifMatch must be a non-negative integer or "*"', 'ifMatch');
|
||||||
|
}
|
||||||
|
expectedEtag = n;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Existing slot: caller must sign with the original owner key. Use
|
||||||
|
// the stored pubkey for verification. The body's `ownerPubkey` is
|
||||||
|
// bound by the signature too, so an attacker cannot trick us into
|
||||||
|
// verifying with a key they control — the canonicalization includes
|
||||||
|
// every field but `signature`.
|
||||||
|
const existing = await store.get(slotId);
|
||||||
|
const verifyKey = existing ? existing.ownerPubkey : claimedKey;
|
||||||
|
|
||||||
|
// Bind slotId into the signed payload so a signature for slot A
|
||||||
|
// can't be replayed against slot B (the URL is otherwise outside
|
||||||
|
// the signed bytes).
|
||||||
|
await verifyPayload(crypto, verifyKey, { ...body, slotId });
|
||||||
|
|
||||||
|
if (existing && !constantTimeEqual(existing.ownerPubkey, claimedKey)) {
|
||||||
|
throw new UnauthorizedError(
|
||||||
|
`Slot ${slotId} is owned by a different signing key`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await store.put({
|
||||||
|
slotId,
|
||||||
|
blob: blobBytes,
|
||||||
|
ownerPubkey: claimedKey,
|
||||||
|
expectedEtag,
|
||||||
|
now: Date.now(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return c.json({
|
||||||
|
ok: true,
|
||||||
|
created: result.created,
|
||||||
|
etag: String(result.etag),
|
||||||
|
updatedAt: result.updatedAt,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── DELETE ──────────────────────────────────────────────────
|
||||||
|
// Body format: { signedAt, signature }. Signed by the owner pubkey
|
||||||
|
// recorded on the first PUT. After deletion, the slot is fully gone —
|
||||||
|
// the next PUT TOFU-claims it again (potentially under a different
|
||||||
|
// signing key, e.g. after a rotation).
|
||||||
|
app.delete('/v1/blob/:slotId', async (c) => {
|
||||||
|
const slotId = validateSlotId(c.req.param('slotId'));
|
||||||
|
if (rateLimitEnabled) await deleteRL.consume(`blob-delete:${getClientIp(c)}`);
|
||||||
|
|
||||||
|
const existing = await store.get(slotId);
|
||||||
|
if (!existing) {
|
||||||
|
return c.json({ error: 'Slot not found', code: 'SHADE_NOT_FOUND' }, 404);
|
||||||
|
}
|
||||||
|
|
||||||
|
const rawBody = await c.req.text();
|
||||||
|
if (rawBody.length > MAX_META_BODY_SIZE) {
|
||||||
|
throw new ValidationError(`Request body too large`);
|
||||||
|
}
|
||||||
|
const body = JSON.parse(rawBody);
|
||||||
|
await verifyPayload(crypto, existing.ownerPubkey, { ...body, slotId });
|
||||||
|
|
||||||
|
const removed = await store.delete(slotId);
|
||||||
|
return c.json({ ok: removed });
|
||||||
|
});
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
86
packages/shade-inbox-server/src/blob-store.ts
Normal file
86
packages/shade-inbox-server/src/blob-store.ts
Normal file
@@ -0,0 +1,86 @@
|
|||||||
|
/**
|
||||||
|
* BlobStore — server-side storage interface for the V4.9 encrypted-blob
|
||||||
|
* primitive. A "slot" is a single AEAD-sealed blob keyed by a
|
||||||
|
* deterministic 32-byte slotId derived client-side via HKDF from a
|
||||||
|
* master key. The relay never sees plaintext, never holds private keys,
|
||||||
|
* and never decrypts.
|
||||||
|
*
|
||||||
|
* Auth model (TOFU per slot, mirrors the inbox-owner pattern):
|
||||||
|
* - First PUT to an empty slot stores the caller's Ed25519 signing
|
||||||
|
* pubkey alongside the blob. Subsequent writes must produce a valid
|
||||||
|
* signature verifiable by that pubkey.
|
||||||
|
* - GET is unauthenticated — slotId is itself a 256-bit secret derived
|
||||||
|
* from the master key, so knowing it implies you derived the master.
|
||||||
|
* - DELETE clears the blob AND the owner pubkey, allowing future TOFU
|
||||||
|
* re-claim by a fresh signing key derived from the same master (e.g.
|
||||||
|
* after a rotation).
|
||||||
|
*
|
||||||
|
* CAS / etag semantics:
|
||||||
|
* - Every successful PUT bumps a per-slot monotonic etag (returned to
|
||||||
|
* the caller as a string).
|
||||||
|
* - A stale `ifMatch` triggers `PreconditionFailedError` (HTTP 412).
|
||||||
|
* - `ifMatch === undefined` against a populated slot triggers
|
||||||
|
* `ConflictError` (HTTP 409) — clients must read-then-write.
|
||||||
|
* - `ifMatch === '*'` against a populated slot is unconditional
|
||||||
|
* overwrite (escape hatch). Against an empty slot it's still 412
|
||||||
|
* per RFC 7232 (no entity to match).
|
||||||
|
*/
|
||||||
|
export interface BlobSlotRecord {
|
||||||
|
/** Lower-hex 64-char slotId (32 bytes). */
|
||||||
|
slotId: string;
|
||||||
|
/** Raw AEAD ciphertext (bytes). The relay never decrypts. */
|
||||||
|
blob: Uint8Array;
|
||||||
|
/** Owner Ed25519 signing pubkey, established TOFU on the first PUT. */
|
||||||
|
ownerPubkey: Uint8Array;
|
||||||
|
/** Monotonic per-slot version. Used as the ETag on the wire. */
|
||||||
|
etag: number;
|
||||||
|
/** Wall-clock ms of the last successful write. */
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Returned to the route layer after a successful PUT. */
|
||||||
|
export interface PutBlobResult {
|
||||||
|
/** Whether the slot was created (true) or updated in place (false). */
|
||||||
|
created: boolean;
|
||||||
|
/** New etag after the write. */
|
||||||
|
etag: number;
|
||||||
|
/** Wall-clock ms of the write. */
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BlobStore {
|
||||||
|
/** Read a slot, or null if it has never been written (or was deleted). */
|
||||||
|
get(slotId: string): Promise<BlobSlotRecord | null>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update a slot.
|
||||||
|
*
|
||||||
|
* Implementations MUST treat `(slotId, ownerPubkey)` atomically: the
|
||||||
|
* route layer has already verified the signature, but the store is the
|
||||||
|
* authority on whether the slot exists and what etag it has. Callers
|
||||||
|
* pass the verified `ownerPubkey` (used on first-write to record the
|
||||||
|
* owner; ignored on subsequent writes — the existing pubkey is the
|
||||||
|
* source of truth for who's allowed to write).
|
||||||
|
*
|
||||||
|
* `expectedEtag` semantics (mirror the wire-level If-Match):
|
||||||
|
* - `undefined` : create-only. Slot must be empty.
|
||||||
|
* - `<number>` : compare-and-swap. Must equal the current etag.
|
||||||
|
* - `'*'` : unconditional overwrite. Slot must already exist.
|
||||||
|
*
|
||||||
|
* On precondition mismatch the store throws `PreconditionFailedError`
|
||||||
|
* (stale etag) or `ConflictError` (slot exists, no ifMatch).
|
||||||
|
*/
|
||||||
|
put(args: {
|
||||||
|
slotId: string;
|
||||||
|
blob: Uint8Array;
|
||||||
|
ownerPubkey: Uint8Array;
|
||||||
|
expectedEtag: number | '*' | undefined;
|
||||||
|
now: number;
|
||||||
|
}): Promise<PutBlobResult>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a slot. Authentication has already been checked by the route
|
||||||
|
* layer. Returns true if a row was removed (i.e. the slot existed).
|
||||||
|
*/
|
||||||
|
delete(slotId: string): Promise<boolean>;
|
||||||
|
}
|
||||||
140
packages/shade-inbox-server/src/bridge-delivery-log.ts
Normal file
140
packages/shade-inbox-server/src/bridge-delivery-log.ts
Normal file
@@ -0,0 +1,140 @@
|
|||||||
|
/**
|
||||||
|
* BridgeDeliveryLog — V4.8.4 cross-channel dedup.
|
||||||
|
*
|
||||||
|
* Records per-`(address, msgId)` "delivered via bridge push" timestamps so
|
||||||
|
* the inbox-fetch route can filter out blobs the bridge has already pushed
|
||||||
|
* to the recipient. The relay's contract becomes:
|
||||||
|
*
|
||||||
|
* one `Inbox.send` ⇒ one observable delivery on the recipient
|
||||||
|
*
|
||||||
|
* even when the recipient runs both a bridge subscription (WS / SSE) AND
|
||||||
|
* the regular inbox-poll. Without it, bridge-push and inbox-poll are
|
||||||
|
* independent paths against the same store and the recipient gets the
|
||||||
|
* same envelope twice — bridge-first, then ~30 s later via the next poll
|
||||||
|
* — tripping on already-consumed prekeys (`one-time prekey not found`)
|
||||||
|
* or surfacing as duplicate `shade.receive` work.
|
||||||
|
*
|
||||||
|
* The log is in-memory per process and intentionally bounded: each entry
|
||||||
|
* lives for `graceMs` (default 60 s, well past a typical `pollIntervalMs`
|
||||||
|
* of 30 s). After grace, the entry is forgotten and inbox-poll falls back
|
||||||
|
* to delivering the blob — that's the legitimate "bridge dropped the
|
||||||
|
* frame, poll picked up" recovery path. If the recipient explicitly
|
||||||
|
* acks the blob (HTTP `DELETE /v1/inbox/:addr/:msgId`), the blob is gone
|
||||||
|
* from storage and the log entry is moot.
|
||||||
|
*
|
||||||
|
* Multi-bridge per address (e.g. WS + SSE redundancy on the same client,
|
||||||
|
* or two devices sharing one signing key) is preserved: every bridge
|
||||||
|
* connection still fetches + pushes the blob — each push records its own
|
||||||
|
* timestamp — so each connected bridge gets the frame. Only the *poll*
|
||||||
|
* fetch is filtered, not the bridge fetches themselves.
|
||||||
|
*
|
||||||
|
* @see Prism FR `cross-channel-duplicate-fanout-v4.8.2.md`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
const DEFAULT_GRACE_MS = 60_000;
|
||||||
|
|
||||||
|
export interface BridgeDeliveryLogOptions {
|
||||||
|
/**
|
||||||
|
* How long a `(address, msgId)` mark suppresses inbox-poll delivery.
|
||||||
|
* Defaults to 60_000ms — twice the default `pollIntervalMs` of the
|
||||||
|
* `@shade/inbox` orchestrator, so a poll cycle that races a bridge
|
||||||
|
* push always sees the mark, but a stuck recipient still gets the
|
||||||
|
* blob via poll within ~minutes.
|
||||||
|
*/
|
||||||
|
graceMs?: number;
|
||||||
|
/**
|
||||||
|
* Maximum entries per address. Bounds memory under a busy address.
|
||||||
|
* Oldest entries (by recorded timestamp) are evicted first. Default
|
||||||
|
* 8192 — comfortably above any realistic backlog.
|
||||||
|
*/
|
||||||
|
maxPerAddress?: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BridgeDeliveryLog {
|
||||||
|
private readonly log = new Map<string, Map<string, number>>();
|
||||||
|
private readonly graceMs: number;
|
||||||
|
private readonly maxPerAddress: number;
|
||||||
|
|
||||||
|
constructor(options: BridgeDeliveryLogOptions = {}) {
|
||||||
|
this.graceMs = options.graceMs ?? DEFAULT_GRACE_MS;
|
||||||
|
this.maxPerAddress = options.maxPerAddress ?? 8192;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mark `(address, msgId)` as bridge-delivered at `now`. */
|
||||||
|
recordDelivered(address: string, msgId: string, now: number): void {
|
||||||
|
let inner = this.log.get(address);
|
||||||
|
if (!inner) {
|
||||||
|
inner = new Map();
|
||||||
|
this.log.set(address, inner);
|
||||||
|
}
|
||||||
|
inner.set(msgId, now);
|
||||||
|
// Lazy cleanup: drop entries past 2× grace so the map stays bounded
|
||||||
|
// without a separate timer. Bound by `maxPerAddress` as a fallback
|
||||||
|
// for pathological burst scenarios.
|
||||||
|
if (inner.size > this.maxPerAddress) {
|
||||||
|
const cutoff = now - this.graceMs * 2;
|
||||||
|
for (const [id, ts] of inner) {
|
||||||
|
if (ts < cutoff) inner.delete(id);
|
||||||
|
}
|
||||||
|
// Still over cap? Drop the oldest.
|
||||||
|
if (inner.size > this.maxPerAddress) {
|
||||||
|
const sorted = Array.from(inner.entries()).sort((a, b) => a[1] - b[1]);
|
||||||
|
const toDrop = sorted.slice(0, inner.size - this.maxPerAddress);
|
||||||
|
for (const [id] of toDrop) inner.delete(id);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns true if `(address, msgId)` was bridge-delivered within the
|
||||||
|
* grace window.
|
||||||
|
*/
|
||||||
|
isRecentlyDelivered(address: string, msgId: string, now: number): boolean {
|
||||||
|
const inner = this.log.get(address);
|
||||||
|
if (!inner) return false;
|
||||||
|
const ts = inner.get(msgId);
|
||||||
|
if (ts === undefined) return false;
|
||||||
|
if (now - ts > this.graceMs) {
|
||||||
|
inner.delete(msgId); // tombstone the stale entry
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Filter `blobs` down to those not currently in the bridge-delivered
|
||||||
|
* grace window. Used by the inbox-fetch route to suppress duplicates.
|
||||||
|
*/
|
||||||
|
filterRecent<T extends { msgId: string }>(
|
||||||
|
address: string,
|
||||||
|
blobs: T[],
|
||||||
|
now: number,
|
||||||
|
): T[] {
|
||||||
|
const inner = this.log.get(address);
|
||||||
|
if (!inner || inner.size === 0) return blobs;
|
||||||
|
return blobs.filter((b) => {
|
||||||
|
const ts = inner.get(b.msgId);
|
||||||
|
if (ts === undefined) return true;
|
||||||
|
if (now - ts > this.graceMs) {
|
||||||
|
inner.delete(b.msgId);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop the entry for `(address, msgId)`. Called from blob-delete paths. */
|
||||||
|
forget(address: string, msgId: string): void {
|
||||||
|
this.log.get(address)?.delete(msgId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Drop every entry for `address`. Called from address-delete paths. */
|
||||||
|
forgetAddress(address: string): void {
|
||||||
|
this.log.delete(address);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Test-only inspection. */
|
||||||
|
size(address: string): number {
|
||||||
|
return this.log.get(address)?.size ?? 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -38,8 +38,16 @@ import {
|
|||||||
import { verifyPayload, validateAddress } from '@shade/server';
|
import { verifyPayload, validateAddress } from '@shade/server';
|
||||||
import type { InboxStore } from './store.js';
|
import type { InboxStore } from './store.js';
|
||||||
import type { InboxServerEvents } from './events.js';
|
import type { InboxServerEvents } from './events.js';
|
||||||
|
import { PresenceTracker, type TrackedBridgeKind } from './presence.js';
|
||||||
|
import { BridgeDeliveryLog } from './bridge-delivery-log.js';
|
||||||
|
|
||||||
export type BridgeKind = 'stream' | 'poll' | 'ws';
|
export type BridgeKind = 'stream' | 'poll' | 'ws';
|
||||||
|
/**
|
||||||
|
* Wire-protocol kind tag for `/v1/bridge/presence`. Distinct from
|
||||||
|
* `BridgeKind` because the canonical signed payload is shaped
|
||||||
|
* differently (`watched: string[]` instead of `since: number`).
|
||||||
|
*/
|
||||||
|
export type PresenceKind = 'presence';
|
||||||
|
|
||||||
export interface BridgeRoutesOptions {
|
export interface BridgeRoutesOptions {
|
||||||
store: InboxStore;
|
store: InboxStore;
|
||||||
@@ -60,6 +68,23 @@ export interface BridgeRoutesOptions {
|
|||||||
* Default 1_000.
|
* Default 1_000.
|
||||||
*/
|
*/
|
||||||
fallbackPollIntervalMs?: number;
|
fallbackPollIntervalMs?: number;
|
||||||
|
/**
|
||||||
|
* Inject an existing presence tracker. Useful when multiple
|
||||||
|
* `createBridgeRoutes` calls need to share state (e.g. mounting the
|
||||||
|
* routes under several hostnames in a single process). When omitted,
|
||||||
|
* the bridge auto-creates an internal tracker bound to `events`.
|
||||||
|
*/
|
||||||
|
presenceTracker?: PresenceTracker;
|
||||||
|
/**
|
||||||
|
* V4.8.4 — shared bridge delivery log. After every successful WS /
|
||||||
|
* SSE push we record `(address, msgId, now)` here so the inbox-fetch
|
||||||
|
* route can suppress the same blob from a subsequent inbox-poll
|
||||||
|
* within the log's grace window. Pass the same instance to
|
||||||
|
* `createInboxRoutes` (or use the auto-created one returned in
|
||||||
|
* `bridgeRoutes.bridgeDeliveryLog`). When omitted, the bridge
|
||||||
|
* auto-creates its own log.
|
||||||
|
*/
|
||||||
|
bridgeDeliveryLog?: BridgeDeliveryLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface VerifiedBridgeRequest {
|
interface VerifiedBridgeRequest {
|
||||||
@@ -68,6 +93,13 @@ interface VerifiedBridgeRequest {
|
|||||||
since: number;
|
since: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface VerifiedPresenceRequest {
|
||||||
|
/** The watcher's address (signer of the request). */
|
||||||
|
address: string;
|
||||||
|
/** Addresses whose presence the watcher is asking to track. */
|
||||||
|
watched: string[];
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Build the bridge Hono router and a paired Bun-WebSocket handler.
|
* Build the bridge Hono router and a paired Bun-WebSocket handler.
|
||||||
*
|
*
|
||||||
@@ -80,6 +112,15 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
app: Hono;
|
app: Hono;
|
||||||
/** Pass to `Bun.serve({ websocket })`. Undefined if Bun adapter is missing. */
|
/** Pass to `Bun.serve({ websocket })`. Undefined if Bun adapter is missing. */
|
||||||
websocket: unknown;
|
websocket: unknown;
|
||||||
|
/** Live presence tracker. Tests + observers can read it; routes update it. */
|
||||||
|
presence: PresenceTracker;
|
||||||
|
/**
|
||||||
|
* V4.8.4 — the shared bridge-delivery log this router writes to on
|
||||||
|
* every successful push. Wire the same instance into
|
||||||
|
* `createInboxRoutes({ bridgeDeliveryLog })` so the inbox-fetch route
|
||||||
|
* can suppress recently-pushed blobs.
|
||||||
|
*/
|
||||||
|
bridgeDeliveryLog: BridgeDeliveryLog;
|
||||||
} {
|
} {
|
||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
const pageLimit = opts.pageLimit ?? 50;
|
const pageLimit = opts.pageLimit ?? 50;
|
||||||
@@ -87,6 +128,8 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
const longPollDefault = opts.longPollTimeoutMs ?? 25_000;
|
const longPollDefault = opts.longPollTimeoutMs ?? 25_000;
|
||||||
const longPollMax = opts.longPollMaxTimeoutMs ?? 55_000;
|
const longPollMax = opts.longPollMaxTimeoutMs ?? 55_000;
|
||||||
const fallbackPollIntervalMs = opts.fallbackPollIntervalMs ?? 1_000;
|
const fallbackPollIntervalMs = opts.fallbackPollIntervalMs ?? 1_000;
|
||||||
|
const presence = opts.presenceTracker ?? new PresenceTracker(opts.events ?? null);
|
||||||
|
const bridgeDeliveryLog = opts.bridgeDeliveryLog ?? new BridgeDeliveryLog();
|
||||||
|
|
||||||
app.onError((err, c) => {
|
app.onError((err, c) => {
|
||||||
if (err instanceof ShadeError) {
|
if (err instanceof ShadeError) {
|
||||||
@@ -102,17 +145,37 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
const verified = await verifyBridgeAuth(c, opts, 'stream');
|
const verified = await verifyBridgeAuth(c, opts, 'stream');
|
||||||
return streamSSE(c, async (stream) => {
|
return streamSSE(c, async (stream) => {
|
||||||
const address = verified.address;
|
const address = verified.address;
|
||||||
|
const connId = presence.newConnectionId();
|
||||||
|
presence.markConnected(address, 'sse', connId);
|
||||||
|
let presenceClosed = false;
|
||||||
|
const closePresence = (reason: 'closed' | 'error'): void => {
|
||||||
|
if (presenceClosed) return;
|
||||||
|
presenceClosed = true;
|
||||||
|
presence.markDisconnected(address, 'sse', connId, reason);
|
||||||
|
};
|
||||||
let cursor = verified.since;
|
let cursor = verified.since;
|
||||||
const writer = makeBlobWriter(opts.store, pageLimit);
|
const writer = makeBlobWriter(opts.store, pageLimit);
|
||||||
|
const delivered = new DeliveredIdLru();
|
||||||
|
|
||||||
|
const recordPush = (msgId: string): void => {
|
||||||
|
bridgeDeliveryLog.recordDelivered(address, msgId, Date.now());
|
||||||
|
};
|
||||||
|
|
||||||
// Initial backlog drain.
|
// Initial backlog drain.
|
||||||
const flushed = await flushTo(writer, address, cursor, async (blob) => {
|
const flushed = await flushTo(
|
||||||
await stream.writeSSE({
|
writer,
|
||||||
id: String(blob.receivedAt),
|
address,
|
||||||
event: 'envelope',
|
cursor,
|
||||||
data: JSON.stringify(serializeBlob(blob)),
|
async (blob) => {
|
||||||
});
|
await stream.writeSSE({
|
||||||
});
|
id: String(blob.receivedAt),
|
||||||
|
event: 'envelope',
|
||||||
|
data: JSON.stringify(serializeBlob(blob)),
|
||||||
|
});
|
||||||
|
recordPush(blob.msgId);
|
||||||
|
},
|
||||||
|
delivered,
|
||||||
|
);
|
||||||
cursor = Math.max(cursor, flushed);
|
cursor = Math.max(cursor, flushed);
|
||||||
|
|
||||||
// Hook up event-driven push if available, else fall back to a poll
|
// Hook up event-driven push if available, else fall back to a poll
|
||||||
@@ -124,19 +187,32 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
const triggerFlush = (): void => {
|
const triggerFlush = (): void => {
|
||||||
signalled = true;
|
signalled = true;
|
||||||
// Serialize fan-in so concurrent triggers don't double-fetch.
|
// Serialize fan-in so concurrent triggers don't double-fetch.
|
||||||
pendingFlushPromise = pendingFlushPromise.then(async () => {
|
// `.catch(() => {})` keeps the chain alive across transient
|
||||||
while (signalled) {
|
// emit failures (e.g. a closed SSE write throws) — without it
|
||||||
signalled = false;
|
// one rejection silently kills every future flush on this
|
||||||
const drained = await flushTo(writer, address, cursor, async (blob) => {
|
// connection.
|
||||||
await stream.writeSSE({
|
pendingFlushPromise = pendingFlushPromise
|
||||||
id: String(blob.receivedAt),
|
.then(async () => {
|
||||||
event: 'envelope',
|
while (signalled) {
|
||||||
data: JSON.stringify(serializeBlob(blob)),
|
signalled = false;
|
||||||
});
|
const drained = await flushTo(
|
||||||
});
|
writer,
|
||||||
if (drained > cursor) cursor = drained;
|
address,
|
||||||
}
|
cursor,
|
||||||
});
|
async (blob) => {
|
||||||
|
await stream.writeSSE({
|
||||||
|
id: String(blob.receivedAt),
|
||||||
|
event: 'envelope',
|
||||||
|
data: JSON.stringify(serializeBlob(blob)),
|
||||||
|
});
|
||||||
|
recordPush(blob.msgId);
|
||||||
|
},
|
||||||
|
delivered,
|
||||||
|
);
|
||||||
|
if (drained > cursor) cursor = drained;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
};
|
};
|
||||||
|
|
||||||
if (opts.events) {
|
if (opts.events) {
|
||||||
@@ -163,6 +239,68 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
clearInterval(fallbackTimer);
|
clearInterval(fallbackTimer);
|
||||||
clearInterval(heartbeat);
|
clearInterval(heartbeat);
|
||||||
await pendingFlushPromise.catch(() => {});
|
await pendingFlushPromise.catch(() => {});
|
||||||
|
closePresence('closed');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Presence (V4.7) ──────────────────────────────────────────
|
||||||
|
// SSE feed of `peer_connected` / `peer_disconnected` events filtered
|
||||||
|
// by a watcher-supplied address list. Subscribing does NOT count as
|
||||||
|
// a peer-bridge connection (it doesn't call `markConnected`) so
|
||||||
|
// monitoring presence doesn't make you appear online to others.
|
||||||
|
app.get('/v1/bridge/presence', async (c) => {
|
||||||
|
const verified = await verifyPresenceAuth(c, opts);
|
||||||
|
return streamSSE(c, async (stream) => {
|
||||||
|
const watched = new Set(verified.watched);
|
||||||
|
|
||||||
|
// Initial snapshot — one frame per watched address with current
|
||||||
|
// status. Lets subscribers render UI immediately rather than
|
||||||
|
// waiting for the next state change.
|
||||||
|
const now = Date.now();
|
||||||
|
for (const addr of verified.watched) {
|
||||||
|
await stream.writeSSE({
|
||||||
|
event: 'presence',
|
||||||
|
data: JSON.stringify({
|
||||||
|
address: addr,
|
||||||
|
status: presence.isOnline(addr) ? 'online' : 'offline',
|
||||||
|
at: now,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
let unsubscribe: (() => void) | null = null;
|
||||||
|
if (opts.events) {
|
||||||
|
unsubscribe = opts.events.on((e) => {
|
||||||
|
if (e.name !== 'inbox.peer_connected' && e.name !== 'inbox.peer_disconnected') return;
|
||||||
|
const data = e.data as { address: string; bridgeKind: TrackedBridgeKind };
|
||||||
|
if (!watched.has(data.address)) return;
|
||||||
|
const status = e.name === 'inbox.peer_connected' ? 'online' : 'offline';
|
||||||
|
// Fire-and-forget: drop the frame if the stream has gone away.
|
||||||
|
void stream
|
||||||
|
.writeSSE({
|
||||||
|
event: 'presence',
|
||||||
|
data: JSON.stringify({
|
||||||
|
address: data.address,
|
||||||
|
status,
|
||||||
|
at: e.timestamp,
|
||||||
|
via: data.bridgeKind,
|
||||||
|
}),
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const heartbeat = setInterval(() => {
|
||||||
|
stream.write(`: ping ${Date.now()}\n\n`).catch(() => {});
|
||||||
|
}, heartbeatIntervalMs);
|
||||||
|
|
||||||
|
await new Promise<void>((resolve) => {
|
||||||
|
const sig = c.req.raw.signal;
|
||||||
|
if (sig.aborted) return resolve();
|
||||||
|
sig.addEventListener('abort', () => resolve(), { once: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
unsubscribe?.();
|
||||||
|
clearInterval(heartbeat);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -183,6 +321,8 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
limit: pageLimit,
|
limit: pageLimit,
|
||||||
});
|
});
|
||||||
if (blobs.length > 0) {
|
if (blobs.length > 0) {
|
||||||
|
const now = Date.now();
|
||||||
|
for (const b of blobs) bridgeDeliveryLog.recordDelivered(verified.address, b.msgId, now);
|
||||||
return c.json(buildPollResponse(blobs, verified.since));
|
return c.json(buildPollResponse(blobs, verified.since));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,6 +337,8 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
fallbackPollIntervalMs,
|
fallbackPollIntervalMs,
|
||||||
abortSignal: c.req.raw.signal,
|
abortSignal: c.req.raw.signal,
|
||||||
});
|
});
|
||||||
|
const now = Date.now();
|
||||||
|
for (const b of blobs) bridgeDeliveryLog.recordDelivered(verified.address, b.msgId, now);
|
||||||
return c.json(buildPollResponse(blobs, verified.since));
|
return c.json(buildPollResponse(blobs, verified.since));
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -230,30 +372,51 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const address = verified.address;
|
const address = verified.address;
|
||||||
|
const connId = presence.newConnectionId();
|
||||||
let cursor = verified.since;
|
let cursor = verified.since;
|
||||||
const writer = makeBlobWriter(opts.store, pageLimit);
|
const writer = makeBlobWriter(opts.store, pageLimit);
|
||||||
|
const delivered = new DeliveredIdLru();
|
||||||
let unsubscribe: (() => void) | null = null;
|
let unsubscribe: (() => void) | null = null;
|
||||||
let fallbackTimer: ReturnType<typeof setInterval> | null = null;
|
let fallbackTimer: ReturnType<typeof setInterval> | null = null;
|
||||||
let pendingFlushPromise: Promise<void> = Promise.resolve();
|
let pendingFlushPromise: Promise<void> = Promise.resolve();
|
||||||
let signalled = false;
|
let signalled = false;
|
||||||
let connected = true;
|
let connected = true;
|
||||||
|
let presenceClosed = false;
|
||||||
|
const closePresence = (reason: 'closed' | 'error'): void => {
|
||||||
|
if (presenceClosed) return;
|
||||||
|
presenceClosed = true;
|
||||||
|
presence.markDisconnected(address, 'ws', connId, reason);
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
onOpen(_evt: unknown, ws: {
|
onOpen(_evt: unknown, ws: {
|
||||||
send: (data: string) => void;
|
send: (data: string) => void;
|
||||||
close: (code?: number, reason?: string) => void;
|
close: (code?: number, reason?: string) => void;
|
||||||
}) {
|
}) {
|
||||||
|
presence.markConnected(address, 'ws', connId);
|
||||||
const triggerFlush = (): void => {
|
const triggerFlush = (): void => {
|
||||||
signalled = true;
|
signalled = true;
|
||||||
pendingFlushPromise = pendingFlushPromise.then(async () => {
|
// `.catch(() => {})` mirrors the SSE chain — keeps the
|
||||||
while (signalled && connected) {
|
// pending-flush queue alive across transient ws.send errors
|
||||||
signalled = false;
|
// (e.g. partial close, backpressure overflow).
|
||||||
const drained = await flushTo(writer, address, cursor, async (blob) => {
|
pendingFlushPromise = pendingFlushPromise
|
||||||
ws.send(JSON.stringify(serializeBlob(blob)));
|
.then(async () => {
|
||||||
});
|
while (signalled && connected) {
|
||||||
if (drained > cursor) cursor = drained;
|
signalled = false;
|
||||||
}
|
const drained = await flushTo(
|
||||||
});
|
writer,
|
||||||
|
address,
|
||||||
|
cursor,
|
||||||
|
async (blob) => {
|
||||||
|
ws.send(JSON.stringify(serializeBlob(blob)));
|
||||||
|
bridgeDeliveryLog.recordDelivered(address, blob.msgId, Date.now());
|
||||||
|
},
|
||||||
|
delivered,
|
||||||
|
);
|
||||||
|
if (drained > cursor) cursor = drained;
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
};
|
};
|
||||||
if (opts.events) {
|
if (opts.events) {
|
||||||
unsubscribe = opts.events.on((e) => {
|
unsubscribe = opts.events.on((e) => {
|
||||||
@@ -269,12 +432,19 @@ export function createBridgeRoutes(opts: BridgeRoutesOptions): {
|
|||||||
connected = false;
|
connected = false;
|
||||||
unsubscribe?.();
|
unsubscribe?.();
|
||||||
if (fallbackTimer) clearInterval(fallbackTimer);
|
if (fallbackTimer) clearInterval(fallbackTimer);
|
||||||
|
closePresence('closed');
|
||||||
|
},
|
||||||
|
onError() {
|
||||||
|
connected = false;
|
||||||
|
unsubscribe?.();
|
||||||
|
if (fallbackTimer) clearInterval(fallbackTimer);
|
||||||
|
closePresence('error');
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
return { app, websocket };
|
return { app, websocket, presence, bridgeDeliveryLog };
|
||||||
}
|
}
|
||||||
|
|
||||||
// ─── helpers ──────────────────────────────────────────────────
|
// ─── helpers ──────────────────────────────────────────────────
|
||||||
@@ -321,11 +491,75 @@ async function verifyBridgeAuth(
|
|||||||
return { address, kind: kind as BridgeKind, since };
|
return { address, kind: kind as BridgeKind, since };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const MAX_WATCHED_ADDRESSES = 64;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify a `/v1/bridge/presence` request.
|
||||||
|
*
|
||||||
|
* Signed canonical payload: `{address, kind: 'presence', watched: string[],
|
||||||
|
* signedAt}`. The watcher's address must be a registered inbox; the
|
||||||
|
* signature is verified against the registered owner key for that
|
||||||
|
* address. The `watched` list bounds what the subscription will
|
||||||
|
* receive — server-side filtering is enforced inside the handler.
|
||||||
|
*/
|
||||||
|
async function verifyPresenceAuth(
|
||||||
|
c: Context,
|
||||||
|
opts: BridgeRoutesOptions,
|
||||||
|
): Promise<VerifiedPresenceRequest> {
|
||||||
|
const url = new URL(c.req.url);
|
||||||
|
const qs = url.searchParams;
|
||||||
|
const address = validateAddress(qs.get('address'));
|
||||||
|
const kind = qs.get('kind');
|
||||||
|
if (kind !== 'presence') {
|
||||||
|
throw new ValidationError(`bridge kind mismatch: expected presence`, 'kind');
|
||||||
|
}
|
||||||
|
const watchedRaw = qs.get('watched');
|
||||||
|
if (watchedRaw === null) throw new ValidationError('missing watched', 'watched');
|
||||||
|
// Empty subscription is allowed (subscribe to nothing — useful for a
|
||||||
|
// client that intends to call addPeer right after open). A null/
|
||||||
|
// missing param is still rejected so the canonicalization is
|
||||||
|
// unambiguous.
|
||||||
|
const watched =
|
||||||
|
watchedRaw === ''
|
||||||
|
? []
|
||||||
|
: watchedRaw.split(',').map((a) => validateAddress(a));
|
||||||
|
if (watched.length > MAX_WATCHED_ADDRESSES) {
|
||||||
|
throw new ValidationError(
|
||||||
|
`watched list too large: ${watched.length} > ${MAX_WATCHED_ADDRESSES}`,
|
||||||
|
'watched',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
const signedAtStr = qs.get('signedAt');
|
||||||
|
const signature = qs.get('signature');
|
||||||
|
if (signedAtStr === null) throw new ValidationError('missing signedAt', 'signedAt');
|
||||||
|
if (!signature) throw new ValidationError('missing signature', 'signature');
|
||||||
|
const signedAt = Number(signedAtStr);
|
||||||
|
if (!Number.isFinite(signedAt)) {
|
||||||
|
throw new ValidationError('signedAt must be a number', 'signedAt');
|
||||||
|
}
|
||||||
|
|
||||||
|
const owner = await opts.store.getAddressOwner(address);
|
||||||
|
if (!owner) {
|
||||||
|
throw new UnauthorizedError(`address ${address} is not registered`);
|
||||||
|
}
|
||||||
|
|
||||||
|
await verifyPayload(opts.crypto, owner, {
|
||||||
|
address,
|
||||||
|
kind,
|
||||||
|
watched,
|
||||||
|
signedAt,
|
||||||
|
signature,
|
||||||
|
});
|
||||||
|
return { address, watched };
|
||||||
|
}
|
||||||
|
|
||||||
interface BlobRow {
|
interface BlobRow {
|
||||||
msgId: string;
|
msgId: string;
|
||||||
ciphertext: Uint8Array;
|
ciphertext: Uint8Array;
|
||||||
receivedAt: number;
|
receivedAt: number;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
/** V4.8 — relay-captured sender fingerprint. Optional for legacy rows. */
|
||||||
|
senderFp?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
interface BlobWriter {
|
interface BlobWriter {
|
||||||
@@ -345,11 +579,41 @@ function makeBlobWriter(store: InboxStore, pageLimit: number): BlobWriter {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Per-connection bounded msgId tracker — defense in depth against duplicate
|
||||||
|
* delivery of the same blob to the same bridge socket. Cursor pagination
|
||||||
|
* already guarantees uniqueness in the happy path, but a dedup gate at the
|
||||||
|
* emit boundary catches any subtle bug (e.g. a flushTo race, a future
|
||||||
|
* refactor, an event-emit retry) without changing wire semantics.
|
||||||
|
*
|
||||||
|
* The cap is intentionally large enough to cover any realistic bridge
|
||||||
|
* pageLimit and small enough to bound memory under long-running streams.
|
||||||
|
*/
|
||||||
|
const DELIVERED_LRU_CAP = 4096;
|
||||||
|
|
||||||
|
class DeliveredIdLru {
|
||||||
|
private readonly seen = new Set<string>();
|
||||||
|
private readonly order: string[] = [];
|
||||||
|
|
||||||
|
/** Returns true if `msgId` has not been seen on this connection yet. */
|
||||||
|
add(msgId: string): boolean {
|
||||||
|
if (this.seen.has(msgId)) return false;
|
||||||
|
this.seen.add(msgId);
|
||||||
|
this.order.push(msgId);
|
||||||
|
if (this.order.length > DELIVERED_LRU_CAP) {
|
||||||
|
const evicted = this.order.shift()!;
|
||||||
|
this.seen.delete(evicted);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function flushTo(
|
async function flushTo(
|
||||||
writer: BlobWriter,
|
writer: BlobWriter,
|
||||||
address: string,
|
address: string,
|
||||||
startCursor: number,
|
startCursor: number,
|
||||||
emit: (blob: BlobRow) => Promise<void>,
|
emit: (blob: BlobRow) => Promise<void>,
|
||||||
|
delivered?: DeliveredIdLru,
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
let cursor = startCursor;
|
let cursor = startCursor;
|
||||||
// Drain page-by-page so a backlog larger than `pageLimit` still flushes.
|
// Drain page-by-page so a backlog larger than `pageLimit` still flushes.
|
||||||
@@ -358,7 +622,12 @@ async function flushTo(
|
|||||||
const page = await writer.fetchPage(address, cursor);
|
const page = await writer.fetchPage(address, cursor);
|
||||||
if (page.length === 0) break;
|
if (page.length === 0) break;
|
||||||
for (const row of page) {
|
for (const row of page) {
|
||||||
await emit(row);
|
// Per-connection dedup gate — prevents the same msgId from being
|
||||||
|
// emitted twice if flushTo is somehow re-entered before the cursor
|
||||||
|
// catches up. See comment on `DeliveredIdLru`.
|
||||||
|
if (!delivered || delivered.add(row.msgId)) {
|
||||||
|
await emit(row);
|
||||||
|
}
|
||||||
if (row.receivedAt > cursor) cursor = row.receivedAt;
|
if (row.receivedAt > cursor) cursor = row.receivedAt;
|
||||||
}
|
}
|
||||||
if (page.length === 0) break;
|
if (page.length === 0) break;
|
||||||
@@ -371,13 +640,26 @@ function serializeBlob(blob: BlobRow): {
|
|||||||
ciphertext: string;
|
ciphertext: string;
|
||||||
receivedAt: number;
|
receivedAt: number;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
from?: string;
|
||||||
} {
|
} {
|
||||||
return {
|
const out: {
|
||||||
|
msgId: string;
|
||||||
|
ciphertext: string;
|
||||||
|
receivedAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
from?: string;
|
||||||
|
} = {
|
||||||
msgId: blob.msgId,
|
msgId: blob.msgId,
|
||||||
ciphertext: toBase64(blob.ciphertext),
|
ciphertext: toBase64(blob.ciphertext),
|
||||||
receivedAt: blob.receivedAt,
|
receivedAt: blob.receivedAt,
|
||||||
expiresAt: blob.expiresAt,
|
expiresAt: blob.expiresAt,
|
||||||
};
|
};
|
||||||
|
// V4.8 — relay-captured sender fingerprint. The transport-bridge
|
||||||
|
// wire format already accepts `from`; populating it lets receivers
|
||||||
|
// bootstrap unknown-sender first-contact via `shade.receive('fp:<hex>',
|
||||||
|
// env)` without requiring an out-of-band sender hint.
|
||||||
|
if (blob.senderFp) out.from = blob.senderFp;
|
||||||
|
return out;
|
||||||
}
|
}
|
||||||
|
|
||||||
function buildPollResponse(blobs: BlobRow[], sinceFallback: number): {
|
function buildPollResponse(blobs: BlobRow[], sinceFallback: number): {
|
||||||
|
|||||||
@@ -21,6 +21,19 @@ export interface InboxServerEventMap {
|
|||||||
'inbox.expired_purged': { count: number };
|
'inbox.expired_purged': { count: number };
|
||||||
'inbox.rate_limited': { route: string; key: string };
|
'inbox.rate_limited': { route: string; key: string };
|
||||||
'inbox.quota_rejected': { address: string; reason: 'address-quota' | 'sender-quota' | 'body-too-large' };
|
'inbox.quota_rejected': { address: string; reason: 'address-quota' | 'sender-quota' | 'body-too-large' };
|
||||||
|
// V4.7 — bridge presence transitions. Emitted on the 0↔1 boundary
|
||||||
|
// across tracked transports for a given address. Long-poll is
|
||||||
|
// intentionally NOT tracked: an LP client toggles in/out of a request
|
||||||
|
// every few seconds, and the resulting flapping would dominate the
|
||||||
|
// event stream. Push transports (WS, SSE) are also the only ones
|
||||||
|
// where the ~50ms revoke window for `BroadcastChannel.removeMember`
|
||||||
|
// matters — long-poll users are already on a slow path.
|
||||||
|
'inbox.peer_connected': { address: string; bridgeKind: 'ws' | 'sse' };
|
||||||
|
'inbox.peer_disconnected': {
|
||||||
|
address: string;
|
||||||
|
bridgeKind: 'ws' | 'sse';
|
||||||
|
reason: 'closed' | 'error';
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
export type InboxServerEventName = keyof InboxServerEventMap;
|
export type InboxServerEventName = keyof InboxServerEventMap;
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
import type { Hono } from 'hono';
|
import { Hono } from 'hono';
|
||||||
import type { CryptoProvider } from '@shade/core';
|
import type { CryptoProvider } from '@shade/core';
|
||||||
import { createInboxRoutes, type InboxRoutesOptions } from './routes.js';
|
import { createInboxRoutes, type InboxRoutesOptions } from './routes.js';
|
||||||
import { MemoryInboxStore } from './memory-store.js';
|
import { MemoryInboxStore } from './memory-store.js';
|
||||||
import type { InboxStore } from './store.js';
|
import type { InboxStore } from './store.js';
|
||||||
import { InboxServerEvents } from './events.js';
|
import { InboxServerEvents } from './events.js';
|
||||||
|
import { createBlobRoutes, type BlobRoutesOptions } from './blob-routes.js';
|
||||||
|
import { MemoryBlobStore } from './memory-blob-store.js';
|
||||||
|
import type { BlobStore } from './blob-store.js';
|
||||||
|
|
||||||
export { createInboxRoutes } from './routes.js';
|
export { createInboxRoutes } from './routes.js';
|
||||||
export type { InboxRoutesOptions } from './routes.js';
|
export type { InboxRoutesOptions } from './routes.js';
|
||||||
@@ -32,6 +35,14 @@ export {
|
|||||||
export type { InboxQuotaConfig } from './quota.js';
|
export type { InboxQuotaConfig } from './quota.js';
|
||||||
export { createBridgeRoutes } from './bridge.js';
|
export { createBridgeRoutes } from './bridge.js';
|
||||||
export type { BridgeRoutesOptions, BridgeKind } from './bridge.js';
|
export type { BridgeRoutesOptions, BridgeKind } from './bridge.js';
|
||||||
|
export { PresenceTracker } from './presence.js';
|
||||||
|
export type { TrackedBridgeKind } from './presence.js';
|
||||||
|
export { BridgeDeliveryLog } from './bridge-delivery-log.js';
|
||||||
|
export type { BridgeDeliveryLogOptions } from './bridge-delivery-log.js';
|
||||||
|
export { createBlobRoutes, DEFAULT_MAX_BLOB_BYTES } from './blob-routes.js';
|
||||||
|
export type { BlobRoutesOptions } from './blob-routes.js';
|
||||||
|
export { MemoryBlobStore } from './memory-blob-store.js';
|
||||||
|
export type { BlobStore, BlobSlotRecord, PutBlobResult } from './blob-store.js';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Create a standalone Shade Inbox Server.
|
* Create a standalone Shade Inbox Server.
|
||||||
@@ -44,17 +55,45 @@ export type { BridgeRoutesOptions, BridgeKind } from './bridge.js';
|
|||||||
* const app = new Hono();
|
* const app = new Hono();
|
||||||
* app.route('/', createInboxServer({ crypto }));
|
* app.route('/', createInboxServer({ crypto }));
|
||||||
*/
|
*/
|
||||||
export function createInboxServer(options: {
|
export function createInboxServer(
|
||||||
crypto: CryptoProvider;
|
options: {
|
||||||
store?: InboxStore;
|
crypto: CryptoProvider;
|
||||||
disableRateLimit?: boolean;
|
store?: InboxStore;
|
||||||
events?: InboxServerEvents;
|
disableRateLimit?: boolean;
|
||||||
} & Pick<InboxRoutesOptions, 'observability' | 'quota'>): Hono {
|
events?: InboxServerEvents;
|
||||||
|
/**
|
||||||
|
* V4.9 — when supplied, mounts the encrypted-blob primitive
|
||||||
|
* (`/v1/blob/<slotId>`) on the same Hono app. Pass `null` to
|
||||||
|
* explicitly opt out; omit to default to a `MemoryBlobStore`.
|
||||||
|
*/
|
||||||
|
blobStore?: BlobStore | null;
|
||||||
|
blobOptions?: Pick<BlobRoutesOptions, 'maxBlobBytes'>;
|
||||||
|
} & Pick<InboxRoutesOptions, 'observability' | 'quota' | 'bridgeDeliveryLog'>,
|
||||||
|
): Hono {
|
||||||
const store = options.store ?? new MemoryInboxStore();
|
const store = options.store ?? new MemoryInboxStore();
|
||||||
const routesOptions: InboxRoutesOptions = {};
|
const routesOptions: InboxRoutesOptions = {};
|
||||||
if (options.disableRateLimit !== undefined) routesOptions.disableRateLimit = options.disableRateLimit;
|
if (options.disableRateLimit !== undefined) routesOptions.disableRateLimit = options.disableRateLimit;
|
||||||
if (options.events !== undefined) routesOptions.events = options.events;
|
if (options.events !== undefined) routesOptions.events = options.events;
|
||||||
if (options.observability !== undefined) routesOptions.observability = options.observability;
|
if (options.observability !== undefined) routesOptions.observability = options.observability;
|
||||||
if (options.quota !== undefined) routesOptions.quota = options.quota;
|
if (options.quota !== undefined) routesOptions.quota = options.quota;
|
||||||
return createInboxRoutes(store, options.crypto, routesOptions);
|
if (options.bridgeDeliveryLog !== undefined) routesOptions.bridgeDeliveryLog = options.bridgeDeliveryLog;
|
||||||
|
|
||||||
|
const inboxApp = createInboxRoutes(store, options.crypto, routesOptions);
|
||||||
|
|
||||||
|
// Compose with the blob primitive unless explicitly disabled. The
|
||||||
|
// blob routes share the same Hono app so a single port serves both.
|
||||||
|
if (options.blobStore === null) return inboxApp;
|
||||||
|
const blobStore = options.blobStore ?? new MemoryBlobStore();
|
||||||
|
const blobRoutesOptions: BlobRoutesOptions = {};
|
||||||
|
if (options.disableRateLimit !== undefined) blobRoutesOptions.disableRateLimit = options.disableRateLimit;
|
||||||
|
if (options.observability !== undefined) blobRoutesOptions.observability = options.observability;
|
||||||
|
if (options.blobOptions?.maxBlobBytes !== undefined) {
|
||||||
|
blobRoutesOptions.maxBlobBytes = options.blobOptions.maxBlobBytes;
|
||||||
|
}
|
||||||
|
const blobApp = createBlobRoutes(blobStore, options.crypto, blobRoutesOptions);
|
||||||
|
|
||||||
|
const composed = new Hono();
|
||||||
|
composed.route('/', inboxApp);
|
||||||
|
composed.route('/', blobApp);
|
||||||
|
return composed;
|
||||||
}
|
}
|
||||||
|
|||||||
85
packages/shade-inbox-server/src/memory-blob-store.ts
Normal file
85
packages/shade-inbox-server/src/memory-blob-store.ts
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
import { ConflictError, PreconditionFailedError } from '@shade/core';
|
||||||
|
import type { BlobStore, BlobSlotRecord, PutBlobResult } from './blob-store.js';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* In-memory BlobStore — used in tests and as the default fallback when
|
||||||
|
* no SQLite/Postgres URL is configured. Rows are kept in a single Map.
|
||||||
|
*
|
||||||
|
* Etag is a strictly-monotonic per-process counter — guarantees a total
|
||||||
|
* order across writes even when many land in the same millisecond. (We
|
||||||
|
* could scope it per-slot, but a global counter keeps the implementation
|
||||||
|
* trivial and the etag values still uniquely identify the write that
|
||||||
|
* produced them, which is all CAS needs.)
|
||||||
|
*/
|
||||||
|
export class MemoryBlobStore implements BlobStore {
|
||||||
|
private slots = new Map<string, BlobSlotRecord>();
|
||||||
|
private nextEtag = 0;
|
||||||
|
|
||||||
|
async get(slotId: string): Promise<BlobSlotRecord | null> {
|
||||||
|
const r = this.slots.get(slotId);
|
||||||
|
if (!r) return null;
|
||||||
|
return {
|
||||||
|
slotId: r.slotId,
|
||||||
|
blob: new Uint8Array(r.blob),
|
||||||
|
ownerPubkey: new Uint8Array(r.ownerPubkey),
|
||||||
|
etag: r.etag,
|
||||||
|
updatedAt: r.updatedAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async put(args: {
|
||||||
|
slotId: string;
|
||||||
|
blob: Uint8Array;
|
||||||
|
ownerPubkey: Uint8Array;
|
||||||
|
expectedEtag: number | '*' | undefined;
|
||||||
|
now: number;
|
||||||
|
}): Promise<PutBlobResult> {
|
||||||
|
const existing = this.slots.get(args.slotId);
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
// Empty slot. `ifMatch: '*'` per RFC 7232 still fails — there is
|
||||||
|
// no entity to match. A numeric etag also fails (we have nothing
|
||||||
|
// to compare against).
|
||||||
|
if (args.expectedEtag !== undefined) {
|
||||||
|
throw new PreconditionFailedError(
|
||||||
|
`Slot ${args.slotId} does not exist; cannot match ifMatch=${String(args.expectedEtag)}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
this.nextEtag = Math.max(this.nextEtag + 1, args.now);
|
||||||
|
const etag = this.nextEtag;
|
||||||
|
this.slots.set(args.slotId, {
|
||||||
|
slotId: args.slotId,
|
||||||
|
blob: new Uint8Array(args.blob),
|
||||||
|
ownerPubkey: new Uint8Array(args.ownerPubkey),
|
||||||
|
etag,
|
||||||
|
updatedAt: args.now,
|
||||||
|
});
|
||||||
|
return { created: true, etag, updatedAt: args.now };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slot exists. Pubkey check is the route layer's job — by the time
|
||||||
|
// we're here the signature has already been verified against
|
||||||
|
// `existing.ownerPubkey`.
|
||||||
|
if (args.expectedEtag === undefined) {
|
||||||
|
throw new ConflictError(
|
||||||
|
`Slot ${args.slotId} already exists; supply ifMatch to update`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (args.expectedEtag !== '*' && args.expectedEtag !== existing.etag) {
|
||||||
|
throw new PreconditionFailedError(
|
||||||
|
`Slot ${args.slotId} etag mismatch: expected=${args.expectedEtag} actual=${existing.etag}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
this.nextEtag = Math.max(this.nextEtag + 1, args.now);
|
||||||
|
const etag = this.nextEtag;
|
||||||
|
existing.blob = new Uint8Array(args.blob);
|
||||||
|
existing.etag = etag;
|
||||||
|
existing.updatedAt = args.now;
|
||||||
|
return { created: false, etag, updatedAt: args.now };
|
||||||
|
}
|
||||||
|
|
||||||
|
async delete(slotId: string): Promise<boolean> {
|
||||||
|
return this.slots.delete(slotId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ interface BlobRow {
|
|||||||
ciphertext: Uint8Array;
|
ciphertext: Uint8Array;
|
||||||
receivedAt: number;
|
receivedAt: number;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
senderFp?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -33,6 +34,7 @@ export class MemoryInboxStore implements InboxStore {
|
|||||||
msgId: string;
|
msgId: string;
|
||||||
ciphertext: Uint8Array;
|
ciphertext: Uint8Array;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
senderFp?: string;
|
||||||
}): Promise<{ created: boolean; receivedAt: number }> {
|
}): Promise<{ created: boolean; receivedAt: number }> {
|
||||||
const list = this.blobs.get(args.address) ?? [];
|
const list = this.blobs.get(args.address) ?? [];
|
||||||
const existing = list.find((r) => r.msgId === args.msgId);
|
const existing = list.find((r) => r.msgId === args.msgId);
|
||||||
@@ -41,12 +43,14 @@ export class MemoryInboxStore implements InboxStore {
|
|||||||
// multiple blobs land in the same millisecond.
|
// multiple blobs land in the same millisecond.
|
||||||
const receivedAt = Math.max(this.nextReceivedAt + 1, Date.now());
|
const receivedAt = Math.max(this.nextReceivedAt + 1, Date.now());
|
||||||
this.nextReceivedAt = receivedAt;
|
this.nextReceivedAt = receivedAt;
|
||||||
list.push({
|
const row: BlobRow = {
|
||||||
msgId: args.msgId,
|
msgId: args.msgId,
|
||||||
ciphertext: new Uint8Array(args.ciphertext),
|
ciphertext: new Uint8Array(args.ciphertext),
|
||||||
receivedAt,
|
receivedAt,
|
||||||
expiresAt: args.expiresAt,
|
expiresAt: args.expiresAt,
|
||||||
});
|
};
|
||||||
|
if (args.senderFp !== undefined) row.senderFp = args.senderFp;
|
||||||
|
list.push(row);
|
||||||
this.blobs.set(args.address, list);
|
this.blobs.set(args.address, list);
|
||||||
return { created: true, receivedAt };
|
return { created: true, receivedAt };
|
||||||
}
|
}
|
||||||
@@ -56,18 +60,36 @@ export class MemoryInboxStore implements InboxStore {
|
|||||||
sinceCursor: number;
|
sinceCursor: number;
|
||||||
now: number;
|
now: number;
|
||||||
limit: number;
|
limit: number;
|
||||||
}): Promise<Array<{ msgId: string; ciphertext: Uint8Array; receivedAt: number; expiresAt: number }>> {
|
}): Promise<
|
||||||
|
Array<{
|
||||||
|
msgId: string;
|
||||||
|
ciphertext: Uint8Array;
|
||||||
|
receivedAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
senderFp?: string;
|
||||||
|
}>
|
||||||
|
> {
|
||||||
const list = this.blobs.get(args.address) ?? [];
|
const list = this.blobs.get(args.address) ?? [];
|
||||||
return list
|
return list
|
||||||
.filter((r) => r.receivedAt > args.sinceCursor && r.expiresAt > args.now)
|
.filter((r) => r.receivedAt > args.sinceCursor && r.expiresAt > args.now)
|
||||||
.sort((a, b) => a.receivedAt - b.receivedAt)
|
.sort((a, b) => a.receivedAt - b.receivedAt)
|
||||||
.slice(0, args.limit)
|
.slice(0, args.limit)
|
||||||
.map((r) => ({
|
.map((r) => {
|
||||||
msgId: r.msgId,
|
const out: {
|
||||||
ciphertext: new Uint8Array(r.ciphertext),
|
msgId: string;
|
||||||
receivedAt: r.receivedAt,
|
ciphertext: Uint8Array;
|
||||||
expiresAt: r.expiresAt,
|
receivedAt: number;
|
||||||
}));
|
expiresAt: number;
|
||||||
|
senderFp?: string;
|
||||||
|
} = {
|
||||||
|
msgId: r.msgId,
|
||||||
|
ciphertext: new Uint8Array(r.ciphertext),
|
||||||
|
receivedAt: r.receivedAt,
|
||||||
|
expiresAt: r.expiresAt,
|
||||||
|
};
|
||||||
|
if (r.senderFp !== undefined) out.senderFp = r.senderFp;
|
||||||
|
return out;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteBlob(address: string, msgId: string): Promise<boolean> {
|
async deleteBlob(address: string, msgId: string): Promise<boolean> {
|
||||||
|
|||||||
75
packages/shade-inbox-server/src/presence.ts
Normal file
75
packages/shade-inbox-server/src/presence.ts
Normal file
@@ -0,0 +1,75 @@
|
|||||||
|
/**
|
||||||
|
* V4.7 — bridge-connection presence tracking.
|
||||||
|
*
|
||||||
|
* The bridge handlers (`/v1/bridge/stream` and `/v1/bridge/ws`) call
|
||||||
|
* `markConnected` on open and `markDisconnected` on close. The tracker
|
||||||
|
* keeps a per-address set of connection ids; the `inbox.peer_connected`
|
||||||
|
* / `inbox.peer_disconnected` events fire only on the 0↔1 boundary so
|
||||||
|
* that two simultaneous bridges (e.g. SSE + WS during a transport-
|
||||||
|
* fallback handover) collapse into a single connected/disconnected
|
||||||
|
* pair from the consumer's point of view.
|
||||||
|
*
|
||||||
|
* Long-poll (`/v1/bridge/poll`) is intentionally NOT tracked — see the
|
||||||
|
* note on `InboxServerEventMap` in `events.ts`.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import type { InboxServerEvents } from './events.js';
|
||||||
|
|
||||||
|
export type TrackedBridgeKind = 'ws' | 'sse';
|
||||||
|
|
||||||
|
export class PresenceTracker {
|
||||||
|
private readonly connections = new Map<string, Set<string>>();
|
||||||
|
private nextConnId = 1;
|
||||||
|
|
||||||
|
constructor(private readonly events: InboxServerEvents | null) {}
|
||||||
|
|
||||||
|
/** Allocate a fresh connection id for `markConnected` / `markDisconnected`. */
|
||||||
|
newConnectionId(): string {
|
||||||
|
return `c${this.nextConnId++}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Snapshot: is `address` currently connected over any tracked transport?
|
||||||
|
* Used by `/v1/bridge/presence` to push the initial state to a new
|
||||||
|
* subscriber.
|
||||||
|
*/
|
||||||
|
isOnline(address: string): boolean {
|
||||||
|
const set = this.connections.get(address);
|
||||||
|
return set !== undefined && set.size > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
markConnected(address: string, bridgeKind: TrackedBridgeKind, connectionId: string): void {
|
||||||
|
let set = this.connections.get(address);
|
||||||
|
const wasOnline = set !== undefined && set.size > 0;
|
||||||
|
if (!set) {
|
||||||
|
set = new Set();
|
||||||
|
this.connections.set(address, set);
|
||||||
|
}
|
||||||
|
set.add(connectionId);
|
||||||
|
if (!wasOnline) {
|
||||||
|
this.events?.emit('inbox.peer_connected', { address, bridgeKind });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
markDisconnected(
|
||||||
|
address: string,
|
||||||
|
bridgeKind: TrackedBridgeKind,
|
||||||
|
connectionId: string,
|
||||||
|
reason: 'closed' | 'error',
|
||||||
|
): void {
|
||||||
|
const set = this.connections.get(address);
|
||||||
|
if (!set) return;
|
||||||
|
if (!set.delete(connectionId)) return;
|
||||||
|
if (set.size === 0) {
|
||||||
|
this.connections.delete(address);
|
||||||
|
this.events?.emit('inbox.peer_disconnected', { address, bridgeKind, reason });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Inspect the underlying map. Test/observability use only. */
|
||||||
|
snapshot(): Map<string, ReadonlySet<string>> {
|
||||||
|
return new Map(
|
||||||
|
Array.from(this.connections.entries(), ([k, v]) => [k, v as ReadonlySet<string>]),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -28,6 +28,7 @@ import type { InboxStore } from './store.js';
|
|||||||
import { InboxServerEvents, shortHash } from './events.js';
|
import { InboxServerEvents, shortHash } from './events.js';
|
||||||
import { computeMsgId, isValidMsgId, constantTimeStringEqual } from './msg-id.js';
|
import { computeMsgId, isValidMsgId, constantTimeStringEqual } from './msg-id.js';
|
||||||
import { clampTtl, DEFAULT_INBOX_QUOTA, type InboxQuotaConfig } from './quota.js';
|
import { clampTtl, DEFAULT_INBOX_QUOTA, type InboxQuotaConfig } from './quota.js';
|
||||||
|
import type { BridgeDeliveryLog } from './bridge-delivery-log.js';
|
||||||
|
|
||||||
/** Max metadata-only body size (no ciphertext). 64 KB is enough headroom. */
|
/** Max metadata-only body size (no ciphertext). 64 KB is enough headroom. */
|
||||||
const MAX_META_BODY_SIZE = 64 * 1024;
|
const MAX_META_BODY_SIZE = 64 * 1024;
|
||||||
@@ -54,6 +55,16 @@ export interface InboxRoutesOptions {
|
|||||||
observability?: ObservabilityHook;
|
observability?: ObservabilityHook;
|
||||||
/** Override quota policy. */
|
/** Override quota policy. */
|
||||||
quota?: Partial<InboxQuotaConfig>;
|
quota?: Partial<InboxQuotaConfig>;
|
||||||
|
/**
|
||||||
|
* V4.8.4 — shared bridge delivery log. When provided (and the same
|
||||||
|
* instance is wired into `createBridgeRoutes`), the inbox-fetch route
|
||||||
|
* filters out blobs already pushed via bridge within the log's grace
|
||||||
|
* window. Without this, a recipient that runs both a bridge
|
||||||
|
* subscription and inbox-poll receives the same envelope twice.
|
||||||
|
* Optional — leaving it unset preserves the pre-V4.8.4 behavior of
|
||||||
|
* always returning every blob the cursor matches.
|
||||||
|
*/
|
||||||
|
bridgeDeliveryLog?: BridgeDeliveryLog;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createInboxRoutes(
|
export function createInboxRoutes(
|
||||||
@@ -171,6 +182,7 @@ export function createInboxRoutes(
|
|||||||
await verifyPayload(crypto, owner, { ...body, address });
|
await verifyPayload(crypto, owner, { ...body, address });
|
||||||
|
|
||||||
await store.deleteAddress(address);
|
await store.deleteAddress(address);
|
||||||
|
options.bridgeDeliveryLog?.forgetAddress(address);
|
||||||
events?.emit('inbox.address_deleted', { address });
|
events?.emit('inbox.address_deleted', { address });
|
||||||
return c.json({ ok: true });
|
return c.json({ ok: true });
|
||||||
});
|
});
|
||||||
@@ -255,11 +267,19 @@ export function createInboxRoutes(
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// V4.8: capture sender fingerprint at PUT time. The sender's
|
||||||
|
// signing key was just verified for this request, so the fingerprint
|
||||||
|
// is bound to the same authentication path that authorized the
|
||||||
|
// store. Surfaced on bridge push + inbox-fetch responses to
|
||||||
|
// bootstrap unknown-sender first-contact (X3DH pair handshake).
|
||||||
|
const senderFp = await shortHash(senderKey);
|
||||||
|
|
||||||
const result = await store.putBlob({
|
const result = await store.putBlob({
|
||||||
address,
|
address,
|
||||||
msgId,
|
msgId,
|
||||||
ciphertext: ctBytes,
|
ciphertext: ctBytes,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
|
senderFp,
|
||||||
});
|
});
|
||||||
if (result.created) {
|
if (result.created) {
|
||||||
events?.emit('inbox.blob_stored', {
|
events?.emit('inbox.blob_stored', {
|
||||||
@@ -309,31 +329,63 @@ export function createInboxRoutes(
|
|||||||
await verifyPayload(crypto, owner, { ...body, address });
|
await verifyPayload(crypto, owner, { ...body, address });
|
||||||
|
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
const rows = await store.fetchBlobs({
|
const rawRows = await store.fetchBlobs({
|
||||||
address,
|
address,
|
||||||
sinceCursor,
|
sinceCursor,
|
||||||
now,
|
now,
|
||||||
limit: quota.fetchPageLimit,
|
limit: quota.fetchPageLimit,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// V4.8.4 — drop blobs the bridge has already pushed to this address
|
||||||
|
// within the grace window. This is the cross-channel dedup gate that
|
||||||
|
// makes "one inbox.send ⇒ one observable delivery" hold even when
|
||||||
|
// the recipient runs both a bridge subscription and inbox-poll. The
|
||||||
|
// cursor still advances over the whole `rawRows` window so the
|
||||||
|
// client doesn't get stuck behind suppressed blobs — pollOnce uses
|
||||||
|
// `nextCursor` (max receivedAt seen by the server, suppressed or
|
||||||
|
// not) for the next fetch.
|
||||||
|
const rows = options.bridgeDeliveryLog
|
||||||
|
? options.bridgeDeliveryLog.filterRecent(address, rawRows, now)
|
||||||
|
: rawRows;
|
||||||
|
|
||||||
let bytes = 0;
|
let bytes = 0;
|
||||||
const blobs = rows.map((r) => {
|
const blobs = rows.map((r) => {
|
||||||
bytes += r.ciphertext.length;
|
bytes += r.ciphertext.length;
|
||||||
return {
|
const out: {
|
||||||
|
msgId: string;
|
||||||
|
ciphertext: string;
|
||||||
|
receivedAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
from?: string;
|
||||||
|
} = {
|
||||||
msgId: r.msgId,
|
msgId: r.msgId,
|
||||||
ciphertext: toBase64(r.ciphertext),
|
ciphertext: toBase64(r.ciphertext),
|
||||||
receivedAt: r.receivedAt,
|
receivedAt: r.receivedAt,
|
||||||
expiresAt: r.expiresAt,
|
expiresAt: r.expiresAt,
|
||||||
};
|
};
|
||||||
|
// V4.8: surface sender fingerprint when present. Empty for blobs
|
||||||
|
// persisted by a pre-4.8 relay that didn't track sender provenance.
|
||||||
|
if (r.senderFp) out.from = r.senderFp;
|
||||||
|
return out;
|
||||||
});
|
});
|
||||||
const nextCursor = rows.length > 0 ? rows[rows.length - 1]!.receivedAt : sinceCursor;
|
// Advance the cursor past the FULL rawRows window — including blobs
|
||||||
|
// we suppressed because the bridge already pushed them. If we
|
||||||
|
// anchored the cursor on `rows` only, suppressed blobs in the
|
||||||
|
// middle of the window would block all subsequent fetches forever
|
||||||
|
// (re-fetched on every poll, re-suppressed, no progress). The
|
||||||
|
// bridge-delivery contract is "the bridge frame is the canonical
|
||||||
|
// delivery"; if the recipient missed processing it, they fall back
|
||||||
|
// to ack-via-DELETE or the blob ages out at TTL — same as a
|
||||||
|
// recipient that crashes mid-handler in the no-bridge case.
|
||||||
|
const cursorAnchor = rawRows.length > 0 ? rawRows[rawRows.length - 1]!.receivedAt : sinceCursor;
|
||||||
|
const nextCursor = cursorAnchor;
|
||||||
|
|
||||||
events?.emit('inbox.blob_fetched', { address, count: blobs.length, bytes });
|
events?.emit('inbox.blob_fetched', { address, count: blobs.length, bytes });
|
||||||
|
|
||||||
return c.json({
|
return c.json({
|
||||||
blobs,
|
blobs,
|
||||||
cursor: nextCursor,
|
cursor: nextCursor,
|
||||||
hasMore: rows.length === quota.fetchPageLimit,
|
hasMore: rawRows.length === quota.fetchPageLimit,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -359,6 +411,10 @@ export function createInboxRoutes(
|
|||||||
if (removed) {
|
if (removed) {
|
||||||
events?.emit('inbox.blob_acked', { address, msgId });
|
events?.emit('inbox.blob_acked', { address, msgId });
|
||||||
}
|
}
|
||||||
|
// Drop any bridge-delivery mark — keeps the log bounded under
|
||||||
|
// sustained traffic (otherwise long-lived addresses accumulate
|
||||||
|
// entries even after the underlying blob is gone).
|
||||||
|
options.bridgeDeliveryLog?.forget(address, msgId);
|
||||||
return c.json({ ok: removed });
|
return c.json({ ok: removed });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -36,12 +36,20 @@ export interface InboxStore {
|
|||||||
* **Idempotent**: if a row already exists for `(address, msgId)` the
|
* **Idempotent**: if a row already exists for `(address, msgId)` the
|
||||||
* implementation MUST return `{ created: false }` and leave the existing
|
* implementation MUST return `{ created: false }` and leave the existing
|
||||||
* row untouched. A fresh insert returns `{ created: true, receivedAt }`.
|
* row untouched. A fresh insert returns `{ created: true, receivedAt }`.
|
||||||
|
*
|
||||||
|
* `senderFp` (V4.8+) is the 8-byte hex of SHA-256(senderSigningKey)
|
||||||
|
* — captured at PUT time when the relay verified the sender's
|
||||||
|
* signature. Optional so legacy 4.7 callers compile, but populated by
|
||||||
|
* `createInboxRoutes` from 4.8 onward and surfaced on bridge push +
|
||||||
|
* inbox-fetch responses to bootstrap unknown-sender first-contact
|
||||||
|
* (X3DH pair handshake).
|
||||||
*/
|
*/
|
||||||
putBlob(args: {
|
putBlob(args: {
|
||||||
address: string;
|
address: string;
|
||||||
msgId: string;
|
msgId: string;
|
||||||
ciphertext: Uint8Array;
|
ciphertext: Uint8Array;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
senderFp?: string;
|
||||||
}): Promise<{ created: boolean; receivedAt: number }>;
|
}): Promise<{ created: boolean; receivedAt: number }>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -57,7 +65,20 @@ export interface InboxStore {
|
|||||||
sinceCursor: number;
|
sinceCursor: number;
|
||||||
now: number;
|
now: number;
|
||||||
limit: number;
|
limit: number;
|
||||||
}): Promise<Array<{ msgId: string; ciphertext: Uint8Array; receivedAt: number; expiresAt: number }>>;
|
}): Promise<
|
||||||
|
Array<{
|
||||||
|
msgId: string;
|
||||||
|
ciphertext: Uint8Array;
|
||||||
|
receivedAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
/**
|
||||||
|
* Sender fingerprint — 8-byte hex of SHA-256(senderSigningKey)
|
||||||
|
* captured at PUT time. Empty/undefined for blobs persisted by a
|
||||||
|
* pre-4.8 relay that didn't track sender provenance.
|
||||||
|
*/
|
||||||
|
senderFp?: string;
|
||||||
|
}>
|
||||||
|
>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Delete a single blob by `(address, msgId)`. Returns true if a row was
|
* Delete a single blob by `(address, msgId)`. Returns true if a row was
|
||||||
|
|||||||
295
packages/shade-inbox-server/tests/blob-routes.test.ts
Normal file
295
packages/shade-inbox-server/tests/blob-routes.test.ts
Normal file
@@ -0,0 +1,295 @@
|
|||||||
|
import { describe, test, expect, beforeEach } from 'bun:test';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import {
|
||||||
|
createBlobRoutes,
|
||||||
|
MemoryBlobStore,
|
||||||
|
type BlobStore,
|
||||||
|
} from '../src/index.js';
|
||||||
|
import { signPayload } from '@shade/server';
|
||||||
|
import { SubtleCryptoProvider, ed25519PublicKeyFromSeed } from '@shade/crypto-web';
|
||||||
|
import { toBase64, fromBase64 } from '@shade/core';
|
||||||
|
|
||||||
|
const crypto = new SubtleCryptoProvider();
|
||||||
|
|
||||||
|
function randBytes(n: number): Uint8Array {
|
||||||
|
const buf = new Uint8Array(n);
|
||||||
|
globalThis.crypto.getRandomValues(buf);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
function hex(bytes: Uint8Array): string {
|
||||||
|
let s = '';
|
||||||
|
for (const b of bytes) s += b.toString(16).padStart(2, '0');
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('Shade Blob Routes (V4.9)', () => {
|
||||||
|
let store: BlobStore;
|
||||||
|
let app: Hono;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
store = new MemoryBlobStore();
|
||||||
|
app = createBlobRoutes(store, crypto, { disableRateLimit: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
async function makeOwner() {
|
||||||
|
const seed = randBytes(32);
|
||||||
|
const pubkey = ed25519PublicKeyFromSeed(seed);
|
||||||
|
return { seed, pubkey };
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeSlotId(): string {
|
||||||
|
return hex(randBytes(32));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signedPut(args: {
|
||||||
|
slotId: string;
|
||||||
|
blob: Uint8Array;
|
||||||
|
seed: Uint8Array;
|
||||||
|
pubkey: Uint8Array;
|
||||||
|
ifMatch?: string;
|
||||||
|
}) {
|
||||||
|
const payload: Record<string, unknown> = {
|
||||||
|
ownerPubkey: toBase64(args.pubkey),
|
||||||
|
blob: toBase64(args.blob),
|
||||||
|
slotId: args.slotId,
|
||||||
|
};
|
||||||
|
if (args.ifMatch !== undefined) payload.ifMatch = args.ifMatch;
|
||||||
|
const signed = await signPayload(crypto, args.seed, payload);
|
||||||
|
const { slotId: _omit, ...wire } = signed as Record<string, unknown>;
|
||||||
|
return app.request(`/v1/blob/${args.slotId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(wire),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function signedDelete(args: {
|
||||||
|
slotId: string;
|
||||||
|
seed: Uint8Array;
|
||||||
|
}) {
|
||||||
|
const signed = await signPayload(crypto, args.seed, {
|
||||||
|
slotId: args.slotId,
|
||||||
|
});
|
||||||
|
const { slotId: _omit, ...wire } = signed as Record<string, unknown>;
|
||||||
|
return app.request(`/v1/blob/${args.slotId}`, {
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(wire),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── GET ─────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('GET on missing slot returns 404', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const res = await app.request(`/v1/blob/${slotId}`);
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('GET requires lowercase 64-hex slotId', async () => {
|
||||||
|
const res = await app.request('/v1/blob/notahex');
|
||||||
|
expect(res.status).toBe(400);
|
||||||
|
const res2 = await app.request(`/v1/blob/${'A'.repeat(64)}`);
|
||||||
|
expect(res2.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── PUT (TOFU) ──────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('first PUT creates slot and returns etag', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const blob = randBytes(128);
|
||||||
|
const res = await signedPut({ slotId, blob, ...owner });
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const json = (await res.json()) as { created: boolean; etag: string };
|
||||||
|
expect(json.created).toBe(true);
|
||||||
|
expect(typeof json.etag).toBe('string');
|
||||||
|
|
||||||
|
const got = await app.request(`/v1/blob/${slotId}`);
|
||||||
|
expect(got.status).toBe(200);
|
||||||
|
const back = (await got.json()) as { blob: string; etag: string };
|
||||||
|
expect(fromBase64(back.blob)).toEqual(blob);
|
||||||
|
expect(back.etag).toBe(json.etag);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT without ifMatch on populated slot returns 409', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
await signedPut({ slotId, blob: randBytes(64), ...owner });
|
||||||
|
const res = await signedPut({ slotId, blob: randBytes(64), ...owner });
|
||||||
|
expect(res.status).toBe(409);
|
||||||
|
const json = (await res.json()) as { code: string };
|
||||||
|
expect(json.code).toBe('SHADE_CONFLICT');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT with stale ifMatch returns 412', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const r1 = await signedPut({ slotId, blob: randBytes(64), ...owner });
|
||||||
|
const j1 = (await r1.json()) as { etag: string };
|
||||||
|
// Use an etag we know does not match.
|
||||||
|
const stale = String(Number(j1.etag) - 999);
|
||||||
|
const res = await signedPut({
|
||||||
|
slotId,
|
||||||
|
blob: randBytes(64),
|
||||||
|
...owner,
|
||||||
|
ifMatch: stale,
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(412);
|
||||||
|
const json = (await res.json()) as { code: string };
|
||||||
|
expect(json.code).toBe('SHADE_PRECONDITION_FAILED');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT with matching ifMatch updates and bumps etag', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const r1 = await signedPut({ slotId, blob: randBytes(64), ...owner });
|
||||||
|
const j1 = (await r1.json()) as { etag: string };
|
||||||
|
const r2 = await signedPut({
|
||||||
|
slotId,
|
||||||
|
blob: randBytes(64),
|
||||||
|
...owner,
|
||||||
|
ifMatch: j1.etag,
|
||||||
|
});
|
||||||
|
expect(r2.status).toBe(200);
|
||||||
|
const j2 = (await r2.json()) as { created: boolean; etag: string };
|
||||||
|
expect(j2.created).toBe(false);
|
||||||
|
expect(Number(j2.etag)).toBeGreaterThan(Number(j1.etag));
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT with ifMatch="*" unconditionally overwrites existing slot', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
await signedPut({ slotId, blob: randBytes(64), ...owner });
|
||||||
|
const res = await signedPut({
|
||||||
|
slotId,
|
||||||
|
blob: randBytes(64),
|
||||||
|
...owner,
|
||||||
|
ifMatch: '*',
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT with ifMatch="*" on empty slot returns 412', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const res = await signedPut({
|
||||||
|
slotId,
|
||||||
|
blob: randBytes(64),
|
||||||
|
...owner,
|
||||||
|
ifMatch: '*',
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(412);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT by a different owner key on existing slot is rejected', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const ownerA = await makeOwner();
|
||||||
|
await signedPut({ slotId, blob: randBytes(64), ...ownerA });
|
||||||
|
|
||||||
|
const ownerB = await makeOwner();
|
||||||
|
const res = await signedPut({
|
||||||
|
slotId,
|
||||||
|
blob: randBytes(64),
|
||||||
|
...ownerB,
|
||||||
|
ifMatch: '*',
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT with bad signature is rejected', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
// Sign the payload, then mutate the blob bytes — signature no
|
||||||
|
// longer matches the canonicalized body.
|
||||||
|
const blob = randBytes(64);
|
||||||
|
const payload = {
|
||||||
|
ownerPubkey: toBase64(owner.pubkey),
|
||||||
|
blob: toBase64(blob),
|
||||||
|
slotId,
|
||||||
|
};
|
||||||
|
const signed = await signPayload(crypto, owner.seed, payload);
|
||||||
|
(signed as any).blob = toBase64(randBytes(64));
|
||||||
|
const { slotId: _omit, ...wire } = signed as Record<string, unknown>;
|
||||||
|
const res = await app.request(`/v1/blob/${slotId}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(wire),
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('PUT rejects empty blob and oversized blob', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const empty = await signedPut({ slotId, blob: new Uint8Array(0), ...owner });
|
||||||
|
expect(empty.status).toBe(400);
|
||||||
|
const tooBig = await signedPut({
|
||||||
|
slotId,
|
||||||
|
blob: randBytes(70 * 1024),
|
||||||
|
...owner,
|
||||||
|
});
|
||||||
|
expect(tooBig.status).toBe(400);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── DELETE ──────────────────────────────────────────────────
|
||||||
|
|
||||||
|
test('DELETE clears slot and lets a fresh key TOFU re-claim', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const ownerA = await makeOwner();
|
||||||
|
await signedPut({ slotId, blob: randBytes(64), ...ownerA });
|
||||||
|
|
||||||
|
const del = await signedDelete({ slotId, seed: ownerA.seed });
|
||||||
|
expect(del.status).toBe(200);
|
||||||
|
|
||||||
|
// Slot is gone.
|
||||||
|
const gone = await app.request(`/v1/blob/${slotId}`);
|
||||||
|
expect(gone.status).toBe(404);
|
||||||
|
|
||||||
|
// A fresh owner can now claim it.
|
||||||
|
const ownerB = await makeOwner();
|
||||||
|
const claim = await signedPut({ slotId, blob: randBytes(64), ...ownerB });
|
||||||
|
expect(claim.status).toBe(200);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('DELETE by a different key is rejected', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const ownerA = await makeOwner();
|
||||||
|
await signedPut({ slotId, blob: randBytes(64), ...ownerA });
|
||||||
|
|
||||||
|
const ownerB = await makeOwner();
|
||||||
|
const res = await signedDelete({ slotId, seed: ownerB.seed });
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('DELETE on missing slot returns 404', async () => {
|
||||||
|
const slotId = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const res = await signedDelete({ slotId, seed: owner.seed });
|
||||||
|
expect(res.status).toBe(404);
|
||||||
|
});
|
||||||
|
|
||||||
|
// ─── Cross-slot replay ───────────────────────────────────────
|
||||||
|
|
||||||
|
test('PUT signed for slot A is rejected against slot B', async () => {
|
||||||
|
const slotA = makeSlotId();
|
||||||
|
const slotB = makeSlotId();
|
||||||
|
const owner = await makeOwner();
|
||||||
|
const blob = randBytes(64);
|
||||||
|
// Sign for slotA, send to slotB (URL).
|
||||||
|
const payload = {
|
||||||
|
ownerPubkey: toBase64(owner.pubkey),
|
||||||
|
blob: toBase64(blob),
|
||||||
|
slotId: slotA,
|
||||||
|
};
|
||||||
|
const signed = await signPayload(crypto, owner.seed, payload);
|
||||||
|
const { slotId: _omit, ...wire } = signed as Record<string, unknown>;
|
||||||
|
const res = await app.request(`/v1/blob/${slotB}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(wire),
|
||||||
|
});
|
||||||
|
expect(res.status).toBe(401);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/inbox",
|
"name": "@shade/inbox",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
208
packages/shade-inbox/src/blob-client.ts
Normal file
208
packages/shade-inbox/src/blob-client.ts
Normal file
@@ -0,0 +1,208 @@
|
|||||||
|
import type { CryptoProvider } from '@shade/core';
|
||||||
|
import {
|
||||||
|
NetworkError,
|
||||||
|
toBase64,
|
||||||
|
fromBase64,
|
||||||
|
ShadeError,
|
||||||
|
ValidationError,
|
||||||
|
} from '@shade/core';
|
||||||
|
import { signPayload } from '@shade/server';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Low-level HTTP client for the V4.9 encrypted-blob primitive
|
||||||
|
* (`/v1/blob/<slotId>`). Stateless and reusable; higher-level wrappers
|
||||||
|
* (e.g. `Profile` in `@shade/sdk`) compose this client.
|
||||||
|
*
|
||||||
|
* The client doesn't care what the blob bytes mean — it just transports
|
||||||
|
* them. Callers are responsible for AEAD-sealing/opening, deriving the
|
||||||
|
* slotId from the master key, and managing the signing key.
|
||||||
|
*/
|
||||||
|
export interface BlobClientOptions {
|
||||||
|
baseUrl: string;
|
||||||
|
crypto: CryptoProvider;
|
||||||
|
/** Optional fetch override (defaults to globalThis.fetch). */
|
||||||
|
fetch?: typeof fetch;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BlobGetResult {
|
||||||
|
blob: Uint8Array;
|
||||||
|
/** ETag string — pass back as `ifMatch` to do a CAS update. */
|
||||||
|
etag: string;
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface BlobPutResult {
|
||||||
|
/** True if this PUT created the slot, false if it updated an existing one. */
|
||||||
|
created: boolean;
|
||||||
|
/** New ETag after the write. */
|
||||||
|
etag: string;
|
||||||
|
updatedAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class BlobClient {
|
||||||
|
private readonly fetchImpl: typeof fetch;
|
||||||
|
|
||||||
|
constructor(private readonly options: BlobClientOptions) {
|
||||||
|
const f = options.fetch ?? globalThis.fetch;
|
||||||
|
this.fetchImpl = f.bind(globalThis);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read a slot. Returns null if no blob has ever been written there
|
||||||
|
* (or if it was DELETE'd). GET is unauthenticated — see the
|
||||||
|
* `BlobStore` JSDoc for the threat-model rationale.
|
||||||
|
*/
|
||||||
|
async get(slotIdHex: string): Promise<BlobGetResult | null> {
|
||||||
|
validateSlotIdHex(slotIdHex);
|
||||||
|
const url = joinUrl(this.options.baseUrl, `/v1/blob/${slotIdHex}`);
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await this.fetchImpl(url, { method: 'GET' });
|
||||||
|
} catch (err) {
|
||||||
|
throw new NetworkError(`Blob GET failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
if (res.status === 404) return null;
|
||||||
|
const text = await res.text();
|
||||||
|
let json: any;
|
||||||
|
try {
|
||||||
|
json = text.length > 0 ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
throw new NetworkError(`Blob response not JSON: ${text.slice(0, 200)}`, res.status);
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new ShadeError(
|
||||||
|
String(json.code ?? 'SHADE_NETWORK'),
|
||||||
|
String(json.message ?? text),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
blob: fromBase64(String(json.blob)),
|
||||||
|
etag: String(json.etag),
|
||||||
|
updatedAt: Number(json.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Create or update a slot.
|
||||||
|
*
|
||||||
|
* `ifMatch` semantics:
|
||||||
|
* - `undefined`: 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).
|
||||||
|
*/
|
||||||
|
async put(args: {
|
||||||
|
slotIdHex: string;
|
||||||
|
blob: Uint8Array;
|
||||||
|
/** 32-byte Ed25519 seed (== `signingPrivateKey`). */
|
||||||
|
signingPrivateKey: Uint8Array;
|
||||||
|
/** Pubkey paired to `signingPrivateKey`. */
|
||||||
|
ownerPubkey: Uint8Array;
|
||||||
|
ifMatch?: string;
|
||||||
|
}): Promise<BlobPutResult> {
|
||||||
|
validateSlotIdHex(args.slotIdHex);
|
||||||
|
if (args.blob.length === 0) {
|
||||||
|
throw new ValidationError('Empty blob');
|
||||||
|
}
|
||||||
|
if (args.ownerPubkey.length !== 32) {
|
||||||
|
throw new ValidationError('ownerPubkey must be 32 bytes (Ed25519)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload: Record<string, unknown> = {
|
||||||
|
ownerPubkey: toBase64(args.ownerPubkey),
|
||||||
|
blob: toBase64(args.blob),
|
||||||
|
slotId: args.slotIdHex,
|
||||||
|
};
|
||||||
|
if (args.ifMatch !== undefined) payload.ifMatch = args.ifMatch;
|
||||||
|
|
||||||
|
const signed = await signPayload(
|
||||||
|
this.options.crypto,
|
||||||
|
args.signingPrivateKey,
|
||||||
|
payload,
|
||||||
|
);
|
||||||
|
// `slotId` was used for the signature canonicalization to bind it
|
||||||
|
// into the payload; the server rebuilds the same canonical form
|
||||||
|
// by mixing the URL slotId back in. Strip it from the wire body
|
||||||
|
// so we don't send it twice (URL is the path param).
|
||||||
|
const { slotId: _omit, ...wireBody } = signed as Record<string, unknown>;
|
||||||
|
|
||||||
|
const url = joinUrl(this.options.baseUrl, `/v1/blob/${args.slotIdHex}`);
|
||||||
|
const json = await this.requestJson('PUT', url, wireBody);
|
||||||
|
return {
|
||||||
|
created: Boolean(json.created),
|
||||||
|
etag: String(json.etag),
|
||||||
|
updatedAt: Number(json.updatedAt),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a slot — the next PUT TOFU-claims it again, possibly under
|
||||||
|
* a fresh signing key (e.g. after a rotation). Used by the "forget
|
||||||
|
* everything" path.
|
||||||
|
*/
|
||||||
|
async delete(args: {
|
||||||
|
slotIdHex: string;
|
||||||
|
signingPrivateKey: Uint8Array;
|
||||||
|
}): Promise<boolean> {
|
||||||
|
validateSlotIdHex(args.slotIdHex);
|
||||||
|
const signed = await signPayload(this.options.crypto, args.signingPrivateKey, {
|
||||||
|
slotId: args.slotIdHex,
|
||||||
|
});
|
||||||
|
const { slotId: _omit, ...wireBody } = signed as Record<string, unknown>;
|
||||||
|
const url = joinUrl(this.options.baseUrl, `/v1/blob/${args.slotIdHex}`);
|
||||||
|
const json = await this.requestJson('DELETE', url, wireBody);
|
||||||
|
return Boolean(json.ok);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ─── HTTP plumbing ──────────────────────────────────────────
|
||||||
|
|
||||||
|
private async requestJson(method: string, url: string, body: unknown): Promise<any> {
|
||||||
|
let res: Response;
|
||||||
|
try {
|
||||||
|
res = await this.fetchImpl(url, {
|
||||||
|
method,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
throw new NetworkError(`Blob request failed: ${(err as Error).message}`);
|
||||||
|
}
|
||||||
|
const text = await res.text();
|
||||||
|
let json: any;
|
||||||
|
try {
|
||||||
|
json = text.length > 0 ? JSON.parse(text) : {};
|
||||||
|
} catch {
|
||||||
|
throw new NetworkError(`Blob response not JSON: ${text.slice(0, 200)}`, res.status);
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new ShadeError(
|
||||||
|
String(json.code ?? 'SHADE_NETWORK'),
|
||||||
|
String(json.message ?? text),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function validateSlotIdHex(s: string): void {
|
||||||
|
if (!/^[0-9a-f]{64}$/.test(s)) {
|
||||||
|
throw new ValidationError('slotIdHex must be 64 lowercase hex chars (32 bytes)');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function joinUrl(base: string, path: string): string {
|
||||||
|
if (base.endsWith('/') && path.startsWith('/')) return base + path.slice(1);
|
||||||
|
if (!base.endsWith('/') && !path.startsWith('/')) return base + '/' + path;
|
||||||
|
return base + path;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Convert a 32-byte slotId Uint8Array into the lowercase-hex wire form. */
|
||||||
|
export function slotIdToHex(slotId: Uint8Array): string {
|
||||||
|
if (slotId.length !== 32) {
|
||||||
|
throw new ValidationError('slotId must be 32 bytes');
|
||||||
|
}
|
||||||
|
let s = '';
|
||||||
|
for (let i = 0; i < slotId.length; i++) {
|
||||||
|
s += slotId[i]!.toString(16).padStart(2, '0');
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
@@ -40,6 +40,16 @@ export interface FetchedBlob {
|
|||||||
receivedAt: number;
|
receivedAt: number;
|
||||||
/** Absolute expiry time (ms since epoch) reported by the server. */
|
/** Absolute expiry time (ms since epoch) reported by the server. */
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
|
/**
|
||||||
|
* Sender fingerprint — 8-byte hex of SHA-256(senderSigningKey),
|
||||||
|
* captured by the relay at PUT time when the sender's signature was
|
||||||
|
* verified. Empty/undefined when the relay is pre-4.8 or the blob
|
||||||
|
* predates sender-fingerprint tracking. Use as an unknown-sender
|
||||||
|
* bootstrap label (`fp:<hex>`) for X3DH first-contact; the
|
||||||
|
* authoritative sender identity is recovered post-decrypt from the
|
||||||
|
* envelope itself, so `from` is a hint, not a trust anchor.
|
||||||
|
*/
|
||||||
|
from?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface FetchResult {
|
export interface FetchResult {
|
||||||
@@ -52,7 +62,14 @@ export class InboxClient {
|
|||||||
private readonly fetchImpl: typeof fetch;
|
private readonly fetchImpl: typeof fetch;
|
||||||
|
|
||||||
constructor(private readonly options: InboxClientOptions) {
|
constructor(private readonly options: InboxClientOptions) {
|
||||||
this.fetchImpl = options.fetch ?? globalThis.fetch;
|
// Bind once. The browser's `globalThis.fetch` is a WebIDL bound
|
||||||
|
// operation that throws "Illegal invocation" when called as a method
|
||||||
|
// on another object (which is what `this.fetchImpl(...)` does).
|
||||||
|
// Node/Bun fetch tolerates a free receiver, but binding is harmless.
|
||||||
|
// A consumer-supplied `options.fetch` is bound to the global too —
|
||||||
|
// a fetch that requires a specific receiver must bind itself.
|
||||||
|
const f = options.fetch ?? globalThis.fetch;
|
||||||
|
this.fetchImpl = f.bind(globalThis);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -144,12 +161,18 @@ export class InboxClient {
|
|||||||
);
|
);
|
||||||
const blobs = Array.isArray(json.blobs) ? json.blobs : [];
|
const blobs = Array.isArray(json.blobs) ? json.blobs : [];
|
||||||
return {
|
return {
|
||||||
blobs: blobs.map((b: any) => ({
|
blobs: blobs.map((b: any): FetchedBlob => {
|
||||||
msgId: String(b.msgId),
|
const out: FetchedBlob = {
|
||||||
ciphertext: fromBase64(String(b.ciphertext)),
|
msgId: String(b.msgId),
|
||||||
receivedAt: Number(b.receivedAt),
|
ciphertext: fromBase64(String(b.ciphertext)),
|
||||||
expiresAt: Number(b.expiresAt),
|
receivedAt: Number(b.receivedAt),
|
||||||
})),
|
expiresAt: Number(b.expiresAt),
|
||||||
|
};
|
||||||
|
// V4.8 — relay-supplied sender fingerprint hint. Optional; absent
|
||||||
|
// on pre-4.8 relays or for blobs persisted before tracking landed.
|
||||||
|
if (typeof b.from === 'string' && b.from.length > 0) out.from = b.from;
|
||||||
|
return out;
|
||||||
|
}),
|
||||||
cursor: Number(json.cursor ?? sinceCursor),
|
cursor: Number(json.cursor ?? sinceCursor),
|
||||||
hasMore: Boolean(json.hasMore),
|
hasMore: Boolean(json.hasMore),
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -16,9 +16,20 @@ import { InboxClientEvents, type InboxClientListener } from './events.js';
|
|||||||
* decrypt path it owns) and either return a sender-hint for telemetry
|
* decrypt path it owns) and either return a sender-hint for telemetry
|
||||||
* (the address the SDK extracted, or `null`) or throw to keep the blob
|
* (the address the SDK extracted, or `null`) or throw to keep the blob
|
||||||
* on the server for a later retry.
|
* on the server for a later retry.
|
||||||
|
*
|
||||||
|
* V4.8: `raw.from` is the relay-captured sender fingerprint (8-byte hex
|
||||||
|
* of SHA-256 over the sender's signing key). Empty when the relay is
|
||||||
|
* pre-4.8 or didn't track the sender. Use it as the `fp:<hex>` bootstrap
|
||||||
|
* label for X3DH first-contact handshakes.
|
||||||
*/
|
*/
|
||||||
export type DecryptHandler = (
|
export type DecryptHandler = (
|
||||||
raw: { msgId: string; ciphertext: Uint8Array; receivedAt: number; expiresAt: number },
|
raw: {
|
||||||
|
msgId: string;
|
||||||
|
ciphertext: Uint8Array;
|
||||||
|
receivedAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
from?: string;
|
||||||
|
},
|
||||||
) => Promise<string | null | undefined> | string | null | undefined;
|
) => Promise<string | null | undefined> | string | null | undefined;
|
||||||
|
|
||||||
export interface InboxOptions {
|
export interface InboxOptions {
|
||||||
@@ -52,6 +63,14 @@ export interface InboxOptions {
|
|||||||
const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60;
|
const DEFAULT_TTL_SECONDS = 7 * 24 * 60 * 60;
|
||||||
const DEFAULT_POLL_INTERVAL_MS = 30_000;
|
const DEFAULT_POLL_INTERVAL_MS = 30_000;
|
||||||
const DEFAULT_MAX_ATTEMPTS = 10;
|
const DEFAULT_MAX_ATTEMPTS = 10;
|
||||||
|
/**
|
||||||
|
* Cap for the cross-channel msgId dedup LRU. Each entry is a 64-char hex
|
||||||
|
* string; 4096 entries ≈ 256 KiB of overhead, plenty of headroom for
|
||||||
|
* bursty traffic (the LRU only needs to span the window between a bridge
|
||||||
|
* push and the next inbox-poll catching up — typically 30 s × the
|
||||||
|
* recipient's throughput).
|
||||||
|
*/
|
||||||
|
const DEFAULT_DEDUP_LRU_CAP = 4096;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* High-level inbox orchestrator.
|
* High-level inbox orchestrator.
|
||||||
@@ -94,6 +113,23 @@ export class Inbox {
|
|||||||
private started = false;
|
private started = false;
|
||||||
private registered = false;
|
private registered = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Bounded msgId dedup window. Used by both the inbox-poll path
|
||||||
|
* (`pollOnce` → `handleBlob`) and the bridge-push path
|
||||||
|
* (`acceptBridgeFrame`). The relay stores blobs durably and pushes
|
||||||
|
* them to every active delivery channel; without a shared dedup gate
|
||||||
|
* here the recipient processes the same envelope twice — once from
|
||||||
|
* the bridge, again from the next inbox-poll. The duplicate receive
|
||||||
|
* trips on consumed one-time prekeys ("OPK not found") and pollutes
|
||||||
|
* logs even when the canonical first delivery succeeded. See V4.8.3
|
||||||
|
* Prism FR `cross-channel-duplicate-fanout-v4.8.2.md`.
|
||||||
|
*
|
||||||
|
* Insertion order is FIFO; the oldest msgId is evicted once the LRU
|
||||||
|
* exceeds `DEFAULT_DEDUP_LRU_CAP`.
|
||||||
|
*/
|
||||||
|
private readonly deliveredIds = new Set<string>();
|
||||||
|
private readonly deliveredOrder: string[] = [];
|
||||||
|
|
||||||
constructor(private readonly options: InboxOptions) {
|
constructor(private readonly options: InboxOptions) {
|
||||||
const clientOptions: ConstructorParameters<typeof InboxClient>[0] = {
|
const clientOptions: ConstructorParameters<typeof InboxClient>[0] = {
|
||||||
baseUrl: options.baseUrl,
|
baseUrl: options.baseUrl,
|
||||||
@@ -149,6 +185,14 @@ export class Inbox {
|
|||||||
signingKey: this.options.signingPublicKey,
|
signingKey: this.options.signingPublicKey,
|
||||||
});
|
});
|
||||||
this.registered = true;
|
this.registered = true;
|
||||||
|
// V4.8: gate the first poll on register success. `start()` calls
|
||||||
|
// `register()` fire-and-forget; without this kick, the very first
|
||||||
|
// `pollOnce()` (scheduled synchronously alongside register) would
|
||||||
|
// race the register HTTP RTT and return SHADE_NOT_FOUND. The
|
||||||
|
// pollOnce() guard skips polls until `registered === true`; this
|
||||||
|
// immediate schedule ensures we don't wait the full pollIntervalMs
|
||||||
|
// for the next attempt once register lands.
|
||||||
|
if (this.started) this.schedulePoll(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Drop the address from the server. Local queue/cursor are preserved. */
|
/** Drop the address from the server. Local queue/cursor are preserved. */
|
||||||
@@ -203,7 +247,10 @@ export class Inbox {
|
|||||||
* after a push-trigger arrives). Does not throw on transient errors.
|
* after a push-trigger arrives). Does not throw on transient errors.
|
||||||
*/
|
*/
|
||||||
async tick(): Promise<{ flushed: number; received: number }> {
|
async tick(): Promise<{ flushed: number; received: number }> {
|
||||||
const flushed = await this.flushOnce();
|
const flushResult = await this.flushOnce();
|
||||||
|
// `null` means another flush was concurrent; report 0 newly-flushed
|
||||||
|
// for this caller (the other flush counted them).
|
||||||
|
const flushed = flushResult?.delivered ?? 0;
|
||||||
const received = await this.pollOnce();
|
const received = await this.pollOnce();
|
||||||
return { flushed, received };
|
return { flushed, received };
|
||||||
}
|
}
|
||||||
@@ -217,7 +264,11 @@ export class Inbox {
|
|||||||
this.scheduleRegisterRetry();
|
this.scheduleRegisterRetry();
|
||||||
});
|
});
|
||||||
this.scheduleFlush();
|
this.scheduleFlush();
|
||||||
this.schedulePoll(0);
|
// V4.8: do NOT schedule the first poll synchronously. `register()`
|
||||||
|
// success kicks `schedulePoll(0)` so the first poll fires after the
|
||||||
|
// server has acknowledged the address. Pre-fix this raced register
|
||||||
|
// and burned a 404 on every fresh-address `start()`.
|
||||||
|
if (this.registered) this.schedulePoll(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Stop background timers. Pending entries remain in the queue. */
|
/** Stop background timers. Pending entries remain in the queue. */
|
||||||
@@ -253,11 +304,27 @@ export class Inbox {
|
|||||||
this.flushTimer = setTimeout(() => {
|
this.flushTimer = setTimeout(() => {
|
||||||
this.flushTimer = null;
|
this.flushTimer = null;
|
||||||
this.flushOnce()
|
this.flushOnce()
|
||||||
.then(() => {
|
.then((result) => {
|
||||||
// If anything is still queued, retry with backoff.
|
// `result === null` means another flush was already in flight
|
||||||
this.queueStore.size().then((n) => {
|
// and this call early-returned via the `flushing` guard. The
|
||||||
if (n > 0 && this.started) this.scheduleFlush(15_000);
|
// already-running flush will reschedule itself when it
|
||||||
});
|
// finishes; do not double-schedule from here.
|
||||||
|
if (result === null) return;
|
||||||
|
if (result.remaining === 0) return;
|
||||||
|
// V4.8.5 — distinguish healthy-drain-but-more-queued from
|
||||||
|
// all-attempts-failed. Pre-fix, both cases used a 15 s
|
||||||
|
// backoff. Under sustained traffic (Prism's typing-into-a-
|
||||||
|
// chatty-shell pattern), bursts of envelopes enqueued
|
||||||
|
// *during* a flush would sit ~10–15 s behind the backoff
|
||||||
|
// timer before the next drain — visible to the receiver as a
|
||||||
|
// "10 s silence then 25-frame burst" wave. Healthy drain
|
||||||
|
// (delivered > 0) means the network is fine and we should
|
||||||
|
// immediately drain whatever piled up; reserve the 15 s
|
||||||
|
// retry for the case where every attempt this round failed.
|
||||||
|
if (this.started) {
|
||||||
|
const delay = result.delivered > 0 ? 0 : 15_000;
|
||||||
|
this.scheduleFlush(delay);
|
||||||
|
}
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
if (this.started) this.scheduleFlush(15_000);
|
if (this.started) this.scheduleFlush(15_000);
|
||||||
@@ -276,45 +343,97 @@ export class Inbox {
|
|||||||
}, delayMs);
|
}, delayMs);
|
||||||
}
|
}
|
||||||
|
|
||||||
private async flushOnce(): Promise<number> {
|
/**
|
||||||
if (this.flushing) return 0;
|
* Drain the outgoing queue. Returns `null` if another flush is already
|
||||||
|
* in flight (the running flush owns the rescheduling); otherwise
|
||||||
|
* returns the count of newly-delivered envelopes and the queue size
|
||||||
|
* after the drain so the caller can decide whether to immediately
|
||||||
|
* re-flush (more piled up during the drain — healthy network) or
|
||||||
|
* back off (everything failed).
|
||||||
|
*
|
||||||
|
* V4.8.5: drain is parallel-per-recipient. Each `recipientAddress`
|
||||||
|
* gets its own sequential worker (so per-peer order is preserved),
|
||||||
|
* but distinct recipients run concurrently. Pre-fix, a single slow
|
||||||
|
* POST head-of-line-blocked the entire queue — including small
|
||||||
|
* frames bound for unrelated peers. See Prism FR
|
||||||
|
* `per-recipient-flush-concurrency-v4.8.md`.
|
||||||
|
*/
|
||||||
|
private async flushOnce(): Promise<{ delivered: number; remaining: number } | null> {
|
||||||
|
if (this.flushing) return null;
|
||||||
this.flushing = true;
|
this.flushing = true;
|
||||||
let delivered = 0;
|
let delivered = 0;
|
||||||
try {
|
try {
|
||||||
const entries = await this.queueStore.list();
|
const entries = await this.queueStore.list();
|
||||||
|
// Group by recipient. Within a bucket we drain sequentially so
|
||||||
|
// per-peer message order matches enqueue order (the relay
|
||||||
|
// assigns `receivedAt` on PUT arrival; concurrent POSTs to the
|
||||||
|
// same peer would let the second arrive first and the recipient
|
||||||
|
// would observe out-of-order envelopes). Across buckets, no
|
||||||
|
// ordering guarantee exists in Shade's wire model anyway, so
|
||||||
|
// parallel drain is safe.
|
||||||
|
const buckets = new Map<string, OutgoingEntry[]>();
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
try {
|
let bucket = buckets.get(entry.recipientAddress);
|
||||||
const result = await this.client.put({
|
if (!bucket) {
|
||||||
recipientAddress: entry.recipientAddress,
|
bucket = [];
|
||||||
senderSigningKey: this.options.signingPublicKey,
|
buckets.set(entry.recipientAddress, bucket);
|
||||||
envelope: entry.ciphertext,
|
}
|
||||||
ttlSeconds: entry.ttlSeconds,
|
bucket.push(entry);
|
||||||
});
|
}
|
||||||
await this.queueStore.remove(entry.recipientAddress, entry.msgId);
|
|
||||||
delivered++;
|
const drainBucket = async (bucket: OutgoingEntry[]): Promise<number> => {
|
||||||
this.events.emit('inbox.message_delivered', {
|
let count = 0;
|
||||||
recipientAddress: entry.recipientAddress,
|
for (const entry of bucket) {
|
||||||
msgId: result.msgId,
|
try {
|
||||||
idempotent: result.idempotent,
|
const result = await this.client.put({
|
||||||
});
|
recipientAddress: entry.recipientAddress,
|
||||||
} catch (err) {
|
senderSigningKey: this.options.signingPublicKey,
|
||||||
await this.queueStore.bumpAttempts(entry.recipientAddress, entry.msgId);
|
envelope: entry.ciphertext,
|
||||||
const attempts = entry.attempts + 1;
|
ttlSeconds: entry.ttlSeconds,
|
||||||
this.events.emit('inbox.message_failed', {
|
});
|
||||||
recipientAddress: entry.recipientAddress,
|
|
||||||
msgId: entry.msgId,
|
|
||||||
attempts,
|
|
||||||
error: (err as Error).message,
|
|
||||||
});
|
|
||||||
if (attempts >= this.maxAttempts) {
|
|
||||||
await this.queueStore.remove(entry.recipientAddress, entry.msgId);
|
await this.queueStore.remove(entry.recipientAddress, entry.msgId);
|
||||||
|
count++;
|
||||||
|
this.events.emit('inbox.message_delivered', {
|
||||||
|
recipientAddress: entry.recipientAddress,
|
||||||
|
msgId: result.msgId,
|
||||||
|
idempotent: result.idempotent,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
await this.queueStore.bumpAttempts(entry.recipientAddress, entry.msgId);
|
||||||
|
const attempts = entry.attempts + 1;
|
||||||
|
this.events.emit('inbox.message_failed', {
|
||||||
|
recipientAddress: entry.recipientAddress,
|
||||||
|
msgId: entry.msgId,
|
||||||
|
attempts,
|
||||||
|
error: (err as Error).message,
|
||||||
|
});
|
||||||
|
if (attempts >= this.maxAttempts) {
|
||||||
|
await this.queueStore.remove(entry.recipientAddress, entry.msgId);
|
||||||
|
// Given up on: it no longer holds a place in the order.
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// Head-of-line, on purpose. Carrying on with the next entry
|
||||||
|
// delivers it AHEAD of this one, which is retried next round —
|
||||||
|
// exactly the reordering the sequential bucket exists to
|
||||||
|
// prevent. For sender-key broadcasts that is not cosmetic: a
|
||||||
|
// receiver that sees iteration N+1 first can no longer open N
|
||||||
|
// unless it kept N's key. One recipient's bucket waits; the
|
||||||
|
// others drain in parallel as before.
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
return count;
|
||||||
|
};
|
||||||
|
|
||||||
|
const counts = await Promise.all(
|
||||||
|
Array.from(buckets.values(), drainBucket),
|
||||||
|
);
|
||||||
|
delivered = counts.reduce((a, b) => a + b, 0);
|
||||||
} finally {
|
} finally {
|
||||||
this.flushing = false;
|
this.flushing = false;
|
||||||
}
|
}
|
||||||
return delivered;
|
const remaining = await this.queueStore.size();
|
||||||
|
return { delivered, remaining };
|
||||||
}
|
}
|
||||||
|
|
||||||
private async pollOnce(): Promise<number> {
|
private async pollOnce(): Promise<number> {
|
||||||
@@ -357,9 +476,52 @@ export class Inbox {
|
|||||||
return total;
|
return total;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Feed a blob delivered by a bridge transport (WS / SSE / long-poll
|
||||||
|
* push) into the same dispatch + ack pipeline that `pollOnce` uses.
|
||||||
|
*
|
||||||
|
* Wire-up pattern:
|
||||||
|
* ```ts
|
||||||
|
* const bridge = new FallbackBridgeTransport([...]);
|
||||||
|
* await bridge.connect({
|
||||||
|
* onMessage: async (msg) => {
|
||||||
|
* await inbox.acceptBridgeFrame({
|
||||||
|
* msgId: msg.msgId!, // present on v4.8+ relays
|
||||||
|
* ciphertext: msg.bytes,
|
||||||
|
* receivedAt: msg.receivedAt,
|
||||||
|
* expiresAt: msg.expiresAt ?? Date.now() + 7 * 24 * 3600 * 1000,
|
||||||
|
* ...(msg.from !== undefined ? { from: msg.from } : {}),
|
||||||
|
* });
|
||||||
|
* },
|
||||||
|
* });
|
||||||
|
* ```
|
||||||
|
*
|
||||||
|
* The Inbox's bounded msgId LRU is shared between this path and
|
||||||
|
* `pollOnce`, so whichever channel delivers first wins; the
|
||||||
|
* other channel acks-and-skips when the same msgId comes back
|
||||||
|
* around. Both paths also DELETE the blob from the relay on success
|
||||||
|
* so subsequent polls don't see it either.
|
||||||
|
*
|
||||||
|
* Returns `true` if the blob was newly dispatched, `false` if it
|
||||||
|
* was a duplicate or rejected by the handler (handler still gets a
|
||||||
|
* chance to retry on the next poll if it threw).
|
||||||
|
*/
|
||||||
|
async acceptBridgeFrame(blob: FetchedBlob): Promise<boolean> {
|
||||||
|
return this.handleBlob(blob);
|
||||||
|
}
|
||||||
|
|
||||||
private async handleBlob(blob: FetchedBlob): Promise<boolean> {
|
private async handleBlob(blob: FetchedBlob): Promise<boolean> {
|
||||||
if (!this.incomingHandler) return false;
|
if (!this.incomingHandler) return false;
|
||||||
|
|
||||||
|
// Cross-channel msgId dedup. If the bridge already delivered this
|
||||||
|
// blob, the inbox-poll copy must not re-dispatch (would re-trigger
|
||||||
|
// X3DH / consume an OPK we no longer have). We still ack so the
|
||||||
|
// relay drops the now-redundant copy.
|
||||||
|
if (this.deliveredIds.has(blob.msgId)) {
|
||||||
|
await this.ackQuietly(blob.msgId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
// Defense-in-depth: verify msgId ↔ ciphertext at the client too. A
|
// Defense-in-depth: verify msgId ↔ ciphertext at the client too. A
|
||||||
// server bug or malicious operator can't sneak a different blob past
|
// server bug or malicious operator can't sneak a different blob past
|
||||||
// the client's hash check.
|
// the client's hash check.
|
||||||
@@ -375,12 +537,20 @@ export class Inbox {
|
|||||||
|
|
||||||
let senderHint: string | null = null;
|
let senderHint: string | null = null;
|
||||||
try {
|
try {
|
||||||
const result = await this.incomingHandler({
|
const raw: {
|
||||||
|
msgId: string;
|
||||||
|
ciphertext: Uint8Array;
|
||||||
|
receivedAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
from?: string;
|
||||||
|
} = {
|
||||||
msgId: blob.msgId,
|
msgId: blob.msgId,
|
||||||
ciphertext: blob.ciphertext,
|
ciphertext: blob.ciphertext,
|
||||||
receivedAt: blob.receivedAt,
|
receivedAt: blob.receivedAt,
|
||||||
expiresAt: blob.expiresAt,
|
expiresAt: blob.expiresAt,
|
||||||
});
|
};
|
||||||
|
if (blob.from !== undefined) raw.from = blob.from;
|
||||||
|
const result = await this.incomingHandler(raw);
|
||||||
senderHint = result ?? null;
|
senderHint = result ?? null;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
this.events.emit('inbox.message_decrypt_failed', {
|
this.events.emit('inbox.message_decrypt_failed', {
|
||||||
@@ -391,17 +561,34 @@ export class Inbox {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
// Mark before the ack so a slow-network ack doesn't leave a window
|
||||||
await this.client.ack({ address: this.options.ownAddress, msgId: blob.msgId });
|
// where a parallel pollOnce sees the same msgId and re-dispatches.
|
||||||
} catch (err) {
|
this.recordDelivered(blob.msgId);
|
||||||
// Decryption succeeded; ack just failed. Will be retried later, and
|
await this.ackQuietly(blob.msgId);
|
||||||
// the duplicate-message ratchet check on `Shade.receive` will dedupe.
|
|
||||||
console.warn('[Shade] Inbox ack failed (will retry):', (err as Error).message);
|
|
||||||
}
|
|
||||||
this.events.emit('inbox.message_received', {
|
this.events.emit('inbox.message_received', {
|
||||||
senderHint,
|
senderHint,
|
||||||
msgId: blob.msgId,
|
msgId: blob.msgId,
|
||||||
});
|
});
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private async ackQuietly(msgId: string): Promise<void> {
|
||||||
|
try {
|
||||||
|
await this.client.ack({ address: this.options.ownAddress, msgId });
|
||||||
|
} catch (err) {
|
||||||
|
// Dispatch (or skip) succeeded; the ack just failed. Next poll
|
||||||
|
// will see the blob again and the dedup gate above will skip it.
|
||||||
|
console.warn('[Shade] Inbox ack failed (will retry):', (err as Error).message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private recordDelivered(msgId: string): void {
|
||||||
|
if (this.deliveredIds.has(msgId)) return;
|
||||||
|
this.deliveredIds.add(msgId);
|
||||||
|
this.deliveredOrder.push(msgId);
|
||||||
|
if (this.deliveredOrder.length > DEFAULT_DEDUP_LRU_CAP) {
|
||||||
|
const evicted = this.deliveredOrder.shift()!;
|
||||||
|
this.deliveredIds.delete(evicted);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -43,3 +43,11 @@ export type {
|
|||||||
} from './events.js';
|
} from './events.js';
|
||||||
|
|
||||||
export { computeMsgId } from './msg-id.js';
|
export { computeMsgId } from './msg-id.js';
|
||||||
|
|
||||||
|
// V4.9 — encrypted-blob primitive (`/v1/blob/<slotId>`).
|
||||||
|
export { BlobClient, slotIdToHex } from './blob-client.js';
|
||||||
|
export type {
|
||||||
|
BlobClientOptions,
|
||||||
|
BlobGetResult,
|
||||||
|
BlobPutResult,
|
||||||
|
} from './blob-client.js';
|
||||||
|
|||||||
@@ -170,6 +170,255 @@ describe('Inbox orchestrator', () => {
|
|||||||
expect(seen[1]!.to).toBe('carol');
|
expect(seen[1]!.to).toBe('carol');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('cross-channel dedup: acceptBridgeFrame + pollOnce never re-dispatch the same msgId (V4.8.3)', async () => {
|
||||||
|
// Reproduces the Prism FR `cross-channel-duplicate-fanout-v4.8.2`:
|
||||||
|
// a single relay PUT was being delivered twice — once via WS bridge
|
||||||
|
// push, again ~30 s later via inbox-poll catching up. Both copies
|
||||||
|
// would dispatch `shade.receive`, the second one tripping on
|
||||||
|
// already-consumed prekeys. The cross-channel msgId LRU inside
|
||||||
|
// Inbox is the dedup gate; this test exercises it directly via
|
||||||
|
// `acceptBridgeFrame` followed by `pollOnce`.
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
|
||||||
|
const bobInbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'bob',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: bob.signingPrivateKey,
|
||||||
|
signingPublicKey: bob.signingPublicKey,
|
||||||
|
pollIntervalMs: 0,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
await bobInbox.register();
|
||||||
|
|
||||||
|
// Alice PUTs a blob via the relay HTTP API.
|
||||||
|
const ct = randBytes(64);
|
||||||
|
const msgId = await computeMsgId(ct);
|
||||||
|
const aliceClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
const putResult = await aliceClient.put({
|
||||||
|
recipientAddress: 'bob',
|
||||||
|
senderSigningKey: alice.signingPublicKey,
|
||||||
|
envelope: ct,
|
||||||
|
});
|
||||||
|
expect(putResult.idempotent).toBe(false);
|
||||||
|
|
||||||
|
const dispatched: string[] = [];
|
||||||
|
bobInbox.onIncoming(async (raw) => {
|
||||||
|
dispatched.push(raw.msgId);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Simulate the bridge push arriving first.
|
||||||
|
await bobInbox.acceptBridgeFrame({
|
||||||
|
msgId,
|
||||||
|
ciphertext: ct,
|
||||||
|
receivedAt: putResult.receivedAt,
|
||||||
|
expiresAt: Date.now() + 60_000,
|
||||||
|
});
|
||||||
|
expect(dispatched).toEqual([msgId]);
|
||||||
|
|
||||||
|
// The inbox-poll path catches up next — without dedup it would
|
||||||
|
// re-dispatch. With the LRU it acks-and-skips.
|
||||||
|
const polled = await bobInbox.tick();
|
||||||
|
expect(polled.received).toBe(0);
|
||||||
|
expect(dispatched).toEqual([msgId]); // still one entry
|
||||||
|
});
|
||||||
|
|
||||||
|
test('cross-channel dedup also covers poll-first then bridge-second order', async () => {
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
|
||||||
|
const bobInbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'bob',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: bob.signingPrivateKey,
|
||||||
|
signingPublicKey: bob.signingPublicKey,
|
||||||
|
pollIntervalMs: 0,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
await bobInbox.register();
|
||||||
|
const ct = randBytes(48);
|
||||||
|
const msgId = await computeMsgId(ct);
|
||||||
|
const aliceClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
const putRes = await aliceClient.put({
|
||||||
|
recipientAddress: 'bob',
|
||||||
|
senderSigningKey: alice.signingPublicKey,
|
||||||
|
envelope: ct,
|
||||||
|
});
|
||||||
|
|
||||||
|
const dispatched: string[] = [];
|
||||||
|
bobInbox.onIncoming(async (raw) => {
|
||||||
|
dispatched.push(raw.msgId);
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
|
||||||
|
// Poll first.
|
||||||
|
const polled = await bobInbox.tick();
|
||||||
|
expect(polled.received).toBe(1);
|
||||||
|
|
||||||
|
// Bridge frame for the same msgId arrives after the poll already
|
||||||
|
// dispatched + ack'd it — must be a no-op.
|
||||||
|
const handled = await bobInbox.acceptBridgeFrame({
|
||||||
|
msgId,
|
||||||
|
ciphertext: ct,
|
||||||
|
receivedAt: putRes.receivedAt,
|
||||||
|
expiresAt: Date.now() + 60_000,
|
||||||
|
});
|
||||||
|
expect(handled).toBe(false);
|
||||||
|
expect(dispatched).toEqual([msgId]);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('burst enqueued during a flush drains immediately, not after 15 s backoff (V4.8.5)', async () => {
|
||||||
|
// Reproduces Prism FR `per-recipient-flush-concurrency-v4.8`: a
|
||||||
|
// burst of envelopes enqueued *during* a slow POST used to sit
|
||||||
|
// ~15 s behind the next flush because both the success path and
|
||||||
|
// the failure path of `flushOnce` rescheduled with the same 15 s
|
||||||
|
// backoff. The fix uses 0 ms when the round delivered something
|
||||||
|
// (network is healthy — drain remainder) and reserves 15 s for
|
||||||
|
// the all-attempts-failed case.
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
const bobClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: bob.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
await bobClient.register({ address: 'bob', signingKey: bob.signingPublicKey });
|
||||||
|
|
||||||
|
// Wrap fetch so the FIRST PUT (only) takes 100 ms — long enough
|
||||||
|
// for many enqueues to land while it's in flight.
|
||||||
|
let firstPutSeen = false;
|
||||||
|
const slowFirstFetch: typeof fetch = (async (input, init) => {
|
||||||
|
const u =
|
||||||
|
typeof input === 'string'
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.toString()
|
||||||
|
: (input as Request).url;
|
||||||
|
const isPut = u.includes('/v1/inbox/bob') && !u.includes('/fetch');
|
||||||
|
if (isPut && !firstPutSeen) {
|
||||||
|
firstPutSeen = true;
|
||||||
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
|
}
|
||||||
|
return honoFetch(app)(input, init);
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const aliceInbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'alice',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
signingPublicKey: alice.signingPublicKey,
|
||||||
|
pollIntervalMs: 0,
|
||||||
|
fetch: slowFirstFetch,
|
||||||
|
});
|
||||||
|
|
||||||
|
aliceInbox.start();
|
||||||
|
|
||||||
|
// First send — this kicks the slow-PUT path.
|
||||||
|
await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(20) });
|
||||||
|
|
||||||
|
// Pile 24 more on top while the first PUT is still in flight. The
|
||||||
|
// first PUT will finish at ~T+100 ms; the subsequent 24 should
|
||||||
|
// drain immediately after, NOT after a 15 s backoff.
|
||||||
|
for (let i = 0; i < 24; i++) {
|
||||||
|
await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(20) });
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait long enough for the slow first PUT + the immediate
|
||||||
|
// reschedule + the 24-envelope drain. Pre-fix this would still
|
||||||
|
// have ≥1 entry pending after 1 s (waiting for the 15 s timer).
|
||||||
|
await new Promise((r) => setTimeout(r, 1_000));
|
||||||
|
expect(await aliceInbox.pendingCount()).toBe(0);
|
||||||
|
aliceInbox.stop();
|
||||||
|
});
|
||||||
|
|
||||||
|
test('per-recipient parallel drain — slow POST to A does not block POSTs to B (V4.8.5)', async () => {
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const carol = await makeIdentity();
|
||||||
|
// Register bob + carol.
|
||||||
|
const reg = async (name: string, kp: { signingPrivateKey: Uint8Array; signingPublicKey: Uint8Array }) => {
|
||||||
|
const c = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: kp.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
await c.register({ address: name, signingKey: kp.signingPublicKey });
|
||||||
|
};
|
||||||
|
await reg('bob', bob);
|
||||||
|
await reg('carol', carol);
|
||||||
|
|
||||||
|
// bob's PUT route stalls 200 ms; carol's is instant. Pre-fix this
|
||||||
|
// would head-of-line block carol behind bob.
|
||||||
|
const slowedFetch: typeof fetch = (async (input, init) => {
|
||||||
|
const u =
|
||||||
|
typeof input === 'string'
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.toString()
|
||||||
|
: (input as Request).url;
|
||||||
|
const m = (init as RequestInit | undefined)?.method ?? 'GET';
|
||||||
|
if (m === 'POST' && u.includes('/v1/inbox/bob') && !u.includes('/fetch')) {
|
||||||
|
await new Promise((r) => setTimeout(r, 200));
|
||||||
|
}
|
||||||
|
return honoFetch(app)(input, init);
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const aliceInbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'alice',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
signingPublicKey: alice.signingPublicKey,
|
||||||
|
pollIntervalMs: 0,
|
||||||
|
fetch: slowedFetch,
|
||||||
|
});
|
||||||
|
|
||||||
|
const carolDeliveredAt = new Promise<number>((resolve) => {
|
||||||
|
aliceInbox.on((e) => {
|
||||||
|
if (e.name === 'inbox.message_delivered' && e.data.recipientAddress === 'carol') {
|
||||||
|
resolve(Date.now());
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
const t0 = Date.now();
|
||||||
|
// Bob queue first, carol second — pre-fix carol would wait 200 ms
|
||||||
|
// behind bob's slow PUT. With per-recipient parallelism, carol's
|
||||||
|
// PUT runs concurrently and lands first.
|
||||||
|
await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(20) });
|
||||||
|
await aliceInbox.send({ recipientAddress: 'carol', envelope: randBytes(20) });
|
||||||
|
|
||||||
|
aliceInbox.start();
|
||||||
|
const carolAt = await carolDeliveredAt;
|
||||||
|
const carolElapsed = carolAt - t0;
|
||||||
|
expect(carolElapsed).toBeLessThan(150);
|
||||||
|
aliceInbox.stop();
|
||||||
|
});
|
||||||
|
|
||||||
test('flush retries on transient server failure', async () => {
|
test('flush retries on transient server failure', async () => {
|
||||||
const store = new MemoryInboxStore();
|
const store = new MemoryInboxStore();
|
||||||
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
@@ -218,6 +467,58 @@ describe('Inbox orchestrator', () => {
|
|||||||
await aliceInbox.tick();
|
await aliceInbox.tick();
|
||||||
expect(await aliceInbox.pendingCount()).toBe(0);
|
expect(await aliceInbox.pendingCount()).toBe(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
test('a failed PUT holds back the rest of its recipient\'s queue, so order survives the retry', async () => {
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const bobClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: bob.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
await bobClient.register({ address: 'bob', signingKey: bob.signingPublicKey });
|
||||||
|
|
||||||
|
// The FIRST PUT fails once. Before the fix the second envelope was
|
||||||
|
// delivered in the same round and the first only on the retry —
|
||||||
|
// bob received them in the wrong order.
|
||||||
|
let failsLeft = 1;
|
||||||
|
const flakyFetch: typeof fetch = (async (input, init) => {
|
||||||
|
const m = (init as RequestInit | undefined)?.method ?? 'GET';
|
||||||
|
const u = typeof input === 'string' ? input : input instanceof URL ? input.toString() : (input as Request).url;
|
||||||
|
if (m === 'POST' && u.includes('/v1/inbox/bob') && !u.includes('/fetch') && failsLeft > 0) {
|
||||||
|
failsLeft--;
|
||||||
|
throw new Error('transient network');
|
||||||
|
}
|
||||||
|
return honoFetch(app)(input, init);
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const aliceInbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'alice',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
signingPublicKey: alice.signingPublicKey,
|
||||||
|
pollIntervalMs: 0,
|
||||||
|
fetch: flakyFetch,
|
||||||
|
queueStore: new MemoryOutgoingQueueStore(),
|
||||||
|
});
|
||||||
|
const delivered: string[] = [];
|
||||||
|
aliceInbox.on((e) => {
|
||||||
|
if (e.name === 'inbox.message_delivered') delivered.push(e.data.msgId);
|
||||||
|
});
|
||||||
|
|
||||||
|
const first = await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(40) });
|
||||||
|
const second = await aliceInbox.send({ recipientAddress: 'bob', envelope: randBytes(40) });
|
||||||
|
|
||||||
|
await aliceInbox.tick();
|
||||||
|
expect(delivered).toEqual([]);
|
||||||
|
expect(await aliceInbox.pendingCount()).toBe(2);
|
||||||
|
await aliceInbox.tick();
|
||||||
|
expect(delivered).toEqual([first, second]);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('tamper detection', () => {
|
describe('tamper detection', () => {
|
||||||
@@ -281,3 +582,195 @@ describe('tamper detection', () => {
|
|||||||
expect(result.received).toBe(0);
|
expect(result.received).toBe(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe('InboxClient — default fetch is bound to globalThis', () => {
|
||||||
|
// Regression: browsers' `fetch` is a WebIDL bound operation that throws
|
||||||
|
// "Illegal invocation" when called as a method on another object. The
|
||||||
|
// class stores `fetchImpl` and calls `this.fetchImpl(...)`, which strips
|
||||||
|
// the Window receiver. Constructor must `bind(globalThis)`.
|
||||||
|
test('default path passes globalThis as `this` (no Illegal invocation)', async () => {
|
||||||
|
const realFetch = globalThis.fetch;
|
||||||
|
let observedReceiver: unknown = 'unset';
|
||||||
|
function strictFetch(this: unknown, _input: unknown, _init?: unknown): Promise<Response> {
|
||||||
|
observedReceiver = this;
|
||||||
|
if (this !== globalThis) {
|
||||||
|
throw new TypeError("Failed to execute 'fetch' on 'Window': Illegal invocation");
|
||||||
|
}
|
||||||
|
return Promise.resolve(
|
||||||
|
new Response('{}', {
|
||||||
|
status: 200,
|
||||||
|
headers: { 'content-type': 'application/json' },
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Object.defineProperty(globalThis, 'fetch', {
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
value: strictFetch,
|
||||||
|
});
|
||||||
|
try {
|
||||||
|
const id = await makeIdentity();
|
||||||
|
const client = new InboxClient({
|
||||||
|
baseUrl: 'http://example.invalid',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: id.signingPrivateKey,
|
||||||
|
// No `fetch` override on purpose — this exercises the default path.
|
||||||
|
});
|
||||||
|
await client.register({ address: 'whoever', signingKey: id.signingPublicKey });
|
||||||
|
expect(observedReceiver).toBe(globalThis);
|
||||||
|
} finally {
|
||||||
|
Object.defineProperty(globalThis, 'fetch', {
|
||||||
|
configurable: true,
|
||||||
|
writable: true,
|
||||||
|
value: realFetch,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('Inbox.start() — fresh-address register/poll race (V4.8)', () => {
|
||||||
|
// Regression: pre-4.8 `start()` called `register()` fire-and-forget AND
|
||||||
|
// `schedulePoll(0)` synchronously, so the first poll often beat the
|
||||||
|
// register HTTP RTT and got SHADE_NOT_FOUND on a fresh address. Fix:
|
||||||
|
// start() defers the first poll; register() success kicks it.
|
||||||
|
test('fresh address: no fetch fires before register completes', async () => {
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
|
||||||
|
// Order observed by the server: must be register-then-fetch, never
|
||||||
|
// fetch-then-register.
|
||||||
|
const calls: Array<'register' | 'fetch' | 'put'> = [];
|
||||||
|
let registerArrived = false;
|
||||||
|
const recordingFetch: typeof fetch = (async (input, init) => {
|
||||||
|
const u =
|
||||||
|
typeof input === 'string'
|
||||||
|
? input
|
||||||
|
: input instanceof URL
|
||||||
|
? input.toString()
|
||||||
|
: (input as Request).url;
|
||||||
|
if (u.includes('/v1/inbox/register')) {
|
||||||
|
calls.push('register');
|
||||||
|
// Hold register for a tick to widen the race window.
|
||||||
|
await new Promise((r) => setTimeout(r, 25));
|
||||||
|
registerArrived = true;
|
||||||
|
} else if (u.endsWith('/fetch')) {
|
||||||
|
// Any fetch arriving before register is the race we're guarding
|
||||||
|
// against.
|
||||||
|
if (!registerArrived) {
|
||||||
|
throw new Error('fetch fired before register completed (race not fixed)');
|
||||||
|
}
|
||||||
|
calls.push('fetch');
|
||||||
|
} else if (u.includes('/v1/inbox/')) {
|
||||||
|
calls.push('put');
|
||||||
|
}
|
||||||
|
return honoFetch(app)(input, init);
|
||||||
|
}) as typeof fetch;
|
||||||
|
|
||||||
|
const inbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'alice',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
signingPublicKey: alice.signingPublicKey,
|
||||||
|
pollIntervalMs: 30_000, // Long enough that only register's kick triggers.
|
||||||
|
fetch: recordingFetch,
|
||||||
|
});
|
||||||
|
inbox.onIncoming(() => null);
|
||||||
|
inbox.start();
|
||||||
|
|
||||||
|
// Wait until register has completed and the success-kick poll lands.
|
||||||
|
await new Promise((r) => setTimeout(r, 100));
|
||||||
|
inbox.stop();
|
||||||
|
|
||||||
|
expect(calls[0]).toBe('register');
|
||||||
|
// First fetch (if any) must be after register.
|
||||||
|
const firstFetchIdx = calls.indexOf('fetch');
|
||||||
|
if (firstFetchIdx !== -1) {
|
||||||
|
expect(firstFetchIdx).toBeGreaterThan(calls.indexOf('register'));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('FetchedBlob.from — relay-supplied sender fingerprint (V4.8)', () => {
|
||||||
|
test('inbox-fetch response carries from = 8-byte hex of SHA-256(senderSigningKey)', async () => {
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
|
||||||
|
const bobClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: bob.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
const aliceClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
|
||||||
|
await bobClient.register({ address: 'bob', signingKey: bob.signingPublicKey });
|
||||||
|
await aliceClient.put({
|
||||||
|
recipientAddress: 'bob',
|
||||||
|
senderSigningKey: alice.signingPublicKey,
|
||||||
|
envelope: randBytes(64),
|
||||||
|
});
|
||||||
|
|
||||||
|
const fetched = await bobClient.fetch({ address: 'bob' });
|
||||||
|
expect(fetched.blobs.length).toBe(1);
|
||||||
|
const fp = fetched.blobs[0]!.from;
|
||||||
|
expect(fp).toBeDefined();
|
||||||
|
expect(fp).toMatch(/^[0-9a-f]{16}$/);
|
||||||
|
|
||||||
|
// Must be reproducible: SHA-256(alice.signingPublicKey) → first 8 bytes hex.
|
||||||
|
const digest = await globalThis.crypto.subtle.digest(
|
||||||
|
'SHA-256',
|
||||||
|
alice.signingPublicKey as unknown as ArrayBuffer,
|
||||||
|
);
|
||||||
|
const expected = Array.from(new Uint8Array(digest).slice(0, 8), (b) =>
|
||||||
|
b.toString(16).padStart(2, '0'),
|
||||||
|
).join('');
|
||||||
|
expect(fp).toBe(expected);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('DecryptHandler raw arg propagates from to the app', async () => {
|
||||||
|
const store = new MemoryInboxStore();
|
||||||
|
const app = createInboxServer({ crypto, store, disableRateLimit: true });
|
||||||
|
const bob = await makeIdentity();
|
||||||
|
const alice = await makeIdentity();
|
||||||
|
|
||||||
|
const aliceClient = new InboxClient({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: alice.signingPrivateKey,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
const bobInbox = new Inbox({
|
||||||
|
baseUrl: 'http://localhost',
|
||||||
|
ownAddress: 'bob',
|
||||||
|
crypto,
|
||||||
|
signingPrivateKey: bob.signingPrivateKey,
|
||||||
|
signingPublicKey: bob.signingPublicKey,
|
||||||
|
pollIntervalMs: 0,
|
||||||
|
fetch: honoFetch(app),
|
||||||
|
});
|
||||||
|
|
||||||
|
await bobInbox.register();
|
||||||
|
await aliceClient.put({
|
||||||
|
recipientAddress: 'bob',
|
||||||
|
senderSigningKey: alice.signingPublicKey,
|
||||||
|
envelope: randBytes(40),
|
||||||
|
});
|
||||||
|
|
||||||
|
let observed: string | undefined = undefined;
|
||||||
|
bobInbox.onIncoming((raw) => {
|
||||||
|
observed = raw.from;
|
||||||
|
return null;
|
||||||
|
});
|
||||||
|
await bobInbox.tick();
|
||||||
|
expect(observed).toMatch(/^[0-9a-f]{16}$/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/key-transparency",
|
"name": "@shade/key-transparency",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/keychain",
|
"name": "@shade/keychain",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/observability",
|
"name": "@shade/observability",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/observer",
|
"name": "@shade/observer",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@shade/proto",
|
"name": "@shade/proto",
|
||||||
"version": "4.2.1",
|
"version": "4.14.1",
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"main": "src/index.ts",
|
"main": "src/index.ts",
|
||||||
"types": "src/index.ts",
|
"types": "src/index.ts",
|
||||||
|
|||||||
@@ -5,7 +5,23 @@ export {
|
|||||||
encodeRatchetMessage,
|
encodeRatchetMessage,
|
||||||
encodeStreamChunk,
|
encodeStreamChunk,
|
||||||
decodeStreamChunk,
|
decodeStreamChunk,
|
||||||
|
encodeBroadcast,
|
||||||
|
decodeBroadcast,
|
||||||
inspectEnvelopeType,
|
inspectEnvelopeType,
|
||||||
|
encodeStreamOpen,
|
||||||
|
encodeStreamOpenAck,
|
||||||
|
decodeStreamHandshake,
|
||||||
|
encodeStreamFrame,
|
||||||
|
decodeStreamFrame,
|
||||||
TYPE_STREAM_CHUNK,
|
TYPE_STREAM_CHUNK,
|
||||||
|
TYPE_BROADCAST,
|
||||||
|
TYPE_STREAM_OPEN,
|
||||||
|
TYPE_STREAM_OPEN_ACK,
|
||||||
|
TYPE_STREAM_FRAME,
|
||||||
|
} from './wire.js';
|
||||||
|
export type {
|
||||||
|
StreamChunkWire,
|
||||||
|
BroadcastWire,
|
||||||
|
StreamHandshakeWire,
|
||||||
|
StreamFrameWire,
|
||||||
} from './wire.js';
|
} from './wire.js';
|
||||||
export type { StreamChunkWire } from './wire.js';
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user