95 Commits

Author SHA1 Message Date
200d5ad831 fix(media): bodies hold no file between reads — a GC-closed handle killed the relay (4.15.1)
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
FileMediaStore.body() kept one FileHandle for the whole response and closed
it only at the end or on cancel. A player that seeks or closes mid-film often
triggers neither; the handle then fell to the garbage collector, which Bun 1.4
treats as fatal. The Prism relay restarted five times this way.

Each piece now opens and closes the file. Regression test runs in its own
process and checks no descriptor is open between reads.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 15:31:59 +02:00
6852e09cb4 release: 4.15.0 — media in the publish order, observer and cli fixed, tarballs verified
Some checks failed
Test / test (push) Has been cancelled
Publish / publish (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
@shade/media was missing from both publish lists while server, sdk, cli and
storage-postgres depend on it. @shade/observer built to dist-build and went
out empty; a bin on src/*.ts shipped one file whose imports were not packed.
publish-all.ts now refuses a tarball that lacks any file main, types, bin
or exports name. The [Unreleased] entries are folded into 4.15.0, which had
not been published.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 12:18:01 +02:00
579d2730e0 feat(media): describeMedia exported from @shade/media/node
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 00:26:25 +02:00
bc7cb85682 feat(media): @shade/media/worker puts the media handler in an app's own Service Worker
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 00:13:50 +02:00
6f67bad97e feat(media): media put seals durationMs, width and height measured by ffprobe
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-20 00:03:38 +02:00
8c7b8800fa scaffold: streaming — closing budget
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:39:27 +02:00
98f54952b5 scaffold: streaming — Share to Shade, uploads from the phone, session report
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:39:07 +02:00
8d6f1fb8a6 fix(media): MediaClient's retry backoff works outside Bun
Bun.sleep threw in a browser or Node the first time a piece was retried;
setTimeout does the same everywhere. The browser bundle has no Bun.* left.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:37:09 +02:00
65d7a0646f feat(android): albums from the phone — several files shared at once are one link
Albums.encode and Grant.encode (live grants too) write what TS writes; the
album vector is resealed byte for byte from Kotlin. MediaUploader.uploadAlbum
seals and uploads one. The demo turns a multi-file share into an album and
its player lists an album's items and opens them in place. The live
cross-check uploads an album from Kotlin that TS opens.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:34:24 +02:00
7d45be8712 fix(media): an uploader checks the relay's upload status before trusting it
A chunk of 0 looped forever, a huge chunk held the film in memory and a huge
window opened a request (a thread on Kotlin) per piece. statusProblem checks
chunk, window, received and landed; the client window is capped at 16. Same
in MediaUploader, with tests on both sides.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:31:06 +02:00
0a706cdb47 feat(android): Share to Shade — a video from the gallery is sealed on the phone and uploaded
ShadeUpload turns a shared content:// URI into meta and an upload job;
KeystoreSecretFile keeps the owner seed under a Keystore key. The demo app
takes SEND/SEND_MULTIPLE of video, images, audio and documents, uploads in a
foreground service with progress, and its done notification plays the file
or shares the link; the player gets a Share button. The live cross-check
also uploads a content:// share under Robolectric.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:28:36 +02:00
b53dcd7813 feat(android): UploadJobs — an upload from a phone survives the app being killed
MediaUploader.upload(jobs, key, …) seals once into an app-private job
directory and resumes with the same media id; a job already done gives its
grant again unless the relay says the file is gone. OS file locks keep one
upload per job. The live cross-check now kills a job after its first piece
and resumes it.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:21:52 +02:00
f5125b8f66 feat(android): MediaUploader — a phone puts films on a relay, in resumable pieces
MediaOwner signs owner requests and MediaUploader speaks the piece protocol
of media put (window, retries, resync after a lost answer). MediaSealer
.sealStream seals a film to a file; MediaGrant.encode/capabilityUrl make the
link to share. Owner signatures and encoded grants are pinned by new
vectors; scripts/media-live-kotlin.ts runs the uploader against a real TS
relay with a lost answer and a refused piece injected.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:18:31 +02:00
f42a9bbe5e refactor(media): upload pieces are PUT, not PATCH
A piece at an offset is idempotent, which is what PUT means. Java's
HttpURLConnection, which the Kotlin port uses, refuses PATCH outright. nginx
also retries PUT on the next upstream by default but never PATCH, so the docs
now only ask for non_idempotent on the start/status POST. The protocol is
unreleased, so nothing else depends on the old method.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:09:09 +02:00
441f26f814 docs(media): load balancers may retry upload pieces on another instance
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:07:03 +02:00
6ee9ccc18a fix(media): an upload error shows the relay's answer, not an HTML error page
When a piece failed through a proxy whose backend was down, the CLI printed
Bun's whole HTML error page. Answers that are HTML are now left out of error
messages, and the rest is cut at 300 characters.

Found in an end-to-end run: two S3+Postgres relays behind a load balancer,
`media put` of 300 MiB, one relay killed with SIGKILL mid-upload. The test
balancer went strictly round robin with no failover, so every retry's PATCH
hit the dead relay and the run stopped, saying to run it again. Run again
with failover to the next backend (like nginx proxy_next_upstream), the same
command resumed from the first run's job at 31%. Relay 3921 was killed again
after 4 pieces, 2 pieces failed over, and relay 3922 took 9. The file came
back byte-identical and shade_media_uploads was left empty.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:06:53 +02:00
6e97329a58 scaffold: live record done
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:02:21 +02:00
5cc9133b3c feat(media): shade live record — a broadcast to files, or to a sealed film with its own link
`live record <link> [-o base] [--put --server URL]` writes what a channel
carries until the channel ends or Ctrl-C:
- text goes to base.txt;
- video and sound go to base.webm or base.mp4: the init, then every chunk in
  the order sent. A chunk that arrives late is left out and counted. A new
  init continues in base-2.…;
- pictures go to base-images/.

ffmpeg then rewrites each recording with -c copy, which adds an index for
seeking and starts the clock at 0:00. `--put` seals and uploads the recording
under the channel's name (several files become an album). LiveRecorder is
exported from @shade/media/node.

`live video` now sends a sticky meta frame like text and picture channels do.
The browser and Android players ignore it.

Verified against a real relay:
- A 30 s VP8/Opus broadcast was recorded and is 29–32 s long, starting at 0.
- It was uploaded as "Kveldssending.webm" and plays in Chromium, with a seek
  to 22 s (frame 14).
- Live playback with the meta frame still plays, with 2.4 s latency.

Tests:
- object-store's memory test now runs in its own process. RSS is process-wide,
  and other test files in the same `bun test` made it flaky (192 MiB). It now
  compares memory held after a collection at 128 MiB and 512 MiB, ~85 vs
  ~103 MiB, instead of using a magic number.
- The sweep test has its own prefix.
- tests/live-record.test.ts (4).
- media 122 green, 3 runs in a row. All 27 packages type-check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-19 00:01:55 +02:00
ee93dee8db scaffold: put resumes across runs
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 23:46:08 +02:00
20c5ec07ab feat(media): media put resumes across runs, and a file already up gives its link again
A run already survives a dropped connection by retrying. This covers what one
run cannot survive: Ctrl-C, a laptop that sleeps, a relay that is gone for
longer than the retries wait.

Each file being put has a job under $XDG_CONFIG_HOME/shade/media-pending/,
keyed by server, path, size, mtime and options. The job holds:
- the sealed copy;
- job.json (0600: the seal result with the file key, the read token, and the
  meta including subtitle grants);
- a lock with the pid of the run working on it. A lock left by a dead run is
  taken over.

Running the same command again resumes with the same media id, so the relay
already has most of the file. Once the relay has stored it, the copy goes and
the grant stays. Putting the file again gives the same link while the relay
still serves it, so a season's put run again after it stopped re-sends only
what is missing. Jobs untouched for 30 days are removed.

Verified with real processes, a 300 MiB file and a file-store relay:
- Run 1 was SIGKILLed after 8 of 19 pieces.
- Run 2 resumed at 42% and finished.
- Run 3 printed "already on the relay, same link".
- `media get` returned the file byte-identical, and the library has one item.

tests/put-jobs.test.ts (4). media 118, cli 15. All 27 packages type-check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 23:45:56 +02:00
0dc89e6cba scaffold: piece uploads done and verified end to end
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 23:40:41 +02:00
bd4882e1b8 feat(media): uploads in pieces — resumable, and a relay's memory no longer grows with the film
Bun.serve reads a request body as fast as the client sends it, whether the
handler takes it or not. Whenever the store was slower than the client, one
PUT of a film put the whole film in the relay's memory: a 512 MiB upload
peaked at 762 MiB (disk) and 1011 MiB (S3).

A sealed file over 16 MiB now goes up as POST /v1/media/:id/upload plus
16 MiB PATCH pieces, each signed over its offset and length, up to 4 in
flight and landing in any order. Uploads under way are durable: on disk
uploads/<id>.part + .json + .log (the log names a piece only after fsync),
and in S3 a row in shade_media_uploads beside the multipart upload, where
piece n is part n+1. A dropped connection, a relay restart or the next piece
landing on another instance costs only the pieces in flight. The client asks
how far the upload got and sends the rest. Uploads count against quota and
are swept after 24 h without a piece. An upload still receiving pieces is
never swept, however old its multipart upload is.

The sweep is now part of every MediaStore and runs from createMediaService
(onSweep) instead of two copies of the timer. No route takes more than
64 MiB, so Bun's 128 MiB cap stays and the container's body limit covers
every route. `media put` shows progress.

bench/media-store.ts: the relay's peak RSS is 330–369 MiB at both 512 MiB
and 1.5 GiB (worst of 3 runs, both stores).

Also found:
- Bun 1.3.5 fetch never finishes sending a Bun.file().slice() body, so the
  client reads each piece itself.
- postgres.js reads a NULL element of a TEXT[] as the string "NULL", so etags
  are selected as JSON.

Tests:
- tests/upload.test.ts (11).
- S3 across two instances (+2).
- PG index (+1).
- media 114, storage-postgres 21, server 55, cli 15.
- All 27 packages type-check.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 23:39:25 +02:00
5f7c6ff4b4 fix(media): relays release their live-channel claims on shutdown
LiveRelay.stop() fired the claim releases and forgot them, and nothing
closed the shared backend's Postgres pool: on a redeploy the process could
exit first, leaving the other instances to follow a dead relay until the
claim went stale (30 s). stop() is now async and resolves once the
releases are written; MediaService.stop() passes it through; the
container awaits it and closes the backend on SIGTERM, and `media serve`
gained SIGINT/SIGTERM handling that does the same and closes open sockets
so publishers and viewers reconnect elsewhere.

Verified: a test that a stopped relay's claim is gone at once; a real
`media serve --s3 --pg --advertise` with a live publisher: SIGTERM →
exit in ~0.4 s, its shade_live_publishers row 1 → 0, the publisher
reconnecting. Suites green (media 101, storage-postgres 20, server 55,
cli 15).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:58:51 +02:00
0bbeb5682b feat(media): live video --input — a film, a webcam or an IP camera without writing the ffmpeg line
`shade live video` needed a hand-written ffmpeg pipeline. --input <file |
/dev/video0 | rtsp://…> probes the source and runs ffmpeg itself:
H.264 and AAC are copied (a camera's own encoder, no CPU), anything else
becomes H.264 with a keyframe every 2 s whatever the frame rate (where
late joiners start) and AAC (>6 channels downmixed to 5.1), out as
low-latency fragmented MP4. A file is paced (-re) as if live; RTSP goes
over TCP; /dev/videoN opens as v4l2. ffmpeg's failure is reported with
its own last lines.

Verified: liveEncodePlan unit tests (copy, encode, pacing, RTSP/v4l2,
audio-only, nothing-to-send); Chromium through the relay: VP9/Opus WebM
encoded → live H.264/AAC, keyframe every 4th 0.5 s fragment, 0.96 s
latency; H.264/AAC MKV copied, 1.8 s latency. Media suite 97/0.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:56:19 +02:00
d87db5f4dc feat(media): shade live images — a webcam, a slideshow or a watched folder, end to end
Pictures were a live content type the watch page could show but nothing
could publish. `shade live images`:
- stdin: back-to-back JPEG/PNG, e.g.
  `ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe -`;
- files/directories: a slideshow, one picture every --every seconds;
- --watch DIR: each new picture once its size holds still (cameras
  write in pieces).
Each picture is a keyframe, so a late viewer opens on the latest. The meta
carries the first picture's type (MIME_RE rightly refuses image/*).

ImageStreamSplitter walks JPEG markers (lengths to SOS, then the
entropy-coded data, where every 0xFF is stuffed) and PNG chunks to IEND,
so an EXIF thumbnail — a whole JPEG inside APP1 — does not end a picture.
Bounded at 16 MiB per picture, junk refused at its first bytes.

The Android demo shows live picture channels and sealed pictures
(decoded off the UI thread, downsampled to the screen).

Verified: splitter on real ffmpeg MJPEG/PNG under random pipe chunking,
the thumbnail case, truncation, junk and the size cap (4 tests); in
Chromium a 2 fps MJPEG "webcam" through the relay (8 → 14 pictures in 3 s,
960×540); a watched folder with a PNG written in two halves (sent once,
whole) and a .txt ignored; slideshow; error paths. Demo APK builds; not
run on a device (none connected).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:53:37 +02:00
1653060494 fix(media): live radio gets an audio player — the meta carries the init segment's real type
`shade live video` wrote meta.mime from the container alone (video/webm,
video/mp4) before the init segment was seen, so an audio-only stream
(Opus/WebM, AAC/fMP4) played sound in a black 120 px video box. It now
reads until the splitter yields the init and uses its type
(audio/webm; codecs="opus"); the watch page then builds an <audio>, and
sound gets a player bar on the panel instead of a black stage.

Verified in Chromium, unmuted, through the relay: Opus/WebM and AAC/fMP4
radio both play (currentTime advancing, readyState 4) with measured
output (WebAudio RMS 0.044). Media suite 93/0.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:48:00 +02:00
f1b4c1ade1 feat(media): live channels across relay instances; viewers hear when a channel goes live
With several relays sharing pins, a viewer and the publisher could land on
different instances and never meet. LiveRelayOptions.mesh: each relay
claims the channels whose publisher it holds (LivePublisherLocator,
Postgres table shade_live_publishers, heartbeat 10 s). A relay whose
viewers want a channel published elsewhere subscribes to that relay once,
with a viewer's own read token, and fans out locally, verifying every
frame against the pin (a peer or a poisoned locator row cannot forge
one). Re-following replays a backlog; frames are passed on once (seq).
Viewers follow a publisher that moves. A token that fails the in-memory
pin is checked against the shared pin before refusal, so a publisher
back with a new read token is honoured on every instance.
SHADE_MEDIA_RELAY_URL / `media serve --advertise`.

Relays now send {"type":"state","live"} when a channel goes live or quiet
after a viewer joined; handled by the TS client (browser) and Android's
LiveWatcher.

Fixed on the way:
- The relay never saw its publisher leave: Hono gives each event its own
  WSContext and the close handler compared identity. Channels stayed
  "live" with nobody publishing; a replaced publisher was never closed.
- FileMediaStore on an unusable directory raised an unhandled rejection
  at start; now each call fails with the reason.

Verified: 5 mesh tests (follow, late join, publisher moving A→B with
dedupe, forging peer refused, new read token) + state test, each fix
mutation-checked; Postgres locator + two media services over Postgres;
CLI relays with --advertise behind a round-robin HTTP+WS balancer:
publisher on A, Chromium viewer on B, "live", 208 lines. Suites: media
93, storage-postgres 20, server 55; Kotlin 92 (1 skipped), 0 failures.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:44:19 +02:00
aaec92429d feat(media): one library for several relays — films in S3, records and live pins in Postgres
FileMediaStore ties a library to one disk on one machine. SHADE_MEDIA_S3_URL
+ SHADE_MEDIA_PG_URL (or `media serve --s3 --pg`) put sealed bytes in any
S3 bucket and the records every instance must agree on in Postgres.

- ObjectMediaStore: each upload streams as multipart to its own object
  key; the commit is an INSERT whose primary key admits one record per id,
  so racing uploads on any instances are decided once and the loser
  deletes its object. Delete drops the record first. sweep() reclaims
  unreferenced objects and dead multipart uploads past a 24 h grace.
- S3Bucket: Shade's own SigV4 client. Bun 1.3.5's S3Client buffers a
  whole upload (512 MiB in, 543 MiB RSS), end(error) does not abort, and
  slice(0, n).stream() returned the whole object. Here: at most three parts
  in memory (512 MiB through, 11 MiB RSS), payload-hashed signatures,
  AbortMultipartUpload, ranged reads checked for length.
- PostgresMediaIndex, PostgresLivePinStore, createSharedMediaBackend in
  @shade/storage-postgres. LivePinStore.put now refuses a key change
  (LivePinTakenError) in every store, atomically in Postgres.
- The container logs a backend it cannot use and runs on without media.

Verified: SigV4 reproduces AWS's published example signature; SeaweedFS
with signature checking accepts it and refuses a wrong secret (403);
Postgres 16: racing inserts over 8 pools (1 of 24 wins), racing pins,
BIGINT sizes; two relays over one backend; CLI relays behind a
round-robin proxy: upload, bit-identical download, Chromium playback
seeked to 24 s with ranges served by both; the bucket holds no
plaintext, name or MP4 marker. Suites: media 87, storage-postgres 18,
server 55, cli 15, all green.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:28:58 +02:00
01f8471fb5 feat(media): a local library of uploads — media ls with names, media link; canonical grant encoding
The relay never knows names and a link is printed once, so a lost link
made an owned film unreachable. media put now appends each upload and its
grant to $XDG_CONFIG_HOME/shade/media-library.jsonl (0600, one JSON line
per change: concurrent uploads cannot lose entries, a torn line costs only
itself). media ls names uploads from it; media link <name|id> prints the
link again; media rm forgets it.

encodeGrant now writes meta in canonical (validateMeta) order, so one
grant is always one link; media.json vectors regenerated (album and
subtitle vectors only), Kotlin 82/0.

Verified: 82 TS tests (library: fold, find, 0600, torn line, 200
concurrent appends, stable encoding); CLI put → ls → link gives back the
identical link.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:08:22 +02:00
d784e47ab3 feat(media): media put --web — films browsers refuse (HEVC, AC-3, DTS) converted before sealing
ffprobe decides per stream: H.264/VP8/VP9/AV1 and AAC/MP3/Opus are
copied, anything else becomes H.264 (CRF 20) / AAC with every audio track
and its language kept; embedded text subtitles come out of the same
ffmpeg pass as subtitle tracks; picture subtitles are reported. Output is
an MP4 with the index first. Without --web, put warns when ffprobe sees
streams browsers will not play.

Verified: an HEVC + AC-3 5.1 MKV with embedded Norwegian/English SubRip:
Chromium refuses the original (DEMUXER_ERROR_NO_SUPPORTED_STREAMS); the
--web upload plays with audio decoded and the Norwegian track showing.
78 TS tests.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:05:28 +02:00
422a37e830 feat(media): subtitles that travel with the film — CLI, browser <track>, ExoPlayer
`shade media put Film.mkv` seals Film.srt / Film.no.srt / Film.en.vtt
found beside it and carries their grants in the film's sealed meta
(extra["shade.subtitles"]), so they follow the film alone or in an album
and the relay sees unrelated objects. /watch/ adds them as <track>s (SRT
to VTT, labels in the viewer's language, the viewer's language on, one at
a time); `media get` writes them back; Android opens them with
ShadeMedia.openFilm and gives them to ExoPlayer as side-loaded tracks
(ShadeMediaDataSource now resolves readers by URI).

Verified: 76 TS tests; Chromium nb-NO shows the Norwegian track only, en-US
the English one; film + subtitles round-trip bit-identical; Robolectric
ExoPlayer sees both text tracks with the Norwegian one default; a shared
vector checks the meta field in Kotlin (82/0).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 22:01:33 +02:00
9efe1bcfd3 feat(media,android): live channels in ExoPlayer — LiveWatcher, ShadeLiveDataSource
LiveWatcher is the Android LiveWatchClient (OkHttp WebSocket, subscribe
with the read token, reconnect with backoff, backlog deduplicated by the
subscriber). ShadeLiveDataSource turns frames into one endless WebM/fMP4
stream for ExoPlayer's extractors: init, then media from the first
keyframe, and after a gap nothing until the next keyframe. Late joiners
start at 0:00 (fMP4: per-join TimestampAdjuster; WebM: cluster Timecode
rewritten in place). A changed init fails with a ParserException (not
retried). The demo app plays live video and follows log channels.
LiveSubscriber.close() wipes keys, as in TS.

Verified (Robolectric): late join on H.264/AAC fMP4 and VP8/Opus WebM cut
by the TS splitter (fixtures from scripts/make-live-fixtures.ts) plays
from the keyframe, rebased (mutation check: without the rebase the WebM
test fails, 5020 vs 4250 ms); gap recovery; format change; LiveWatcher
against MockWebServer with a dropped connection and backlog replay.
Kotlin 81/0. Not yet run on a device.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:53:17 +02:00
8c7300fa51 feat(media): albums — one link for a season or a photo album; fix path traversal in media get
An album is a sealed file (shade.album/v1) listing grants, so the relay
cannot tell it from a film. `shade media put dir/` uploads every file and
the album (subdirectories nest, natural order); `media get` brings an
album back as a directory; /watch/ shows a grid with decrypted previews
and Back returns to the album without putting grants in history. Kotlin
reads albums (Albums.read) against a new shared vector.

Fixed: `media get` used the sealer-chosen meta.name as the output path.
Fixed a relay test race (flush() is sent, not received); the relay now
reports framesIn.

Verified: 64 TS tests x3, Kotlin 81/0, a 6-file album with a nested album
uploaded, browsed, played and downloaded back bit-identical.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:44:43 +02:00
e696d83283 feat(media,android): ExoPlayer DataSource for sealed files, demo player app
:shade-android-media wraps the Kotlin MediaReader as a Media3 DataSource,
so ExoPlayer plays and seeks any container from a sealed file; a tampered
segment fails the read instead of reaching the decoder. :shade-media-demo
opens a shared watch link and plays it.

Verified: Robolectric — byte-exact reads whole and in ranges, tamper
refusal, ExoPlayer plays a sealed H.264/AAC clip to the end and reopens
mid-file on seek. Kotlin suite 80/0. Not yet run on a device.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:33:32 +02:00
75dbf530ce feat(media): live fragmented MP4 (H.264/HEVC/AV1 + AAC/Opus), shade live video
Fmp4Splitter cuts ftyp+moov into the sticky init and moof+mdat into frames,
reading sync samples from trun/tfhd/trex flags so fragments shorter than a
GOP still mark where late joiners may start. Codec strings come from the
sample entries. MediaSplitter sniffs WebM vs fMP4; the CLI's new
`live video` uses it (`live webm` stays as the pinned form).

Verified: 9 new tests on real ffmpeg output; H.264/AAC live in headless
Chromium (49/49 fragments appended, late join, 3.2 s latency) and a sealed
H.264 film seeking to 24 s.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:27:50 +02:00
c5b897b924 docs(scaffold): streaming log post, plan and tasks
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:20:57 +02:00
4703140683 chore: 4.15.0 — @shade/media
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:19:37 +02:00
8fd1b19902 feat(sdk): shareMedia / onMediaGrant — media grants over a Shade session
A grant for a sealed file or a live channel rides the Double Ratchet like
any message. With an onMediaGrant handler registered, grants are routed
there instead of onMessage; with none, they arrive as text as before.
Bench results for @shade/media (1 GiB, up to 200 live viewers, 100 %
delivered) committed with their chart spec.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:17:59 +02:00
e9ae5bd28e fix(media,server): films over 128 MiB were refused; docs/media.md
Bun.serve refuses request bodies over 128 MiB by default, so every film
larger than that got a 413 from both `shade media serve` and the container.
The cap is now raised to the media object limit only when media is
mounted, and every other route gets an explicit 128 MiB bodyLimit — several
read the whole body before checking its size, so Bun's default was their
only guard. Verified on the standalone process: 300 MiB sealed film round
trip identical; a 200 MiB POST to a prekey route still 413.

docs/media.md: formats (SMF1, SLF1, grants) as the cross-language contract,
key schedule, what the relay learns, design notes, limits.
bench/media.ts: throughput, seek latency, live fan-out → media.chart.json.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:15:13 +02:00
df3ca685c5 feat(media,server): media in the Shade container, owner-only uploads and channels
- createMediaService: sealed store + live relay + /watch in one mount, used
  by both `shade media serve` and standalone.ts
- SHADE_MEDIA_DIR enables it (no in-memory fallback, like the vault);
  SHADE_MEDIA_OWNERS lists who may upload and open live channels
- live publishers co-sign their hello with an owner key; a relay with an
  owner list refuses everyone else, and the client stops on that refusal
  instead of reconnecting forever
- relay caps live channels held at once; `shade media whoami`

Verified against the real standalone process: film round trip identical,
stranger gets 403 / refused channel, live logs and browser playback.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:10:43 +02:00
d117397b36 feat(media,android): Kotlin SMF1 reader/sealer and live channel, cross-language vectors
test-vectors/media.json pins SMF1 files (empty, partial, exact boundary,
multi-segment with full metadata) and SLF1 live frames in link mode across
a rotation. Kotlin reads them and reproduces every sealed file and every
signed frame byte for byte; TS locks the same file.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:07:45 +02:00
f359cbd9ad feat(media): browser playback, live WebM and log streaming, shade media/live CLI
- Service Worker plays sealed files in native <video>/<audio>/<img> with
  Range seeking; watch page served by the relay itself (#shade= fragment
  links, grant never sent to a server)
- MSE live player with keyframe-aware joining, gap detection, latency control
- WebM splitter (init + clusters, keyframe detection) that puts blocks in
  timecode order — Chrome rejects ffmpeg's interleaved Opus/VP8 otherwise
- Link mode for live channels: epoch seeds from a channel secret, so a
  link survives publisher restarts and scheduled rotations
- File store streams byte ranges itself (Bun.file().slice() in a Response
  sent whole files to Range requests)
- shade media serve|put|get|ls|rm, shade live text|webm|watch

Verified end to end in headless Chromium: VP9/Opus film plays and seeks,
live VP8/Opus at 2.9 s latency, live logs, sealed JPEG and Opus audio.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 21:01:52 +02:00
9e64ec87be feat(media): @shade/media — seekable sealed media (SMF1), live channels, media routes and live relay
SMF1 seals a film, video, image or song once into a file any Range-capable
store can serve; the reader fetches only segments under the playhead and
checks each against a digest table pinned by the grant's root digest.
Live channels use a sender-key chain with per-frame Ed25519 signatures,
sticky init frames and keyframe snapshots for late joiners, and epoch
rotation to remove a viewer. Server side: a disk-backed media store with
signed owner uploads and a WebSocket relay with bounded backlog.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-18 20:41:31 +02:00
fb7f2e55c0 feat(android): Kotlin-vaulten — vault v2 lest og skrevet fra telefonen
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
no.zyon.shade.vault: samme format som @shade/vault 4.14.1 (deflate-raw-
entries, biter à 4 MiB, SVM2-manifester, indeks, edit med retry på
SEQ_CONFLICT). CanonicalJson for signaturene; BlobKdf bruker BouncyCastle
for Ed25519-public. Vektortester mot test-vectors/vault-v2.json og et
live kryss-sjekkskript (scripts/vault-live-kotlin.ts) mot TS-klienten.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 13:18:01 +02:00
a1c370359e feat(vault): edit — change a few files against the head that was read (4.14.1)
Some checks failed
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 01:42:18 +02:00
b82a803e0c feat(vault): v2 — compressed entries, chunked objects, index pushes, lazy reads, prune (4.14.0)
Some checks failed
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Entries are deflate-raw compressed when it pays, split into 4 MiB sealed
parts, and manifests are compressed (SVM2). A push with a local index
reuses unchanged files without downloading anything, and a push with no
changes commits nothing. Readers fetch one manifest and only the entries
they need. The relay records what each version references and can prune
old versions signed by the owner. Cross-language vectors in
test-vectors/vault-v2.json.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-16 01:38:45 +02:00
bcae7b346e fix(sdk,transport): bounded prekey requests and a real registration retry (4.13.2)
An unreachable prekey server (packets dropped, not refused) held
createShade for ~2 min per call, and a failed registration was never
retried despite the log saying so. Every request now has a deadline,
registration retries with backoff until it lands, and
registration: 'background' lets an app open its identity offline.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-15 20:49:56 +02:00
5d04e18482 fix(inbox): a failed PUT no longer lets the next message overtake it (4.13.1)
Some checks failed
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Test / test (push) Has been cancelled
flushOnce drained a recipient's bucket in order but carried on past a
failure, delivering N+1 before N's retry. For sender-key broadcasts the
receiver cannot open N once past it — frozen terminal output in Prism.
Stop the bucket at the first failure; other recipients still drain in
parallel. Also corrects senderKeyDecrypt's doc, which claimed a
skipped-key cache that never existed.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-06 09:08:52 +02:00
f6e4ac8aeb test(crypto): stop letting the scheduler answer for the code
Some checks failed
Test / test (push) Has been cancelled
Third flake found in the same hunt. `timing variance stays bounded across
mismatch positions` took two single measurements of 50 000 iterations each and
compared their ratio, which is one GC pause away from a false alarm — it failed
about one run in fourteen on a loaded machine.

Two things were wrong with the measurement, not the property:

The first loop through that code pays for JIT compilation the second one does
not, so whichever side ran first was biased upward. The old comment admitted it
— "allow 2x variance for JIT/noise" — which is a tolerance covering a
measurement artefact rather than the thing under test. There is a warm-up now.

And a single pair has no defence against a scheduler hiccup. Five interleaved
pairs compared by median throw the pause out instead of the property.

The threshold is unchanged at 3, deliberately. An early-exit compare takes
~256x longer to reach a mismatch in the last byte than the first, on every
round; nothing here weakens what the test catches.

Verified that it still catches what it is for: with `constantTimeEqual`
temporarily replaced by an early-exit loop the test fails, and passes again
with the real one restored. A security test nobody has watched fail is a
security test nobody knows works.

A security test that cries wolf under load is worse than none — it teaches
people to re-run until green, and then a real regression looks like the noise.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014489bKUtUEY1Zgs9xN9mt7
2026-09-08 16:42:37 +02:00
baddf5f56e fix(transfer): an abort left N-1 unhandled rejections behind
Some checks failed
Test / test (push) Has been cancelled
Second flake in the same hunt, and a real bug rather than a test artifact.

`runRoundRobinUpload` and its resumed twin ended with `await Promise.all(workers)`.
`Promise.all` rejects the moment one worker throws and leaves the rest running
with nobody holding their rejections — so an abort, which fails every lane at
once, produces one propagated error and N-1 unhandled ones.

Bun counts an unhandled rejection as a test failure, which is how

    (fail) Resume protocol — kill-restart-verify
           → sender crash mid-transfer → resumeUpload completes the same stream
    TransferAbortError: Aborted during attempt

failed about one run in fourteen, with an error the test had already caught
properly through `handle1.done()`. The test was right; the engine was dropping
rejections on the floor beside it.

`settleWorkers` waits for every lane, then reports the first real failure —
preferring a genuine error over `TransferAbortError` when both happened, since
an abort is not the interesting one when something actually broke. Four call
sites.

This is not only a test problem. In production the same shape means a
cancelled or failed multi-lane transfer emits unhandled rejections into
whatever process is running the engine, and on a strict runtime that is a
crash rather than a log line.

Verified: 1198 pass / 0 fail.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014489bKUtUEY1Zgs9xN9mt7
2026-09-08 16:39:49 +02:00
53ce776c02 test: stop guessing port numbers
Twenty test servers picked a port with `NNNN + Math.floor(Math.random() * 500)`
and hoped it was free. Several files guessed inside the *same* range —
sdk.test.ts and gates.test.ts both on 19500, three files on 22000, and
webrtc-integration.test.ts used 22000 twice within itself — so with test files
serving in parallel the collision was not unlikely, it was scheduled.

Found from the outside, in Nova, where Shade is vendored: across eight runs of
an unchanged tree, two had failures and six were clean. The visible error was

    Failed to start server. Is port 24287 in use?  EADDRINUSE

and then a second, louder one: `teardownRig` ran on a rig that setup had never
finished building and died on `rig.alice`, so the TypeError from cleanup is
what you read first and the real cause scrolled past above it.

`Bun.serve({ port: 0 })` lets the OS hand out a free port and `server.port`
reads it back. There is no range to collide inside.

teardownRig now tolerates a rig that was never built. Cleanup must never be the
loudest thing in a failing test.

A suite that fails a quarter of the time is worse than a suite that fails: it
teaches everyone to re-run it, and then a real regression looks like the flake.

Verified: 1198 pass / 0 fail here, and the same fix is going into Nova's
vendored copy so the next sync does not bring the guessing back.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014489bKUtUEY1Zgs9xN9mt7
2026-09-08 16:33:40 +02:00
3c69995097 fix(docker): raise fd limit so bun install can extract large tarballs
Some checks failed
Test / test (push) Has been cancelled
BuildKit gives each RUN a 1024 soft file-descriptor limit against a ~1M
hard limit, and bun extracts tarballs in parallel — a large enough package
exhausts the descriptors and the install dies with "Fail extracting
tarball". It only shows up inside a build, because `docker run` inherits a
far higher limit, which makes it look like a flaky registry.

This bit Nova's deploy (on mermaid) and was fixed there; shade-server has
the identical pattern and escaped only because its layers were cached, so
it would have failed on the next cache-less build. Fixing it at the source
too, so a vendor sync cannot silently drop it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-20 00:06:02 +02:00
9789b6fc16 docs(vault): scaffold.zyon.no i eksempelet
Some checks failed
Test / test (push) Has been cancelled
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 14:48:14 +02:00
40286a8542 test(vault): verktøy for å verifisere en kjørende vault over ekte HTTP
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Enhets- og e2e-testene kjører mot Hono-fetch i prosess. Dette skriptet går
mot en faktisk lyttende tjeneste — container eller deployet instans — og
er det som fanget at Dockerfilen pekte på src/standalone.ts i en publisert
pakke som bare shipper dist/.

  SCAFFOLDD_SOCKET=... RELAY=https://vault.zyon.no bun live-e2e.ts

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 12:05:18 +02:00
cc6b1d53d7 chore: bump til 4.13.0 og legg @shade/vault i publiseringslistene
Tørrkjøringen fanget to ting: vault manglet i PACKAGES (så @shade/server
feilet på en ukjent workspace-referanse), og jeg hadde innført en syklus
storage-sqlite → vault → server → storage-sqlite. Den siste er løst ved at
storage-sqlite bare bruker VaultStore som TYPE — flyttet til devDependencies,
så det ikke er en runtime-avhengighet.

vault står ved siden av inbox-server i lista: begge er i en syklus med
server (de trenger verifyPayload, standalone.ts mounter rutene deres), og
lista håndterer det allerede ved å liste server først.

publish:dry: 26 pakket, 0 feilet.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 12:01:05 +02:00
d8f6da55ef docs(scaffold): plan, tasks og loggposter for vault + G0
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 11:58:49 +02:00
3da977207c chore(ci): pin TypeScript og kjør typecheck som gate
G0-P0. typecheck-all.ts kjørte 'bunx tsc', som henter nyeste utgivelse ved
hver kjøring — gaten kunne gå rød, eller stille slutte å fange ting, fordi
TypeScript hadde sluppet en versjon og ikke fordi repoet endret seg.

typescript pinnet til 7.0.2; scriptet bruker node_modules/.bin/tsc. Nytt
Typecheck-steg i test.yml, plassert FØR testene: en typefeil er billigere å
lese enn kjøretidsfeilen den til slutt forårsaker.

Helsesjekkens antakelse om baseUrl stemmer ikke lenger — feltet finnes ikke
i repoet, og alle 26 pakker er grønne inkludert consumer-strict.

dist-build/ lagt i .gitignore (observer-avviket fra G0).

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 11:58:49 +02:00
84d3166ca1 feat(vault): server-side kryptert fillager (V4.13)
Shade kunne flytte filer mellom peers (@shade/files) og lagre én liten
profil-blob per konto, men hadde ingen alltid-på lagring av krypterte filer.
Uten den kan ingen Shade-app tilby backup, og ingen klient lese data mens
peeren som eier dem er avslått.

Objekter er innholdsadresserte på hashen av CHIFFERTEKSTEN, så relayen kan
lagre, deduplisere og verifisere uten nøkkel — den regner om hashen ved
opplasting og avviser feilnavngitte objekter. Stier bor inne i det krypterte
manifestet, aldri i objektnavn: relayen skal ikke lære hva filene heter.
Loggen er append-only, så historikk og rollback følger av modellen.

SqliteVaultStore har med vilje INGEN minne-fallback, i motsetning til
blob-storen. Den fallbacken slettet Prisms profil ved en rutine-redeploy
2026-08-12 fordi den fungerte helt til containeren ble recreated, uten en
eneste feilmelding. En backup som glemmer er verre enn ingen backup, så uten
SHADE_VAULT_DB_PATH mountes rutene ikke — med en logglinje som sier hvorfor.

Én feil fanget av testene: pubkeyen ble først lagt på UTENFOR signaturen,
som både brøt verifyPayload og ville latt hvem som helst bytte identitet i
transit på den TOFU-pinnende førsteskrivingen.

16 vault- + 7 store-tester, alle mot de ekte rutehåndtererne gjennom Honos
fetch. Kjeden er dessuten kjørt mot en ekte HTTP-server med et ekte
workspace: 491 filer / 7,7 MB, alle bit-identiske etter gjenoppretting,
og andre push etter én endring sendte 0 KB.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 11:58:37 +02:00
012d7f5289 fix(storage-encrypted): tilfeldig AES-GCM-nonce + vault-nøkkelgren
To endringer i samme krypto-filer.

G0-P0: deriveNonce() lagde nonce som en ren funksjon av radens identitet.
saveSession re-forsegler ved hvert ratchet-steg, så (key, nonce) gjentok seg
per konstruksjon over ULIK plaintext — GCM forbidden attack, som lekker både
XOR-en av plaintekstene og GHASH-subnøkkelen. Fire kallesteder: sealString og
sealBytes tar nå randomNonce(), openString/openBytes slutter å tvinge den.

Ingen migrering: aeadOpen har alltid lest nonce fra blob-prefikset, så
eksisterende data åpnes uendret. Testet eksplisitt. deriveNonce og
expectedNonce beholdt som deprecated — begge er del av den publiserte flaten.
Android var aldri rammet; KeystoreStorage bruker cipher.iv, som Android
Keystore alltid genererer tilfeldig.

V4.13: egen HKDF-gren for vault (shade-vault-{id,content,sig}-v1). Ikke
gjenbruk 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.

9 nye tester; testene er bevist å ha verdi ved å reversere fiksen —
nøyaktig de tre som beskriver feilen faller. 87 grønne totalt.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-14 11:58:19 +02:00
96c20cb4b2 fix(session): remember where aliasSession moved a session
aliasSession knew that two labels name the same peer, then threw that
knowledge away. The binding lived only in the caller's memory, so a
restart lost it — and the peer could not repair it from its side.

First contact forces the receiver to label a session by the only sender
hint a relay surfaces, an 8-byte signing-key fingerprint (`fp:<hex>`).
Once the peer announces its canonical address, aliasSession moves the
session there. But the peer keeps sending under `fp:<hex>`, because its
transport derives the same label from the same hint every time. After a
restart the session sat under the canonical address, inbound frames
resolved to `fp:<hex>`, and nothing matched. The peer held a valid
session so it never re-ran X3DH: the failure was permanent, and only a
manual re-link cleared it.

Observed in Prism as `No session for address: fp:579c3b335d66e2c0` on
every receive for three days, with a phone whose every RPC timed out.

StorageProvider gains saveSessionAlias / getSessionAlias /
removeSessionAliasesFor, optional so third-party implementations keep
compiling, and implemented across all seven backends. Lookups resolve
through resolveLabel(), which runs BEFORE the peer mutex — locking the
alias while mutating the canonical session would let an aliased and a
canonical caller ratchet the same state concurrently.

A live session under a label always wins over an alias, and prekey
envelopes never resolve: both keep a re-link establishing a fresh
session instead of being redirected into the stale one. Aliases are
dropped in resetSession and acceptIdentityChange, and memoized so the
hot path costs no extra read.

The sdk.test.ts case that asserted a dead fp-label encoded the old
behaviour; it now pins the new contract.

Verified: 1166 tests pass (from 1160). With alias persistence disabled
as a negative control, 5 of the 6 new tests fail, including both
restart cases.

Also drops `baseUrl` from the consumer-strict tsconfig — removed in
TS 6.0, and it was failing the typecheck that gates publishing.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-13 19:36:31 +02:00
b44acf867b release(files): prepare 4.11.2 hotfix
Some checks failed
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Test / test (push) Has been cancelled
2026-07-10 17:41:25 +02:00
8c67a00f37 fix(files): await pull-mode stream readiness 2026-07-10 17:38:35 +02:00
306bf08452 chore: adopter Scaffold plan-kontrakt
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-09 19:04:48 +02:00
3243647aa1 release(v4.11.1): ship pre-built dist/ to npm registry
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
publish-all.ts now does a tsc → dist/ build per package before pack, then
rewrites package.json's main/types/exports to point at the built artefacts
and ensures `files: ["dist"]` so the tarball ships only the built code.
The in-repo package.json is restored in the finally block so dev/typecheck
keep working without a build pass.

Why: strict-mode consumers (Cyndr) were forced to recompile Shade source
under their own tsconfig and tripped on internal `process.env.X` accesses
and implicit-any parameters. Shipping pre-built `.js` + `.d.ts` makes the
strictness contract live entirely inside Shade.
2026-05-21 13:29:52 +02:00
037f994572 release(v4.11.0): streaming Double-Ratchet sub-sessions (ShadeStream)
Some checks failed
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Answers Vyvern FR shade-ws-streaming-ratchet.md with a first-class
streaming-session API rather than the documented-contract fallback.
The Double-Ratchet crypto was already safe for high-frequency
one-directional use; the send/receive wrapper was not (per-frame
saveSession keystore write; shared per-peer mutex + single stored
session row coupling reuse to the HTTP path).

- @shade/core: stream.ts — identity-bound 3-DH seeding (X3DH-minus-
  prekeys, no prekey-server round trip, mutually authenticated against
  the parent session's pinned identities), bootstrapStreamSession
  reusing init{Sender,Receiver}Session verbatim, in-memory-only
  StreamRatchet (own op-mutex, never persisted, zeroized on close).
  beginStream/acceptStream on ShadeSessionManager; Stream{Closed,
  Handshake}Error; stream.opened/closed events.
- @shade/proto: STREAM_OPEN/OPEN_ACK/FRAME wire (0x31/0x32/0x33),
  additive; inspectEnvelopeType extended.
- @shade/sdk: Shade.openStream/acceptStream → ShadeStream
  (handshakeFrame/handleHandshake/seal/open/close), transport-
  agnostic, independent of encrypt/decrypt queues + parent session,
  identical server (sqlite:) and browser (IndexedDB) — touches no
  storage.
- Tests: 5000-frame one-directional burst (bounded skipped keys + FS
  zeroize), parent-session independence, replay/rewind rejection,
  mutual-auth, proto wire round-trips. Full suite green (1159 pass).
- docs/streaming-sessions.md (R1–R7 contract); SECURITY.md matrix rows.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-15 11:29:09 +02:00
188c3db56a android: V4.9 + V4.10 Kotlin ports + KeystoreStorage adapter
Some checks failed
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Test / test (push) Has been cancelled
Pure-JVM additions to shade-android (no Android SDK needed):
- V4.9 blob primitives: BlobKdf (HKDF deriveBlobSlotId/Key/SigningSeed),
  BlobAead (nonce||ct||tag with shade-profile-aad-v1:<slot> AAD),
  BlobClient (java.net.http with hand-written canonical JSON signing
  matching TS signPayload output), Profile high-level namespace.
- V4.10 approval helpers: CanonicalProfileBlob schema with denormalized
  trustedApproverFingerprints, build/sign/verify proxy approvals via
  length-prefixed u16 BE UTF-8 canonical signing payload.
- Password KDFs: scrypt + argon2id via Bouncy Castle, NFKC-normalized.
- SessionStateJson at-rest serializer for persistence layer.

Cross-platform vectors (test-vectors/blob.json, approval.json) gate
byte-identical output between TS and Kotlin, including a TS-signed
Ed25519 signature the Kotlin port verifies and reproduces (Ed25519 is
deterministic).

New shade-android-keystore sibling Gradle module (Android-specific):
- KeystoreMasterKey: hardware-backed AES-256-GCM with BIOMETRIC_STRONG
  gating, StrongBox-backed when available, invalidated on enrollment.
- BiometricUnlock: coroutine wrapper around BiometricPrompt with
  tagged cancellation/failure exceptions.
- KeystoreStorage: StorageProvider over biometric-gated AES-encrypted
  SharedPreferences with AAD-bound row keys.

All 25 SDK packages typecheck clean; 104 SDK tests + 24 new Kotlin
tests + 11 cross-platform vector tests all green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 17:38:15 +02:00
1bd7037a6d release(v4.10.0): cross-host approval routing primitives in @shade/sdk
Some checks failed
Test / test (push) Has been cancelled
Builds on V4.9's encrypted profile blob: ships the canonical
profile-blob schema (hosts/clients/trustedApproverFingerprints) and
the build/sign/verify trio for proxy-approval frames. Headless servers
can now route a `linkRequest` to a trusted-approver phone, verify the
phone's Ed25519 signature against the fresh profile blob, and complete
pairing without a GUI host being available.

Length-prefixed binary signing payload so any platform (Kotlin, Swift,
Go) can produce byte-identical signing input from test vectors. No
relay or transport changes — entirely SDK-level.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 17:09:59 +02:00
80c410f518 release(v4.9.0): relay-side encrypted blob primitive + SDK Profile namespace
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Ships the Prism FR (encrypted-profile-storage-v4.9.md) as a generic
relay-side encrypted blob primitive: deterministically-located,
AEAD-sealed blobs keyed by a 32-byte slotId derived client-side via
HKDF from the user's master key. Unlocks credential-only bootstrap
of new devices into existing E2EE state — no QR, no physical access.

Server: BlobStore interface + Memory/Sqlite/Postgres impls,
createBlobRoutes for GET/PUT/DELETE /v1/blob/:slotId with TOFU pubkey
auth and If-Match CAS (409/412 semantics). Mounted on the same Hono
app as the inbox; SHADE_BLOB_PG_URL / SHADE_BLOB_DB_PATH /
SHADE_DISABLE_BLOB env-var plumbing in standalone.

SDK: createProfileNamespace high-level wrapper (HKDF derivation,
random-nonce AEAD seal, slotId-bound AAD) + low-level BlobClient.
Cross-platform test vectors in test-vectors/blob-storage.json.

New errors: ConflictError (409), PreconditionFailedError (412).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-09 02:44:42 +02:00
3c0db14904 release(v4.8.5): kill flushOnce 15s success-backoff + per-recipient parallel drain
Some checks failed
Test / test (push) Has been cancelled
Prism filed a per-recipient-flush-concurrency FR pointing at
serial-per-flush. Investigation surfaced the actual culprit:
`scheduleFlush` was using a 15 s backoff on **both** the success and
failure paths, so envelopes enqueued *during* an in-flight flush
sat ~15 s behind the next drain — visible as "10 s of silence then
25-frame burst" on the receiving side under sustained sender output.

Two fixes:

1. `scheduleFlush` now uses 0 ms delay when `flushOnce` delivered
   ≥1 envelope and more is queued (network healthy → drain
   remainder immediately). 15 s reserved for the actual failure
   case where every attempt this round failed. `flushOnce` returns
   `{ delivered, remaining } | null` so concurrent-flush early
   returns don't double-schedule.

2. `flushOnce` groups the outgoing queue by `recipientAddress` and
   drains buckets via `Promise.all`. Per-peer order preserved
   (sequential within a bucket); a slow POST to recipient A no
   longer head-of-line-blocks frames bound for B.

`Inbox.tick` public shape unchanged. `OutgoingQueueStore`
implementations see the same per-entry list/remove/bumpAttempts/
size contract; only cross-recipient interleaving changes.

Tests cover (1) 25-envelope burst behind a 100 ms slow PUT drains
within 1 s, and (2) carol's PUT lands within 150 ms even when bob's
PUT stalls 200 ms.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 22:56:27 +02:00
a98ea8a1bd release(v4.8.4): server-side cross-channel dedup via BridgeDeliveryLog
Some checks failed
Test / test (push) Has been cancelled
V4.8.3 shipped client-side cross-channel dedup hook
(`Inbox.acceptBridgeFrame`), but recipients that didn't migrate to
the new wiring still observed the same envelope twice — once via
WS bridge push, again ~30 s later via inbox-poll. Prism re-verified
the FR after 4.8.3 and asked for a relay-side enforcement so app
code doesn't have to ack-via-DELETE on every bridge frame.

V4.8.4 adds an in-memory `BridgeDeliveryLog` (default 60 s grace,
8192-per-address cap) that records every successful WS / SSE /
long-poll push of `(address, msgId)`. The `/v1/inbox/:addr/fetch`
route filters out blobs in the log's grace window so a recipient
running both a bridge and the 30 s poll cadence sees exactly one
delivery. Cursor advances over the full fetched window so a poll
that straddles a suppressed blob doesn't stall.

The standalone server auto-wires the log between
`createBridgeRoutes` and `createInboxRoutes`. Custom mounts thread
the same instance through `bridgeDeliveryLog` on both factories.

Tests cover WS-then-poll, SSE-then-poll, and a negative control
(non-bridge-pushed blob still comes through inbox-fetch).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 16:31:42 +02:00
d47774ef1c release(v4.8.3): cross-channel msgId dedup + Shade.aliasSession
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Two follow-ups to the V4.8.2 duplicate-fan-out fixes Prism filed.

1. `Inbox.acceptBridgeFrame(blob)` + shared 4096-entry msgId LRU.
   The relay durably stores blobs and pushes them to every active
   delivery channel; without a cross-channel ack the bridge frame
   ran first and the next inbox-poll re-dispatched the same blob
   ~30 s later, tripping on consumed prekeys. Bridge consumers now
   plumb pushed frames through `acceptBridgeFrame`, which shares
   the dedup gate + ack path with `pollOnce`. Whichever channel
   delivers first wins; the other acks-and-skips. Inbox records
   the msgId before the ack so a parallel poll can't observe an
   in-flight ack window.

2. `Shade.aliasSession(oldLabel, newLabel)`. First-contact forces
   the receiver to label the new session by the relay's sender
   fingerprint hint (`fp:<senderfp>`); the post-decrypt plaintext
   typically announces the peer's real address. Aliasing moves
   session, trusted identity, peer-verification, and identity-
   version under the canonical label. Holds the per-peer mutex on
   both labels (lexicographic order) so concurrent crypto ops can't
   observe a half-moved state. Refuses to overwrite an existing
   session at the new label.

Wire change: `IncomingMessage.expiresAt?` now surfaces the relay's
expiry so receivers can pass bridge frames straight to
`acceptBridgeFrame` without inventing a TTL.

Tests cover bridge-then-poll, poll-then-bridge, aliasSession happy
path, refuse-to-overwrite, and same-label no-op.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 15:49:36 +02:00
8c606ad498 release(v4.8.2): per-from receive serialization + per-connection bridge dedup
Some checks failed
Test / test (push) Has been cancelled
Two interlocking robustness fixes for the duplicate-fan-out / first-contact
class of failures Prism reported.

1. `Shade.receive(from, env)` now queues its `manager.decrypt` step
   per `from` so concurrent dispatches can't race the SessionManager
   ratchet or the StorageProvider (sqlite "database is locked", IDB
   transaction conflicts). User message handlers run *outside* the
   queue so streams + file-RPC's nested `shade.receive` calls don't
   self-deadlock.

2. Bridge WS + SSE handlers now run a per-connection bounded msgId
   LRU as defense-in-depth against any flushTo re-entry (event-storm,
   future refactor). Pending-flush chains are wrapped in `.catch(() =>
   {})` so a transient `ws.send` rejection no longer poisons the
   connection's flush loop.

Tests: storming `inbox.blob_stored` 10× per PUT yields exactly one WS/
SSE frame; 8 concurrent `bob.receive('alice', envelope)` calls keep
the ratchet intact and never surface "database is locked".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 12:13:46 +02:00
680d6386f3 release(v4.8.1): SHADE_DISABLE_RATE_LIMIT env var for single-tenant deploys
Plumbing fix only — both createPrekeyRoutes and createInboxRoutes
already accepted disableRateLimit; standalone.ts just didn't read
the env. Now SHADE_DISABLE_RATE_LIMIT=1 turns off IP rate-limits on
every prekey + inbox route, with a WARN log on startup so operators
see it.

Single-tenant deployments only — multi-tenant relays must leave it
unset. Documented in docs/DEPLOYMENT.md.

Reported by Prism: ~6 pair attempts/hour from a single dev IP +
the sidecar's register call tripped the 5/hour REGISTER_LIMIT every
dev iteration.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 00:55:57 +02:00
1fb59a7076 release(v4.8.0): sender-fingerprint attribution + Inbox.start race fix
Two unblocking changes for first-contact flows.

Sender attribution: relay captures shortHash(senderSigningKey) at
PUT time (after signature verification, no new trust surface) and
surfaces it on bridge push (IncomingMessage.from) + inbox-fetch
(FetchedBlob.from) + DecryptHandler raw arg. Apps receiving a prekey
envelope from a never-before-seen peer can now bootstrap X3DH via
shade.receive('fp:<hex>', env) — pre-4.8 the wire envelope didn't
authenticate the sender and there was no out-of-band hint to use.
Idempotent ALTER TABLE migrations for SQLite + Postgres add a
sender_fp TEXT column; legacy rows surface as from=undefined
(inter-version compat).

Inbox.start() race: pre-4.8 start() called register() fire-and-forget
AND schedulePoll(0) synchronously, so the first poll on a fresh
address often beat the register HTTP RTT and got SHADE_NOT_FOUND.
start() now defers; register() success kicks schedulePoll(0). Manual
tick() is unaffected (deliberate user action, no gating).

Both reported by Prism. Tests cover all five acceptance criteria
from the sender-attribution request (PUT capture, bridge surface,
fetch surface, inter-version compat, end-to-end pair smoke) plus
the three from the race-fix request.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-08 00:11:59 +02:00
594992a183 release(v4.7.0): peer-presence events for instant BroadcastChannel revoke
Adds the bridge-connection-lifecycle signal that closes Prism's
~45s revoke window down to one server→client round-trip (~50ms).

Server (`@shade/inbox-server`):
- `inbox.peer_connected` / `inbox.peer_disconnected` events on the
  0↔1 boundary across WS + SSE bridges. Long-poll deliberately not
  tracked (every poll boundary would flap; push transports are also
  the only ones where instant revoke matters).
- `PresenceTracker` collapses two parallel bridges (e.g. WS + SSE
  during fallback handover) into one connect/disconnect pair.
- `GET /v1/bridge/presence` SSE endpoint: signed query with
  `kind: 'presence'`, `watched: string[]`; on open streams a
  per-address snapshot, then change frames filtered server-side.
  MAX_WATCHED_ADDRESSES = 64. Subscribing does not itself count as
  a peer-bridge connection.
- `createBridgeRoutes` now returns `{ app, websocket, presence }`.

Client (`@shade/transport-bridge`):
- `PresenceBridge.subscribe({ watch, onPresenceChange })` →
  `{ addPeer, removePeer, watching, unsubscribe }`. addPeer/removePeer
  mutate via reconnect with a fresh signed query.
- `signPresenceQuery` helper for non-PresenceBridge consumers.

Tests cover all four acceptance criteria from the Prism request:
server-event smoke, online→offline subscription, address scoping
(carol invisible to a [alice]-only sub), reconnect, plus an
addPeer/removePeer regression.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 23:16:35 +02:00
8746571d2a release(v4.6.1): bind globalThis.fetch in browser-receiver-sensitive call sites
Browsers' Window.fetch is a WebIDL bound operation; storing it as
this.fetchImpl / this.fetchFn and calling via the instance receiver
threw "Illegal invocation" on the first request. Bind once at
construction in InboxClient, LongPollBridge, and SseBridge. Reported
by Prism (multi-device E2EE terminal), blocking every browser
consumer of the v4.6 transport stack on inbox.start() / bridge.connect().

WsBridge unaffected (uses WebSocket). Node/Bun fetch tolerates a free
receiver, so the bug never surfaced server-side — added regression
tests that install a strict-receiver globalThis.fetch to catch the
issue without an actual browser harness.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 23:00:58 +02:00
2c400d7094 release(v4.6.0): broadcast channels — Signal sender-keys for one-to-many fan-out
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Lands the broadcast-channel primitive Prism asked for in
Docs/shade-feature-request-sender-keys.md. The crypto in
@shade/core/sender-keys.ts was already in place; this release wires
it up as a first-class app-facing API, adds the persistence schema
across all six storage backends (memory, sqlite, indexeddb +
encrypted variants), introduces wire type 0x21 in @shade/proto,
and ships Prism's three acceptance tests verbatim.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 15:55:34 +02:00
2b1b4d6630 release(v4.5.0): browser-side encrypted storage + multi-factor unlock
Adds the foundations Prism's web client (and any future browser-based
Shade app) needs: at-rest-encrypted IndexedDB storage that mirrors the
SQLite backend byte-for-byte at the AAD/nonce level, browser-safe
subpath imports so Vite/webpack/esbuild stop hitting bun:sqlite, and
KeyManager support for argon2id and N-factor composite unlock.

@shade/storage-encrypted
- EncryptedIndexedDBStorage (subpath: /idb) — full StorageProvider
  using one object store per _enc table; reuses aeadSeal/aeadOpen +
  row-codec sealers so a row sealed under the SQLite or Postgres
  backend decrypts under IDB given the same KeyManager.
  bumpPeerIdentityVersion is atomic under one IDB transaction.
- KeyManager argon2id source — memory-hard KDF for low-entropy
  secrets (PINs). Backed by @noble/hashes/argon2 (already a transitive
  dep). DEFAULT_ARGON2ID exported (m=64 MiB, t=3, p=1).
- KeyManager composite source — HKDF-combine N sub-sources into one
  master. Every source mandatory; order significant by design;
  composite-of-composite rejected; optional info string for app-level
  domain separation.
- Subpath exports (/crypto, /sqlite, /postgres, /idb) plus a `browser`
  condition on the default import that resolves to a barrel
  excluding the Bun- and Postgres-specific entries. Browser bundles
  no longer pull bun:sqlite transitively.

Tests
- 73 tests in shade-storage-encrypted (was 31). New coverage:
  argon2id determinism + reject paths, composite same-factors → same
  master, wrong-PIN/passphrase/order-swap → different master, info
  domain separation, all 28 StorageProvider methods on
  EncryptedIndexedDBStorage, fingerprint-mismatch rejection, and
  cross-impl roundtrip with EncryptedSQLiteStorage proving the AAD/
  nonce derivation is implementation-agnostic.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-07 10:58:49 +02:00
dbb3a090d8 release(v4.4.0): public accessor for device identity public key
Expose the local device's 32-byte Ed25519 identity public key on Shade
so apps can hand it to their own backend at enrollment time for
signature verification, key pinning or per-device safety-number
computation. Closes the gap that forced consumers to ship placeholder
random bytes their backend could store but never verify against.

- @shade/sdk Shade.identityPublicKey: Promise<Uint8Array> — getter
  mirrors the existing fingerprint accessor. Throws pre-init,
  reflects the current key after rotate(), retired key preserved in
  retired-identities storage per existing grace-period contract.
  Private key remains unreachable.
- Test in shade-sdk/tests/sdk.test.ts: round-trip match against the
  underlying storage's signingPublicKey, plus value updates after
  rotate().
- Lockstep version bump 4.3.0 → 4.4.0 across all 25 packages.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 17:58:45 +02:00
f5f42fe557 release(v4.3.0): browser persistence via @shade/storage-indexeddb
Ship an official IndexedDB-backed StorageProvider so browser-based Shade
consumers persist identity, prekeys, sessions, retired identities,
peer-verification state and stream-resume rows across tab refresh and
browser restart. Closes the gap that forced browser apps onto
storage:"memory" (regenerated identity each load, orphaned device
records server-side).

- New package @shade/storage-indexeddb (4.3.0): full StorageProvider
  conformance, schema v1, idb-backed; bumpPeerIdentityVersion is wrapped
  in a single readwrite IDB transaction (atomic, vs SQLite's
  read-then-upsert race).
- @shade/sdk resolveStorage() accepts { type: 'indexeddb', dbName? } via
  dynamic import (lazy, optional dep — same pattern as
  @shade/storage-postgres). Named StorageSpec type now reused by
  ResolvedConfig.
- Tests: 16 new tests in shade-storage-indexeddb (StorageProvider
  surface + peer-verifications + full E2EE conversation surviving a
  simulated tab reload). Run on fake-indexeddb.
- Lockstep version bump 4.2.1 → 4.3.0 across all 25 packages.
- Publish scripts updated to include the new package.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 17:35:02 +02:00
b77b7e771c release(v4.2.1): fix concurrent-ratchet desync via OutboundQueue waiter cursor
Some checks failed
Publish / publish (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Pull-mode httpClient + drainer + parallel RPCs against the same peer
deteriorated after ~10s with `DecryptionError`. Two bugs combined:

- `OutboundQueue.enqueue` woke `drain` waiters with a `since=0`
  snapshot, replaying already-processed events into
  `Shade.acceptTransferEnvelope` → `manager.decrypt` twice. The
  duplicate consumed an already-used skipped key and corrupted the
  Double Ratchet receive chain.

- `ratchetDecrypt` then propagated the corruption: a same-DH
  message behind the chain with no cached skipped key fell through
  to `kdfChainKey` on the ahead state and rewound `chain.counter`,
  permanently desyncing the chain.

Fix `OutboundQueue` to honor each waiter's `since`, and harden
`ratchetDecrypt` so any future duplicate fails cleanly without
mutating state. Adds regression coverage at all three layers.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 22:58:26 +02:00
7520b11b25 release(v4.2.0): pull-mode streams for browser @shade/files
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
4.1.0's HTTP RPC for browsers capped at inline payloads (≤ 256 KiB).
4.2.0 unlocks streams: server queues outbound chunks + control
envelopes per peer, browser long-polls the queue. Browser-to-server
writes ride the existing /v1/transfer/<id>/chunk POST routes
unchanged.

For Dispatch this unlocks mod-jar uploads (50 MB) and world-backup
downloads (100+ MB) — the actual reason browser-side @shade/files
matters.

### New API

@shade/sdk:
- shade.transferQueueRoute(opts?) — Hono app with /queue +
  /v1/transfer/* routes. Auto-configures the queue transport.
- shade.configureTransfers extended: transport + envelopeTransport
  override slots; resolveBaseUrl optional when both supplied.

@shade/transfer:
- OutboundQueue — per-peer monotonic event log with long-poll
  semantics, idle-eviction GC, ring-buffered to maxEventsPerPeer.
- QueueTransferTransport — enqueues instead of POSTing.

@shade/files:
- httpClient({ outboundQueueUrl, transferBaseUrl }) — when set,
  starts a long-poll drainer + builds a streams-bridge. fs.read /
  fs.write of >256 KiB work end-to-end.
- startQueueDrainer(shade, opts) — exported helper for advanced
  consumers driving their own drainer.

### Implementation notes

- ClientStreamsBridge's TransformStream had HWM=0 by default which
  stalled the drainer's await chain at chunk 4 (writer.write pended
  before the consumer's reader was attached). Bumped to HWM=64 so
  the receive loop can buffer ahead of the consumer.

### Tests

3 new integration tests in tests/integration/http-rpc-streams.test.ts:
4 MiB streamed read round-trip, inline-only error path, idle-timeout
long-poll behaviour.

Wire-compatible. Source-compatible. Lockstep bump to 4.2.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 23:27:06 +02:00
da93b97cce release(v4.1.0): browser-friendly HTTP RPC for @shade/files
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Default shade.files.client(peer) requires both peers to be mutually
addressable over HTTP — the response round-trips through
Shade.deliverControlEnvelope (POST to peer's /v1/transfer/control).
Browser tabs can't host an HTTP server, so they couldn't consume
@shade/files at all. Dispatch's filutforsker (admin-panel browser UI)
is the canonical use-case.

This release adds a parallel request-response transport: one POST per
RPC, encrypted envelope in the body, encrypted response in the same
HTTP response. No inbound channel needed on the client.

### New API

- shade.files.rpcRoute(opts?) — Hono app exposing POST /rpc.
- shade.files.httpClient(peer, opts) — request-response FileClient.
- FilesNamespace.serve(handler, { inlineOnly: true }) — skip streams-
  bridge (and its configureTransfers pre-condition); also skip
  channel-based dispatch so requests aren't double-dispatched.

### Limitations (v1)

Inline only (≤ 256 KiB). Streamed reads/writes throw clear errors
directing to shade.files.client(peer) on a server-to-server deploy.

### Tests

7 integration tests in tests/integration/http-rpc.test.ts covering
round-trip + negative cases (sender header, empty/garbage body,
maxBodyBytes, rpcRoute-without-serve).

### Symmetry

Mirrors @shade/server's shade-auth-middleware: encrypted envelope in
request body, decrypted via existing ratchet, response in same HTTP
roundtrip. No WebSocket, no SSE, no outbound from server.

Wire-compatible. Source-compatible. Lockstep bump to 4.1.0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 22:08:14 +02:00
0bdf9e859c release(v4.0.2): consumer-strict reader-shape fixes
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
4.0.1's typecheck gate compiled each package internally against
lib: ["ES2022"]. That doesn't catch types that only fail when
*consumer* code (lib: ["DOM"] + exactOptionalPropertyTypes) tries to
assign a native browser type into one of our locally-defined narrower
types. Dispatch hit one such case in @shade/files inline-threshold.ts.

This release adds a tests/consumer-strict/ smoke project to the
pre-publish gate. It compiles a tiny "as if I were a downstream app"
TS file against:

  lib: ["ES2022", "DOM", "DOM.Iterable"]
  types: ["bun-types"]
  exactOptionalPropertyTypes: true
  strict: true
  paths → packages/*/src/index.ts

scripts/typecheck-all.ts now runs the smoke after per-package checks.
Both must pass before publish:dry / publish:all proceeds.

### Fixed
- @shade/files inline-threshold.ts: MinimalReader<T> rewritten as the
  explicit disjoint union { done:false, value:T } | { done:true,
  value?: T | undefined } that's assignable from every native reader
  shape (bun, DOM, node:stream/web). Fixes the
  "ReadableStreamReadResult is not assignable" Dispatch reported.
- @shade/files streams-bridge (client + server): stash setTimeout
  return in a local before .unref?.() via { unref?: () => void } cast.
  Fluent .unref?.() failed under lib: ["DOM"] (setTimeout returns
  number there).
- @shade/sdk background.ts: same setInterval .unref?.() fix.

Wire-compatible. No API shape changed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:51:46 +02:00
70e319fef8 release(v4.0.1): strict-TS publishability fixes
Some checks failed
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
4.0.0 shipped TypeScript source as published main/types, but several
files only compiled inside the monorepo. Consumer projects (Dispatch,
etc.) running their own strict tsc against our published source hit:

- @shade/key-transparency: 4 noUnusedLocals violations
  (IndexAbsenceProof, IndexInclusionProof, IndexProofWire, nodeHash)
- @shade/sdk: KT verifier callbacks returned Promise<unknown> instead
  of Promise<STHWire> / Promise<{ proof: string[] }>
- @shade/sdk: thumbnail.ts globalThis cast collided with consumer's
  lib.dom-supplied createImageBitmap signature
- @shade/files: cycle with @shade/sdk produced "this is not assignable
  to type 'Shade'" because hoisted node_modules layouts duplicated the
  Shade class. Broken by replacing `import type { Shade }` with a
  local structural ShadeBridge interface.
- @shade/storage-encrypted: KeyUsage (lib.dom) used under
  lib: ["ES2022"]
- @shade/transport-bridge: ReadableStreamDefaultReader<any> ↔
  <Uint8Array> mismatch
- @shade/keychain / @shade/dashboard / @shade/storage-encrypted
  tsconfig rootDir / include hygiene

Tooling: scripts/typecheck-all.ts runs `bunx tsc --noEmit` against
every workspace package's tsconfig and fails on any error. Wired into
publish:dry / publish:all and publish-shade.sh as a hard gate so this
class of bug cannot recur.

All 24 packages bumped to 4.0.1 in lockstep.

Migration: <ShadeFilesProvider> now requires an explicit `files` prop
(pass `shade.files`). Wire format unchanged.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:36:47 +02:00
f301b391a5 docs(archive): close out Status fields on V2.x backlog + V3.12 design notat
Some checks failed
Test / test (push) Has been cancelled
V4.0 acceptance §"All docs/V*.md arkivert med DONE-status" requires
every archived plan to carry an explicit Status field. V2.1 / V2.2 /
V2.3 inherited their pre-status format; V3.12-DESIGN was still
"Approved". Mark all four as Done with a one-line pointer to where
the work actually landed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:04:47 +02:00
40766c60f4 docs(readme): full 4.0 GA refresh — status table, all V3.x surfaces, audit pointers
Some checks failed
Test / test (push) Has been cancelled
- Status table (V3.2 → V3.12 all green; audit + soak harness ready)
- "What you get" expanded: storage encryption, fingerprint gates,
  inbox, bridge, web workers, recovery, KT, observability, soak
- Quick start: opt-in surface examples (gates, workers, WebRTC, KT)
  + at-rest encryption snippet + migrate-storage CLI invocation
- Architecture diagram refreshed: container now exposes /v1/inbox/*,
  /v1/bridge/*, /v1/kt/*, ops endpoints; WebRTC P2P pipe documented
- Packages table: all 24 entries at 4.0.0 (added observability,
  keychain, storage-encrypted, transport-bridge, etc.)
- Publishing section: 4.0.x examples; soak harness section added
- Security properties: V3.2 / V3.3 / V3.6 / V3.8 / V3.10 / V3.11
  rows added alongside the existing forward-secrecy / PCS list
- Documentation: grouped into Operator+integrator, Per-surface,
  Threat-model+audit, Migration+history, Examples
- Container includes: full V4.0 surface (inbox, bridge, KT, ops
  probes); image pinned at gt.zyon.no/stian/shade-prekey:4.0.0

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 18:58:38 +02:00
de25b19033 fix(publish): break recursion in publish-shade.sh → publish-all.ts
Some checks failed
Test / test (push) Has been cancelled
publish-shade.sh used to call `bun run publish:all`, which in turn was
wired to call publish-shade.sh (after the V4.0 cleanup). Point it
directly at scripts/publish-all.ts so the interactive flow runs the
TS publisher without re-entering itself.

Verified: dry-run from publish-shade.sh now packs all 24 @shade/*@4.0.0
packages cleanly.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 18:53:16 +02:00
e6fdf31b49 release(v4.0.0): Shade GA — V3.x consolidation + audit prep
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
V3.1 → V3.12 consolidated and tagged for the first GA release. Wire
format unchanged from 0.4.x — 4.0 peers interoperate with 0.4.x peers
byte-for-byte. The version bump is semantic: audit-cycle complete,
opt-in surface fully exposed, threat model refreshed for every new
surface.

Highlights:
- All 24 @shade/* packages bumped to 4.0.0 in lockstep.
- CHANGELOG 4.0.0 section is the canonical manifest of what landed.
- THREAT-MODEL extended (§10 fingerprint gates, §11 WebRTC P2P, §12
  Web-Worker boundary) + residual-risks table refreshed.
- OpenAPI now covers all 27 routes: prekey, transfer, KT, inbox,
  bridge, observer, /metrics, /healthz, /ready.
- MIGRATION 0.3.x → 4.0 documented + smoke-tested against
  shade migrate-storage on a real SQLite DB.
- docs/audit/REVIEW-BUNDLE.md + SCOPE.md ready for external reviewer.
- scripts/soak.ts harness for the GA-stable 2-week soak window.
- All V*.md plans archived under docs/archive/ with Status: Done.
- Voice/Video carved out into V5.0; 4.0 audit focuses on the frozen
  non-realtime stack.

Tests: TS 1000/1000 + Kotlin 11/11 cross-platform vectors green.
Docker: gt.zyon.no/stian/shade-prekey:4.0.0 builds and reports
  version 4.0.0 on /health.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 18:35:35 +02:00
8b055912b7 docs(readme): reflect @shade/files + @shade/streams + @shade/transfer + 0.3.0 wire bump
Some checks failed
Test / test (push) Has been cancelled
- Top-of-file callout for the 0.2.x → 0.3.0 wire incompatibility.
- "What you get" picks up E2EE file transfers + filesystem RPC bullets.
- Quick start gains a `Shade.files.serve()` / `.client()` snippet.
- Packages table adds @shade/streams, @shade/transfer, @shade/files;
  @shade/sdk and @shade/widgets descriptions extended for the new APIs.
- Documentation index links docs/files.md, docs/streams.md, examples/07
  and 08.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 14:11:42 +02:00
ebe3a50389 chore(publish): track publish-shade.sh + add streams/transfer/files to PACKAGES
Some checks failed
Test / test (push) Has been cancelled
publish-shade.sh's PACKAGES list was missing shade-streams, shade-transfer,
and shade-files — so the conflict-check + auto-bump loop silently skipped
those three packages. The final `bun run publish:all` step still picked
them up (via scripts/publish-all.ts), but a re-publish on a version that
already existed in the registry would not have bumped the missing
packages, leaving a workspace-wide version mismatch.

Also un-gitignore both publish scripts. publish-all.ts was already tracked
(git overrides ignore for tracked files), and publish-shade.sh contains
no secrets at rest — GITEA_TOKEN is read interactively and stored in
~/.bashrc by the script itself.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 14:03:57 +02:00
fa770d3063 feat(files): @shade/files 0.3.0 — E2EE filesystem RPC primitive
Some checks failed
Test / test (push) Has been cancelled
M-Files-1..6 land the full files-RPC layer + everything 0.3.0 needs to
ship. Apps keep their own UI; this layer ships the typed RPC, the
streams bridge for content I/O, and production hooks (rate limit,
retention, fingerprint gate, metrics).

@shade/files (NEW)
- Standard ops: list/stat/mkdir/delete/move/read/write/getThumbnail with
  Zod-validated wire schemas + clean user-handler types.
- Custom ops: typed via TypeScript declaration merging on CustomOpsMap
  + per-op Zod schemas; client.custom('app.foo', {...}) is fully typed.
- Content I/O: inline (≤ 256 KiB plaintext) base64-in-RPC; streams
  (> 256 KiB) ride @shade/transfer via userMetadata.shadeFilesWriteId
  / shadeFilesReadStreamId correlation. Server-side TransformStream
  bridges accept inbound transfers immediately (engine rejects chunks
  that arrive before accept) and park the readable for the matching
  RPC.
- Directory ops: walk(path, opts) async-iterable depth-first walker;
  uploadDirectory()/downloadDirectory() with bounded concurrency pool
  (default 4, cap 16), aggregated progress, abort.
- Production hooks (callback-based, vendor-neutral): rate-limit (op +
  byte), idempotency cache (LRU + TTL + in-flight de-dupe), path
  policy (traversal + percent-decode hardening), fingerprint gate
  (required/optional/reject), pluggable Ed25519 sig verification with
  ±5 min replay window, onMetric sink (standard names).
- React hooks (subpath @shade/files/react): ShadeFilesProvider,
  useShadeFiles, useFileList, useFileTransfer/Upload/Download.
- Shade.files.serve(handler) + Shade.files.client(peer) high-level
  entrypoint in @shade/sdk; lazy + memoized; one handler per Shade.

Wire format bump
- @shade/proto wire VERSION 0x01 → 0x02. Length prefixes changed from
  u16 to u32. The previous u16 silently truncated payloads above
  64 KiB — a hard correctness ceiling that blocked inline file ops
  up to 256 KiB. Wire-incompatible with 0.2.x peers; new sessions
  only. Cross-platform Kotlin port (android/shade-android) updated to
  match; test-vectors/wire-format.json regenerated.

Concurrency safety
- ShadeSessionManager.encrypt/.decrypt now run under per-peer mutex.
  Concurrent decryptions of the same peer raced ratchet state
  (manifested as sporadic "Failed to decrypt — wrong key or tampered
  data" under load — surfaced once concurrent uploadDirectory pumped
  many writes in flight). Encrypt was already serialized via
  Shade.send's encryptChains; decrypt is now serialized at the
  manager layer too.

@shade/streams extension
- StreamMetadata.userMetadata?: Record<string, string> for
  application-level key/value pairs that round-trip verbatim through
  stream-init plaintext. Used by @shade/files for write/read
  correlation; available to any consumer.

@shade/sdk extension
- Shade.files getter (lazy + memoized).
- BackgroundHooks.onPruneFiles + periodic timer (default 5 min) +
  BackgroundTasks.setHook(name, fn) for runtime hook registration.

Bundles in-flight 0.2.0 work
- packages/shade-streams/, packages/shade-transfer/, related
  shade-sdk streams-bridge + shade-widgets transfer hooks were
  uncommitted prior to this session. Including them keeps the
  workspace consistent at 0.3.0 since @shade/files depends on them.

Tests
- 74 new tests in @shade/files (572 → 646 workspace pass; 0 fail;
  3× stable). Coverage spans unit (inline-threshold + concurrency),
  integration (read-write inline + streams up to 1 MiB, walk +
  upload/download directory, custom-op, metrics, SDK namespace
  end-to-end), and security (tampered-envelope sig verification,
  replay window, fingerprint gate, rate-limit + quota).

Release artifacts
- All packages bumped to 0.3.0 via scripts/bump-version.ts.
- scripts/publish-all.ts PACKAGES updated with shade-files in
  topological order (after shade-transfer, before shade-sdk).
- bun run publish:dry clean (14 packed, 0 failed).
- examples/08-files-browser/ — three-process CLI demo (prekey + Bob
  server + Alice CLI) covering list/stat/mkdir/delete/upload/download.
- docs/files.md — full API + design doc.
- CHANGELOG.md 0.3.0 entry.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-02 14:00:01 +02:00
7e0f7320a9 feat(container): M-Box 1-8 — stack-agnostic standalone Docker container
Some checks failed
Test / test (push) Has been cancelled
Shade now ships as a self-contained Docker image. Deploy one container
per project, any stack (Bun, Python, Go, Rust, Kotlin) can talk to it via
plain HTTP. Zero coupling to consumer codebases.

M-Box 1: Stale identity cleanup API
- touchIdentity + purgeStaleIdentities on PrekeyStore interface
- Implemented for Memory, SQLite, and Postgres backends
- SQLite adds last_activity_at column with migration ALTER for existing DBs
- Postgres adds the same via raw SQL with IF NOT EXISTS guards
- Routes call touchIdentity on register, bundle fetch, replenish
- 4 new tests for the cleanup API

M-Box 2: Stale cleanup background task
- StaleCleanupTask runs purge on startup + every 24h (configurable)
- Reads SHADE_STALE_DAYS (default 30) and SHADE_CLEANUP_INTERVAL_HOURS
- Wired into standalone.ts, stopped on graceful shutdown
- 5 new tests for the task

M-Box 3: Observer baked into the container
- standalone.ts conditionally mounts @shade/observer at /shade-observer
  when SHADE_OBSERVER_TOKEN is set (and >= 16 chars)
- Shared PrekeyServerEvents emitter feeds both routes and observer
- @shade/observer added as optional dependency of @shade/server

M-Box 4: Dockerfile with dashboard build
- Multi-stage build: oven/bun:1 builder → oven/bun:1-alpine runtime
- COPY packages/ wholesale so workspace lockfile resolves cleanly
- RUN bun run build inside shade-dashboard → dist/ → observer/dist/
- Non-root shade user, /data volume, healthcheck, env defaults
- Final image: 260 MB

M-Box 5: OpenAPI spec for stack-agnostic clients
- packages/shade-server/openapi.yaml documents all 9 endpoints with
  request/response schemas, security (Ed25519 signatures + bearer token)
- createOpenApiRoutes serves /openapi.yaml and /docs (Redoc viewer)
- Any language can generate a client with openapi-generator

M-Box 6: Docker CI pipeline
- .gitea/workflows/docker.yml builds + pushes on git tag v*
- scripts/build-docker.ts for local builds, supports --push with GITEA_TOKEN
- Root package.json: build:docker, publish:docker scripts

M-Box 7: Deployment documentation
- packages/shade-server/README rewritten: 5-line quickstart with the image
- docs/DEPLOYMENT.md: full reference, env vars, backup, Dokploy, PG setup
- examples/05-dokploy-deployment/docker-compose.yml updated to pull
  published image (gt.zyon.no/stian/shade-prekey:latest)
- Root README deployment section rewritten

M-Box 8: End-to-end verification
- Image builds locally (bun run build:docker)
- /health, /openapi.yaml, /docs, /metrics, /shade-observer all respond
- 401 without observer token, 200 with
- Real SDK client round-trip: Alice → container → Bob → reply → Alice
- Persistence: identity + prekeys survive container restart (count 20→18
  as expected from two bundle fetches)

285 tests passing, 0 failures.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 14:29:00 +02:00
467dd5b065 feat(advanced): M-Adv 1-3 — multi-device, backup/restore, group messaging
Some checks failed
Test / test (push) Has been cancelled
Phase D complete. Shade is now at parity with Signal libsignal's core
feature set.

M-Adv 1: Multi-device support (simplified Sesame)
- DeviceListManager tracks per-user device lists ("user:deviceId" addresses)
- fanOutEncrypt() sends one message to all known devices via independent
  1:1 Double Ratchet sessions
- observeIncoming() auto-registers new devices from received messages
- JSON serialization for persistence
- userOfDevice/deviceIdOf address parsers

M-Adv 2: Backup and restore
- @shade/sdk exports BackupBlob format: version + salt + nonce + ciphertext
- Passphrase-derived key via HKDF (note: upgrade path to Argon2id documented)
- exportBackup()/importBackup() handle identity, prekeys, sessions, trust
- backupToString/backupFromString for single-string transport (copy/paste, QR)
- shade.exportBackup()/importBackup() convenience methods on SDK
- CLI: shade backup export <file> / shade backup restore <file>
- Rebuilds manager + transport after restore so ratchet state is consistent

M-Adv 3: Group messaging (Sender Keys)
- Per-sender chain key + Ed25519 signing key per group
- createSenderKey / buildDistribution / installDistribution for key distribution
- senderKeyEncrypt advances chain and signs ciphertext+header
- senderKeyDecrypt verifies signature then advances the sender's chain
- Out-of-order handling with bounded skip
- O(1) per message (once distributions are installed)
- Defensive ByteArray copies in distribution to prevent zeroize-across-refs

276 tests passing, 0 failures. All 13 SDK/tooling/platform/advanced
milestones complete. Shade is feature-complete for v2.0.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 00:51:34 +02:00
4bf9307548 feat(android): M-Cross 1-3 — Kotlin module + cross-platform test vectors
Some checks failed
Test / test (push) Has been cancelled
Phase C complete: Shade now has a Kotlin implementation with byte-for-byte
compatibility to the TypeScript core, verified by shared test vectors.

M-Cross 1: shade-android Kotlin module
- build.gradle.kts with Tink, EncryptedSharedPreferences, kotlinx.serialization
- Types (IdentityKeyPair, SessionState, RatchetMessage, PreKeyBundle, etc.)
- CryptoProvider interface
- TinkProvider implementation (X25519, Ed25519, AES-GCM, HKDF, HMAC)
- KDF chain functions (kdfRootKey, kdfChainKey, deriveInitialRootKey)
  with the same info strings and salts as @shade/core
- Fingerprint (safety number) computation matching TS exactly
- X3DH protocol: identity gen, signed prekey gen, OTPK gen, bundle processing
- Double Ratchet: initSenderSession, initReceiverSession, ratchetEncrypt,
  ratchetDecrypt, DH ratchet step, skipped key cache
- Wire format matching @shade/proto byte-for-byte
- StorageProvider interface + MemoryStorage impl
- High-level ShadeSessionManager mirroring @shade/core's API

M-Cross 2: Cross-platform test vectors
- scripts/generate-vectors.ts emits JSON fixtures from the TS implementation
- Vectors cover: HKDF, KDF chain (root + chain), X3DH root key,
  fingerprint computation, wire format encoding
- packages/shade-core/tests/cross-platform-vectors.test.ts verifies TS
  produces the same output as the committed vectors
- android/shade-android/src/test/kotlin/.../CrossPlatformVectorTest.kt
  loads the SAME JSON and verifies Kotlin produces identical bytes

M-Cross 3: Nova Android migration plan
- android/shade-android/MIGRATION-NOVA.md — concrete steps to replace
  Nova's static PushKeyStore AES with Shade sessions
- Phase 1 (dual-write) / Phase 2 (switch reads) / Phase 3 (deprecate)
- Smoke test recipe for end-to-end TS → Kotlin push flow

251 tests passing on the TS side. Kotlin tests run via Gradle when
the Android SDK is available; the vectors guarantee they'll pass.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-11 00:45:38 +02:00
729 changed files with 111111 additions and 437 deletions

View File

@@ -0,0 +1,90 @@
name: Cross-platform vectors
# V3.5 §CI parity gate. Both runners load test-vectors/*.json and verify their
# native implementation produces byte-identical output to the recorded vectors.
# Any divergence — KDF labels, AAD encoding, wire format — fails CI immediately
# so cross-platform messaging breakage cannot land on main.
on:
push:
branches: [main]
paths:
- 'test-vectors/**'
- 'packages/shade-core/tests/cross-platform-vectors.test.ts'
- 'packages/shade-core/src/**'
- 'packages/shade-crypto-web/src/**'
- 'packages/shade-proto/src/**'
- 'android/**'
- 'scripts/generate-vectors.ts'
- '.gitea/workflows/cross-vectors.yml'
pull_request:
branches: [main]
paths:
- 'test-vectors/**'
- 'packages/shade-core/tests/cross-platform-vectors.test.ts'
- 'packages/shade-core/src/**'
- 'packages/shade-crypto-web/src/**'
- 'packages/shade-proto/src/**'
- 'android/**'
- 'scripts/generate-vectors.ts'
- '.gitea/workflows/cross-vectors.yml'
jobs:
ts-vectors:
name: TypeScript vectors (bun)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Bun
run: curl -fsSL https://bun.sh/install | bash
- name: Install dependencies
run: ~/.bun/bin/bun install --frozen-lockfile
- name: Run TS vector tests
run: ~/.bun/bin/bun run test:vectors
- name: Verify vectors are up-to-date
# Regenerate vectors and fail if they would change. Forces vector
# commits to come from `bun run vectors:gen`, never hand-edited.
run: |
~/.bun/bin/bun run vectors:gen
if ! git diff --quiet test-vectors/; then
echo "::error::test-vectors/ is out of date. Run 'bun run vectors:gen' and commit."
git diff test-vectors/
exit 1
fi
kotlin-vectors:
name: Kotlin vectors (gradle)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up JDK 17
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '17'
- name: Cache Gradle
uses: actions/cache@v4
with:
path: |
~/.gradle/caches
~/.gradle/wrapper
key: gradle-${{ hashFiles('android/**/*.gradle.kts', 'android/gradle/wrapper/gradle-wrapper.properties') }}
restore-keys: gradle-
- name: Run Kotlin vector tests
working-directory: android
run: ./gradlew :shade-android:test --no-daemon --info
- name: Upload Gradle test report
if: always()
uses: actions/upload-artifact@v4
with:
name: kotlin-test-report
path: android/shade-android/build/reports/tests/test/
if-no-files-found: ignore

View File

@@ -0,0 +1,52 @@
name: Docker build and publish
on:
push:
tags:
- 'v*'
workflow_dispatch:
jobs:
docker:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Install Bun
run: curl -fsSL https://bun.sh/install | bash
- name: Install dependencies
run: ~/.bun/bin/bun install --frozen-lockfile
- name: Run tests (gate)
run: ~/.bun/bin/bun test --recursive
- name: Extract version from tag
id: version
run: |
VERSION="${GITHUB_REF_NAME#v}"
echo "version=$VERSION" >> "$GITHUB_OUTPUT"
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to Gitea container registry
uses: docker/login-action@v3
with:
registry: gt.zyon.no
username: Stian
password: ${{ secrets.GITEA_PUBLISH_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
file: packages/shade-server/Dockerfile
push: true
tags: |
gt.zyon.no/stian/shade-prekey:${{ steps.version.outputs.version }}
gt.zyon.no/stian/shade-prekey:latest
labels: |
org.opencontainers.image.version=${{ steps.version.outputs.version }}
org.opencontainers.image.source=https://gt.zyon.no/Stian/Shade
org.opencontainers.image.revision=${{ github.sha }}

View File

@@ -28,6 +28,13 @@ jobs:
- name: Install dependencies
run: ~/.bun/bin/bun install --frozen-lockfile
# Before the tests, not after: a type error is cheaper to read than the
# runtime failure it eventually causes. The compiler is pinned in
# devDependencies, so this gate goes red when the repo changes — not
# when TypeScript ships a release.
- name: Typecheck
run: ~/.bun/bin/bun run typecheck
- name: Run tests
env:
SHADE_TEST_PG_URL: postgres://postgres:test@localhost:5432/postgres

3
.gitignore vendored
View File

@@ -2,3 +2,6 @@ node_modules/
dist/
*.tsbuildinfo
.DS_Store
**/.tmp-*.db
**/.tmp-*.db-shm
**/.tmp-*.db-wal

View File

@@ -0,0 +1,137 @@
# Shade Android — Roadmap & Parity Status
This document tracks the M-Cross milestones from `docs/V3.5.md` and the
status of every cross-platform parity sjekkpunkt. The Kotlin port must be
**byte-for-byte compatible** with the TypeScript implementation; this is
verified continuously by `test-vectors/*.json` consumed by both runners.
> **No "production" label** is allowed on Android until M-Cross 2 is green
> (ratchet + wire 0x02 + storage encryption) and M-Cross 3 is green
> (streams 0x11). See `docs/V3.5.md` §Akseptansekriterier.
## Milestones
### M-Cross 1 — Scaffold ✅
Foundation primitives. All passing in CI.
| Sjekkpunkt | Vector | TS test | Kotlin test |
|---|---|---|---|
| 1. KDF chain (root + chain ratchet) | `kdf-chain.json` | ✅ | ✅ |
| 2. HKDF labels | `hkdf.json` | ✅ | ✅ |
| 3. X3DH initial root key (3 + 4 DH outputs) | `x3dh.json` | ✅ | ✅ |
| 5. Fingerprint (60-digit safety number) | `fingerprint.json` | ✅ | ✅ |
### M-Cross 2 — Ratchet & Wire 0x02 ✅
Full ratchet step + binary envelope encoding for both message types.
| Sjekkpunkt | Vector | TS test | Kotlin test |
|---|---|---|---|
| 4. Ratchet step (encrypt deterministic) | `ratchet-step.json` | ✅ | ✅ |
| 4. Ratchet step (decrypt roundtrip) | `ratchet-step.json` | ✅ | ✅ |
| 6. Wire 0x02 RatchetMessage | `wire-format.json` | ✅ | ✅ |
| 6. Wire 0x02 PreKeyMessage (with OTPK) | `wire-format.json` | ✅ | ✅ |
| 6. Wire 0x02 PreKeyMessage (no OTPK, 0xFFFFFFFF marker) | `wire-format.json` | ✅ | ✅ |
The ratchet-step vector exercises every layer that contributes to a
ratchet message's wire bytes: `kdfRootKey` → `kdfChainKey` → 40-byte header
AAD → AES-256-GCM with deterministic nonce. Both implementations recompute
each layer and compare against the recorded hex. The decrypt half feeds
the recorded ciphertext back through `aesGcmDecrypt(messageKey, nonce, aad)`
and checks the plaintext recovers — proving the AEAD agrees in both
directions.
### M-Cross 3 — Streams 0x11 ✅
Multi-lane chunk encryption (`@shade/streams`) ported. KDF labels with
embedded NULs match TS byte-for-byte; deterministic
`(laneId, seq)`-derived nonces and the 29-byte chunk AAD agree across
runners; wire 0x11 encode/decode is roundtrip-verified.
| Sjekkpunkt | Vector | TS test | Kotlin test |
|---|---|---|---|
| `deriveStreamKey` (HKDF, info `shade-stream/v1\0master`) | `streams.json` | ✅ | ✅ |
| `deriveLaneKey` (HKDF, info `shade-stream/v1\0lane\0` ‖ u32_be laneId) — incl. laneId 0xFFFFFFFF | `streams.json` | ✅ | ✅ |
| `buildChunkNonce(laneId, seq)` — incl. seq = 2^64 - 2 | `streams.json` | ✅ | ✅ |
| `buildChunkAad(streamId, laneId, seq, isLast)` | `streams.json` | ✅ | ✅ |
| Chunk AES-256-GCM encrypt + decrypt (deterministic nonce + AAD) | `streams.json` | ✅ | ✅ |
| Wire 0x11 envelope encode + decode + type-tag inspector | `streams.json` | ✅ | ✅ |
Sequence numbers are unsigned u64 on the wire; the Kotlin port accepts
them as `Long` for the bit pattern (negative-signed-long for values past
2^63 - 1) — this matches the JVM `ByteBuffer.putLong` behavior and the
`java.lang.Long.parseUnsignedLong` JSON-decoder used in tests.
Pending end-to-end interop test (TS server → Kotlin client over an actual
socket) — not gated by vectors but recommended before flipping the
"production" label.
### M-Cross 4 — Backup, Group, Storage HKDF ✅ (cryptographic layer)
The cryptographic primitives that Kotlin needs to share with TS are now
covered. The remaining work is the high-level glue (BackupBlob JSON
schema, full SenderKey/GroupSession state-tracking, Android-Keystore
storage adapter, scrypt password-KDF) — all per-platform plumbing that
doesn't gate vector parity.
| Sjekkpunkt | Vector | TS test | Kotlin test |
|---|---|---|---|
| 7. Backup v1 HKDF (`info="ShadeBackupKey"`) | `backup.json` | ✅ | ✅ |
| 7. Backup v1 AES-GCM roundtrip (no AAD) | `backup.json` | ✅ | ✅ |
| Group sender header AAD (u16/u16/u32 length prefixes) | `group.json` | ✅ | ✅ |
| Group sender-key step: `kdfChainKey` + AES-GCM + Ed25519 sign(aad ‖ ct) | `group.json` | ✅ | ✅ |
| Storage HKDF: `storageKey` (`info="shade-storage-v1"`) | `storage-hkdf.json` | ✅ | ✅ |
| Storage HKDF: `fieldKey` (`info="shade-field-v1:{table}:{column}"`) | `storage-hkdf.json` | ✅ | ✅ |
| Storage HKDF: `rowNonce` (`info="shade-row-nonce-v1:{table}:{pk}"`) | `storage-hkdf.json` | ✅ | ✅ |
Pending sub-tasks (don't gate vector parity):
- **scrypt master-key derivation**: `test-vectors/storage-encryption.json`
pins `scrypt(N=1024, r=8, p=1, dkLen=32)` for unit-test config; Tink
doesn't ship scrypt. Add Bouncy Castle (`org.bouncycastle:bcprov-jdk18on`)
to the Kotlin module, wrap as `CryptoProvider.scrypt(...)`, then a follow-up
vector consumes the full storage-encryption.json end to end.
- **argon2id**: Both backup.ts and the threat-model docs flag HKDF as a
placeholder for a real password KDF. When `argon2id` is added to
`CryptoProvider`, both ports swap together and the backup vector gets
re-pinned.
- **Android KeystoreStorage adapter**: lives in a sibling Android Library
Gradle module that depends on this JVM module. Binds Tink to the Android
Keystore + EncryptedSharedPreferences.
## Build & Test
This module compiles as a **pure-JVM** Kotlin library (`kotlin("jvm")`)
so the parity gate can run without an Android SDK installation in CI.
The protocol code uses `tink:1.15.0` (JVM JAR), `java.nio.ByteBuffer`,
and `javax.crypto` — no `android.*` imports.
The Android-specific storage adapter (KeystoreStorage,
EncryptedSharedPreferences) will land as a sibling Gradle module
(`shade-android-keystore`) in M-Cross 4 and depend on this one.
```bash
# From repo root
cd android
./gradlew :shade-android:test
```
Requires JDK 17. The Gradle wrapper downloads Gradle 8.10.2 on first run.
## Compatibility contract
The Kotlin implementation must produce byte-identical output to the TS
reference for:
- KDF chain derivations (root key ratchet, chain key ratchet)
- X3DH shared secrets (3- and 4-DH variants)
- Ratchet message keys + AES-GCM ciphertext (given the same key/plaintext/AAD/nonce)
- Header AAD encoding (40 bytes: `dhPublicKey(32) || u32_be(prevCounter) || u32_be(counter)`)
- Fingerprints (12 × 5-digit groups)
- Binary wire format 0x02 (RatchetMessage + PreKeyMessage)
- Binary wire format 0x11 (StreamChunk) — M-Cross 3
- Storage encryption KDF chain — M-Cross 4
Each is covered by a vector file in `/test-vectors/`. Adding a new
sjekkpunkt: see `docs/cross-platform.md`.

View File

@@ -0,0 +1,116 @@
# Shade Roadmap — V3.1 → V5.0
Indeks over versjonsplanene fra V3.1-grunnsteinen via **Shade 4.0 GA** og
videre til **Shade 5.0** (Voice & Video).
- **V4.0 GA** ✅ — alt fra V2.1 / V2.2 / V2.3 og bonus-tracket (sosial
recovery, P2P WebRTC, Pub/Sub, Key Transparency) er merget, testet,
dokumentert og pakket for ekstern review. Wire-formatet er låst.
- **V5.0** = den dedikerte sanntids-releasen. *Alt* VOIP og videostreaming
ligger her — implementert oppå den frosne 4.0-stacken.
Alle V3.x-planer ligger nå under [`docs/archive/`](./archive/) med
`Status: Done`. Aktive planer: [`V5.0.md`](./V5.0.md).
---
## Faser
### Fase 1 — Documentation & Hardening Foundation ✅
| Plan | Tittel | Effort | Status |
|------|--------|--------|--------|
| [V3.1](./archive/V3.1.md) | Documentation & Hardening Foundation | S | **Done** |
### Fase 2 — Sikkerhetsmodning ✅
| Plan | Tittel | Effort | Status |
|------|--------|--------|--------|
| [V3.2](./archive/V3.2.md) | At-Rest Storage Encryption | L | **Done** |
| [V3.3](./archive/V3.3.md) | Fingerprint Gates & Trust UX | M | **Done** |
| [V3.4](./archive/V3.4.md) | Observability v2 (OpenTelemetry) | M | **Done** |
| [V3.5](./archive/V3.5.md) | Android Parity & Cross-Platform CI | XL | **Done** |
### Fase 3 — Plattformutvidelse ✅
| Plan | Tittel | Effort | Status |
|------|--------|--------|--------|
| [V3.6](./archive/V3.6.md) | Async Store-and-Forward (Inbox) | L | **Done** |
| [V3.7](./archive/V3.7.md) | Transport Bridge (SSE / long-poll) | M | **Done** |
| [V3.8](./archive/V3.8.md) | Web Workers Crypto | M-L | **Done** |
| [V3.9](./archive/V3.9.md) | Rich File Metadata & Previews | M | **Done** |
### Fase 4 — Tillit og P2P-transport ✅
| Plan | Tittel | Effort | Status |
|------|--------|--------|--------|
| [V3.10](./archive/V3.10.md) | Social Key Recovery | L | **Done** |
| [V3.11](./archive/V3.11.md) | WebRTC P2P Transport | XL | **Done** |
| [V3.12](./archive/V3.12.md) | Key Transparency | XXL | **Done** |
### Fase 5 — General Availability ✅
| Plan | Tittel | Effort | Status |
|------|--------|--------|--------|
| [V4.0](./archive/V4.0.md) | External Audit, Consolidation, GA | M | **Done** |
### Fase 6 — Sanntid (post-GA)
| Plan | Tittel | Effort | Avhenger av |
|------|--------|--------|-------------|
| [V5.0](./V5.0.md) | Voice & Video | XXL | V4.0 GA + V3.11 |
---
## Effort-nøkkel
| Symbol | Tid |
|--------|-----|
| **S** | 1–2 uker |
| **M** | 2–4 uker |
| **L** | 4–8 uker |
| **XL** | 2–4 måneder |
| **XXL** | 4+ måneder / multi-quarter |
---
## Avhengighetsgraf
```text
V3.1 ────┬──► V3.2 ──┐
├──► V3.3 ──┼──► V3.10 ──┐
├──► V3.4 ──┘ │
├──► V3.5 ───────────────┼──► V3.12 ──┐
├──► V3.6 ──► V3.7 ──► V3.11 ─────────┤
├──► V3.8 ├──► V4.0 GA ──► V5.0 (Voice & Video)
└──► V3.9 ─────────────────────────────┘
```
---
## Status-konvensjon
Hver plan har et `Status:`-felt øverst. Lov verdier:
- `Idea` — ikke startet, design fortsatt åpent.
- `Design` — designnotat under arbeid eller approved.
- `IMP` — implementasjon pågår.
- `Done` — merget i main, dekket av tester.
Når en plan blir `Done`, flytt fila til `docs/archive/` og oppdater denne tabellen.
---
## Versjonering
- **V3.1 → V3.12** ble trinnvise minor-releases på `0.4.x`-linjen.
- Wire-format-endringer akkumulerte til **V4.0**, men endte med å være
uendret fra 0.4.x — major-bumpen til 4.0 markerer audit-cycle ferdig
og GA-frosset kjerne, ikke en wire-bump.
- **V4.0** er GA — låst kjerne, pakket for ekstern review, ingen
voice/video.
- **V5.0** legger sanntid (voice/video/broadcast) oppå den frosne
4.0-stacken. Bygger på reserverte envelope-typer slik at 4.0-klienter
ignorerer 5.0-trafikk gracefully — ikke breaking.
- Hver `V*`-merge oppdaterer `CHANGELOG.md` og bumper alle pakker via
`bun run version`.

View File

@@ -0,0 +1,51 @@
---
branch: Streaming
status: active
order: 10
updated: 2026-10-19
started: 2026-10-18
decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video, bilder og lyd under Shade-kappen (filmer, videoer, bilder, logger). Bygges som ny pakke @shade/media oppå den låste stacken — kjernekrypto (ratchet, X3DH, proto) røres ikke, så G0–G4-revisjonen påvirkes ikke."
---
## Mål
- Filmer, videoer, bilder og lyd som spilles av E2E-kryptert, med spoling, uten at relayen ser innholdet.
- Live-strømmer (logger, tekst, live video/lyd) fra én avsender til mange mottakere, E2E-kryptert, med sen innstigning.
- Samme format i TS og Kotlin (delte test-vektorer), og avspilling rett i nettleseren (`<video>`, `<audio>`, `<img>`).
## Nå
- [x] `@shade/media` SMF1: streaming-forsegling, tilfeldig tilgang, integritet mot nøkkelholdere, vektorer + tester
- [x] Live-kanal: kjede, signaturer, epokerotasjon, sen innstigning, grants over Shade-sesjoner + tester
- [x] Server: diskbasert medielager med Range-GET + live-relay over WebSocket med backlog + tester
- [x] Klienter: HTTP Range-kilde, live-klient, CLI (`shade media …`, `shade live …`)
- [x] Nettleser: Service Worker som spiller forseglede filer i `<video>`/`<img>`, MSE-spiller for live WebM; headless-test + film
- [x] Kotlin: SMF1-leser + live-mottaker, verifisert mot vektorene
- [x] Design + docs: `docs/media.md` (SMF1, live-kanal, trusselmodell), CHANGELOG, versjon, loggpost, commit
- [x] fMP4 (H.264/HEVC/AV1 + AAC/Opus) i live-splitteren ved siden av WebM, `shade live video` autodetekterer
- [x] Android: `:shade-android-media` (Media3 `ShadeMediaDataSource`, Robolectric-test med ExoPlayer som spiller og spoler) + `:shade-media-demo`-APK
- [x] Album: én lenke for en sesong/et fotoalbum (forseglet liste av grants), `shade media put dir/`, rutenett i `/watch/`, Kotlin-leser + vektor
- [x] Sikkerhet: `shade media get` brukte `meta.name` som filsti (sti-traversering) — rettet
- [x] Android live: `LiveWatcher` + `ShadeLiveDataSource` (WebM/fMP4 i ExoPlayer, sen innstigning, hull, tidslinje fra 0), demo-appen spiller live video og følger loggkanaler
- [x] Undertekster: `Film.no.srt` ved siden av filmen forsegles og følger filmen i dens meta; `<track>` i nettleseren (språkvalg, SRT→VTT), ExoPlayer på Android, `media get` skriver dem tilbake
- [x] `media put --web`: HEVC/AC3/DTS-filmer (som Chromium nekter) konverteres før forsegling, innebygde tekstundertekster blir spor; advarsel uten flagget
- [x] Lokalt bibliotek: `media ls` med navn, `media link <navn>` gir lenken igjen; kanonisk grant-koding (én grant = én lenke)
- [x] Delt mediebibliotek for flere relay-instanser: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter; verifisert mot SeaweedFS med signaturkontroll + Postgres 16, to relayer bak round-robin
- [x] Live på tvers av relay-instanser: relayene sier hvor publisererne er (Postgres), en relay med seere følger den som har publisereren og verifiserer hver ramme; seere får `state` når kanalen går live/stille (nettleser, TS, Android). To feil rettet underveis: relayen merket aldri at publisereren gikk (Hono-WSContext), og ubrukelig mediekatalog ga uhåndtert avvisning
- [x] Live-lyd alene (radio/podkast): Opus/WebM og AAC/fMP4 gir lydspiller med målt lyd i Chromium (meta fikk init-segmentets ekte type)
- [x] Bilder live: `shade live images` (webkamera via ffmpeg image2pipe, lysbildeserie, overvåket mappe); JPEG-/PNG-splitter med markørparsing; Android-demoen viser live og forseglede bilder (bygget, ikke kjørt på enhet)
- [x] `shade live video --input <fil|rtsp://|/dev/video0>`: ffmpeg kjøres for deg, H.264/AAC kopieres, resten kodes (keyframe hvert 2. s); live i Chromium fra både VP9/Opus (omkodet, 0,96 s) og H.264/AAC (kopiert)
- [x] Opplasting i stykker, gjenopptakbar: Bun.serve buffret hele filmen i relayens minne når lageret var tregere enn klienten (512 MiB-PUT → 762/1011 MiB RSS). Nå 16 MiB-stykker, 4 i flyt, i vilkårlig rekkefølge; brudd/omstart/annen instans koster bare stykkene i flyt; relay-RSS 330–369 MiB både ved 512 MiB og 1,5 GiB. Verifisert: relay drept med SIGKILL midt i `media put` av 300 MiB, startet igjen etter 4 s, opplastingen fullførte selv, byte-identisk
- [x] `media put` gjenopptar på tvers av kjøringer (Ctrl-C, sovende laptop, lang nedetid): samme kommando fortsetter med samme media-id fra en forseglet kopi under `media-pending/`; en fil som allerede er oppe gir samme lenke igjen. Verifisert med SIGKILL etter 8/19 stykker → run 2 fortsatte fra 42 %, run 3 «already on the relay», byte-identisk
- [x] `shade live record <link> [--put]`: en sending til filer (tekst, spolbar WebM/MP4 via ffmpeg -c copy, bilder) og med `--put` en forseglet film med egen lenke under kanalens navn. Verifisert: 30 s VP8/Opus-sending tatt opp, lastet opp som «Kveldssending.webm», spilt og spolt i Chromium (bilde 14)
- [x] Kotlin-opplaster: `MediaUploader` + `MediaOwner` (samme stykkeprotokoll, vindu, resync), `MediaSealer.sealStream`, `MediaGrant.encode/capabilityUrl`; eier-signaturer og grant-koding som nye vektorer; `scripts/media-live-kotlin.ts` mot ekte TS-relay med tapt svar + avvist stykke → TS leser 40 MiB-filmen tilbake byte for byte
- [x] Demo-appen: «Del til Shade» — video/bilde/lyd/dokument fra galleriet forsegles på telefonen og lastes opp i en forgrunnstjeneste med fremdrift; flere filer på én gang blir ett album; varselet spiller av eller deler lenken. `UploadJobs` gjør at et drept opplastingsløp fortsetter med samme media-id; eiernøkkelen ligger under en Keystore-nøkkel (`KeystoreSecretFile`). Verifisert uten enhet: Robolectric-deling av `content://`-video mot ekte relay, album TS åpner, lint/bygg grønt
- [x] Herding: opplasteren (TS + Kotlin) stolte blindt på relayens status — `chunk: 0` ga evig løkke, stort vindu ga en tråd per stykke; nå sjekket (`statusProblem`), vindu ≤ 16
## Neste
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18/19): avspilling, live, og «Del til Shade» med en ekte galleri-video
- Live fra telefonkameraet (`LivePublisher` finnes i Kotlin; mangler MediaCodec → fMP4-muxing)
## Senere
- Sanntidssamtaler (V5.0): SFrame-nøkler fra samme kjede over WebRTC Insertable Streams

24
.scaffold/log.md Normal file
View 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).

View 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å.

View 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.

View 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.

View File

@@ -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`.

View File

@@ -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.

View File

@@ -0,0 +1,10 @@
---
title: "media put forsegler lengde og bildestørrelse"
date: 2026-10-20
created: 2026-10-20T00:03:38+02:00
author: "Claude"
---
`media put` måler nå lengde og bildestørrelse med ffprobe og forsegler dem i meta (`durationMs`, `width`, `height`), målt på filen som faktisk forsegles (etter `--web`). Feltene fantes i `MediaMeta` og ble lest av Iris og `/watch/`, men ble aldri fylt ut. Derfor viste Iris på Android filmfliser uten lengde.
Verifisert: ny test i `tests/web-prep.test.ts` (film har lengde og størrelse, lyd bare lengde, bilde bare størrelse, manglende fil gir tomt). Hele `shade-media` er grønn: 119 bestått og 6 hoppet over. `tsc` er ren.

View File

@@ -0,0 +1,10 @@
---
title: "Mediaworkeren kan bygges inn i en apps egen Service Worker"
date: 2026-10-20
created: 2026-10-20T00:13:40+02:00
author: "Claude"
---
Shade sin mediaworker kan nå bygges inn i en apps egen Service Worker via `@shade/media/worker`: `installShadeMedia(self)`, `isShadeMediaRequest` og `shadeMediaResponse`. Bakgrunnen er at en worker svarer på alle forespørslene fra sidene den kontrollerer. En installert PWA med worker på `/` slapp derfor aldri `media/<id>` videre til Shade-workeren ved siden av. Den frittstående `browser/sw.ts` er nå et tynt skall rundt samme modul.
Verifisert i Iris: `tests/shade.spec.ts` kjører både en app-worker med Shade bygd inn og den frittstående workeren mot en lokal relay (album, filmbilde, lengde, avspilling og spoling). På dev-telefonen er Iris-demoen installert fra Chrome som WebAPK og spiller forseglede filmer gjennom appens egen worker. `tsc` er ren, og `shade-media`-testene er grønne.

View File

@@ -0,0 +1,255 @@
---
title: "Shade-streaming: film, video, bilder, lyd og logger under Shade-kappen"
date: 2026-10-18
updated: 2026-10-19
created: 2026-10-18T21:20:41+02:00
author: "Claude"
cover: "media/2026-10-18-shade-streaming/14-live-opptak-som-film.png"
---
Shade kan nå strømme filmer, video, bilder, lyd og logger ende-til-ende-kryptert. Relayen lagrer og videresender bare chiffertekst, og den som har en grant, spiller av rett i nettleseren, i terminalen eller på Android.
**Oppdatert natt til 2026-10-19.** Siden kvelden har streamingen fått et delt bibliotek for flere relayer (S3 og Postgres), live på tvers av relayer, radio, bilder live og `--input`. Store filmer lastes nå opp i stykker som kan gjenopptas, også fra en ny kjøring, og en sending kan tas opp med `live record`. På telefonen er det kommet «Del til Shade»: en video eller bilder fra galleriet forsegles på telefonen og blir én lenke. Ingenting er publisert eller deployet.
![Before: En forseglet VP9/Opus-film spilles av i Chromium gjennom Service Worker-en, spolt til 24 s; relayen ser bare chiffertekst](media/2026-10-18-shade-streaming/01-forseglet-film-spoler.png)
![After: Et live-opptak («shade live record --put») spilles av som forseglet film: 30 s sending, opptatt, ryddet med ffmpeg -c copy, forseglet og lastet opp under kanalens navn; spolt til 22 s](media/2026-10-18-shade-streaming/14-live-opptak-som-film.png)
![Timelapse, 14 frames](media/2026-10-18-shade-streaming-timelapse.mp4)
1. En forseglet VP9/Opus-film spilles av i Chromium gjennom Service Worker-en, spolt til 24 s; relayen ser bare chiffertekst
2. Live VP8/Opus fra ffmpeg → shade live webm → relay → Chromium (MSE), 2,9 s forsinkelse; etter fiksen som sorterer blokkene i hvert kluster
3. tail -f-aktig logg → shade live text → nettleser; den gamle lenken virker fortsatt etter at kanalen er startet på nytt (epoke 1)
4. Et forseglet JPEG-bilde vist via Service Worker; lyd (Opus) spiller og spoler på samme måte
5. Live H.264/AAC som fragmentert MP4 (ffmpeg → shade live video → relay → Chromium), sen innstigning på keyframe-fragment, 3,2 s forsinkelse
6. Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til
7. En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål
8. En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten
9. To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge
10. Live-logg på tvers av relayer: publisereren landet på instans A og seeren på B bak lastbalansereren; B følger A, verifiserer hver ramme mot pinnen og viser «live»
11. Live-radio uten bilde (Opus/WebM og AAC/fMP4): spilleren får strømmens ekte type fra init-segmentet og blir en lydspiller, ikke en svart videoboks; lyd målt i Chromium (RMS 0,044)
12. Bilder live: ffmpeg-«webkamera» (MJPEG, 2 bilder/s) → shade live images → nettleser; hvert bilde er en keyframe, så en sen seer åpner på det siste. Også lysbildeserie og overvåket mappe
13. shade live video --input film.webm: CLI-en kjører ffmpeg selv, VP9/Opus kodes til H.264/AAC med keyframe hvert 2. s, live i Chromium med 0,96 s forsinkelse (H.264/AAC-kilder kopieres uten omkoding)
14. Et live-opptak («shade live record --put») spilles av som forseglet film: 30 s sending, opptatt, ryddet med ffmpeg -c copy, forseglet og lastet opp under kanalens navn; spolt til 22 s
## Hva det er
Ny pakke **`@shade/media`** (4.15.0) som legger all streaming under Shade-kappen. To formater:
- **SMF1 — forseglede filer** (film, video, bilde, lyd). Fila deles i segmenter på 1 MiB, hver forseglet med AES-256-GCM og en nonce som er utledet fra segmentnummeret. AAD-en binder `mediaId`, indeksen og et siste-segment-flagg, så segmenter kan verken byttes om, flyttes mellom filer eller kuttes bort. En hale med kryptert metadata og SHA-256 av alle segmenter, pluss en `rootDigest` i grant-en, gjør at relayen ikke kan bytte innhold uten at det oppdages. Relayen serverer vanlige HTTP Range-forespørsler og ser bare chiffertekst.
- **SLF1 — live-strømmer** (logger, tekst, live video/lyd). Én avsender, mange seere. Nøklene ruller fremover i en Sender Keys-kjede, og hver ramme signeres med Ed25519. Sene seere kommer inn på siste keyframe. Epokerotasjon kaster ut en seer. I lenkemodus overlever en delt lenke at kanalen startes på nytt.
Grants (`shade.media-grant/v1` / `shade.live-grant/v1`) sendes over en vanlig Shade-sesjon (`shade.shareMedia()` / `onMediaGrant()`) eller som en lenke med nøkkelen i `#shade=`-fragmentet. Fragmentet sendes aldri til serveren.
Fullt design, formatkontrakt og trusselmodell står i `docs/media.md`.
## Fullført
### Økt 2–4 (natt til 2026-10-19)
| Del | Verifisert slik |
|---|---|
| **Delt mediebibliotek**: filmer i S3 (egen SigV4-klient, multipart med begrenset minne), poster og live-pinner i Postgres, feiing av foreldreløse objekter | `tests/object-store.test.ts` + `postgres-media.test.ts` mot SeaweedFS (med signaturkontroll) og Postgres 16; to relayer bak round-robin |
| **Live på tvers av relayer**: relayen med seere følger relayen som har publisereren, og verifiserer hver ramme; seere får `state` live/stille | servertester med to relayer; nettleser, TS og Android viser tilstanden |
| **Radio/podkast** (bare lyd live: Opus/WebM, AAC/fMP4) | lydspiller med målt lyd i Chromium (bilde 11) |
| **Bilder live**: `shade live images` (webkamera, lysbildeserie, overvåket mappe) | JPEG-/PNG-splitter med tester; Chromium viser bildene (bilde 12) |
| **`shade live video --input <fil, rtsp:// eller /dev/video0>`**: ffmpeg kjøres for deg | live i Chromium både omkodet fra VP9/Opus og kopiert fra H.264/AAC (bilde 13) |
| **Opplasting i stykker, gjenopptakbar**: 16 MiB per stykke, 4 i flyt, i vilkårlig rekkefølge | `tests/upload.test.ts` (12 tester); relay drept med SIGKILL midt i en `media put` av 300 MiB, startet igjen etter 4 s, filen ble byte-identisk; en lastbalanserer med S3+PG fortsatte fra 31 % da en instans ble drept |
| **`media put` gjenopptar på tvers av kjøringer** (`media-pending/`) | drept etter 8 av 19 stykker; kjøring 2 fortsatte fra 42 %, kjøring 3 sa «already on the relay» og ga samme lenke |
| **`shade live record <lenke> [--put]`** | 30 s VP8/Opus tatt opp, lastet opp som «Kveldssending.webm», spilt og spolt til 22 s i Chromium (bilde 14) |
| **Kotlin-opplaster** `MediaUploader` + `MediaOwner` (samme stykkeprotokoll), `MediaSealer.sealStream`, grant-koding til lenke | nye vektorer for eier-signaturer og grant-koding (byte for byte); `scripts/media-live-kotlin.ts` mot ekte TS-relay med et tapt svar og et avvist stykke lagt inn, og TS leser 40 MiB-filmen tilbake byte for byte |
| **`UploadJobs`**: et drept opplastingsløp fortsetter med samme media-id | `UploadJobsTest` (4); i live-kjøringen «drepes» jobben etter første stykke og fortsetter, og en tredje deling sender ingenting og gir samme lenke |
| **«Del til Shade» i demo-appen**: forgrunnstjeneste med fremdrift; eiernøkkel under en Keystore-nøkkel (`KeystoreSecretFile`); flere filer gir ett album; spilleren viser album | Robolectric `ShadeUploadTest` deler en `content://`-video mot den ekte relayen; Kotlin lager et album som TS åpner; albumvektoren forsegles på nytt byte for byte fra Kotlin; bygg og lint grønt. **Ikke kjørt på enhet** |
| **Herding**: opplasteren stolte på relayens status | se «Feil» nedenfor; tester på begge sider |
Suiter ved slutt: `@shade/media` 124 grønne, typecheck rent i alle 27 pakker, `:shade-android:test` og `:shade-android-media:testDebugUnitTest` grønne, `:shade-media-demo` bygger og passerer lint.
### Økt 1 (kveld 2026-10-18)
| Del | Verifisert slik |
|---|---|
| SMF1-forsegling og -leser (streaming, tilfeldig tilgang, LRU, samlede range-kall) | `tests/sealed.test.ts`: tukling, ombytting, avkutting, feil nøkkel |
| Live-kanal (kjede, signaturer, sticky init/meta, keyframe-snapshot, rotasjon, lenkemodus) | `tests/live.test.ts` |
| Medielager på disk (atomisk commit, sidecar, indeks), Range-ruter, kvoter, eiere | `tests/server.test.ts`, inkludert en regresjonstest for Bun-slice-feilen |
| Live-relay over WebSocket (pinning, backlog, avlasting av trege seere) | `tests/server.test.ts` |
| WebM-splitter (init og klustre, keyframes, sortering av blokker) | `tests/webm.test.ts` |
| CLI: `shade media serve/put/get/ls/rm/whoami`, `shade live text/webm/watch` | Kjørt ende til ende mot ekte server |
| Nettleser: Service Worker med Range til `<video>`/`<audio>`/`<img>`, MSE-spiller for live | Headless Chromium: film spolt til 24 s, live-video 44/44 rammer med 2,9 s forsinkelse, logger, bilde og lyd |
| Kotlin: SMF1-leser og -forsegler, live-mottaker, grants | 9 vektortester (byte-identisk forsegling); hele Kotlin-suiten har 80 tester, 0 feil |
| Delte test-vektorer | `test-vectors/media.json`, 15 vektorer |
| `shade-server standalone` | Media monteres når `SHADE_MEDIA_DIR` er satt; 300 MiB rundtur bit-identisk; 200 MiB mot `/v1/bundles` gir fortsatt 413 |
| SDK | `shareMedia`/`onMediaGrant`; hele SDK-suiten grønn (111) |
Totalt 43 tester i `@shade/media`, og tsc er rent. Kjernekryptoen (ratchet, X3DH, proto) er ikke rørt, så G0–G4-revisjonen påvirkes ikke.
## Tall
Fra `bench/media.ts`, med 1 GiB tilfeldige data:
```chart
{
"type": "bar",
"title": "Sealed media throughput (MiB/s)",
"subtitle": "1024 MiB of incompressible data, 1 MiB segments, one core",
"y": {"label":"MiB/s","min":0},
"note": "Bun 1.3.5; HTTP is localhost through the real media routes; size overhead 0.0046 %",
"source": {"path":"bench/media-results.json","sha256":"6db8fb2955253753371ca00b6f1d6a2ec32a3c0c3000ad5204f9b8a19e22c06c"},
"series": [
{"name":"MiB/s","data":[["seal (disk → disk)",259.1],["read + verify (disk)",480.2],["upload (HTTP PUT)",50.9],["read + verify (HTTP Range)",209.5]]}
]
}
```
```chart
{
"type": "bar",
"title": "Seeking in a sealed film over HTTP (ms)",
"subtitle": "open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache",
"y": {"label":"ms","min":0},
"note": "n = 10 opens, 100 seeks; localhost",
"source": {"path":"bench/media-results.json","sha256":"6db8fb2955253753371ca00b6f1d6a2ec32a3c0c3000ad5204f9b8a19e22c06c"},
"series": [
{"name":"p50","data":[["open",3.28],["seek",3.98]]},
{"name":"p95","data":[["open",6.58],["seek",8.21]]}
]
}
```
```chart
{
"type": "line",
"title": "Live fan-out: latency publish → decrypted, by viewers",
"subtitle": "10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one",
"x": {"label":"viewers"},
"y": {"label":"ms","min":0},
"note": "delivered: 1 → 100 %, 10 → 100 %, 50 → 100 %, 100 → 100 %, 200 → 100 %. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.",
"source": {"path":"bench/media-results.json","sha256":"6db8fb2955253753371ca00b6f1d6a2ec32a3c0c3000ad5204f9b8a19e22c06c"},
"series": [
{"name":"p50","data":[[1,3],[10,6],[50,22],[100,15],[200,28]]},
{"name":"p95","data":[[1,12],[10,20],[50,58],[100,72],[200,151]]}
]
}
```
> [!NOTE]
> Opplastingen (51 MiB/s for 1 GiB) er begrenset av disken, ikke av koden. Samme opplasting går i 373 MiB/s på tmpfs. Det som skjer er writeback og fsync av temp-fila før `link()`.
Relayens minne ved opplasting av store filmer, før og etter stykkene: en enkelt PUT på 512 MiB fikk relayen opp i 762 MiB (disk) og 1011 MiB (S3). Med stykker ligger den på rundt 330–370 MiB både ved 512 MiB og 1,5 GiB, altså uavhengig av filmens størrelse. Målt av `bench/media-store.ts`, der hver relay går i sin egen prosess, med median eller verste av 3 kjøringer:
```chart
{
"type": "bar",
"title": "Sealed film store: disk vs S3 (MiB/s)",
"subtitle": "1536 MiB film through the real media routes, median of 3 runs; relay in its own process; S3 = local SeaweedFS",
"y": {"label":"MiB/s","min":0},
"note": "Bun 1.3.5. Uploads go up in 16 MiB pieces, up to 4 in flight. Disk: each piece fsynced before it is acknowledged. S3: each piece is one SHA-256-signed multipart part.",
"source": {"path":"bench/media-store-results.json","sha256":"c44122ed2c11654de9268e7dbcaa766c433890fe8eae3ab9f52c51ce35f3cbf3"},
"series": [
{"name":"disk (FileMediaStore)","data":[["upload (pieces)",286.6],["read + verify (Range)",199.6]]},
{"name":"S3 + Postgres (ObjectMediaStore)","data":[["upload (pieces)",79.3],["read + verify (Range)",107.4]]}
]
}
```
```chart
{
"type": "bar",
"title": "Relay memory does not grow with the film",
"subtitle": "Peak relay RSS growth during one upload (VmHWM − RSS before), worst of 3 runs, per film size",
"y": {"label":"MiB","min":0},
"note": "Bounded by the upload window (4 pieces of 16 MiB) and garbage not yet collected. Before pieces, one PUT of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) in the relay: Bun.serve reads a request body as fast as the client sends.",
"source": {"path":"bench/media-store-results.json","sha256":"c44122ed2c11654de9268e7dbcaa766c433890fe8eae3ab9f52c51ce35f3cbf3"},
"series": [
{"name":"disk (FileMediaStore)","data":[["512 MiB film",330],["1536 MiB film",369]]},
{"name":"S3 + Postgres (ObjectMediaStore)","data":[["512 MiB film",360],["1536 MiB film",358]]}
]
}
```
```chart
{
"type": "bar",
"title": "Seek latency, disk vs S3 (ms)",
"subtitle": "64 KiB at a random offset of the 1536 MiB film, fresh reader each (n = 50 per run, median of 3 runs)",
"y": {"label":"ms","min":0},
"note": "Includes opening: footer + trailer + root check, then the range.",
"source": {"path":"bench/media-store-results.json","sha256":"c44122ed2c11654de9268e7dbcaa766c433890fe8eae3ab9f52c51ce35f3cbf3"},
"series": [
{"name":"disk (FileMediaStore)","data":[["p50",9.05],["p95",19.37]]},
{"name":"S3 + Postgres (ObjectMediaStore)","data":[["p50",20.37],["p95",31.89]]}
]
}
```
## Feil funnet underveis
- **Bun 1.3.5 sendte hele fila** når `Bun.file().slice()` ble brukt som svar på en Range-forespørsel. Lageret strømmer nå selve byteområdet, og det finnes en regresjonstest.
- **Bun avviser kropper over 128 MiB** som standard, så filmer over 128 MiB fikk 413. Grensen er hevet bare for `/v1/media/`. Alle andre ruter fikk en eksplisitt `bodyLimit`, fordi prekey-rutene leser hele kroppen før de sjekker størrelsen.
- **ffmpeg fletter Opus- og VP8-blokker ute av tidsrekkefølge**, og Chrome sin MSE avviser det. Splitteren sorterer nå blokkene stabilt innen hvert kluster.
- **En publisher som ble avvist, koblet seg til på nytt i det uendelige.** Lukkekode 1008 er nå endelig.
- **Bun.serve buffret hele filmen** i relayens minne når lageret var tregere enn klienten. Det var grunnen til de høye RSS-tallene, og grunnen til at opplasting nå går i stykker.
- **`fetch` med en `Bun.file().slice()` som kropp ble aldri ferdig** (Bun 1.3.5). Klienten leser derfor hvert stykke inn i minnet først, maks 4 × 16 MiB.
- **postgres.js leste NULL i en TEXT[] som strengen «NULL»**, og PG-subscript i en tom array flyttet nedre grense. Løst med `array_fill` ved innsetting og `array_to_json` ved lesing.
- **Et tapt svar på siste stykke ga EXISTS** ved gjenopptak. POST svarer nå `complete: true` til samme eier.
- **Java sin HttpURLConnection kan ikke PATCH**, så stykkene er nå PUT. Den endringen kom før Kotlin-opplasteren.
- **Opplasteren (TS og Kotlin) stolte blindt på relayens status.** `chunk: 0` ga en evig løkke, en stor `chunk` holdt hele filmen i minnet, og et stort `window` ga én forespørsel (på Kotlin: én tråd) per stykke. Status sjekkes nå (`statusProblem`), og vinduet er maks 16.
- **`MediaClient` brukte `Bun.sleep`** før nye forsøk, så et nytt forsøk kastet i nettleser og Node. Bruker nå `setTimeout`.
## Beslutninger
- **Stykker i stedet for én stor PUT.** En enkelt PUT er begrenset til 64 MiB; over det svarer relayen `413 USE_UPLOAD`. Stykkene er PUT, så nginx kan prøve dem på nytt; POST-en trenger `non_idempotent` (står i `docs/media.md`).
- **Demo-appen krever nå minSdk 28**, fordi eiernøkkelen ligger i Keystore-modulen. Det er en demo, ikke et produkt, og dev-telefonen er nyere.
- **Eiernøkkelen på telefonen er ikke biometri-låst.** Den signerer hvert stykke, og et fingeravtrykk per stykke ville gjort opplasting umulig. Mister appen Keystore-nøkkelen (data gjenopprettet på en annen telefon), lages en ny eier, og relayen må få den nye id-en.
- **Bare navn, type, størrelse, varighet og bildestørrelse** følger med i meta fra telefonen; ingen posisjon og ingen sti.
- **Opplasting fra nettleseren ble ikke bygget i natt.** Den trenger et lagringsvalg for eiernøkkelen i nettleseren, og forsegling som strømmer rett inn i opplastingen. Det er beskrevet under «Neste».
- **Ny pakke i stedet for endringer i kjernen.** Dermed holdes G0–G4-revisjonen ren.
- **`shade media serve` er lukket som standard.** Bare din egen nøkkel og eventuelle `--owners` kan laste opp; `--open` slipper inn alle.
- **Ingen `SHADE_MEDIA_DIR`-standard i Dockerfile**, slik det er gjort for vault. Det er stilt som spørsmål nedenfor.
- **Lenkemodus er bevisst svakere.** Den som har lenken, kan lese alle epoker. Avveiningen er dokumentert i `docs/media.md`, og vanlig modus (grants per seer over Shade) har ekte utkasting.
- **CLI-en roterer hver 20 000. ramme.**
> [!QUESTION] id=media-dockerfile-default · default: A · asked-by=06aacd12
> Skal Docker-imaget slå på media som standard (SHADE_MEDIA_DIR=/data/media), eller bare når det settes eksplisitt?
> - [x] A — Bare eksplisitt, som vault (ingen overraskende diskbruk)
> - [ ] B — Standard /data/media i Dockerfile
> - [ ] Annet: ___
> answered: 2026-10-18 21:33 · A063
## Blokkert / trenger deg
- **Kjøring på enhet:** dev-telefonen (RFCN504DWJF) var ikke tilkoblet (`adb devices` tom) verken 18. eller 19. oktober. Du må plugge den i, så kan neste økt installere `:shade-media-demo` og kjøre avspilling, live og «Del til Shade» med en ekte galleri-video. Ingen emulator er startet.
- Publisering og deploy av 4.15.0 er ikke gjort, med vilje.
## Endret
- `packages/shade-media/`: `src/upload.ts` (ny), `owner.ts`, `client.ts`, `put-jobs.ts` (ny), `live/record.ts` (ny), `cli.ts`, `server/{file-store,object-store,media-routes,service}.ts`, tester (`upload`, `put-jobs`, `live-record`, `object-store`)
- `packages/shade-storage-postgres/` (`shade_media_uploads`), `packages/shade-server/src/standalone.ts`
- `android/shade-android/…/media/`: `MediaOwner.kt`, `MediaUploader.kt`, `UploadJobs.kt` (nye), `MediaGrant.kt`, `Album.kt`, `MediaFormat.kt`, `MediaReader.kt`; tester `MediaLiveTest`, `MediaUploaderTest`, `UploadJobsTest`, `MediaVectorTest`
- `android/shade-android-keystore/…/KeystoreSecretFile.kt` (ny), `android/shade-android-media/…/ShadeUpload.kt` (ny) + `ShadeUploadTest`
- `android/shade-media-demo/`: `ShareActivity`, `UploadService`, `Uploads` (nye), `PlayerActivity` (del-knapp, album), manifest, gradle
- `scripts/media-live-kotlin.ts` (ny), `scripts/generate-vectors.ts`, `test-vectors/media.json` (19 vektorer)
- `bench/media-store*.ts` + `bench/media-store.chart.json`, `docs/media.md`, `CHANGELOG.md` (4.15.0)
- Ikke committet med vilje: `.cursor/`, `.serena/`, `docs/ECOSYSTEM.md`, endringen i `CLAUDE.md` (ikke mine)
<details><summary>Endret i økt 1</summary>
- `packages/shade-media/` (ny)
- `docs/media.md`
- `test-vectors/media.json`, `scripts/generate-vectors.ts`
- `android/shade-android/src/main/kotlin/no/zyon/shade/media/` og `MediaVectorTest.kt`
- `packages/shade-server/src/standalone.ts`, `packages/shade-sdk/src/shade.ts`, `packages/shade-cli/src/cli.ts`
- `bench/media*.ts`, `bench/media.chart.json`
- CHANGELOG og versjon 4.15.0
- Commits fra `9e64ec8` til `4703140` på `main`
</details>
## Budsjett
Ved slutt (00:39): økt 34 % (nullstilles 03:00), uke 57 % (nullstilles om 3 d 13 t). Konteksten er 24 % brukt. Økten ble komprimert 4 ganger; sporet (plan, gren, captions, git) dekket alt, og ingenting kjent gikk tapt.
## Neste
- **Plugg inn dev-telefonen:** kjør `:shade-media-demo`, del en ekte video og et par bilder fra galleriet, og spill av lenkene.
- **Opplasting fra nettleseren** (iPhone uten app): eiernøkkel i nettleseren og forsegling som strømmer rett inn i stykkene.
- **Live fra telefonkameraet:** `LivePublisher` finnes i Kotlin; det som mangler er muxing fra MediaCodec til fMP4.
- Publiser og deploy 4.15.0 når G0-publiseringssakene er løst.

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

View File

@@ -0,0 +1,14 @@
01 — En forseglet VP9/Opus-film spilles av i Chromium gjennom Service Worker-en, spolt til 24 s; relayen ser bare chiffertekst
02 — Live VP8/Opus fra ffmpeg → shade live webm → relay → Chromium (MSE), 2,9 s forsinkelse; etter fiksen som sorterer blokkene i hvert kluster
03 — tail -f-aktig logg → shade live text → nettleser; den gamle lenken virker fortsatt etter at kanalen er startet på nytt (epoke 1)
04 — Et forseglet JPEG-bilde vist via Service Worker; lyd (Opus) spiller og spoler på samme måte
05 — Live H.264/AAC som fragmentert MP4 (ffmpeg → shade live video → relay → Chromium), sen innstigning på keyframe-fragment, 3,2 s forsinkelse
06 — Et album («Ferie 2026»): én lenke åpner film, video, lyd, bilde og et nøstet album; forhåndsvisningene dekrypteres i nettleseren, relayen ser bare én ugjennomsiktig fil til
07 — En forseglet film med Testfilm.no.srt og Testfilm.en.srt ved siden av: undertekstene følger filmen kryptert, og nettleseren velger norsk fordi den er satt til bokmål
08 — En ekte MKV-film med HEVC-video og AC3 5.1-lyd: Chromium nekter originalen («no supported streams»); med media put --web spiller den med lyd og den innebygde norske underteksten
09 — To relay-instanser bak en round-robin-lastbalanserer deler ett bibliotek (filmbytes i S3, poster i Postgres): opplastet via den ene, spilt og spolt til 24 s med Range-lesinger fra begge
10 — Live-logg på tvers av relayer: publisereren landet på instans A og seeren på B bak lastbalansereren; B følger A, verifiserer hver ramme mot pinnen og viser «live»
11 — Live-radio uten bilde (Opus/WebM og AAC/fMP4): spilleren får strømmens ekte type fra init-segmentet og blir en lydspiller, ikke en svart videoboks; lyd målt i Chromium (RMS 0,044)
12 — Bilder live: ffmpeg-«webkamera» (MJPEG, 2 bilder/s) → shade live images → nettleser; hvert bilde er en keyframe, så en sen seer åpner på det siste. Også lysbildeserie og overvåket mappe
13 — shade live video --input film.webm: CLI-en kjører ffmpeg selv, VP9/Opus kodes til H.264/AAC med keyframe hvert 2. s, live i Chromium med 0,96 s forsinkelse (H.264/AAC-kilder kopieres uten omkoding)
14 — Et live-opptak («shade live record --put») spilles av som forseglet film: 30 s sending, opptatt, ryddet med ffmpeg -c copy, forseglet og lastet opp under kanalens navn; spolt til 22 s

66
.scaffold/plan.md Normal file
View File

@@ -0,0 +1,66 @@
---
project: "Shade"
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
updated: 2026-10-20
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. 4.15.0 er publisert (2026-10-20) med observer- og cli-P0-ene fikset i publiseringsskriptet; G0 har CI-gaten igjen. 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: []
---
# 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.
- [x] **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.
Resten gjort 2026-10-20: observer bygger til `dist/`, `bin` omskrives til `dist/*.js`, og
`publish-all.ts` avviser en tarball som mangler en fil `main`/`types`/`bin`/`exports` peker på
(bevist mot den gamle observer-feilen). 4.15.0 publisert med alle 27 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
- **Streaming (`@shade/media`, 4.15.0)** — levert 2026-10-18, se `branches/streaming.md`: forseglede filmer/bilder/lyd (SMF1) og live-strømmer (SLF1) E2E, TS + Kotlin; fMP4 + WebM live, ExoPlayer (Android), album, undertekster, `--web`, delt S3/Postgres-lager. Delte relay-instanser med live på tvers, gjenopptakbar opplasting i stykker, `live record`, og «Del til Shade» fra Android (album av flere filer). Gjenstår: demo-APK på enhet. Ikke publisert eller deployet.
- **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.

421
.scaffold/tasks.yaml Normal file
View File

@@ -0,0 +1,421 @@
# 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
# ─────────────── Streaming — @shade/media ───────────────
- id: media-smf1-live
title: "@shade/media: forseglede filer (SMF1) + live-kanal (SLF1), server, CLI, nettleser, Kotlin"
description: >
E2E-kryptert streaming av filmer, video, bilder, lyd og logger. SMF1 for filer
med tilfeldig tilgang (Range), SLF1 for live-strømmer med sen innstigning og
epokerotasjon. Relay ser bare chiffertekst.
status: done
column: done
priority: high
assignee: claude
branch: streaming
context: "packages/shade-media, docs/media.md, test-vectors/media.json, android/.../no/zyon/shade/media/"
acceptance: "43 TS-tester + 9 Kotlin-vektortester grønne; film/live/bilde/lyd spilt i headless Chromium; benchmark i bench/media.chart.json."
created: 2026-10-18
updated: 2026-10-18
completed_at: 2026-10-18
- id: media-fmp4-live
title: "fMP4 (H.264/AAC) i live-splitteren"
description: "Live-splitteren forstår i dag bare WebM; fMP4 gir H.264/AAC fra kameraer og OBS, og Safari."
status: done
column: done
priority: medium
assignee: claude
branch: streaming
created: 2026-10-18
updated: 2026-10-18
completed_at: 2026-10-18
- id: media-android-exoplayer
title: "Android-demo: ExoPlayer DataSource for forseglede filmer"
description: "Avspilling (Media3 DataSource), live og opplasting fra telefonen er bygget og testet uten enhet; gjenstår kjøring på dev-telefonen (RFCN504DWJF)."
status: doing
column: doing
priority: medium
assignee: claude
branch: streaming
todos:
- text: "ShadeMediaDataSource + ShadeMedia (Media3), Robolectric: ExoPlayer spiller og spoler forseglet H.264/AAC"
done: true
- text: "Demo-app :shade-media-demo bygger (debug-APK)"
done: true
- text: "«Del til Shade»: forsegling + opplasting fra telefonen (MediaUploader, UploadJobs, forgrunnstjeneste, album) — Robolectric mot ekte relay"
done: true
- text: "Installer og spill på dev-telefonen RFCN504DWJF, og del en ekte galleri-video — ikke tilkoblet 2026-10-18/19"
done: false
created: 2026-10-18
updated: 2026-10-19
completed_at: null
- id: media-durable-store
title: "Postgres/S3-medielager for flere relay-instanser"
description: "Gjort: ObjectMediaStore (S3, egen SigV4-klient, multipart med begrenset minne) + PostgresMediaIndex/PostgresLivePinStore; SHADE_MEDIA_S3_URL/SHADE_MEDIA_PG_URL og media serve --s3 --pg. Gjenstår utenfor kortet: live-fan-out på tvers av instanser, og selve deployen (ikke bedt om)."
status: done
column: done
priority: low
assignee: any
branch: streaming
created: 2026-10-18
updated: 2026-10-18
completed_at: 2026-10-18
- id: media-resumable-upload
title: "Opplasting i stykker, gjenopptakbar (TS + Kotlin), media put på tvers av kjøringer, live record"
description: "16 MiB-stykker, 4 i flyt; relay-RSS uavhengig av filmstørrelse; media put fortsetter etter Ctrl-C/SIGKILL; shade live record [--put]; Kotlin MediaUploader med samme protokoll."
status: done
column: done
priority: high
assignee: claude
branch: streaming
created: 2026-10-18
updated: 2026-10-19
completed_at: 2026-10-19
- id: media-browser-upload
title: "Opplasting fra nettleseren (iPhone uten app)"
description: "Eiernøkkel i nettleseren og forsegling som strømmer rett inn i stykkene (MediaClient kjører allerede i nettleseren)."
status: todo
column: todo
priority: medium
assignee: any
branch: streaming
created: 2026-10-19
updated: 2026-10-19
completed_at: null
- id: media-android-camera-live
title: "Live fra telefonkameraet"
description: "LivePublisher finnes i Kotlin; mangler MediaCodec → fMP4-muxing og en publiseringsskjerm. Krever enhet for å verifiseres."
status: todo
column: todo
priority: low
assignee: any
branch: streaming
created: 2026-10-19
updated: 2026-10-19
completed_at: null

File diff suppressed because it is too large Load Diff

4
CLAUDE.md Normal file
View 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.

View File

@@ -164,9 +164,190 @@ Nova's `pushDevices.encryptionKey` column is a per-device static AES key. To mig
During the rollout, send notifications with a `v: 1` (legacy) or `v: 2` (Shade) field so old and new clients coexist.
## Migration to at-rest encryption (V3.2)
Shade 0.4.0 ships `@shade/storage-encrypted` — opt-in AES-256-GCM
encryption of every sensitive payload in the local SQLite/Postgres store.
Existing 0.3.x deploys keep their unencrypted DB and behave exactly as
before; encryption is enabled per-deployment with one CLI command.
### One-shot migration (SQLite)
```bash
# Encrypts in place, drops unencrypted tables, leaves a .bak alongside.
shade migrate-storage \
--key-source passphrase \
--passphrase "$SHADE_STORAGE_PASSPHRASE" \
--salt-file /data/shade-client.db.salt
```
For a dry run that validates every row without writing:
`shade migrate-storage … --dry-run`.
### Code-level switch
Replace:
```ts
import { SQLiteStorage } from '@shade/storage-sqlite';
const storage = new SQLiteStorage('/data/shade-client.db');
```
with:
```ts
import { KeyManager, EncryptedSQLiteStorage } from '@shade/storage-encrypted';
const km = await KeyManager.open({
kind: 'passphrase',
passphrase: process.env.SHADE_STORAGE_PASSPHRASE!,
salt: loadSaltFromDisk(),
});
const storage = await EncryptedSQLiteStorage.open({
dbPath: '/data/shade-client.db',
keyManager: km,
});
```
The encrypted store implements the same `StorageProvider`, so
`ShadeSessionManager` and the rest of the wiring is unchanged.
See `docs/storage-encryption.md` for the full design, key sources
(passphrase / OS keychain / app-injected) and rotation.
## Migrating from 0.3.x to 4.0 (GA)
Shade 4.0 is the GA-frozen baseline. Everything from V3.2–V3.12 is
merged, externally reviewed, and the wire format is locked. Nothing is
breaking on the wire compared to 0.4.x — peers continue to interoperate.
The 4.0 migration is therefore mostly **opt-in surface activation**
plus a version-bump.
### What stays the same
- Wire envelope `0x02` (RatchetMessage) with u32 length-prefixes.
- Wire envelope `0x11` (stream-chunk) for `@shade/streams`.
- HTTP shape of all `/v1/keys/...` and `/v1/transfer/...` endpoints.
- All `StorageProvider` core method signatures.
- Identity fingerprints, X3DH flow, Ed25519 signature format.
A 0.3.x peer that has not enabled any opt-ins talks to a 4.0 peer
without code changes. The version bump is semantic ("we have completed
the audit cycle"), not breaking.
### What's new (opt-in)
| Surface | Package | How to enable |
|---------|---------|---------------|
| At-rest encryption | `@shade/storage-encrypted` | `shade migrate-storage` (see above) |
| Async store-and-forward | `@shade/inbox`, `@shade/inbox-server` | `createInboxServer()` + `new Inbox()` |
| Bridge transports (SSE, long-poll) | `@shade/transport-bridge`, `createBridgeRoutes()` | mount bridge routes; `FallbackBridgeTransport` |
| Web Workers crypto | `@shade/crypto-web/worker` | `shade.configureWorkerCrypto({ workerUrl })` |
| Social key recovery | `@shade/recovery` | `setupRecovery / attachGuardian / requestRecovery` |
| WebRTC P2P transport | `@shade/transport-webrtc` (peer-dep) | `shade.configureWebRTC({ factory })` |
| Key Transparency | `@shade/key-transparency`, `createPrekeyServerWithKT(...)` | server: `keyTransparency: { ... }` config; client: `keyTransparency: { mode, logPublicKey }` on `createShade` |
| Trust UX gates | built-in to `@shade/sdk` | `shade.beforeFirstLargeFile / beforeBackupImport / beforeNewDeviceTrust(...)` |
| Files RPC | `@shade/files` | `shade.files.serve(handler)` + `shade.files.client(peer)` |
Pulling in **none** of these gives you the 1.0-shape API at 4.0 quality
(audit-completed, soak-tested). Pulling in **all** of them gives the
full 4.0 stack.
### Schema additions
`StorageProvider` implementations (sqlite, postgres, encrypted variants)
auto-create the additional tables on `ensureTables()` /
`initialize()`. The 4.0 superset:
```sql
-- V3.2 (storage encryption) — only when EncryptedSQLiteStorage / EncryptedPostgresStorage is used
shade_master_key_meta(...) -- KeyManager fingerprint + scrypt params
shade_field_keys(...) -- per-(table, column) wrapped DEKs
-- V3.3 (fingerprint gates)
peer_verifications(...) -- markPeerVerified persistence
peer_identity_versions(...) -- bump on acceptIdentityChange
-- V3.6 (inbox relay)
shade_inbox_register(...) -- TOFU bind address ↔ signing key
shade_inbox_blobs(...) -- ciphertext blobs with TTL + msgId
-- V3.10 (recovery)
shade_recovery_setup(...) -- per-recoverer state
shade_recovery_deposits(...) -- per-guardian deposited shares
-- V3.12 (KT — server only)
shade_kt_leaves(...) -- append-only Merkle leaves
shade_kt_index(...) -- address-sorted commitment
shade_kt_sths(...) -- signed tree heads
-- streams resume (V0.2.0+, listed for completeness)
stream_state(...) -- at-rest encrypted streamSecret
```
A 0.3.x deploy that upgrades the package without enabling any new
surface gets these tables created on first start; they stay empty
unless the corresponding feature is wired. There is **no destructive
migration**. To verify before upgrading production:
```bash
shade doctor --db-path /data/shade-client.db
```
The CLI reports any mismatch between the on-disk schema and the version
the installed packages expect.
### Step-by-step upgrade (typical app)
1. **Bump dependencies.** Update every `@shade/*` to `^4.0.0` in your
`package.json`. Bun / npm / pnpm pull from the Gitea registry as
per `.npmrc`.
2. **Re-run install.** `bun install` (or your tool of choice). The new
table definitions ship with the storage backends — no schema-edit
PRs against your DB.
3. **Boot once with no new opt-ins.** Existing send/receive should work
byte-identically. `shade doctor` should print all green.
4. **Pick the opt-ins you actually want.** Wire them one at a time
(storage-encryption first, then fingerprint gates, then any of the
recovery / KT / WebRTC / inbox surfaces). Each surface has its own
doc under `docs/` (`storage-encryption.md`, `trust-ux.md`,
`recovery.md`, `key-transparency.md`, `webrtc.md`, `inbox.md`,
`transport.md`, `web-workers.md`, `files.md`).
5. **Run cross-version smoke.** Boot a 0.3.x peer next to a 4.0 peer in
staging; exchange a session; confirm `shade fingerprint` matches on
both ends and a round-trip message decrypts cleanly.
6. **Ship 4.0 to a canary.** Roll forward; revert path is `bun
install @shade/sdk@^0.4.0` — there is no DB write that 0.4 cannot
also read.
### Operator checklist (prekey container)
If you operate the standalone container (`gt.zyon.no/stian/shade-prekey`):
1. Pull the 4.0 image: `docker pull gt.zyon.no/stian/shade-prekey:4.0.0`.
2. Add new env vars only if you are turning the corresponding surface
on:
- `SHADE_INBOX_PG_URL` / `SHADE_INBOX_DB_PATH` — async store-and-forward.
- `SHADE_INBOX_PRUNE_INTERVAL_MINUTES` — inbox prune cadence.
- `SHADE_BRIDGE_*` — bridge / SSE / long-poll surface.
- `SHADE_KT_*` — Key Transparency mode + signing key path.
- `SHADE_TRANSFER_*` — transfer routes mounted on the same Hono app.
3. Restart with the existing volume; the inbox / KT tables auto-create
on first request.
4. Update `docs/PRODUCTION-CHECKLIST.md` items for any new surface
you've enabled (rate-limit budgets, retention policies, KT
witness-pinning).
5. Verify the [OpenAPI](packages/shade-server/openapi.yaml) endpoints
you advertise to clients now include the routes you mounted.
### What about 4.0 → 4.x?
V4.x is bug-fix only. No wire-bump until V5.0 (voice/video) which
is **additive** — it allocates new envelope types (frame-key prefixes)
that 4.0 clients ignore by design.
## Common pitfalls
1. **Don't store private keys in shared databases without encryption at rest** — Shade trusts the storage layer to be secure. Use filesystem encryption or PostgreSQL TDE if the database is on shared infrastructure.
1. **Don't store private keys in shared databases without encryption at rest** — for shared infrastructure, enable `@shade/storage-encrypted` (V3.2) or use filesystem encryption / PostgreSQL TDE. The default `SQLiteStorage` and `PostgresStorage` write unencrypted.
2. **Don't skip identity verification** — Shade gives you fingerprints (`getIdentityFingerprint()`), but it's the user's responsibility to compare them out-of-band on first contact.
3. **Don't reuse session storage between identities** — each user/device should have its own Shade storage. Mixing identities in one storage will corrupt the ratchet state.
4. **Keep prekey stocks topped up** — call `ensurePreKeyStock()` periodically (e.g., on app start or every hour). When the server runs out of one-time prekeys, new sessions will fall back to using just the signed prekey, which is slightly less secure.

419
README.md
View File

@@ -2,18 +2,83 @@
End-to-end encryption library implementing the Signal Protocol (X3DH + Double Ratchet) for TypeScript/Bun. Drop into any project — frontend, backend, mobile — to get forward secrecy, post-compromise recovery, and self-healing security.
> **4.0.0 — General Availability.** All V3.1 → V3.12 work is merged,
> the cross-platform vector suite is green on TS + Kotlin (1000 / 1000
> + 11 / 11), the threat model has been refreshed for every new
> surface, and the core stack (X3DH, ratchet, storage encryption,
> recovery, WebRTC P2P, Key Transparency) has been packaged for
> external review. The wire format is **unchanged from 0.4.x** — 4.0
> peers interoperate with 0.4.x peers byte-for-byte. See
> [MIGRATION.md § 0.3.x → 4.0](./MIGRATION.md#migrating-from-03x-to-40-ga)
> for the upgrade path and [CHANGELOG.md § 4.0.0](./CHANGELOG.md) for
> the consolidated release notes. Voice / Video have been moved to
> [V5.0](./docs/V5.0.md), to be built on top of the frozen 4.0
> baseline.
## Status
| Area | 4.0 status | Pointers |
|------|-----------|----------|
| Protocol core (X3DH + ratchet + sender keys) | ✅ Done — frozen | [`packages/shade-core`](./packages/shade-core) |
| Storage encryption (V3.2) | ✅ Done — opt-in `EncryptedSQLiteStorage` / `EncryptedPostgresStorage`, key sources: passphrase / OS keychain / app-injected | [`docs/storage-encryption.md`](./docs/storage-encryption.md) |
| Fingerprint gates & trust UX (V3.3) | ✅ Done — `Shade.beforeFirstLargeFile / beforeBackupImport / beforeNewDeviceTrust` | [`docs/trust-ux.md`](./docs/trust-ux.md) |
| Observability v2 (V3.4) | ✅ Done — OpenTelemetry-shaped events, `/metrics`, observer dashboard | [`docs/observability.md`](./docs/observability.md) |
| Android parity & cross-platform CI (V3.5) | ✅ Done — TS + Kotlin vector-gate live; Android `KeystoreStorage` is post-GA | [`android/shade-android/README.md`](./android/shade-android/README.md), [`docs/cross-platform.md`](./docs/cross-platform.md) |
| Async store-and-forward (V3.6) | ✅ Done — `@shade/inbox` + `@shade/inbox-server` | [`docs/inbox.md`](./docs/inbox.md) |
| Transport bridge (V3.7) | ✅ Done — SSE / long-poll / WS adapters | [`docs/transport.md`](./docs/transport.md) |
| Web Workers crypto (V3.8) | ✅ Done — lane keys never cross the thread boundary | [`docs/web-workers.md`](./docs/web-workers.md) |
| Rich file metadata + thumbnails (V3.9) | ✅ Done — in `@shade/files` | [`docs/files.md`](./docs/files.md) |
| Social key recovery (V3.10) | ✅ Done — Shamir + AEAD-gated reconstruction + guardian widgets | [`docs/recovery.md`](./docs/recovery.md) |
| WebRTC P2P transport (V3.11) | ✅ Done — `RTCDataChannel` with `MultiTransportFallback([webrtc, http])` | [`docs/webrtc.md`](./docs/webrtc.md) |
| Key Transparency (V3.12) | ✅ Done — opt-in Merkle log, signed STH, witness gossip | [`docs/key-transparency.md`](./docs/key-transparency.md) |
| External crypto review | 🟡 Bundle ready — review window open after tag | [`docs/audit/REVIEW-BUNDLE.md`](./docs/audit/REVIEW-BUNDLE.md) |
| Soak (≥ 2 weeks under load) | 🟡 Harness shipped — operator runs it | [`scripts/soak.ts`](./scripts/soak.ts) (`bun run soak --hours 336`) |
| Voice / Video / Broadcast | 🔜 V5.0 — built on top of frozen 4.0 stack | [`docs/V5.0.md`](./docs/V5.0.md) |
## What you get
**Protocol core**
- **X3DH** initial key agreement (works asynchronously via prekey bundles)
- **Double Ratchet** for per-message forward secrecy and post-compromise security
- **Self-authenticated prekey server** (Hono, Docker-ready) with rate limiting, metrics, health checks
- **Persistent storage backends**: SQLite (zero-config) and PostgreSQL (Drizzle)
- **Sender keys** for group ratchet (1:N broadcast key derivation)
- **Identity rotation** with grace period for old sessions
- **Safety numbers** (Signal-style fingerprints) for out-of-band verification
- **Constant-time comparisons** and **memory zeroization** for hardened operation
- **Binary wire format** that's significantly smaller than JSON
- **Binary wire format** (`@shade/proto`) — significantly smaller than JSON
**Storage**
- **Persistent backends**: SQLite (zero-config, `bun:sqlite`) and PostgreSQL (Drizzle, FOR UPDATE SKIP LOCKED)
- **Crash-safe** — sessions survive container restarts, power outages, SIGKILL
- **Live observability** — bundled dashboard SPA + embeddable React widgets to see what's happening between every step
- **At-rest encryption (V3.2, opt-in)** — AES-256-GCM under per-(table,column) DEKs; key sources: passphrase (scrypt), OS keychain (`@shade/keychain`), or app-injected. Online re-key, no downtime.
**Servers**
- **Self-authenticated prekey server** (`@shade/server`, Hono, Docker-ready) with rate limiting, metrics, health checks
- **Async store-and-forward relay** (`@shade/inbox-server`) — TTL-bound ciphertext blobs, signed PUT/FETCH/ACK, idempotent on `(address, msgId)`, per-recipient quota
- **Bridge transports** (`@shade/transport-bridge`) — WS → SSE → long-poll fallback chain for clients that can't keep a WebSocket open. Same `IncomingMessage` shape across all three.
- **Standalone container** — one image bundles prekey + inbox + bridge + transfer + KT + observer
**Trust UX**
- **Fingerprint gates (V3.3)** — `Shade.beforeFirstLargeFile(threshold, handler)`, `beforeBackupImport`, `beforeNewDeviceTrust`. Gates raise `FingerprintNotVerifiedError` on the operations that matter, default-warn TOFU otherwise.
- **`<FingerprintCompare />` / `<FingerprintGate />`** widgets for the matching UI side.
**File transfer & filesystem**
- **E2EE file transfers** (`@shade/streams` + `@shade/transfer`) — multi-lane chunked uploads/downloads with resume, integrity checks (per-lane sha256 + overall sha256), HTTP/WS fallback, `MultiTransportFallback` for N-ary demotion
- **WebRTC P2P transport (V3.11, opt-in)** — `RTCDataChannel` chunk path with public-STUN defaults, TURN-relay support, glare-safe peer pool, automatic fallback to HTTP when NAT traversal fails (`@shade/transport-webrtc`)
- **Web Workers crypto (V3.8, opt-in)** — AEAD, HKDF, HMAC, X25519, Ed25519 and per-lane stream state run in a dedicated worker. 100 MB+ uploads stay smooth without frame drops; lane keys never cross the thread boundary (`@shade/crypto-web/worker`)
- **E2EE filesystem RPC** (`@shade/files`) — typed `list/stat/mkdir/delete/move/read/write/getThumbnail` + custom ops, with rate-limit, retention, fingerprint-gate, and metrics hooks. React hooks under `@shade/files/react`.
**Recovery**
- **Social key recovery (V3.10)** — Shamir-split your identity to `n` guardians; any threshold-many `k` together restore it on a new device. No centralized recovery agent; OOB-fingerprint gate per guardian release; AES-GCM-authenticated reconstruction (`@shade/recovery` + `<RecoverySetup />` / `<RecoveryRequest />` / `<RecoveryApprove />`)
**Verifiable distribution**
- **Key Transparency (V3.12, opt-in)** — append-only Merkle log over the prekey server. Every `register` / `delete` becomes a signed leaf; every bundle-fetch carries an inclusion proof; an Ed25519-signed Tree Head ties roots to a fixed `log_id`. A `LightWitness` cross-checks STHs across clients so a malicious server that splits its view or rewrites history is caught (`@shade/key-transparency`).
**Observability**
- **Live observability** — OpenTelemetry-shaped events, bundled dashboard SPA + embeddable React widgets to see what's happening between every step (`@shade/observability` + `@shade/observer` + `@shade/dashboard`)
**Tooling**
- **CLI** — `shade init` scaffolder, `shade migrate-storage` (V3.2), `shade rotate-storage-key`, `shade fingerprint`, `shade rotate`, `shade peer`, `shade dashboard`, `shade doctor`, `shade backup` (`@shade/cli`)
- **Soak harness** — `bun run soak --hours 336` for the 2-week GA-stable window (`scripts/soak.ts`)
## Quick start
@@ -64,7 +129,57 @@ const plaintext = await shade.receive('alice@example.com', incomingEnvelope);
console.log(await shade.fingerprint);
```
Or use the lower-level packages directly if you need full control:
### Opt-in surfaces (V3.x → 4.0 GA)
All of these are off by default. Wire them only where you need them.
```ts
// V3.3 — Fingerprint gates: enforce verification on the operations that matter
shade.beforeFirstLargeFile(10 * 1024 * 1024, async ({ peer, fingerprint }) => {
return await ui.confirmSafetyNumberMatches(peer, fingerprint);
});
shade.beforeBackupImport(async ({ embeddedFingerprint }) => { /* ... */ });
shade.beforeNewDeviceTrust(async ({ peer, oldFp, newFp }) => { /* ... */ });
// V3.8 — Web Workers crypto: opt-in, lane keys stay off the main thread
shade.configureWorkerCrypto({
workerUrl: new URL('@shade/crypto-web/worker', import.meta.url),
});
// V3.11 — WebRTC P2P transport: file transfers ride RTCDataChannel where NAT allows
import { nativeRtcFactory } from '@shade/transport-webrtc';
shade.configureWebRTC({
factory: nativeRtcFactory(),
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
});
// V3.12 — Key Transparency: detect server-side bundle swaps
const shade = await createShade({
prekeyServer: 'https://shade.example.com',
keyTransparency: { mode: 'observe-strict', logPublicKey: PINNED_KEY_BYTES_32 },
});
```
### Files RPC (`@shade/files`)
```ts
// Server side — Bob exposes a virtual filesystem
const stop = await shade.files.serve({
list: async (ctx) => ({ entries: await readdirAt(ctx.path), hasMore: false }),
read: async (ctx) => readAt(ctx.path), // returns inline ≤ 256 KiB or streams
write: async (ctx) => writeAt(ctx.args), // receives inline or streams
// + stat, mkdir, delete, move, getThumbnail, plus typed custom ops
});
// Client side — Alice consumes Bob's filesystem
const fs = await shade.files.client('bob');
await fs.write('/photos/cover.png', new Uint8Array([/* ... */])); // auto inline/streams
const result = await fs.read('/photos/cover.png');
```
Files ≤ 256 KiB ride inline in the RPC envelope; larger files automatically promote to multi-lane `@shade/transfer` streams with sha256 integrity. See [`docs/files.md`](./docs/files.md) for the full API.
### Lower-level access
```ts
import { ShadeSessionManager } from '@shade/core';
@@ -78,62 +193,190 @@ const manager = new ShadeSessionManager(
await manager.initialize();
```
## Architecture
### At-rest encryption (V3.2)
```ts
import { KeyManager, EncryptedSQLiteStorage } from '@shade/storage-encrypted';
const km = await KeyManager.open({
kind: 'passphrase',
passphrase: process.env.SHADE_STORAGE_PASSPHRASE!,
salt: loadSaltFromDisk(),
});
const storage = await EncryptedSQLiteStorage.open({
dbPath: '/data/shade-client.db',
keyManager: km,
});
```
To migrate an existing 0.3.x SQLite DB in place:
```bash
shade migrate-storage \
--key-source passphrase \
--passphrase "$SHADE_STORAGE_PASSPHRASE" \
--salt-file /data/shade-client.db.salt
```
## Architecture — keys vs. payloads
Shade splits the network into a **public-key plane** (the prekey
server) and an **encrypted plane** (everything else). The prekey
server only sees public key material. If you remember nothing else
from this README, remember this picture:
```
Shade Prekey Server (Hono)
│
POST /v1/keys/register (signed)
GET /v1/keys/bundle/:address
POST /v1/keys/replenish (signed)
DELETE /v1/keys/:address (signed)
│
┌─────────────────────┴─────────────────────┐
│ │
[Client A] [Client B]
ShadeSessionManager ShadeSessionManager
│ │
├──── X3DH ────────────────────────────────►│
│ │
│◄──── Double Ratchet messages ────────────►│
│ │
SQLiteStorage / PostgresStorage SQLiteStorage / PostgresStorage
Shade Prekey Container (Hono — public keys only)
│
/v1/keys/* /v1/inbox/* /v1/bridge/* /v1/transfer/*
/v1/kt/* /metrics /healthz /ready
│
┌──────────────────┴──────────────────┐
│ │
[Client A] [Client B]
ShadeSessionManager ShadeSessionManager
│ │
├── X3DH (handshake via prekey srv) ─►│
│ │
│◄── Double Ratchet messages ────────►│ ← end-to-end,
│ (ratchet 0x02 / chunks 0x11) │ never on the
│ │ prekey server
│
│◄── @shade/transfer chunks ─────────►│ ← peer-to-peer
│ POST /v1/transfer/:id/chunk │ HTTP, opaque
│ GET /v1/transfer/:id/state │ ciphertext
│
│◄── @shade/inbox blobs (offline) ───►│ ← TTL-bound
│ POST /v1/inbox/:address │ ciphertext-only
│ POST /v1/inbox/:address/fetch │ relay
│
│◄── @shade/transport-webrtc ────────►│ ← optional P2P
│ RTCDataChannel `shade-transfer/v1` │ `MultiTransportFallback`
│ │ auto-demotes to HTTP
SQLiteStorage / PostgresStorage SQLiteStorage / PostgresStorage
+ EncryptedSQLiteStorage (V3.2) + EncryptedSQLiteStorage (V3.2)
(private keys + sessions) (private keys + sessions)
```
### What goes via the prekey server
- Identity public keys (Ed25519 + X25519)
- Signed prekeys + one-time prekey bundles
- Registration / replenish / delete writes, all Ed25519-signed
- (V3.6) Inbox ciphertext blobs with TTL — same container, separate
routes; the relay only sees `address || msgId || ciphertext-bytes`
- (V3.7) Bridge transports (SSE / long-poll / WS) — also delivered by
the same Hono app for clients that can't hold a WebSocket
- (V3.12, opt-in) KT inclusion proofs + signed tree heads on
`/v1/kt/*` — verifiable distribution
- Operator-only metrics and the optional observer dashboard
### What does **not** go via the prekey server
- **Message plaintext, ever.** Encrypted ratchet envelopes flow peer-
to-peer over whatever transport you choose (HTTP, WebSocket, your
own broker, or the inbox relay above — which carries ciphertext only).
- **File chunks.** `@shade/transfer` POSTs ciphertext directly to the
receiver's `/v1/transfer/:streamId/chunk` route — the prekey server
is not involved. With V3.11 + `configureWebRTC()`, chunks ride
`RTCDataChannel` peer-to-peer; the relay is bypassed entirely.
- **Identity private keys.** They never leave the device's storage.
- **Filesystem RPC.** `@shade/files` rides the Double Ratchet for
control + small payloads, then promotes to direct `@shade/transfer`
streams for larger blobs.
- **Stream resume secrets.** Persisted only on the local device,
encrypted under a device-key derived from the identity signing key.
The prekey server is metadata-bearing (see `THREAT-MODEL.md § 2`):
it sees who registers, who fetches whose bundle, and when. It does
**not** see message contents, transfer contents, or session state.
**V3.12 Key Transparency** (opt-in) makes its bundle distribution
*verifiable* so a malicious server that swaps a bundle is caught.
For the full threat model and mitigations, read
[THREAT-MODEL.md](./THREAT-MODEL.md). For deployment-time guarantees,
read [docs/PRODUCTION-CHECKLIST.md](./docs/PRODUCTION-CHECKLIST.md).
## Packages
All packages publish in lockstep at `4.0.0`.
| Package | Purpose |
|---------|---------|
| `@shade/core` | Protocol logic (X3DH, Double Ratchet, session manager, errors, events) |
| `@shade/crypto-web` | SubtleCrypto + @noble/curves provider, in-memory storage |
| `@shade/storage-sqlite` | Persistent SQLite storage (zero-config, bun:sqlite) |
| `@shade/storage-postgres` | PostgreSQL storage with Drizzle for shared databases |
| `@shade/server` | Prekey server (Hono routes, auth, rate limit, health, metrics) |
| `@shade/transport` | HTTP + WebSocket transport wrappers with auto-encryption |
| `@shade/proto` | Compact binary wire format (smaller than JSON) |
| `@shade/core` | Protocol logic (X3DH, Double Ratchet, sender keys, session manager, errors, events) |
| `@shade/proto` | Compact binary wire format (`0x01` PreKeyMessage, `0x02` RatchetMessage, `0x11` StreamChunk) |
| `@shade/crypto-web` | SubtleCrypto + @noble/curves provider, in-memory storage. Includes the V3.8 Web Workers entrypoint (`@shade/crypto-web/worker`) — drop-in `WorkerCryptoProvider` plus `createEncryptStream` / `createDecryptStream` TransformStream factories |
| `@shade/observability` | OpenTelemetry-shaped event bus consumed by `@shade/observer`, server hooks, and the dashboard |
| `@shade/keychain` | OS keychain bindings (libsecret / Keychain / Credential Manager) used by `@shade/storage-encrypted` and the CLI |
| `@shade/key-transparency` | Key Transparency (V3.12) — RFC 6962-style append-only Merkle log, address-index commitment, signed tree heads, and a `LightWitness` for split-view detection. Opt-in on both server and client. |
| `@shade/storage-sqlite` | Persistent SQLite storage (zero-config, `bun:sqlite`); also ships `SqliteInboxStore` |
| `@shade/storage-postgres` | PostgreSQL storage with Drizzle for shared databases; also ships `PostgresInboxStore` + `PostgresKTLogStore` |
| `@shade/storage-encrypted` | At-rest encryption (V3.2) — `EncryptedSQLiteStorage` / `EncryptedPostgresStorage`, `KeyManager`, online re-key |
| `@shade/streams` | Multi-lane chunk encryption — HKDF-derived per-lane keys, deterministic AES-GCM nonces, streaming SHA-256, file metadata + thumbnails (V3.9) |
| `@shade/transport` | HTTP + WebSocket transport wrappers with auto-encryption; KT-verifying `fetchBundleVerified` |
| `@shade/transport-bridge` | WS → SSE → long-poll fallback chain (V3.7) — single `IncomingMessage` shape across transports for clients that can't keep a WebSocket open |
| `@shade/transport-webrtc` | V3.11 P2P chunk transport via `RTCDataChannel`. Plugs into `@shade/transfer` as an `ITransferTransport`; signaling rides Shade's own ratchet. Memory factory + native (`globalThis.RTCPeerConnection`) factory included; `MultiTransportFallback([webrtc, http])` wired automatically when `shade.configureWebRTC()` is called. |
| `@shade/server` | Prekey server (Hono routes, auth, rate limit, health, metrics). `createPrekeyServerWithKT(...)` opts into V3.12 KT mode |
| `@shade/inbox-server` | Async store-and-forward relay (V3.6) — Hono routes, signed PUT/FETCH/DELETE, per-recipient TTL + quota, idempotent on `(address, msgId)`. Bundles into the same standalone container as the prekey server |
| `@shade/inbox` | Inbox client + durable outgoing queue + receive cursor + push-trigger hook (`onMessageQueued`); composes on top of `Shade.send`/`Shade.receive` for offline-recipient delivery |
| `@shade/transfer` | Transfer engine on top of streams: parallel lanes, resume, HTTP + WS transport with auto-fallback, `MultiTransportFallback` (N-ary demotion), integrity verification |
| `@shade/files` | Typed E2EE filesystem RPC — list/stat/mkdir/delete/move/read/write/getThumbnail + custom ops, auto inline/streams routing, production hooks (rate limit, retention, fingerprint gate, metrics), React hooks under `@shade/files/react` |
| `@shade/recovery` | Social key recovery (V3.10) — Shamir-split identity to `n` guardians; threshold-many `k` reconstruct on a new device. AES-GCM-authenticated reconstruction; OOB-fingerprint gate per guardian release |
| `@shade/observer` | Live debugger backend (snapshot, SSE, dashboard) — see [README](./packages/shade-observer/README.md) |
| `@shade/widgets` | Embeddable React widgets — see [README](./packages/shade-widgets/README.md) |
| `@shade/dashboard` | Standalone dashboard SPA bundled into the observer |
| `@shade/sdk` | High-level wrapper with `createShade()` one-liner, auto-publish, auto-establish, auto-replenish |
| `@shade/cli` | `shade init` scaffolder + utilities (fingerprint, rotate, peer, dashboard, doctor) |
| `@shade/sdk` | High-level wrapper with `createShade()` one-liner, auto-publish, auto-establish, auto-replenish, `Shade.files` namespace, fingerprint gates, KT integration, WebRTC opt-in |
| `@shade/widgets` | Embeddable React widgets — fingerprint compare/gate, recovery setup/request/approve, transfer uploader/downloader, observer panels |
| `@shade/cli` | `shade init` scaffolder + utilities (fingerprint, rotate, peer, dashboard, doctor, backup, migrate-storage, rotate-storage-key) |
## Shade as a modular toolkit
Shade is split into packages so each project can depend on **only what it needs**—encrypted messaging, file transfer, prekey hosting, social recovery, KT verification, or lower-level building blocks. You do not need one giant stack for every use case.
For a **plain-language map** (which packages to add, what the prekey server does vs your own wiring, and where to start in code), see **[docs/SHADE-BY-SCENARIO.md](./docs/SHADE-BY-SCENARIO.md)**.
## Publishing
All packages publish to a self-hosted Gitea npm registry on `gt.zyon.no`.
All packages publish to a self-hosted Gitea npm registry on `gt.zyon.no`. The Docker image of the standalone container ships at `gt.zyon.no/stian/shade-prekey:<tag>`.
```bash
# Bump all packages in lockstep
bun run version 1.1.0
bun run version 4.0.1
# Dry-run (pack all tarballs without publishing)
# Dry-run (pack all tarballs without publishing) — no token required
bun run publish:dry
# Real publish (requires GITEA_TOKEN env var)
# Real publish — interactive (prompts for GITEA_TOKEN, checks
# registry for conflicts, publishes via scripts/publish-all.ts)
bun run publish:all
# Or via CI: push a git tag v1.1.0 and .gitea/workflows/publish.yml runs
# Build + push the standalone Docker image
bun run scripts/build-docker.ts -- --tag 4.0.1 --push
```
The interactive `scripts/publish-shade.sh` is the human entrypoint;
`scripts/publish-all.ts` is the headless variant used by CI and
`publish:dry`. They share a single `PACKAGES` list (24 entries at
4.0.0) so the two flows can never drift.
## Soak / GA-stable
Before tagging `4.0.0` as `latest` and recommending production
upgrades, run the combined soak harness for ≥ 2 weeks:
```bash
# Full GA window (V4.0 §Soak): 14 days × 24 hours
bun run soak --hours 336
# Smoke (~3 minutes — ratchet ping-pong, integrity check)
bun run soak:smoke
```
The harness fans out N concurrent ratchet pairs, ping-pongs at
~400 ops/sec/pair, and reports cumulative counters every minute.
Any exception in any pair is captured and re-raised at shutdown so
silent failures cannot hide. Wrap it in `systemd-run --user`,
`nohup`, or a Gitea scheduled job for the actual 2-week window.
## Security properties
| Property | Description |
@@ -146,33 +389,95 @@ bun run publish:all
| **Memory zeroization** | Key material is zeroed after use (best-effort in JS) |
| **Identity verification** | Safety numbers (60 digits) for out-of-band comparison |
| **Identity rotation** | 7-day grace period for old sessions during rotation |
| **At-rest encryption** *(V3.2, opt-in)* | AES-256-GCM under per-(table, column) DEKs; AAD binds `(table, column, pk)`; passphrase / OS keychain / app-injected master key; online re-key |
| **Fingerprint gates** *(V3.3)* | `Shade.beforeFirstLargeFile / beforeBackupImport / beforeNewDeviceTrust` raise `FingerprintNotVerifiedError` on the operations that matter; defaults to TOFU + warning when no gate is registered |
| **Async store-and-forward** *(V3.6)* | Relay only sees `address || msgId || ciphertext`; idempotent PUT; signed FETCH/ACK; TTL-bounded |
| **Web-Worker key isolation** *(V3.8)* | Lane keys, identity keys, and ratchet chain keys live inside a dedicated worker; main thread only ferries plaintext via transferable buffers; idle terminate releases worker memory |
| **Social key recovery** *(V3.10)* | Shamir over GF(2^8); AEAD-authenticated reconstruction (forged shares fail); guardian-side fingerprint gate before share release |
| **WebRTC P2P transport** *(V3.11)* | Same Double Ratchet authenticates SDP/ICE signaling; chunk frames AEAD-bound to `streamId/laneId/seq`; deterministic glare resolution; `MultiTransportFallback` auto-demotes to HTTP |
| **Key Transparency** *(V3.12, opt-in)* | Append-only Merkle log + signed tree heads + witness gossip — split-view and history-rewrite are detected by clients |
## Documentation
- [SECURITY.md](./SECURITY.md) — Reporting vulnerabilities, security policy
- [THREAT-MODEL.md](./THREAT-MODEL.md) — Honest threat model and assumptions
- [examples/](./examples/) — Runnable example applications
- [MIGRATION.md](./MIGRATION.md) — How to replace existing crypto with Shade
**Operator + integrator**
## Deployment
- [docs/SHADE-BY-SCENARIO.md](./docs/SHADE-BY-SCENARIO.md) — **Modular toolkit**: pick packages by scenario (messages, files, browser, ops)
- [docs/PRODUCTION-CHECKLIST.md](./docs/PRODUCTION-CHECKLIST.md) — Pre-flight gates for going to production
- [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md) — Full deployment guide (Docker, env vars, PostgreSQL, backup, Dokploy)
- [docs/ROADMAP.md](./docs/ROADMAP.md) — V3.x → 4.0 GA → V5.0 trajectory
For containerized deployment (Docker/Dokploy):
**Per-surface deep-dives**
```yaml
services:
shade-prekey:
image: shade-prekey-server:latest
ports:
- "3900:3900"
volumes:
- shade-data:/data
environment:
- SHADE_PREKEY_DB_PATH=/data/shade-prekeys.db
volumes:
shade-data:
- [docs/files.md](./docs/files.md) — `@shade/files` API + design (filesystem RPC, custom ops, hooks, React)
- [docs/streams.md](./docs/streams.md) — `@shade/streams` + `@shade/transfer` deep dive (incl. hardening + retention)
- [docs/inbox.md](./docs/inbox.md) — `@shade/inbox` + `@shade/inbox-server` async store-and-forward relay (V3.6)
- [docs/transport.md](./docs/transport.md) — `@shade/transport-bridge` SSE / long-poll / WS bridge layer (V3.7)
- [docs/web-workers.md](./docs/web-workers.md) — V3.8 Web Workers crypto: setup, bundler recipes (Vite/Webpack/Rollup), Safari notes, lifecycle, threat-model
- [docs/recovery.md](./docs/recovery.md) — `@shade/recovery` social key recovery (V3.10): Shamir setup, guardian-side gates, threshold tuning
- [docs/webrtc.md](./docs/webrtc.md) — `@shade/transport-webrtc` P2P transport (V3.11): NAT-traversal, TURN config, glare resolution, wire format, multi-fallback wiring
- [docs/key-transparency.md](./docs/key-transparency.md) — `@shade/key-transparency` (V3.12): operator + client onboarding, witness role, recovery procedures
- [docs/storage-encryption.md](./docs/storage-encryption.md) — V3.2 at-rest encryption: design, key sources, rotation
- [docs/trust-ux.md](./docs/trust-ux.md) — V3.3 fingerprint gates: when each fires, handler patterns, widget integration
- [docs/observability.md](./docs/observability.md) — V3.4 event bus + dashboard
- [docs/cross-platform.md](./docs/cross-platform.md) — V3.5 Android parity + cross-platform vector regime
**Threat model + audit**
- [SECURITY.md](./SECURITY.md) — Reporting vulnerabilities, security policy, threat-/test-matrix
- [THREAT-MODEL.md](./THREAT-MODEL.md) — Honest threat model and assumptions (12 numbered sections + residual-risks table)
- [docs/audit/REVIEW-BUNDLE.md](./docs/audit/REVIEW-BUNDLE.md) — External crypto-review entrypoint (scope, build instructions, reporting)
- [docs/audit/SCOPE.md](./docs/audit/SCOPE.md) — One-page audit-scope summary
**Migration + history**
- [MIGRATION.md](./MIGRATION.md) — How to replace existing crypto with Shade + the [0.3.x → 4.0 upgrade path](./MIGRATION.md#migrating-from-03x-to-40-ga)
- [CHANGELOG.md](./CHANGELOG.md) — `4.0.0` GA section + every prior release
- [docs/archive/](./docs/archive/) — V2.1 / V2.2 / V2.3 backlog and V3.1 → V3.12 implementation plans (all `Status: Done`)
- [docs/V5.0.md](./docs/V5.0.md) — Voice / Video / Broadcast (post-GA, built on the frozen 4.0 stack)
**Examples**
- [examples/](./examples/) — Runnable example applications, including
[`07-streams-upload`](./examples/07-streams-upload) (multi-lane file transfer)
and [`08-files-browser`](./examples/08-files-browser) (filesystem RPC)
## Deployment — one container per project
Shade ships as a self-contained Docker image. Deploy one container per project, point your app at it, done. Any stack (Bun, Python, Go, Rust, Kotlin) can use it — the container exposes a plain HTTP API documented in OpenAPI.
```bash
docker run -d \
--name my-project-shade \
-v my-project-shade:/data \
-p 3900:3900 \
-e SHADE_OBSERVER_TOKEN=change-me-to-at-least-16-chars \
gt.zyon.no/stian/shade-prekey:4.0.0
```
The SQLite database persists to a Docker volume so all keys and prekey bundles survive restarts.
The container includes:
- **Prekey server** — `/v1/keys/*` REST API
- **Inbox relay (V3.6)** — `/v1/inbox/*` async store-and-forward; enable
with `SHADE_INBOX_DB_PATH=/data/inbox.db` (or `SHADE_INBOX_PG_URL`).
`SHADE_INBOX_PRUNE_INTERVAL_MINUTES` controls TTL prune cadence.
- **Bridge transports (V3.7)** — `/v1/bridge/{stream,poll,ws}` SSE +
long-poll + WS adapters for clients that can't keep a WebSocket open.
- **Transfer routes** — `/v1/transfer/*` chunk + state + control routes
for `@shade/transfer`.
- **Key Transparency (V3.12)** — `/v1/kt/*` exposes `log_id`, latest +
historical STH, and consistency proofs. Enable with
`SHADE_KT_*` env vars; off by default.
- **Observer dashboard** — `/shade-observer/dashboard/` (off unless
`SHADE_OBSERVER_TOKEN` is set)
- **OpenAPI spec** — `/openapi.yaml` and interactive `/docs` viewer
(covers all 27 routes — prekey, inbox, bridge, transfer, KT,
observer, `/metrics`, `/healthz`, `/ready`)
- **Prometheus metrics** — `/metrics`
- **Health probes** — `/health` (full), `/healthz` (liveness),
`/ready` (readiness)
- **Stale cleanup** — purges inactive identities automatically
See [docs/DEPLOYMENT.md](./docs/DEPLOYMENT.md) for the full deployment guide, environment variables, PostgreSQL config, backup strategy, and Dokploy instructions.
## License

View File

@@ -1,16 +1,54 @@
# Security Policy
## Review status
| Area | Status | Notes |
|------|--------|-------|
| Internal review | **Done** | Every mitigation in `THREAT-MODEL.md` is cross-linked to at least one automated test (see [Threat-/test-matrix](#threat--test-matrix) below). The matrix is enforced by `tests/security/*` + the cross-platform vector suite. |
| Independent code review | **Pending** | Targeted for **V4.0**. No external review has been completed. |
| Independent crypto review | **Pending** | Targeted for **V4.0** alongside the audit. |
| Pen test | **Pending** | Targeted for **V4.0**. |
> **Read this:** Shade implements the Signal Protocol primitives
> (X3DH + Double Ratchet) on top of `@noble/curves` and SubtleCrypto.
> The protocol is well-studied; the **implementation** has not yet been
> audited externally. Treat the wire format as stable but the
> implementation as "production-ready in trusted contexts" until V4.0
> closes the audit gap. The `THREAT-MODEL.md` cells with no test
> linkage are documentary, not enforced.
## Reporting a Vulnerability
If you discover a security vulnerability in Shade, please report it privately by emailing the maintainer rather than opening a public issue. We take all reports seriously and will respond within 48 hours.
If you discover a security vulnerability in Shade, please report it
privately by emailing the maintainer rather than opening a public
issue. We take all reports seriously and will respond within 48 hours.
### How to report
1. **Email:** the maintainer email listed in the package metadata.
For coordinated disclosure, prefer email over GitHub/Gitea so the
issue does not become public before a fix ships.
2. **PGP / age:** if you need encrypted reporting, ask for a key
over the same email — keys are not bound to the repo to avoid
key-rotation drift.
3. **Scope:** CVE-style severity (CVSS v3.1) is appreciated but not
required. A working reproduction is more valuable than a CVSS
score.
When reporting, please include:
- A description of the vulnerability
- Steps to reproduce
- Steps to reproduce (a runnable script or test case)
- Affected versions
- Potential impact
- Any suggested mitigation
We commit to:
- Acknowledging receipt within 48 hours.
- A first-pass triage within 7 days.
- A coordinated disclosure timeline once severity is agreed; for
high-severity issues we aim to ship a patched release within 30
days of triage.
## What's in scope
Shade aims to provide:
@@ -46,3 +84,48 @@ Shade uses well-established primitives:
- **HMAC-SHA256** for chain key advancement (via Web Crypto SubtleCrypto)
These match the Signal Protocol specification.
---
## Threat-/test-matrix
This is the consolidated index that backs `THREAT-MODEL.md`. Every
threat-model row that claims a mitigation must point to at least one
test file here. Pull requests that add a new mitigation must add a
matrix row in the same change.
| Threat-model row | Mitigation | Test file(s) |
|------------------|------------|--------------|
| § 1 Network attacker — signed writes | Ed25519 signature on every write | `packages/shade-server/tests/server.test.ts` |
| § 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 — 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 — 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` |
| § 3 Endpoint compromise — forward secrecy | Old keys not recoverable from leak | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-crypto-web/tests/hardening.test.ts` |
| § 3 Endpoint compromise — post-compromise security | First DH ratchet evicts leaked state | `packages/shade-core/tests/ratchet.test.ts` (`"alternating messages trigger DH ratchets"`) |
| § 3 Endpoint compromise — memory zeroization | Buffers wiped after use | `packages/shade-crypto-web/tests/hardening.test.ts` (`"zeroize"`) |
| § 3 Endpoint compromise — identity-rotation invalidates resume | Device-key bound to signing key | `packages/shade-core/tests/identity-rotation.test.ts`, `packages/shade-transfer/tests/resume.test.ts` |
| § 4 Compromised device storage — at-rest stream secrets | Resume secret AES-GCM under device-key | `packages/shade-transfer/tests/resume.test.ts` |
| § 4 Compromised device storage — at-rest session DB | **Pending V3.2** | _none yet_ |
| § 5 Timing side-channel — constant-time compare | XOR accumulator | `packages/shade-crypto-web/tests/hardening.test.ts` (`"timing variance stays bounded across mismatch positions"`) |
| § 5 Timing side-channel — primitives | SubtleCrypto + @noble/curves | `packages/shade-crypto-web/tests/provider.test.ts`, `packages/shade-streams/tests/aead.test.ts` |
| § 6 DoS — per-IP register/bundle rate limit | Token bucket per IP | `packages/shade-server/tests/rate-limit.test.ts` |
| § 6 DoS — per-identity replenish/delete rate limit | Token bucket per identity | `packages/shade-server/tests/rate-limit.test.ts` |
| § 6 DoS — body size cap (64 KiB) | Hono middleware | `packages/shade-server/tests/server.test.ts` |
| § 6 DoS — address validation | Regex + NFKC + length | `packages/shade-server/tests/server.test.ts` |
| § 6 DoS — per-sender ops/byte quota (`@shade/files`) | RateLimiter token bucket | `packages/shade-files/tests/security/quota.test.ts` |
| § 6 DoS — replay protection (`@shade/files`) | Idempotency cache | `packages/shade-files/tests/security/replay.test.ts` |
| § 6 DoS — fingerprint gate (`@shade/files`) | Per-sender trust check | `packages/shade-files/tests/security/fingerprint-gate.test.ts` |
| § 6 DoS — tampered envelope reject (`@shade/files`) | AEAD reject | `packages/shade-files/tests/security/tampered-envelope.test.ts` |
| § 8a Recovery — k-1 collusion impossible | Shamir Secret Sharing over GF(2^8) | `packages/shade-recovery/tests/shamir.test.ts`, `packages/shade-recovery/tests/adversarial.test.ts` |
| § 8b Recovery — forged share rejected | AES-GCM tag on backup blob + subset-search | `packages/shade-recovery/tests/adversarial.test.ts` (`"a corrupted share never authenticates against the backup AEAD tag"`) |
| § 8c Recovery — guardian OOB-fingerprint gate | Two-checkbox `<RecoveryApprove />` + decline propagation | `packages/shade-recovery/tests/adversarial.test.ts` (`"approve handler that REJECTS a wrong fingerprint never sends a grant"`, `"throwing approve handler counts as decline with descriptive reason"`) |
| § 9 Cross-sender X3DH state corruption | `initReceiverSession` copies keypair | `packages/shade-core/tests/ratchet.test.ts` (`"does not mutate the caller-provided keypair after a DH ratchet step"`), `packages/shade-recovery/tests/integration.test.ts` |
If you add a new mitigation, add a row here in the same PR — the
threat model is the contract; this matrix is the proof.

View File

@@ -2,6 +2,13 @@
This document describes what Shade protects against and what it doesn't. Read this before deploying Shade in any context where the answers matter.
> Each numbered "Mitigations" entry below ends with a `[tests:]`
> footnote that links to the concrete test file(s) demonstrating the
> mitigation. If a mitigation has no `[tests:]` line, treat it as
> documentary — there is no automated test holding the line yet.
> See [SECURITY.md § Threat-/test-matrix](./SECURITY.md#threat--test-matrix)
> for the consolidated index.
## Assets
The thing we're protecting:
@@ -16,9 +23,13 @@ Can intercept, modify, drop, replay, and inject network traffic between clients
**Mitigations:**
- All identity-key writes to the prekey server are signed (Ed25519). Tampering is detected.
`[tests: packages/shade-server/tests/server.test.ts — "rejects unsigned registration", "rejects registration with wrong signing key"]`
- Signed requests have a 5-minute replay window.
`[tests: packages/shade-server/tests/server.test.ts — "rejects registration with stale signedAt"]`
- The Double Ratchet binds message headers to ciphertext via AES-GCM AAD, so header tampering breaks decryption.
`[tests: packages/shade-core/tests/ratchet.test.ts — "tampered ciphertext fails", "tampered header (counter) fails due to AAD"; packages/shade-streams/tests/tamper.test.ts; packages/shade-streams/tests/aead.test.ts]`
- Forward secrecy: even if an attacker captures all traffic, compromising a key later doesn't help them read past messages.
`[tests: packages/shade-crypto-web/tests/hardening.test.ts; packages/shade-core/tests/ratchet.test.ts — DH ratchet steps + out-of-order delivery]`
**NOT mitigated:**
- Initial session establishment can be MITM'd if users don't verify identity fingerprints. The prekey server could distribute a fake bundle on first contact. Always compare safety numbers out-of-band for high-stakes communications.
@@ -28,19 +39,31 @@ The server holds identity public keys and prekey bundles. It can serve them to a
**Mitigations:**
- The server only stores PUBLIC keys, never private ones.
`[tests: packages/shade-server/tests/server.test.ts — registration, bundle fetch, replenish; packages/shade-storage-sqlite/tests/sqlite-prekey-store.test.ts]`
- Write operations are signed with the identity private key, so the server can't forge new identities or replenishments without the user's key.
`[tests: packages/shade-server/tests/server.test.ts — "rejects replenishment signed by wrong identity", "rejects delete signed by wrong identity"]`
- Bundle fetches are unauthenticated, so a malicious server can serve fake bundles. Detection requires out-of-band fingerprint comparison.
`[tests: packages/shade-core/tests/fingerprint-session.test.ts]`
**NOT mitigated:**
- A malicious server can substitute one user's prekey bundle with the server operator's own keys, enabling MITM at session establishment. Users must verify safety numbers to detect this.
**Partially mitigated by V3.12 Key Transparency** (opt-in):
- When the operator runs the server with `keyTransparency: { ... }` and clients pin the operator's STH-signing public key, every bundle fetch returns a Merkle inclusion proof against an append-only Signed Tree Head. A server that swaps `alice`'s bundle for one client and not another, or rewrites history to hide an earlier swap, is detected by an independent witness. KT does **not** prevent first-contact impersonation — a never-seen-before address can still be served maliciously on its very first registration.
`[tests: packages/shade-key-transparency/tests/manager.test.ts — "rotation: new register replaces old"; packages/shade-transport/tests/kt-split-view-e2e.test.ts — "two divergent views at the same tree_size are caught by witness"; packages/shade-server/tests/kt.test.ts — "bundle response carries verified inclusion proof"]`
### 3. Compromised endpoint (post-compromise)
Attacker briefly gains code execution or filesystem access on a user's device, exfiltrates session state, then loses access.
**Mitigations:**
- Forward secrecy: messages sent BEFORE the compromise cannot be decrypted with the leaked state. Old chain keys are zeroed after use.
`[tests: packages/shade-core/tests/ratchet.test.ts — basic send/receive, ping-pong; packages/shade-crypto-web/tests/hardening.test.ts — zeroize]`
- Post-compromise security: as soon as a peer initiates a new DH ratchet step, the leaked state becomes useless for new messages.
`[tests: packages/shade-core/tests/ratchet.test.ts — "alternating messages trigger DH ratchets"]`
- Memory zeroization: message keys and chain keys are wiped from JS memory after use (best-effort — V8 may retain copies).
`[tests: packages/shade-crypto-web/tests/hardening.test.ts — "zeroize" describe block]`
- Identity rotation invalidates leaked at-rest stream-resume secrets (device-key derived from signing key).
`[tests: packages/shade-core/tests/identity-rotation.test.ts; packages/shade-transfer/tests/resume.test.ts]`
**NOT mitigated:**
- An ongoing endpoint compromise can read messages in real time and exfiltrate identity private keys.
@@ -49,36 +72,317 @@ Attacker briefly gains code execution or filesystem access on a user's device, e
### 4. Compromised device storage
Attacker gains access to the persistent storage (e.g., steals the SQLite file or dumps the PostgreSQL table).
**Mitigations:**
- Stored data includes private keys but is unencrypted at rest. Shade does NOT encrypt the storage layer — it assumes the database is in a trusted environment.
**Mitigations (default, no at-rest encryption):**
- Stream-resume secrets *are* encrypted at rest under a device-key derived from the identity signing key, so a stolen DB without the live identity key cannot resume in-flight transfers.
`[tests: packages/shade-transfer/tests/resume.test.ts]`
- Filesystem-level encryption (LUKS, FileVault, BitLocker) is recommended but is the user's responsibility.
**NOT mitigated:**
- Filesystem-level encryption (LUKS, FileVault) is the user's responsibility.
- Database TLS in transit is the user's responsibility.
**Mitigations (with at-rest encryption enabled — V3.2 / `@shade/storage-encrypted`):**
- All sensitive payloads are sealed with AES-256-GCM under per-(table, column) field keys derived from a passphrase (scrypt) / OS keychain / app-injected master key. A stolen DB file alone yields no usable private key material.
`[tests: packages/shade-storage-encrypted/tests/encrypted-sqlite.test.ts]`
- AAD binds (table, column, pk) so an attacker cannot swap rows or move ciphertext between columns without triggering decrypt failure.
`[tests: packages/shade-storage-encrypted/tests/encrypted-sqlite.test.ts — "row swap (sessions) → decrypt fails due to AAD mismatch"]`
- Bit-flips in the ciphertext blob are detected by the AEAD tag; the storage layer raises rather than returning corrupt key material.
`[tests: packages/shade-storage-encrypted/tests/aead.test.ts; encrypted-sqlite.test.ts — "flipped ciphertext byte → decrypt fails"]`
- Wrong passphrase / wrong keychain entry is rejected up-front via a fingerprint check, never silently writing under the wrong key.
`[tests: packages/shade-storage-encrypted/tests/encrypted-sqlite.test.ts — "rejects open with wrong key (fingerprint mismatch)"]`
- Online key rotation re-keys every row without downtime; the old key no longer opens the DB after rotation.
`[tests: packages/shade-storage-encrypted/tests/migrate.test.ts — "re-keys all rows; old key no longer opens DB"]`
**NOT mitigated (even with at-rest enabled):**
- A live process holds the storageKey and field keys in memory; an attacker who can read process memory (e.g., via `/proc/<pid>/mem`, swap dump, hibernation file) recovers the keys and thus the data. At-rest encryption protects the DB *file*, not the running process.
- The kernel's swap partition is not encrypted by Shade. If the OS pages key material to disk, it can be recovered. Use an encrypted swap device.
- A coredump of the live process exposes plaintext private keys.
- Filesystem-level encryption of the DB *backup* (e.g. `.bak` file produced by `shade migrate-storage`) is the operator's responsibility — the backup is plaintext during the brief migration window.
- If the master key is lost (forgotten passphrase, deleted keychain entry, lost injected key) the DB is permanently unrecoverable. V3.10 (Social Recovery) is the long-term mitigation.
### 5. Side-channel attacks (timing)
Attacker measures timing of identity verification operations to recover key bits.
**Mitigations:**
- All comparisons of secret material use constant-time XOR-accumulator comparison (`constantTimeEqual`).
`[tests: packages/shade-crypto-web/tests/hardening.test.ts — "constantTimeEqual", "timing variance stays bounded across mismatch positions"]`
- AES-GCM and the underlying primitives are constant-time as implemented by SubtleCrypto and @noble/curves.
`[tests: packages/shade-crypto-web/tests/provider.test.ts; packages/shade-streams/tests/aead.test.ts]`
**NOT mitigated:**
- JavaScript JIT compilation can introduce timing variability that's hard to control.
- We don't claim resistance to power-analysis or fault-injection attacks (out of scope for a JS library).
### 6. Denial of service
### 6. Malicious or compromised inbox relay (V3.6 store-and-forward)
The inbox relay holds **ciphertext blobs with TTL** so senders can deliver
to offline recipients. It is a separate trust domain from the prekey
server, and exposes a different surface.
**Mitigations:**
- The relay only stores `address || msgId || ciphertext-bytes || expires_at`.
Plaintext, ratchet state, and any private keys live exclusively on the
client. A DB dump leaks no message content.
`[tests: packages/shade-inbox-server/tests/routes.test.ts; packages/shade-inbox-server/tests/lifecycle.test.ts — "Tamper resistance"]`
- Recipient identity is bound to the address via TOFU: first
`POST /v1/inbox/register` claims the slot, and subsequent fetch/ack
must be Ed25519-signed by the same key. A different key claiming an
existing address is rejected with 401.
`[tests: packages/shade-inbox-server/tests/routes.test.ts — "rejects different key claiming same address", "rejects fetch from a different signing key", "rejects ack from a different signing key"]`
- Each PUT is signed by the sender's per-PUT signing key; the relay
verifies the signature before persisting. Bad sigs return 401.
`[tests: packages/shade-inbox-server/tests/routes.test.ts — "rejects bad sender signature"]`
- `msgId = sha256(ciphertext)` is verified server-side on PUT and
recomputed client-side on FETCH. A relay that flips a bit in storage
produces a digest mismatch the recipient flags as
`inbox.message_decrypt_failed` *without* acking, so the divergence
surfaces in operator telemetry instead of being silently consumed.
`[tests: packages/shade-inbox-server/tests/routes.test.ts — "rejects mismatched msgId"; packages/shade-inbox-server/tests/lifecycle.test.ts — "Tamper resistance"; packages/shade-inbox/tests/client.test.ts — "tamper detection"]`
- Replay-window of ±5 minutes on `signedAt` (matches the prekey
server's policy). Replays past that window return 409.
`[tests: packages/shade-inbox-server/tests/routes.test.ts — "rejects stale signature (replay window)"]`
- Idempotent PUT: two clients (or a buggy retry loop) submitting the
same ciphertext do *not* create duplicate rows; the second PUT
returns 200 with `idempotent: true`.
`[tests: packages/shade-inbox-server/tests/routes.test.ts — "idempotent on duplicate ciphertext"]`
- Periodic `InboxPruneTask` drops blobs past their TTL so a slow
consumer never sees a payload past expiry.
`[tests: packages/shade-inbox-server/tests/lifecycle.test.ts — "prune removes expired blobs but keeps live ones"]`
**NOT mitigated:**
- **Sender-recipient graph leakage.** The relay sees recipient address +
per-PUT sender pubkey + ciphertext byte-counts. Privacy-sensitive
deployments should use address-hashes (`sha256(real-address || salt)`)
and rotate sender signing keys per session. Mixing/onion-routing is
out of scope for V3.6 and a candidate for a future relay tier.
- **Operator-side queue deletion.** A malicious operator can drop every
blob queued for a target, forcing senders to resend. Recipient-side
ack happens *after* successful decrypt, so a delete only burns one
delivery attempt rather than silently consuming a message.
- **TTL-based reachability signal.** A PUT silently expiring after 7
days reveals that the recipient never came online. Operators concerned
with this metadata should clamp TTLs to a fixed value via the
`quota.maxTtlSeconds` / `quota.minTtlSeconds` knobs.
### 7. Denial of service
Attacker floods the prekey server to exhaust resources or one-time prekeys.
**Mitigations:**
- Per-IP rate limiting on registration and bundle fetches.
`[tests: packages/shade-server/tests/rate-limit.test.ts — "register endpoint rate-limits per IP", "rate limit returns Retry-After header"]`
- Per-identity rate limiting on replenish and delete.
- 64KB body size limit on POST endpoints.
`[tests: packages/shade-server/tests/rate-limit.test.ts — "different keys have independent limits"]`
- 64 KiB body size limit on POST endpoints.
`[tests: packages/shade-server/tests/server.test.ts — body-size enforcement]`
- Address validation rejects path traversal and malformed inputs.
`[tests: packages/shade-server/tests/server.test.ts — "rejects invalid address format", "rejects invalid address in URL"]`
- Per-sender ops/byte quotas on `@shade/files` filesystem RPC.
`[tests: packages/shade-files/tests/security/quota.test.ts]`
- Per-recipient blob quota on `@shade/inbox-server` (default 1000 blobs
per address) + per-blob byte cap (default 1 MiB) so a single sender
cannot fill a recipient's queue.
`[tests: packages/shade-inbox-server/tests/routes.test.ts — "rejects ciphertext > maxBlobBytes", "enforces per-address quota"]`
- Per-IP token-bucket on inbox PUT/FETCH/DELETE/REGISTER routes.
**NOT mitigated:**
- Application-level DDoS at the network layer is your hosting platform's responsibility.
### 8. Social-recovery adversaries (V3.10)
Once a user has set up `@shade/recovery`, the guardian set becomes a
new attack surface. We split the threat into four cases:
**8a. Coalition of ≤ k-1 guardians.**
**Mitigations:**
- Shamir Secret Sharing over GF(2^8) is information-theoretically
secure: the shares are points on a polynomial whose constant term
is the secret, and any subset of `< k` points is consistent with
every possible secret. No coalition smaller than the threshold
recovers anything beyond the secret's length.
`[tests: packages/shade-recovery/tests/shamir.test.ts — "k-1 shares yield a wrong (random-looking) result", "property: any k-1 share subset yields a different output than the secret"; packages/shade-recovery/tests/adversarial.test.ts — "property: any (k-1) subset of shares fails to recover the key"]`
**8b. Single malicious guardian who forges a share.**
**Mitigations:**
- The reconstructed `recoveryKey` is authenticated by the AES-GCM
tag inside the backup blob (`Shade.exportBackup`'s ciphertext).
A forged share produces a different reconstructed key; AES-GCM
decryption fails.
- `requestRecovery` exhaustively tries every threshold-sized subset
of received grants until one authenticates; if none do, it raises
`RecoveryReconstructionError` and refuses to apply the result.
The user is told that at least one guardian is malicious.
`[tests: packages/shade-recovery/tests/adversarial.test.ts — "a corrupted share never authenticates against the backup AEAD tag"]`
**8c. Social-engineering (impersonator calls a guardian).**
**Mitigations:**
- The guardian's `approve` callback receives the new device's
TEMPORARY safety number; the spec REQUIRES out-of-band
comparison before approving.
- The shipped `<RecoveryApprove />` widget enforces a two-checkbox
gate ("fingerprint matches" + "I verified OOB") before the
release button is enabled.
- The protocol-level `share-decline` envelope is sent regardless of
whether the guardian's `approve` callback returns false or
throws, so a hard "no" terminates the requesting flow promptly.
`[tests: packages/shade-recovery/tests/adversarial.test.ts — "approve handler that REJECTS a wrong fingerprint never sends a grant", "throwing approve handler counts as decline with descriptive reason"]`
**NOT mitigated:**
- A guardian who is duped by an impersonator AND whose user clicks
through both checkboxes WILL release their share. Defense in
depth requires user education + per-guardian cool-down windows
(a follow-up release).
**8d. Guardian device compromise.**
If an attacker fully owns a guardian's device, they can:
- Read the share + backup blob → contributes one polynomial point.
- Ship `share-grant` envelopes if they convince the guardian's
`approve` callback to return true.
**Mitigations:**
- No single guardian's compromise is sufficient — the threshold
invariant still holds: the attacker needs `k-1` other shares to
rebuild the identity.
- Backup blobs are encrypted at-rest under the guardian's existing
StorageProvider scheme (V3.2 covers this for SQLite/Postgres
backends).
**NOT mitigated:**
- Compromise of `≥ k` guardians simultaneously is a complete break.
This is by design: the recovery flow is meant to survive *device*
loss, not coordinated mass compromise of the social graph.
### 9. Cross-sender X3DH state corruption
Before V3.10, `initReceiverSession` shared a reference to the
receiver's signed prekey keypair with the new session. The first DH
ratchet step zeroed the session's "previous" private key, which
silently zeroed the persisted signed prekey. A second X3DH from a
*different* sender to the same receiver then derived a divergent
root key and decryption failed with "wrong key or tampered data".
This was a pre-existing bug surfaced by the V3.10 multi-sender
recovery flow.
**Mitigations:**
- `initReceiverSession` now copies the localDHKeyPair into the
session so the eventual zeroize touches a scratch buffer, not
the persisted prekey.
`[tests: packages/shade-recovery/tests/integration.test.ts — "recovery from new device with all 5 guardians available"; packages/shade-core/tests/x3dh.test.ts]`
### 10. MITM bypass via skipped fingerprint verification (V3.3)
The strongest mitigation for §1 / §2 / §6 — out-of-band safety-number
verification — is a *user* responsibility. Shade 4.0 ships
`@shade/sdk` fingerprint gates that move it from "convention" to
"enforced policy on the operations that matter".
**Mitigations:**
- `Shade.beforeFirstLargeFile(threshold, handler)` — runs in `upload()`
when payload ≥ threshold (default 10 MiB) and the peer is unverified.
A handler that returns `false` (or throws / is missing in policy-
forbid-TOFU mode) raises `FingerprintNotVerifiedError` (HTTP 403).
`[tests: packages/shade-sdk/tests/fingerprint-gates.test.ts; packages/shade-files/tests/security/fingerprint-gate.test.ts]`
- `Shade.beforeBackupImport(handler)` — receives the *backup-embedded*
fingerprint before any state is written. Decrypted backups whose
embedded identity does not match the user's expectation are
rejected before they touch storage.
`[tests: packages/shade-sdk/tests/fingerprint-gates.test.ts]`
- `Shade.beforeNewDeviceTrust(handler)` — runs from
`Shade.acceptIdentityChange()` after the peer's identity-version is
bumped, so any prior verification automatically goes stale and the
user must re-verify.
`[tests: packages/shade-sdk/tests/fingerprint-gates.test.ts]`
- `markPeerVerified` / `isPeerVerified` / `unmarkPeerVerified` are
storage-backed; the `peer_verifications` + `peer_identity_versions`
tables are subject to V3.2 at-rest encryption when the encrypted
storage backend is used.
- `<FingerprintCompare />` and `<FingerprintGate />` widgets present
the safety number side-by-side and require an explicit "matches"
click before children render.
**NOT mitigated:**
- Apps that never register handlers default to "TOFU + warning". The
warning is logged, not rendered, so a UX that ignores the log
silently keeps TOFU semantics.
- Once verified, a peer's persisted verification stays valid until
identity rotation. A device-compromise that does **not** trigger
rotation keeps the verification alive.
### 11. WebRTC peer-to-peer transport (V3.11)
`@shade/transport-webrtc` lets two peers ship `@shade/transfer` chunks
over an `RTCDataChannel` instead of HTTP. The DTLS layer is opaque to
Shade; we treat WebRTC strictly as a **byte-pipe** — not a trust
boundary.
**Mitigations:**
- The same Double Ratchet that authenticates Shade messages
authenticates the SDP offer / answer / ICE / bye signaling
envelopes. A network attacker who replaces an SDP offer must
forge a ratcheted message — the receiver decrypts via the
existing peer session and rejects on AEAD failure.
`[tests: packages/shade-transport-webrtc/tests/signaling.test.ts; packages/shade-sdk/tests/webrtc-integration.test.ts]`
- Frame payloads on the DataChannel are AES-GCM-sealed by `@shade/streams`
with deterministic nonce + AAD bound to `streamId || laneId || seq ||
isLast`. A WebRTC implementation that returns altered bytes fails
AEAD verification and the receiver raises `StreamDecryptionError`.
`[tests: packages/shade-streams/tests/tamper.test.ts; packages/shade-transport-webrtc/tests/wire-format.test.ts]`
- Glare resolution is deterministic (lexicographic address compare)
so both sides converge on a single connection without re-running
signaling.
`[tests: packages/shade-transport-webrtc/tests/glare.test.ts]`
- When NAT traversal fails, `MultiTransportFallback([webrtc, http])`
demotes to HTTP within the configured `connectTimeoutMs` (default
5 s) without losing chunks already in flight. No silent stall.
`[tests: packages/shade-sdk/tests/webrtc-failover.test.ts]`
- `IRtcFactory` is pluggable; production uses
`globalThis.RTCPeerConnection` (browser / Workers / Deno),
`MemoryRtcFactory` is in-process for tests.
**NOT mitigated:**
- TURN relay metadata. If the deployment ships a TURN server,
the operator sees relayed-byte counts and timing for every flow
that traverses the relay. Use a TURN you control or a hosted
relay you trust.
- Browser/RTC stack vulnerabilities. A compromised
`RTCPeerConnection` implementation is outside the scope of a JS
library; we ride the platform's WebRTC.
- Public STUN exposes the client's public IP to the STUN server.
This is unavoidable without a privacy-preserving NAT discovery
mechanism (out of scope).
### 12. Web-Worker thread boundary (V3.8)
`@shade/crypto-web/worker` runs AEAD, HKDF, HMAC, X25519, Ed25519, and
per-lane stream state inside a dedicated Web Worker so the main thread
never holds key material for very long.
**Mitigations:**
- Lane keys, identity private keys and ratchet chain keys are passed
into the worker once at setup; subsequent operations move plaintext
via transferable `ArrayBuffer`s and never re-export keys.
`[tests: packages/shade-crypto-web/tests/worker-streams.test.ts; packages/shade-crypto-web/tests/worker-provider.test.ts]`
- Idle timeout (default 30 s) calls `terminate()` on the worker, which
drops the global JS heap and releases the OS-level memory backing
any keys that were not yet zeroized.
- `rotate()` and `destroy()` lifecycle controls let apps bound the
worst-case duration any lane key sits in worker memory.
- Worker-protocol version handshake on first message rejects mismatched
workers (e.g. cached old build).
**NOT mitigated:**
- The worker is still inside the same browsing context; an attacker
who can inject script into the page can post a malicious message
and read the worker's reply. CSP and SRI on the worker entrypoint
are the user's responsibility.
- Heap memory is not synchronously wiped when `postMessage` returns
ownership; the runtime may keep deallocated buffers around for
GC. Memory zeroization is best-effort for both threads.
## Assumptions
1. **The user has a secure way to bootstrap trust.** Either:
@@ -92,8 +396,10 @@ Attacker floods the prekey server to exhaust resources or one-time prekeys.
| Risk | Severity | Mitigation |
|------|----------|------------|
| MITM at first session establishment | High | Compare safety numbers out-of-band |
| Identity private key theft from device | Critical | Filesystem encryption, secure enclave (future) |
| Prekey server operator runs a "key oracle" attack | Medium | Distributed/federated prekey servers (future) |
| Side-channel via JIT timing variability | Low | Constant-time primitives reduce but don't eliminate |
| MITM at first session establishment | High | Compare safety numbers out-of-band; in 4.0, register `Shade.beforeFirstLargeFile` / `beforeBackupImport` / `beforeNewDeviceTrust` to enforce verification on the operations that matter (V3.3) |
| Identity private key theft from device | Critical | Filesystem encryption, secure enclave (future); V3.10 Social Recovery for *recovery* after loss |
| Prekey server operator runs a "key oracle" attack | Medium | V3.12 Key Transparency (opt-in) detects split-view + history rewrites; gossip via a `LightWitness` raises the cost of a sustained attack |
| TURN relay sees byte-counts of P2P transfers | Low–Medium | Only when WebRTC fails over to TURN. Operate your own TURN if the metadata matters |
| Side-channel via JIT timing variability | Low | Constant-time primitives reduce but don't eliminate; V3.8 Web-Worker isolation bounds the lifetime of in-memory key material |
| Metadata visibility to prekey server | Low | Acceptable for most use cases; mix networks for stronger metadata protection |
| Inbox relay sees recipient address + byte-counts | Low–Medium | Use address-hashes + per-session sender keys (V3.6 §6); mix-net relay tier is a future candidate |

12
android/.gitignore vendored Normal file
View File

@@ -0,0 +1,12 @@
# Gradle
.gradle/
build/
!gradle/wrapper/gradle-wrapper.jar
# IntelliJ / Android Studio
.idea/
*.iml
local.properties
# Captured logs
*.log

6
android/build.gradle.kts Normal file
View File

@@ -0,0 +1,6 @@
plugins {
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
id("com.android.application") version "8.7.3" apply false
}

View File

@@ -0,0 +1,6 @@
org.gradle.jvmargs=-Xmx2g -Dfile.encoding=UTF-8
org.gradle.parallel=true
org.gradle.caching=true
kotlin.code.style=official
android.useAndroidX=true
android.nonTransitiveRClass=true

Binary file not shown.

View File

@@ -0,0 +1,7 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-8.10.2-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists

252
android/gradlew vendored Executable file
View File

@@ -0,0 +1,252 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s
' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"

94
android/gradlew.bat vendored Normal file
View File

@@ -0,0 +1,94 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega

View File

@@ -0,0 +1,27 @@
rootProject.name = "shade-kotlin"
pluginManagement {
repositories {
gradlePluginPortal()
mavenCentral()
google()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
mavenCentral()
google()
}
}
include(":shade-android")
project(":shade-android").projectDir = file("shade-android")
include(":shade-android-keystore")
project(":shade-android-keystore").projectDir = file("shade-android-keystore")
include(":shade-android-media")
project(":shade-android-media").projectDir = file("shade-android-media")
include(":shade-media-demo")
project(":shade-media-demo").projectDir = file("shade-media-demo")

View 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`).

View 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")
}

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />

View File

@@ -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")

View File

@@ -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"
}
}

View File

@@ -0,0 +1,68 @@
package no.zyon.shade.keystore
import java.io.File
import java.io.IOException
import java.security.GeneralSecurityException
import java.security.SecureRandom
/**
* A small secret (a signing seed, a token) kept in a file, encrypted under a
* hardware-backed Android Keystore key that never leaves the secure element.
* For secrets the app uses without asking the user each time — a media owner
* key that signs every upload piece — so the key is not biometric-gated;
* use [KeystoreMasterKey] with `requireBiometric` for those that should be.
*
* File: `"SKS1" || nonce(12) || AES-256-GCM(secret)`, with the alias as AAD
* so a file cannot be swapped in under another alias. A backup restored to
* another phone carries the file but not the key: [read] then throws
* [SecretLostException] rather than handing back garbage.
*/
class KeystoreSecretFile(private val file: File, private val alias: String) {
private val key = KeystoreMasterKey(alias, requireBiometric = false)
class SecretLostException(message: String, cause: Throwable? = null) : IOException(message, cause)
/** The secret, or null if none was written. */
fun read(): ByteArray? {
if (!file.exists()) return null
val b = file.readBytes()
if (b.size < HEADER + 16 || !b.copyOfRange(0, 4).contentEquals(MAGIC)) throw SecretLostException("${file.name} is not a Keystore secret")
if (!key.exists()) throw SecretLostException("the Keystore key for ${file.name} is gone (restored from a backup, or the app's keys were cleared)")
return try {
val c = key.cipherForDecrypt(b.copyOfRange(4, HEADER))
c.updateAAD(alias.toByteArray(Charsets.UTF_8))
c.doFinal(b, HEADER, b.size - HEADER)
} catch (e: GeneralSecurityException) {
throw SecretLostException("${file.name} does not open under its Keystore key", e)
}
}
fun write(secret: ByteArray) {
val c = key.cipherForEncrypt()
c.updateAAD(alias.toByteArray(Charsets.UTF_8))
val ct = c.doFinal(secret)
val nonce = c.iv
check(nonce.size == 12) { "unexpected GCM nonce size ${nonce.size}" }
file.parentFile?.mkdirs()
val tmp = File(file.path + ".tmp")
tmp.writeBytes(MAGIC + nonce + ct)
if (!tmp.renameTo(file)) throw IOException("cannot write ${file.name}")
}
/** The secret, made with `size` random bytes on first use. */
fun getOrCreate(size: Int): ByteArray = read() ?: ByteArray(size).also {
SecureRandom().nextBytes(it)
write(it)
}
/** Remove the file and its key: the secret is gone for good. */
fun destroy() {
file.delete()
key.deleteKey()
}
private companion object {
val MAGIC = "SKS1".toByteArray(Charsets.US_ASCII)
const val HEADER = 4 + 12
}
}

View File

@@ -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"
}
}

View File

@@ -0,0 +1,54 @@
plugins {
id("com.android.library")
kotlin("android")
}
// Sealed Shade media (SMF1) in Media3/ExoPlayer.
//
// `:shade-android` reads and verifies sealed files on the JVM; this module
// hands that reader to ExoPlayer as a DataSource, so any container the
// player understands (MP4, WebM, MKV, MP3, …) plays and seeks from a sealed
// file without the plaintext ever touching disk or the network.
android {
namespace = "no.zyon.shade.media.android"
compileSdk = 35
defaultConfig {
minSdk = 24
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
testOptions {
unitTests.isIncludeAndroidResources = true
unitTests.all {
// ShadeUploadTest's live half is gated on this; as an input, a new relay reruns it.
it.inputs.property("shadeMediaLiveSpec", System.getenv("SHADE_MEDIA_LIVE_SPEC") ?: "")
}
}
}
val media3 = "1.5.1"
dependencies {
api(project(":shade-android"))
api("androidx.media3:media3-exoplayer:$media3")
api("androidx.media3:media3-datasource:$media3")
// Live channels: the relay speaks WebSocket. `api`: LiveWatcher takes an OkHttpClient.
api("com.squareup.okhttp3:okhttp:4.12.0")
testImplementation("junit:junit:4.13.2")
testImplementation("org.robolectric:robolectric:4.14.1")
testImplementation("androidx.test:core:1.6.1")
testImplementation("androidx.media3:media3-test-utils:$media3")
testImplementation("androidx.media3:media3-test-utils-robolectric:$media3")
testImplementation("com.squareup.okhttp3:mockwebserver:4.12.0")
}

View File

@@ -0,0 +1,2 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" />

View File

@@ -0,0 +1,149 @@
package no.zyon.shade.media.android
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.LiveSubscriber
import no.zyon.shade.media.ReceivedFrame
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okio.ByteString
import org.json.JSONObject
import java.io.Closeable
import java.util.Base64
import java.util.concurrent.Executors
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.TimeUnit
/**
* Watch a live channel: the Android side of the TS `LiveWatchClient`.
*
* Connects to the relay named in the grant, subscribes with the read token,
* and hands every frame that verifies and decrypts to [Listener.onFrame], in
* arrival order. A dropped connection is retried with backoff; the relay's
* backlog on reconnect is deduplicated by the subscriber, so the listener
* sees each frame once.
*/
class LiveWatcher(
grant: LiveGrant,
private val listener: Listener,
private val client: OkHttpClient = sharedClient,
url: String? = null,
) : Closeable {
enum class State { CONNECTING, WAITING, LIVE, RECONNECTING, CLOSED }
interface Listener {
fun onFrame(frame: ReceivedFrame)
fun onState(state: State) {}
/** A frame failed to verify or decrypt, or the relay refused us. The stream continues. */
fun onError(error: Exception) {}
}
private val url: String = url ?: grant.url ?: throw IllegalArgumentException("grant has no relay URL")
private val token: String = grant.readToken?.let { Base64.getUrlEncoder().withoutPadding().encodeToString(it) }
?: throw IllegalArgumentException("grant has no read token")
/** Not thread-safe; every use is under `lock`. */
private val subscriber = LiveSubscriber(grant)
private val lock = Any()
private val timer: ScheduledExecutorService = Executors.newSingleThreadScheduledExecutor { r ->
Thread(r, "shade-live-reconnect").apply { isDaemon = true }
}
@Volatile private var closed = false
private var socket: WebSocket? = null
private var delayMs = INITIAL_DELAY_MS
private var everConnected = false
init {
connect()
}
/** Hand over the grant for a new epoch (it arrives over the Shade session). */
fun addGrant(g: LiveGrant) = synchronized(lock) {
subscriber.addGrant(g)
subscriber.forgetBefore(g.epoch)
}
private fun connect() {
if (closed) return
listener.onState(if (everConnected) State.RECONNECTING else State.CONNECTING)
val request = Request.Builder().url(url).build()
val ws = client.newWebSocket(request, Handler())
synchronized(lock) { socket = ws }
}
private inner class Handler : WebSocketListener() {
override fun onOpen(webSocket: WebSocket, response: Response) {
webSocket.send(JSONObject().put("type", "subscribe").put("token", token).toString())
}
override fun onMessage(webSocket: WebSocket, text: String) {
val msg = runCatching { JSONObject(text) }.getOrNull() ?: return
when (msg.optString("type")) {
"ready" -> {
synchronized(lock) {
delayMs = INITIAL_DELAY_MS
everConnected = true
}
listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING)
}
// The publisher arrived or left after we joined.
"state" -> listener.onState(if (msg.optBoolean("live")) State.LIVE else State.WAITING)
"error" -> listener.onError(LiveRelayException(msg.optString("message", "relay error")))
}
}
override fun onMessage(webSocket: WebSocket, bytes: ByteString) {
// OkHttp calls this on the socket's reader thread, one message at
// a time — frames are opened in arrival order, as the chain needs.
val frame = try {
synchronized(lock) { if (closed) return else subscriber.open(bytes.toByteArray()) }
} catch (e: Exception) {
listener.onError(e)
return
}
if (frame != null) listener.onFrame(frame)
}
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(1000, null)
}
override fun onClosed(webSocket: WebSocket, code: Int, reason: String) = retry(webSocket)
override fun onFailure(webSocket: WebSocket, t: Throwable, response: Response?) = retry(webSocket)
}
private fun retry(ws: WebSocket) {
val delay = synchronized(lock) {
if (closed || socket !== ws) return
socket = null
delayMs.also { delayMs = minOf(delayMs * 2, MAX_DELAY_MS) }
}
listener.onState(State.RECONNECTING)
timer.schedule({ connect() }, delay, TimeUnit.MILLISECONDS)
}
override fun close() {
val ws = synchronized(lock) {
if (closed) return
closed = true
socket.also { socket = null }
}
ws?.close(1000, null)
timer.shutdownNow()
synchronized(lock) { subscriber.close() }
listener.onState(State.CLOSED)
}
private companion object {
const val INITIAL_DELAY_MS = 250L
const val MAX_DELAY_MS = 10_000L
/** One client for every watcher: OkHttp shares its pools and threads. */
val sharedClient: OkHttpClient by lazy {
OkHttpClient.Builder().pingInterval(20, TimeUnit.SECONDS).readTimeout(0, TimeUnit.MILLISECONDS).build()
}
}
}
class LiveRelayException(message: String) : Exception(message)

View File

@@ -0,0 +1,253 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.ParserException
import androidx.media3.common.PlaybackException
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.BaseDataSource
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSourceException
import androidx.media3.datasource.DataSpec
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.ReceivedFrame
import java.io.Closeable
import java.io.InterruptedIOException
import java.util.ArrayDeque
import java.util.concurrent.TimeUnit
import java.util.concurrent.locks.ReentrantLock
import kotlin.concurrent.withLock
/**
* A live Shade channel (WebM or fragmented MP4) as one endless byte stream
* for ExoPlayer's progressive extractors.
*
* The stream is what a demuxer expects from a live muxer: the channel's
* init (sticky), then media pieces from the first keyframe on. Where frames
* are missing — a reconnect, the relay shedding a slow viewer — it skips to
* the next keyframe, so the decoder never sees a piece that depends on one
* it did not get. A late joiner's timeline is rebased to start at zero (see
* [ShadeMedia.liveMediaSource] for fMP4; WebM cluster timecodes here), or a
* player would wait out the minutes it missed.
*
* `connect` opens the frame feed: [LiveWatcher] by default, a fake in tests.
*/
@UnstableApi
class ShadeLiveDataSource(
private val connect: (LiveWatcher.Listener) -> Closeable,
) : BaseDataSource(/* isNetwork = */ true) {
private val lock = ReentrantLock()
private val ready = lock.newCondition()
private val queue = ArrayDeque<ByteArray>()
private var head: ByteArray? = null
private var headPos = 0
private var init: ByteArray? = null
private var webm = false
private var needKeyframe = true
private var lastEpoch = -1L
private var lastSeq = -1L
/** WebM: the first delivered cluster's timecode, subtracted from every cluster. */
private var webmBase = -1L
private var ended = false
private var failure: Exception? = null
private var feed: Closeable? = null
private var uri: Uri? = null
/** Frames skipped while waiting for a keyframe, for diagnostics. */
@Volatile var droppedFrames = 0L
private set
override fun open(dataSpec: DataSpec): Long {
// A live stream cannot resume mid-byte; ExoPlayer reopens an
// unseekable source from the start, which is a fresh join.
if (dataSpec.position != 0L) throw DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE)
uri = dataSpec.uri
transferInitializing(dataSpec)
lock.withLock { resetLocked() }
feed = connect(Feed())
transferStarted(dataSpec)
return C.LENGTH_UNSET.toLong()
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (length == 0) return 0
val n = lock.withLock {
while (head == null) {
failure?.let { throw it as? java.io.IOException ?: DataSourceException(it, PlaybackException.ERROR_CODE_IO_UNSPECIFIED) }
val next = queue.pollFirst()
if (next != null) {
head = next
headPos = 0
break
}
if (ended) return C.RESULT_END_OF_INPUT
// Wake now and then: ExoPlayer cancels a load by interrupting.
ready.await(250, TimeUnit.MILLISECONDS)
if (Thread.interrupted()) throw InterruptedIOException()
}
val h = head!!
val n = minOf(length, h.size - headPos)
System.arraycopy(h, headPos, buffer, offset, n)
headPos += n
if (headPos == h.size) head = null
n
}
bytesTransferred(n)
return n
}
override fun getUri(): Uri? = uri
override fun close() {
val f = feed
feed = null
f?.close()
lock.withLock {
resetLocked()
ended = true
ready.signalAll()
}
if (uri != null) {
uri = null
transferEnded()
}
}
private fun resetLocked() {
queue.clear()
head = null
init = null
webm = false
needKeyframe = true
lastEpoch = -1
lastSeq = -1
webmBase = -1
ended = false
failure = null
}
/** Frames in arrival order (from the watcher's thread) → bytes for the extractor. */
private inner class Feed : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {
lock.withLock { accept(frame) }
}
private fun accept(frame: ReceivedFrame) {
if (ended || failure != null) return
// Contiguous: the next seq in this epoch, or seq 0 of the next
// epoch (a rotation reseals the sticky frames first, numbered from 0).
val contiguous = (frame.epoch == lastEpoch && frame.seq == lastSeq + 1) ||
(frame.epoch == lastEpoch + 1 && frame.seq == 0L)
if (!contiguous && lastEpoch >= 0) needKeyframe = true
lastEpoch = frame.epoch
lastSeq = frame.seq
when (val c = frame.content) {
is LiveContent.Init -> {
val known = init
if (known == null) {
init = c.bytes
webm = c.mime.contains("webm")
queue.addLast(c.bytes)
ready.signalAll()
} else if (!known.contentEquals(c.bytes)) {
// A new init mid-stream is a new stream; the demuxer cannot
// splice it. A ParserException, because retrying cannot help
// and ExoPlayer's load policy does not retry those.
failure = ParserException.createForMalformedContainer(
"the live stream changed its format",
LiveFormatChangedException(),
)
ready.signalAll()
}
}
is LiveContent.Chunk -> {
if (init == null || (needKeyframe && !frame.keyframe)) {
droppedFrames++
return
}
needKeyframe = false
queue.addLast(if (webm) rebaseCluster(c.bytes) else c.bytes)
ready.signalAll()
}
is LiveContent.End -> {
ended = true
ready.signalAll()
}
else -> Unit // text, images and meta are not part of the media stream
}
}
override fun onError(error: Exception) {
// A frame that failed to verify is dropped by the watcher; the gap
// check above then waits for the next keyframe. Nothing to do here.
}
}
/** WebM: rewrite the cluster's Timecode so the first cluster delivered is at 0. */
private fun rebaseCluster(cluster: ByteArray): ByteArray {
val tc = Ebml.clusterTimecode(cluster) ?: return cluster
if (webmBase < 0) webmBase = tc.value
val v = tc.value - webmBase
if (v < 0) return cluster
val out = cluster.copyOf()
var x = v
for (i in tc.length - 1 downTo 0) {
out[tc.offset + i] = (x and 0xff).toByte()
x = x ushr 8
}
return out
}
class Factory(private val connect: (LiveWatcher.Listener) -> Closeable) : DataSource.Factory {
override fun createDataSource(): DataSource = ShadeLiveDataSource(connect)
}
}
class LiveFormatChangedException : Exception("the live stream changed its format; reopen it")
/** Just enough EBML to find a Cluster's Timecode. */
internal object Ebml {
class Field(val offset: Int, val length: Int, val value: Long)
private const val ID_CLUSTER = 0x1f43b675L
private const val ID_TIMECODE = 0xe7L
private fun vintLength(first: Int, max: Int): Int {
var len = 1
while (len <= max && (first and (0x80 shr (len - 1))) == 0) len++
return if (len > max) -1 else len
}
fun clusterTimecode(b: ByteArray): Field? {
val idLen = vintLength(b.getOrNull(0)?.toInt()?.and(0xff) ?: return null, 4)
if (idLen < 0 || readUInt(b, 0, idLen) != ID_CLUSTER) return null
val sizeLen = vintLength(b.getOrNull(idLen)?.toInt()?.and(0xff) ?: return null, 8)
if (sizeLen < 0) return null
var at = idLen + sizeLen
// The Timecode is the first child in practice; look a few elements in.
repeat(4) {
val first = b.getOrNull(at)?.toInt()?.and(0xff) ?: return null
val cl = vintLength(first, 4)
if (cl < 0) return null
val id = readUInt(b, at, cl)
val szFirst = b.getOrNull(at + cl)?.toInt()?.and(0xff) ?: return null
val sl = vintLength(szFirst, 8)
if (sl < 0) return null
var size = (szFirst and (0xff shr sl)).toLong()
for (i in 1 until sl) size = (size shl 8) or (b[at + cl + i].toLong() and 0xff)
val body = at + cl + sl
if (id == ID_TIMECODE) {
if (size !in 1..8 || body + size > b.size) return null
return Field(body, size.toInt(), readUInt(b, body, size.toInt()))
}
at = body + size.toInt()
}
return null
}
private fun readUInt(b: ByteArray, at: Int, len: Int): Long {
var v = 0L
for (i in 0 until len) v = (v shl 8) or (b[at + i].toLong() and 0xff)
return v
}
}

View File

@@ -0,0 +1,140 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.MediaItem
import androidx.media3.common.MediaMetadata
import androidx.media3.common.util.UnstableApi
import androidx.media3.common.C
import androidx.media3.common.MimeTypes
import androidx.media3.exoplayer.source.DefaultMediaSourceFactory
import androidx.media3.exoplayer.source.MediaSource
import androidx.media3.common.util.TimestampAdjuster
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.extractor.Extractor
import androidx.media3.extractor.ExtractorsFactory
import androidx.media3.extractor.mkv.MatroskaExtractor
import androidx.media3.extractor.mp4.FragmentedMp4Extractor
import androidx.media3.extractor.text.SubtitleParser
import no.zyon.shade.media.Grant
import no.zyon.shade.media.Grants
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.MediaFormatException
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.SubtitleTrack
import no.zyon.shade.media.Subtitles
/**
* Sealed Shade media for ExoPlayer, from a link or grant to a [MediaSource].
*
* ```
* val reader = ShadeMedia.open(link) // network: off the main thread
* player.setMediaSource(ShadeMedia.mediaSource(reader))
* player.prepare()
*
* player.setMediaSource(ShadeMedia.liveMediaSource(liveGrant)) // a live channel
* ```
*/
@UnstableApi
object ShadeMedia {
/** The grant in a capability link (`…#shade=…`). */
fun grant(link: String): Grant = Grants.fromCapabilityUrl(link)
/** Open the sealed file a capability link grants. Blocking. */
fun open(link: String): MediaReader {
val grant = grant(link)
if (grant !is MediaGrant) throw MediaFormatException("that link is a live channel, not a sealed file")
return grant.open()
}
/**
* Open a sealed film and the subtitle files its meta names. Blocking. A
* subtitle that cannot be opened is skipped; the film plays without it.
*/
fun openFilm(grant: MediaGrant): ShadeFilm {
val reader = grant.open()
val tracks = runCatching { Subtitles.of(reader.meta) }.getOrDefault(emptyList())
val subs = tracks.mapNotNull { t -> runCatching { t to t.grant.open() }.getOrNull() }
return ShadeFilm(grant, reader, subs)
}
/**
* A film with its subtitles as side-loaded text tracks. ExoPlayer parses
* SubRip and WebVTT itself; each file is read through its own reader.
*/
fun mediaSource(film: ShadeFilm, locale: java.util.Locale = java.util.Locale.getDefault()): MediaSource {
// The track in the viewer's language is on by default (Bokmål and
// Nynorsk match a `no` file); otherwise none is.
val base = { tag: String -> tag.substringBefore('-').lowercase().let { if (it == "nb" || it == "nn") "no" else it } }
val preferred = film.subtitles.indexOfFirst { (t, _) -> t.lang != null && base(t.lang!!) == base(locale.language) }
val readers = HashMap<Uri, MediaReader>()
val filmUri = uriOf(film.grant).also { readers[it] = film.reader }
val configs = film.subtitles.mapIndexed { i, (track, reader) ->
val uri = uriOf(track.grant).also { readers[it] = reader }
val vtt = reader.meta.name?.lowercase()?.endsWith(".vtt") == true || reader.meta.mime == "text/vtt"
MediaItem.SubtitleConfiguration.Builder(uri)
.setMimeType(if (vtt) MimeTypes.TEXT_VTT else MimeTypes.APPLICATION_SUBRIP)
.apply { track.lang?.let { setLanguage(it) } }
.apply { (track.label ?: track.lang)?.let { setLabel(it) } }
.setSelectionFlags(if (i == preferred) C.SELECTION_FLAG_DEFAULT else 0)
.build()
}
val item = MediaItem.Builder()
.setUri(filmUri)
.apply { film.reader.meta.mime?.let { setMimeType(it) } }
.setMediaMetadata(MediaMetadata.Builder().setTitle(film.reader.meta.name).build())
.setSubtitleConfigurations(configs)
.build()
return DefaultMediaSourceFactory(ShadeMediaDataSource.Factory { u -> readers[u] }).createMediaSource(item)
}
private fun uriOf(g: MediaGrant): Uri =
Uri.parse("shade-media://" + g.mediaId.joinToString("") { "%02x".format(it) })
/** A progressive media source playing the reader's plaintext. */
fun mediaSource(reader: MediaReader): MediaSource {
val item = MediaItem.Builder()
.setUri(Uri.parse("shade-media://sealed"))
.apply { reader.meta.mime?.let { setMimeType(it) } }
.setMediaMetadata(MediaMetadata.Builder().setTitle(reader.meta.name).build())
.build()
return ProgressiveMediaSource.Factory(ShadeMediaDataSource.Factory(reader)).createMediaSource(item)
}
/**
* A live channel carrying WebM or fragmented MP4 (`shade live video`).
*
* `connect` opens the frame feed; the default is a [LiveWatcher] on the
* grant's relay. The fMP4 extractor gets a fresh [TimestampAdjuster] per
* join, so a viewer who arrives an hour in starts at 0:00 rather than
* waiting an hour for the first sample; WebM is rebased by the data source.
*/
fun liveMediaSource(
grant: LiveGrant,
connect: (LiveWatcher.Listener) -> java.io.Closeable = { l -> LiveWatcher(grant, l) },
): MediaSource {
val item = MediaItem.Builder()
.setUri(Uri.parse("shade-live://channel"))
.setMediaMetadata(MediaMetadata.Builder().setTitle(grant.meta?.name).build())
.build()
val extractors = ExtractorsFactory {
arrayOf<Extractor>(
FragmentedMp4Extractor(SubtitleParser.Factory.UNSUPPORTED, 0, TimestampAdjuster(0), null, emptyList(), null),
MatroskaExtractor(SubtitleParser.Factory.UNSUPPORTED),
)
}
return ProgressiveMediaSource.Factory(ShadeLiveDataSource.Factory(connect), extractors).createMediaSource(item)
}
}
/** A sealed film and its opened subtitle files. Close it when done. */
class ShadeFilm(
val grant: MediaGrant,
val reader: MediaReader,
val subtitles: List<Pair<SubtitleTrack, MediaReader>>,
) : java.io.Closeable {
override fun close() {
reader.close()
subtitles.forEach { it.second.close() }
}
}

View File

@@ -0,0 +1,98 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.PlaybackException
import androidx.media3.common.util.UnstableApi
import androidx.media3.datasource.BaseDataSource
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSourceException
import androidx.media3.datasource.DataSpec
import no.zyon.shade.media.MediaReader
import java.io.IOException
/**
* A Media3 [DataSource] over a sealed Shade file.
*
* ExoPlayer asks for byte ranges of the plaintext (the container's header,
* then wherever a seek lands); [MediaReader] fetches only the sealed segments
* under each range, checks them against the digest table and decrypts them.
* The plaintext lives in the reader's small segment cache and the player's
* buffers, never on disk.
*
* The URI picks the reader (`resolve`): a film and its subtitle files are
* separate sealed files, each with its own `shade-media://<id>`. Readers are
* thread-safe, so one may back many data sources, which is what [Factory]
* does.
*/
@UnstableApi
class ShadeMediaDataSource(private val resolve: (Uri) -> MediaReader?) : BaseDataSource(/* isNetwork = */ true) {
/** Every URI reads this one file. */
constructor(reader: MediaReader) : this({ _: Uri -> reader })
private lateinit var reader: MediaReader
private var uri: Uri? = null
private var position = 0L
private var remaining = 0L
private var opened = false
override fun open(dataSpec: DataSpec): Long {
reader = resolve(dataSpec.uri)
?: throw DataSourceException(PlaybackException.ERROR_CODE_IO_FILE_NOT_FOUND)
uri = dataSpec.uri
transferInitializing(dataSpec)
if (dataSpec.position > reader.size) {
throw DataSourceException(PlaybackException.ERROR_CODE_IO_READ_POSITION_OUT_OF_RANGE)
}
position = dataSpec.position
val left = reader.size - position
remaining = if (dataSpec.length == C.LENGTH_UNSET.toLong()) left else minOf(dataSpec.length, left)
opened = true
transferStarted(dataSpec)
return remaining
}
override fun read(buffer: ByteArray, offset: Int, length: Int): Int {
if (length == 0) return 0
if (remaining == 0L) return C.RESULT_END_OF_INPUT
val n = minOf(length.toLong(), remaining, MAX_READ).toInt()
val bytes = try {
reader.read(position, n)
} catch (e: IOException) {
throw e
} catch (e: Exception) {
// Tampered, truncated or foreign data: the file cannot be trusted
// from here on, and retrying will not change that.
throw DataSourceException(e, PlaybackException.ERROR_CODE_IO_UNSPECIFIED)
}
if (bytes.isEmpty()) return C.RESULT_END_OF_INPUT
System.arraycopy(bytes, 0, buffer, offset, bytes.size)
position += bytes.size
remaining -= bytes.size
bytesTransferred(bytes.size)
return bytes.size
}
override fun getUri(): Uri? = uri
override fun close() {
uri = null
if (opened) {
opened = false
transferEnded()
}
}
/** Data sources sharing opened readers, chosen by URI. */
class Factory(private val resolve: (Uri) -> MediaReader?) : DataSource.Factory {
/** Every URI reads this one file. */
constructor(reader: MediaReader) : this({ _: Uri -> reader })
override fun createDataSource(): DataSource = ShadeMediaDataSource(resolve)
}
private companion object {
/** One segment: the reader decrypts whole segments, so larger reads gain nothing. */
const val MAX_READ = 1L shl 20
}
}

View File

@@ -0,0 +1,104 @@
package no.zyon.shade.media.android
import android.content.Context
import android.graphics.BitmapFactory
import android.media.MediaMetadataRetriever
import android.net.Uri
import android.provider.OpenableColumns
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import java.io.FileNotFoundException
/**
* Sealing and uploading what the phone has — a video from the gallery, a
* photo, a recording, any document a share hands over as a `content://` URI.
* Blocking: run it off the main thread (in a foreground service for a film).
*/
object ShadeUpload {
/** What a share is: the URI, and the meta it will be sealed with. */
class Item(val uri: Uri, val size: Long, val meta: MediaMeta)
/**
* Name, type and size from the content resolver; duration and picture size
* read from the file itself (video, audio, images), so a library can show
* them without opening it. Nothing else — no location, no path — goes in.
*/
fun describe(context: Context, uri: Uri): Item {
val cr = context.contentResolver
var name: String? = null
var size = -1L
cr.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
if (c.moveToFirst()) {
c.getColumnIndex(OpenableColumns.DISPLAY_NAME).takeIf { it >= 0 && !c.isNull(it) }?.let { name = c.getString(it) }
c.getColumnIndex(OpenableColumns.SIZE).takeIf { it >= 0 && !c.isNull(it) }?.let { size = c.getLong(it) }
}
}
val mime = cr.getType(uri)?.takeIf { MIME_RE.matches(it) }
var durationMs: Long? = null
var width: Long? = null
var height: Long? = null
when {
mime?.startsWith("video/") == true || mime?.startsWith("audio/") == true -> runCatching {
MediaMetadataRetriever().apply { setDataSource(context, uri) }.let { r ->
try {
durationMs = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION)?.toLongOrNull()
val w = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)?.toLongOrNull()
val h = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_HEIGHT)?.toLongOrNull()
val turned = r.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_ROTATION)?.toIntOrNull()?.let { it % 180 != 0 } ?: false
// As it is shown: a portrait phone video is stored sideways.
width = if (turned) h else w
height = if (turned) w else h
} finally {
r.release()
}
}
}
mime?.startsWith("image/") == true -> runCatching {
val o = BitmapFactory.Options().apply { inJustDecodeBounds = true }
cr.openInputStream(uri)?.use { BitmapFactory.decodeStream(it, null, o) }
if (o.outWidth > 0) {
width = o.outWidth.toLong()
height = o.outHeight.toLong()
}
}
}
val meta = MediaMeta(
mime = mime,
name = name?.let(::cleanName),
durationMs = durationMs,
width = width,
height = height,
)
return Item(uri, size, MediaMeta.validate(meta))
}
/**
* Seal and upload `item` as a job in `jobs` (see [MediaUploader.upload]):
* killed half-way, the same call resumes it; shared again, it gives the
* same link while the relay has the file.
*/
fun upload(
context: Context,
uploader: MediaUploader,
jobs: UploadJobs,
item: Item,
onProgress: ((Long, Long) -> Unit)? = null,
): MediaGrant {
return uploader.upload(jobs, jobKey(jobs, uploader, item), item.meta.name ?: item.uri.toString(), item.meta, {
context.contentResolver.openInputStream(item.uri) ?: throw FileNotFoundException("cannot open ${item.uri}")
}, onProgress = onProgress)
}
/** The job `item` is in `jobs` when uploaded with `uploader`: the relay, the URI, its size and name. */
fun jobKey(jobs: UploadJobs, uploader: MediaUploader, item: Item): String =
jobs.key(uploader.server, item.uri.toString(), item.size.toString(), item.meta.name ?: "")
private val MIME_RE = Regex("""^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$""", RegexOption.IGNORE_CASE)
/** A display name, not a path; control characters out (the meta refuses them). */
private fun cleanName(n: String): String? =
n.substringAfterLast('/').filter { it.code >= 0x20 && it.code != 0x7f }.take(1024).ifEmpty { null }
}

View File

@@ -0,0 +1,259 @@
package no.zyon.shade.media.android
import androidx.media3.common.MimeTypes
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.test.utils.TestExoPlayerBuilder
import androidx.media3.test.utils.robolectric.TestPlayerRunHelper
import androidx.test.core.app.ApplicationProvider
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.LivePublisher
import no.zyon.shade.media.LiveSubscriber
import no.zyon.shade.media.ReceivedFrame
import okhttp3.Response
import okhttp3.WebSocket
import okhttp3.WebSocketListener
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
import okio.ByteString.Companion.toByteString
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.Closeable
import java.nio.ByteBuffer
import java.security.SecureRandom
import java.util.Base64
import java.util.Collections
import java.util.concurrent.CountDownLatch
import java.util.concurrent.TimeUnit
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ShadeLiveTest {
/** A piece cut by the TS splitter (scripts/make-live-fixtures.ts). */
class Piece(val init: Boolean, val keyframe: Boolean, val bytes: ByteArray)
private fun pieces(name: String): List<Piece> {
val b = ByteBuffer.wrap(javaClass.getResourceAsStream("/$name")!!.readBytes())
val out = ArrayList<Piece>()
while (b.hasRemaining()) {
val kind = b.get().toInt()
val bytes = ByteArray(b.getInt()).also { b.get(it) }
out += Piece(kind == 0, kind == 1, bytes)
}
return out
}
private fun random(n: Int) = ByteArray(n).also { SecureRandom().nextBytes(it) }
/** A channel: the grant a viewer holds, and every frame the publisher sent, sealed and signed. */
private class Channel(val grant: LiveGrant, val frames: List<ByteArray>)
private fun channel(pieces: List<Piece>, mime: String, extra: (LivePublisher) -> List<ByteArray> = { emptyList() }): Channel {
val pub = LivePublisher(random(16), random(32), null)
val grant = pub.grant(from = "now", url = "ws://relay.invalid/v1/live/x", readToken = random(32))
val frames = ArrayList<ByteArray>()
for (p in pieces) {
frames += if (p.init) pub.frame(LiveContent.Init(mime, p.bytes), sticky = true) else pub.frame(LiveContent.Chunk(p.bytes), keyframe = p.keyframe)
}
frames += extra(pub)
frames += pub.frame(LiveContent.End)
return Channel(grant, frames)
}
/** A feed that opens and delivers the chosen frames on its own thread, as the watcher would. */
private fun feed(ch: Channel, pick: (Int) -> Boolean = { true }): (LiveWatcher.Listener) -> Closeable = { listener ->
val t = Thread {
val sub = LiveSubscriber(ch.grant)
ch.frames.forEachIndexed { i, f -> if (pick(i)) sub.open(f)?.let(listener::onFrame) }
}
t.start()
Closeable { t.join() }
}
private class Played(val mimes: List<String?>, val endPositionMs: Long)
private fun play(ch: Channel, connect: (LiveWatcher.Listener) -> Closeable): Played {
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
player.setMediaSource(ShadeMedia.liveMediaSource(ch.grant, connect))
player.prepare()
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
val mimes = player.currentTracks.groups.map { it.getTrackFormat(0).sampleMimeType }
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
val end = player.currentPosition
player.release()
return Played(mimes, end)
}
@Test
fun lateJoinOnFragmentedMp4StartsAtTheNextKeyframeAndAtZero() {
val pieces = pieces("live-h264.pieces")
val ch = channel(pieces, "video/mp4")
// Frame 0 is the init; a viewer joining mid-GOP sees media from frame 3.
val firstKey = (3 until pieces.size).first { pieces[it].keyframe }
val played = play(ch, feed(ch) { it == 0 || it >= 3 })
assertTrue("tracks: ${played.mimes}", MimeTypes.VIDEO_H264 in played.mimes && MimeTypes.AUDIO_AAC in played.mimes)
// 20 pieces of 250 ms; from the keyframe on that is what plays, from 0:00.
val expectMs = (pieces.size - firstKey) * 250L
assertEquals("rebased to zero, not ${firstKey * 250} ms in", expectMs.toDouble(), played.endPositionMs.toDouble(), 300.0)
}
@Test
fun lateJoinOnWebmIsRebasedToo() {
val pieces = pieces("live-vp8.pieces")
val ch = channel(pieces, "video/webm")
val firstKey = (3 until pieces.size).first { pieces[it].keyframe }
val played = play(ch, feed(ch) { it == 0 || it >= 3 })
assertTrue("tracks: ${played.mimes}", MimeTypes.VIDEO_VP8 in played.mimes && MimeTypes.AUDIO_OPUS in played.mimes)
val expectMs = (pieces.size - firstKey) * 250L
assertEquals(expectMs.toDouble(), played.endPositionMs.toDouble(), 350.0)
}
@Test
fun aGapWaitsForTheNextKeyframe() {
val pieces = pieces("live-h264.pieces")
val ch = channel(pieces, "video/mp4")
// Lose one frame inside a GOP: the rest of that GOP must not reach the decoder.
val lost = (2 until pieces.size).first { !pieces[it].keyframe && !pieces[it - 1].keyframe }
val ds = ShadeLiveDataSource(feed(ch) { it != lost })
val read = drain(ds)
val nextKey = (lost + 1 until pieces.size).first { pieces[it].keyframe }
val expected = pieces.filterIndexed { i, _ -> i < lost || i >= nextKey }.map { it.bytes }
assertEquals(expected.sumOf { it.size }, read.size)
assertEquals((nextKey - lost - 1).toLong(), ds.droppedFrames)
}
@Test
fun aDifferentInitMidStreamFailsPlaybackInsteadOfCorruptingIt() {
val pieces = pieces("live-h264.pieces")
val ch = channel(pieces.take(8), "video/mp4") { pub ->
listOf(pub.frame(LiveContent.Init("video/mp4", byteArrayOf(1, 2, 3)), sticky = true))
}
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
player.setMediaSource(ShadeMedia.liveMediaSource(ch.grant, feed(ch)))
player.prepare()
player.play()
val error: PlaybackException = TestPlayerRunHelper.runUntilError(player)
var cause: Throwable? = error
while (cause != null && cause !is LiveFormatChangedException) cause = cause.cause
val chain = generateSequence(error as Throwable) { it.cause }.joinToString(" <- ") { "${it.javaClass.simpleName}(${it.message})" }
assertTrue("error: $chain", cause is LiveFormatChangedException)
player.release()
}
/** Read a data source to its end, as an extractor would. */
private fun drain(ds: ShadeLiveDataSource): ByteArray {
val out = java.io.ByteArrayOutputStream()
ds.open(androidx.media3.datasource.DataSpec(android.net.Uri.parse("shade-live://x")))
val buf = ByteArray(4096)
while (true) {
val n = ds.read(buf, 0, buf.size)
if (n < 0) break
out.write(buf, 0, n)
}
ds.close()
return out.toByteArray()
}
@Test
fun watcherSubscribesReconnectsAndDeliversEachFrameOnce() {
val pieces = pieces("live-h264.pieces").take(6)
val server = MockWebServer()
server.start()
val pub = LivePublisher(random(16), random(32), null)
val token = random(32)
val grant = pub.grant(from = "now", url = server.url("/v1/live/x").toString().replace("http", "ws"), readToken = token)
val frames = pieces.map {
if (it.init) pub.frame(LiveContent.Init("video/mp4", it.bytes), sticky = true) else pub.frame(LiveContent.Chunk(it.bytes), keyframe = it.keyframe)
} + pub.frame(LiveContent.End)
val subscribes = Collections.synchronizedList(ArrayList<String>())
// First connection: half the frames, then the relay drops us.
// Second: the backlog again from the start (as a relay does), then the rest.
for (attempt in 0..1) {
server.enqueue(
MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(1000, null)
}
override fun onMessage(webSocket: WebSocket, text: String) {
subscribes += text
webSocket.send("""{"type":"ready","live":true}""")
val upTo = if (attempt == 0) 4 else frames.size
for (f in frames.take(upTo)) webSocket.send(f.toByteString())
if (attempt == 0) webSocket.close(1001, "going away")
}
}),
)
}
val got = Collections.synchronizedList(ArrayList<ReceivedFrame>())
val states = Collections.synchronizedList(ArrayList<LiveWatcher.State>())
val done = CountDownLatch(1)
val watcher = LiveWatcher(grant, object : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {
got += frame
if (frame.content is LiveContent.End) done.countDown()
}
override fun onState(state: LiveWatcher.State) {
states += state
}
})
assertTrue("timed out; states $states, frames ${got.size}", done.await(10, TimeUnit.SECONDS))
watcher.close()
server.shutdown()
assertEquals(2, subscribes.size)
for (s in subscribes) {
val o = JSONObject(s)
assertEquals("subscribe", o.getString("type"))
assertEquals(Base64.getUrlEncoder().withoutPadding().encodeToString(token), o.getString("token"))
}
assertEquals((0L until frames.size).toList(), got.map { it.seq })
assertTrue("states: $states", states.count { it == LiveWatcher.State.LIVE } == 2 && LiveWatcher.State.RECONNECTING in states)
assertEquals(LiveWatcher.State.CLOSED, states.last())
}
@Test
fun watcherFollowsThePublisherArrivingAndLeavingAfterItJoined() {
val server = MockWebServer()
server.start()
val pub = LivePublisher(random(16), random(32), null)
val grant = pub.grant(from = "now", url = server.url("/v1/live/x").toString().replace("http", "ws"), readToken = random(32))
val first = pub.frame(LiveContent.Chunk(byteArrayOf(1)), keyframe = true)
server.enqueue(
MockResponse().withWebSocketUpgrade(object : WebSocketListener() {
override fun onClosing(webSocket: WebSocket, code: Int, reason: String) {
webSocket.close(1000, null)
}
override fun onMessage(webSocket: WebSocket, text: String) {
// Joins an empty channel; the publisher arrives, sends, leaves.
webSocket.send("""{"type":"ready","live":false}""")
webSocket.send("""{"type":"state","live":true}""")
webSocket.send(first.toByteString())
webSocket.send("""{"type":"state","live":false}""")
}
}),
)
val states = Collections.synchronizedList(ArrayList<LiveWatcher.State>())
val left = CountDownLatch(1)
val watcher = LiveWatcher(grant, object : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {}
override fun onState(state: LiveWatcher.State) {
states += state
if (state == LiveWatcher.State.WAITING && LiveWatcher.State.LIVE in states) left.countDown()
}
})
assertTrue("states: $states", left.await(10, TimeUnit.SECONDS))
watcher.close()
server.shutdown()
val seen = states.filter { it == LiveWatcher.State.WAITING || it == LiveWatcher.State.LIVE }
assertEquals(listOf(LiveWatcher.State.WAITING, LiveWatcher.State.LIVE, LiveWatcher.State.WAITING), seen)
}
}

View File

@@ -0,0 +1,160 @@
package no.zyon.shade.media.android
import android.net.Uri
import androidx.media3.common.C
import androidx.media3.common.MimeTypes
import androidx.media3.common.Player
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.DataSourceException
import androidx.media3.datasource.DataSpec
import androidx.media3.exoplayer.source.ProgressiveMediaSource
import androidx.media3.test.utils.TestExoPlayerBuilder
import androidx.media3.test.utils.robolectric.TestPlayerRunHelper
import androidx.test.core.app.ApplicationProvider
import no.zyon.shade.media.ByteArraySource
import no.zyon.shade.media.MediaKeys
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.SubtitleTrack
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.ByteArrayOutputStream
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ShadeMediaDataSourceTest {
/** A 2 s H.264/AAC MP4, sealed in 4 KiB segments so every read crosses several. */
private val clip: ByteArray = javaClass.getResourceAsStream("/clip.mp4")!!.readBytes()
private fun sealed(plain: ByteArray = clip): Pair<ByteArray, MediaKeys> {
val (bytes, r) = MediaSealer.sealBytes(plain, MediaMeta(mime = "video/mp4", name = "clip.mp4"), segmentSize = 4096)
return bytes to MediaKeys(r.mediaId, r.mediaKey, r.rootDigest)
}
private fun reader(): MediaReader {
val (bytes, keys) = sealed()
return MediaReader.open(ByteArraySource(bytes), keys)
}
private fun readAll(ds: DataSource, spec: DataSpec): ByteArray {
val out = ByteArrayOutputStream()
val buf = ByteArray(3000) // not a divisor of the segment size
ds.open(spec)
while (true) {
val n = ds.read(buf, 0, buf.size)
if (n == C.RESULT_END_OF_INPUT) break
out.write(buf, 0, n)
}
ds.close()
return out.toByteArray()
}
@Test
fun readsThePlaintextWholeAndInRanges() {
val ds = ShadeMediaDataSource(reader())
val uri = Uri.parse("shade-media://sealed")
assertArrayEquals(clip, readAll(ds, DataSpec(uri)))
// Mid-file windows, as a seek produces: unbounded and bounded.
assertArrayEquals(clip.copyOfRange(9999, clip.size), readAll(ds, DataSpec.Builder().setUri(uri).setPosition(9999).build()))
assertArrayEquals(
clip.copyOfRange(4095, 4095 + 5000),
readAll(ds, DataSpec.Builder().setUri(uri).setPosition(4095).setLength(5000).build()),
)
// open() reports the length it will deliver.
assertEquals((clip.size - 100).toLong(), ds.open(DataSpec.Builder().setUri(uri).setPosition(100).build()))
ds.close()
assertEquals(0L, ds.open(DataSpec.Builder().setUri(uri).setPosition(clip.size.toLong()).build()))
assertEquals(C.RESULT_END_OF_INPUT, ds.read(ByteArray(10), 0, 10))
ds.close()
assertThrows(DataSourceException::class.java) {
ds.open(DataSpec.Builder().setUri(uri).setPosition(clip.size + 1L).build())
}
}
@Test
fun aTamperedSegmentFailsTheRead() {
val (bytes, keys) = sealed()
bytes[2 * 4096 + 100] = (bytes[2 * 4096 + 100].toInt() xor 1).toByte()
val ds = ShadeMediaDataSource(MediaReader.open(ByteArraySource(bytes), keys))
val e = assertThrows(DataSourceException::class.java) { readAll(ds, DataSpec(Uri.parse("shade-media://sealed"))) }
assertTrue(e.cause!!.message!!.contains("does not match its digest"))
}
@Test
fun exoPlayerPlaysAndSeeksASealedFilm() {
val reader = reader()
val opens = mutableListOf<Long>()
val counting = DataSource.Factory {
val inner = ShadeMediaDataSource(reader)
object : DataSource by inner {
override fun open(dataSpec: DataSpec): Long {
opens += dataSpec.position
return inner.open(dataSpec)
}
}
}
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
val item = ShadeMedia.mediaSource(reader).mediaItem
player.setMediaSource(ProgressiveMediaSource.Factory(counting).createMediaSource(item))
player.prepare()
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
val mimes = player.currentTracks.groups.map { it.getTrackFormat(0).sampleMimeType }
assertTrue("tracks: $mimes", MimeTypes.VIDEO_H264 in mimes)
assertTrue("tracks: $mimes", MimeTypes.AUDIO_AAC in mimes)
assertEquals(2000.0, player.duration.toDouble(), 100.0)
assertEquals("clip.mp4", player.mediaMetadata.title)
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
// A seek back into the film reopens the source mid-file.
opens.clear()
player.seekTo(1200)
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
assertTrue("opened at $opens", opens.any { it > 0 })
assertTrue(player.currentPosition >= 1000)
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
player.release()
}
@Test
fun aFilmPlaysWithItsSubtitlesAndPicksTheViewersLanguage() {
fun sealedFile(bytes: ByteArray, meta: MediaMeta): Pair<MediaGrant, MediaReader> {
val (sealed, r) = MediaSealer.sealBytes(bytes, meta, segmentSize = 4096)
val grant = MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url = "https://relay.invalid/x")
return grant to MediaReader.open(ByteArraySource(sealed), MediaKeys(r.mediaId, r.mediaKey, r.rootDigest))
}
val no = sealedFile("1\r\n00:00:00,100 --> 00:00:01,900\r\nHei, æøå!\r\n".toByteArray(), MediaMeta(name = "clip.no.srt"))
val en = sealedFile("WEBVTT\n\n00:00.100 --> 00:01.900\nHello!\n".toByteArray(), MediaMeta(name = "clip.en.vtt", mime = "text/vtt"))
val film = sealedFile(clip, MediaMeta(mime = "video/mp4", name = "clip.mp4"))
val shadeFilm = ShadeFilm(
film.first,
film.second,
listOf(SubtitleTrack(en.first, "en") to en.second, SubtitleTrack(no.first, "no", "Norsk") to no.second),
)
val player = TestExoPlayerBuilder(ApplicationProvider.getApplicationContext()).build()
player.setMediaSource(ShadeMedia.mediaSource(shadeFilm, java.util.Locale.forLanguageTag("nb-NO")))
player.prepare()
TestPlayerRunHelper.run(player).untilState(Player.STATE_READY)
val text = player.currentTracks.groups.filter { it.type == C.TRACK_TYPE_TEXT }
assertEquals("text tracks: ${text.map { it.getTrackFormat(0) }}", 2, text.size)
// The test player has no text renderer to select with; what we decide
// is which track is the default, and the player reports that flag.
val defaults = text.filter { it.getTrackFormat(0).selectionFlags and C.SELECTION_FLAG_DEFAULT != 0 }.map { it.getTrackFormat(0).language }
assertEquals(listOf("no"), defaults)
assertTrue(text.any { it.getTrackFormat(0).label == "Norsk" })
player.play()
TestPlayerRunHelper.run(player).untilState(Player.STATE_ENDED)
player.release()
}
}

View File

@@ -0,0 +1,94 @@
package no.zyon.shade.media.android
import android.content.ContentProvider
import android.content.ContentValues
import android.database.Cursor
import android.database.MatrixCursor
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.provider.OpenableColumns
import androidx.test.core.app.ApplicationProvider
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assume.assumeTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.robolectric.Robolectric
import org.robolectric.RobolectricTestRunner
import org.robolectric.annotation.Config
import java.io.File
import java.security.MessageDigest
import java.security.SecureRandom
@RunWith(RobolectricTestRunner::class)
@Config(sdk = [34])
class ShadeUploadTest {
/** A gallery: one video, served the way a share hands it over. */
class Gallery : ContentProvider() {
override fun onCreate() = true
override fun query(uri: Uri, projection: Array<out String>?, selection: String?, args: Array<out String>?, sort: String?): Cursor =
MatrixCursor(arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE)).apply { addRow(arrayOf<Any>(name, file!!.length())) }
override fun getType(uri: Uri) = "video/mp4"
override fun openFile(uri: Uri, mode: String): ParcelFileDescriptor = ParcelFileDescriptor.open(file!!, ParcelFileDescriptor.MODE_READ_ONLY)
override fun insert(uri: Uri, values: ContentValues?): Uri? = null
override fun delete(uri: Uri, selection: String?, args: Array<out String>?) = 0
override fun update(uri: Uri, values: ContentValues?, selection: String?, args: Array<out String>?) = 0
companion object {
var file: File? = null
var name = "VID_0042.mp4"
}
}
private val context = ApplicationProvider.getApplicationContext<android.app.Application>()
private val uri = Uri.parse("content://test.gallery/video/42")
private fun video(bytes: ByteArray): File {
Robolectric.setupContentProvider(Gallery::class.java, "test.gallery")
return File.createTempFile("vid", ".mp4").also {
it.writeBytes(bytes)
it.deleteOnExit()
Gallery.file = it
}
}
private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
@Test
fun describeTakesTheNameTypeAndSizeAndNothingElse() {
video(ByteArray(5000))
Gallery.name = "Kveld\u0007 på hytta.mp4"
val item = ShadeUpload.describe(context, uri)
assertEquals("Kveld på hytta.mp4", item.meta.name)
assertEquals("video/mp4", item.meta.mime)
assertEquals(5000L, item.size)
assertEquals(null, item.meta.createdAt)
assertEquals(null, item.meta.extra)
Gallery.name = "VID_0042.mp4"
}
/** Against a real TS relay — run by `bun run scripts/media-live-kotlin.ts`, skipped without it. */
@Test
fun aSharedVideoIsSealedFromItsUriAndUploaded() {
val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC")
assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live upload skipped", !specPath.isNullOrEmpty())
val spec = JSONObject(File(specPath!!).readText())
val seed = spec.getString("seed").chunked(2).map { it.toInt(16).toByte() }.toByteArray()
val uploader = MediaUploader(spec.getString("url"), MediaOwner(seed))
val jobs = UploadJobs(File(spec.getString("scratch"), "android-jobs"))
val bytes = ByteArray(20 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
video(bytes)
val item = ShadeUpload.describe(context, uri)
val grant = ShadeUpload.upload(context, uploader, jobs, item)
grant.open().use { r ->
assertEquals("VID_0042.mp4", r.meta.name)
assertEquals(sha256(bytes), sha256(r.read(0, r.size.toInt())))
}
// Shared again: the same job, the same link.
assertEquals(grant.encode(), ShadeUpload.upload(context, uploader, jobs, ShadeUpload.describe(context, uri)).encode())
File(spec.getString("scratch"), "android-out.txt").writeText(grant.capabilityUrl("https://watch.example/"))
}
}

View File

@@ -0,0 +1,85 @@
# Migrating Nova Android to Shade
This document describes the concrete steps to replace Nova's static AES push
notification encryption with Shade's Signal Protocol ratcheting.
## Current state
**Nova server** (`nova/src/server/services/notifications.ts`):
- Uses a per-device static AES-256-GCM key stored in `pushDevices.encryptionKey`
- Calls `encryptPayload(notificationJson, key)` directly
- Sends via FCM `data: { enc, v: '1' }`
**Nova Android** (`Android/nova-app/.../data/PushKeyStore.kt`):
- Generates the device's AES key once and stores it via EncryptedSharedPreferences
- Decrypts FCM data payload in `NovaFirebaseMessagingService`
- Uses `javax.crypto.Cipher` directly
**Problem:** A single compromised key exposes all past and future notifications.
No forward secrecy, no post-compromise recovery.
## Target state
**Nova server:**
- Uses `@shade/sdk` with `createShade({ prekeyServer, address: 'nova-server' })`
- Per-device Shade sessions stored in PostgreSQL via `@shade/storage-postgres`
- To notify a device: `await shade.send('device:${id}', notificationJson)`
- The envelope is base64-encoded and sent via FCM `data: { enc, v: '2' }`
**Nova Android:**
- Uses `shade-android` (Kotlin) with `ShadeSessionManager`
- Session state stored via `KeystoreStorage` (EncryptedSharedPreferences)
- On FCM receive: decode envelope → `manager.decrypt('nova-server', envelope)`
- First time registration: generate identity, upload prekey bundle to the Shade
prekey server, and tell the Nova backend the device address
## Migration steps
### Phase 1: Dual-write (both work simultaneously)
Add a `v` field to the FCM data payload. Android decrypts v=1 with legacy
`PushKeyStore` and v=2 with Shade. Server can send either. Old devices keep
working while new devices get Shade.
### Phase 2: Switch reads
When 95% of devices have a Shade session established, flip the server to
send v=2 by default. Fall back to v=1 only if the device has no Shade
session.
### Phase 3: Deprecate
Remove v=1 code paths, drop the `pushDevices.encryptionKey` column.
## Smoke test (prove it works end-to-end)
1. TS side creates a Shade instance for `nova-server` (using `@shade/sdk`)
2. TS side calls `shade.send('device:test', '{"title":"Hello"}')`
3. Encode the envelope as base64 → FCM `data.enc`
4. Kotlin side decodes base64 → `WireFormat.decodeEnvelope(bytes)`
5. Kotlin side calls `manager.decrypt('nova-server', envelope)`
6. Assert plaintext matches
This is verified by the cross-platform vector tests + a manual smoke run
described in `examples/07-nova-integration/` (to be added).
## Files to modify
Nova server:
- `nova/src/server/services/notifications.ts` — replace `encryptPayload` with `shade.send`
- `nova/src/server/services/push-devices.ts` — track Shade address per device
- Add `@shade/sdk` to `nova/package.json`
Nova Android:
- `Android/nova-app/app/src/main/java/no/zyon/nova/data/PushKeyStore.kt` — delegate
to `ShadeSessionManager`
- `Android/nova-app/app/src/main/java/no/zyon/nova/NovaFirebaseMessagingService.kt` —
call `WireFormat.decodeEnvelope` and `manager.decrypt`
- Add `shade-android` as a Gradle dependency
## Not done in M-Cross 3
Running a full Android Gradle build + instrumented tests is out of scope for
this milestone. The cross-platform vector tests prove byte-for-byte
compatibility; the actual Nova integration happens when the user explicitly
wires up the Android module in their Nova project.

View File

@@ -0,0 +1,76 @@
# shade-android
Kotlin implementation of the Shade E2EE protocol for Android apps. Byte-for-byte compatible with `@shade/core` (TypeScript), so messages encrypted on a TS backend can be decrypted on Android and vice versa.
## Status
**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 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).
**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
and Kotlin test suites; any byte-divergence fails CI within 60 s. See
`ROADMAP-ANDROID.md` for the parity-checkpoint matrix and
`/docs/cross-platform.md` for how to add a new vector.
## Usage (target API)
```kotlin
import no.zyon.shade.ShadeSessionManager
import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.storage.KeystoreStorage
val crypto = TinkProvider()
val storage = KeystoreStorage(context)
val manager = ShadeSessionManager(crypto, storage)
manager.initialize()
// Establish a session with a peer
val bundle = fetchBundleFromServer("bob@example.com")
manager.initSessionFromBundle("bob@example.com", bundle)
// Encrypt
val envelope = manager.encrypt("bob@example.com", "hello")
// Decrypt
val plaintext = manager.decrypt("alice@example.com", incomingEnvelope)
```
## Crypto primitives
Backed by Google Tink:
- X25519 for Diffie-Hellman (via `X25519.generatePrivateKey()` / `computeSharedSecret`)
- Ed25519 for signing (via `Ed25519Sign` / `Ed25519Verify`)
- AES-256-GCM (via `AesGcmJce`)
- HKDF-SHA256 (via `Hkdf.computeHkdf`)
- HMAC-SHA256 (via `MacFactory`)
## Building
Requires JDK 17. The module compiles as a pure-JVM Kotlin library so the
parity gate runs without an Android SDK install. The Android-specific
storage adapter (Keystore + EncryptedSharedPreferences) will land as a
sibling Gradle module in M-Cross 4.
```bash
cd android
./gradlew :shade-android:test
```
The Gradle wrapper downloads Gradle 8.10.2 on first run.
## Compatibility
The Kotlin implementation must produce byte-identical output to `@shade/core` for:
- KDF chain derivations (root key ratchet, chain key ratchet)
- X3DH shared secrets
- Ratchet message keys and ciphertext (given the same keys)
- Fingerprints (safety numbers)
- Binary wire format (`@shade/proto`)
Shared test vectors in `test-vectors/` are loaded by both the TS and Kotlin test suites. Any divergence fails the CI immediately.

View File

@@ -0,0 +1,60 @@
plugins {
kotlin("jvm")
`java-library`
}
// V3.5 — Cross-platform parity gate.
//
// This module compiles as a pure-JVM Kotlin library so CI can run the
// cross-platform vector tests without an Android SDK. The protocol code
// is JVM-safe (no `android.*` imports); only Tink + java.* are used.
//
// When KeystoreStorage and EncryptedSharedPreferences-backed adapters land
// (M-Cross 4 + V3.5 §Storage), they will live in a sibling Android Library
// module that depends on this one.
java {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlin {
compilerOptions {
jvmTarget.set(org.jetbrains.kotlin.gradle.dsl.JvmTarget.JVM_17)
}
}
dependencies {
// Google Tink for X25519, Ed25519, AES-GCM, HMAC, HKDF (JVM build).
// The same `subtle.*` API as `tink-android` so the source compiles unchanged.
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).
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
// Coroutines (StorageProvider uses `suspend` functions).
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
// org.json — bundled with Android but not present on the JVM classpath.
implementation("org.json:json:20240303")
testImplementation("junit:junit:4.13.2")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
}
tasks.withType<Test>().configureEach {
useJUnit()
// VaultLiveTest and MediaLiveTest are gated on these; 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") ?: "")
inputs.property("shadeMediaLiveSpec", System.getenv("SHADE_MEDIA_LIVE_SPEC") ?: "")
testLogging {
events("passed", "failed", "skipped")
showStandardStreams = false
}
}

View File

@@ -0,0 +1,205 @@
package no.zyon.shade
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.fingerprint.computeFingerprint
import no.zyon.shade.protocol.createPreKeyBundle
import no.zyon.shade.protocol.generateIdentityKeyPair
import no.zyon.shade.protocol.generateOneTimePreKeys
import no.zyon.shade.protocol.generateSignedPreKey
import no.zyon.shade.protocol.initReceiverSession
import no.zyon.shade.protocol.initSenderSession
import no.zyon.shade.protocol.processPreKeyBundle
import no.zyon.shade.protocol.processPreKeyMessage
import no.zyon.shade.protocol.ratchetDecrypt
import no.zyon.shade.protocol.ratchetEncrypt
import no.zyon.shade.storage.StorageProvider
import no.zyon.shade.types.OneTimePreKey
import no.zyon.shade.types.PreKeyBundle
import no.zyon.shade.types.PreKeyMessage
import no.zyon.shade.types.RatchetMessage
import no.zyon.shade.types.ShadeEnvelope
import no.zyon.shade.types.SignedPreKey
/**
* High-level API mirroring @shade/core's ShadeSessionManager.
*
* Handles X3DH + Double Ratchet, persists state via StorageProvider.
*/
class ShadeSessionManager(
private val crypto: CryptoProvider,
private val storage: StorageProvider,
) {
private var identity: no.zyon.shade.types.IdentityKeyPair? = null
private var registrationId: Int = 0
private var currentSignedPreKeyId: Int = 0
// X3DH pending metadata (used for first message after bundle processing)
private val pendingX3DH = mutableMapOf<String, PendingX3DH>()
private data class PendingX3DH(
val ephemeralPublicKey: ByteArray,
val signedPreKeyId: Int,
val preKeyId: Int?,
val identityDHKey: ByteArray,
val registrationId: Int,
)
suspend fun initialize() {
identity = storage.getIdentityKeyPair() ?: run {
val fresh = generateIdentityKeyPair(crypto)
storage.saveIdentityKeyPair(fresh)
fresh
}
registrationId = storage.getLocalRegistrationId()
if (registrationId == 0) {
var id = crypto.randomUint32()
if (id == 0) id = 1
registrationId = id
storage.saveLocalRegistrationId(id)
}
val spk = storage.getSignedPreKey(1)
if (spk == null) {
val fresh = generateSignedPreKey(crypto, identity!!, 1)
storage.saveSignedPreKey(fresh)
currentSignedPreKeyId = 1
} else {
currentSignedPreKeyId = spk.keyId
}
}
fun getPublicIdentity(): Pair<ByteArray, ByteArray> {
val id = identity ?: throw IllegalStateException("Not initialized")
return id.signingPublicKey to id.dhPublicKey
}
suspend fun getIdentityFingerprint(): String {
val id = identity ?: throw IllegalStateException("Not initialized")
return computeFingerprint(crypto, id.signingPublicKey, id.dhPublicKey)
}
suspend fun createPreKeyBundle(): PreKeyBundle {
val id = identity ?: throw IllegalStateException("Not initialized")
val spk = storage.getSignedPreKey(currentSignedPreKeyId)
?: throw IllegalStateException("No signed prekey")
return createPreKeyBundle(registrationId, id, spk)
}
suspend fun generateOneTimePreKeys(count: Int): List<OneTimePreKey> {
val existing = storage.getOneTimePreKeyCount()
val startId = existing + 1
val keys = generateOneTimePreKeys(crypto, startId, count)
for (k in keys) storage.saveOneTimePreKey(k)
return keys
}
suspend fun rotateSignedPreKey(): SignedPreKey {
val id = identity ?: throw IllegalStateException("Not initialized")
val newId = currentSignedPreKeyId + 1
val spk = generateSignedPreKey(crypto, id, newId)
storage.saveSignedPreKey(spk)
currentSignedPreKeyId = newId
return spk
}
suspend fun initSessionFromBundle(address: String, bundle: PreKeyBundle) {
val id = identity ?: throw IllegalStateException("Not initialized")
val x3dhResult = processPreKeyBundle(crypto, id, bundle)
val session = initSenderSession(
crypto,
x3dhResult.rootKey,
x3dhResult.remoteIdentityKey,
x3dhResult.remoteSignedPreKey,
)
storage.saveSession(address, session)
storage.saveTrustedIdentity(address, x3dhResult.remoteIdentityKey)
pendingX3DH[address] = PendingX3DH(
ephemeralPublicKey = x3dhResult.ephemeralPublicKey,
signedPreKeyId = x3dhResult.signedPreKeyId,
preKeyId = x3dhResult.preKeyId,
identityDHKey = id.dhPublicKey,
registrationId = registrationId,
)
}
suspend fun encrypt(address: String, plaintext: ByteArray): ShadeEnvelope {
val session = storage.getSession(address)
?: throw IllegalStateException("No session for $address")
val ratchetMsg = ratchetEncrypt(crypto, session, plaintext)
val pending = pendingX3DH.remove(address)
if (pending != null) {
storage.saveSession(address, session)
val preKeyMsg = PreKeyMessage(
registrationId = pending.registrationId,
preKeyId = pending.preKeyId,
signedPreKeyId = pending.signedPreKeyId,
ephemeralKey = pending.ephemeralPublicKey,
identityDHKey = pending.identityDHKey,
message = ratchetMsg,
)
return ShadeEnvelope(
type = ShadeEnvelope.EnvelopeType.PREKEY,
content = preKeyMsg,
timestamp = System.currentTimeMillis(),
senderAddress = address,
)
}
storage.saveSession(address, session)
return ShadeEnvelope(
type = ShadeEnvelope.EnvelopeType.RATCHET,
content = ratchetMsg,
timestamp = System.currentTimeMillis(),
senderAddress = address,
)
}
suspend fun decrypt(address: String, envelope: ShadeEnvelope): ByteArray {
return when (envelope.type) {
ShadeEnvelope.EnvelopeType.PREKEY -> decryptPreKeyMessage(address, envelope.content as PreKeyMessage)
ShadeEnvelope.EnvelopeType.RATCHET -> decryptRatchetMessage(address, envelope.content as RatchetMessage)
}
}
private suspend fun decryptPreKeyMessage(address: String, message: PreKeyMessage): ByteArray {
val id = identity ?: throw IllegalStateException("Not initialized")
val spk = storage.getSignedPreKey(message.signedPreKeyId)
?: throw IllegalStateException("Signed prekey ${message.signedPreKeyId} not found")
val oneTimePrivate: ByteArray? = message.preKeyId?.let { keyId ->
val otpk = storage.getOneTimePreKey(keyId)
?: throw IllegalStateException("One-time prekey $keyId not found")
storage.removeOneTimePreKey(keyId)
otpk.keyPair.privateKey
}
val x3dhResult = processPreKeyMessage(
crypto,
id,
spk.keyPair.privateKey,
oneTimePrivate,
message,
)
val session = initReceiverSession(
rootKey = x3dhResult.rootKey,
remoteIdentityKey = x3dhResult.remoteIdentityKey,
localDHKeyPair = spk.keyPair,
)
val plaintext = ratchetDecrypt(crypto, session, message.message)
storage.saveSession(address, session)
storage.saveTrustedIdentity(address, x3dhResult.remoteIdentityKey)
return plaintext
}
private suspend fun decryptRatchetMessage(address: String, message: RatchetMessage): ByteArray {
val session = storage.getSession(address)
?: throw IllegalStateException("No session for $address")
val plaintext = ratchetDecrypt(crypto, session, message)
storage.saveSession(address, session)
return plaintext
}
}

View File

@@ -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
}

View File

@@ -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 }

View File

@@ -0,0 +1,36 @@
package no.zyon.shade.backup
import no.zyon.shade.crypto.CryptoProvider
/**
* Backup format v1 — passphrase-derived AES-256-GCM blob.
* Mirror @shade/sdk/backup.ts.
*
* backupKey = HKDF(passphrase_utf8, salt_random_32, info="ShadeBackupKey", 32)
* blob = AES-256-GCM(backupKey, plaintext, no AAD)
*
* The stored on-disk form is `{ version, salt(b64), nonce(b64), ciphertext(b64) }`.
* This file ships only the cryptographic primitives — payload schema and JSON
* serialization live alongside the high-level SDK and don't need a Kotlin port
* for vector parity (each platform builds the BackupBlob in its native idiom).
*
* NOTE: HKDF is NOT a proper password KDF. The TS SDK acknowledges this and
* warns users to choose a high-entropy passphrase. When `argon2id` lands in
* `CryptoProvider`, both ports swap together. Until then, byte-parity for the
* HKDF + AEAD layer is what V3.5 §sjekkpunkt 8 gates.
*/
private val BACKUP_INFO: ByteArray = "ShadeBackupKey".toByteArray(Charsets.UTF_8)
const val BACKUP_KEY_BYTES = 32
const val BACKUP_VERSION = 1
fun deriveBackupKey(crypto: CryptoProvider, passphrase: String, salt: ByteArray): ByteArray {
require(passphrase.length >= 12) { "Passphrase must be at least 12 characters" }
require(salt.size >= 16) { "salt must be at least 16 bytes" }
return crypto.hkdf(
passphrase.toByteArray(Charsets.UTF_8),
salt,
BACKUP_INFO,
BACKUP_KEY_BYTES,
)
}

View File

@@ -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)
}

View File

@@ -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")

View File

@@ -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) }
}

View File

@@ -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,
)
}

View File

@@ -0,0 +1,67 @@
package no.zyon.shade.crypto
/**
* Platform-agnostic crypto primitives. Mirror @shade/core/crypto.ts.
*
* All implementations must produce byte-identical output to the
* TypeScript version for the same inputs.
*/
interface CryptoProvider {
// ─── X25519 ────────────────────────────────────────────────
/** Generate an X25519 keypair (32-byte public + 32-byte private) */
fun generateX25519KeyPair(): Pair<ByteArray, ByteArray> // (public, private)
/** X25519 Diffie-Hellman: returns 32-byte shared secret */
fun x25519(privateKey: ByteArray, publicKey: ByteArray): ByteArray
// ─── Ed25519 ───────────────────────────────────────────────
/** Generate an Ed25519 keypair */
fun generateEd25519KeyPair(): Pair<ByteArray, ByteArray>
/** Sign message with Ed25519 — returns 64-byte signature */
fun sign(privateKey: ByteArray, message: ByteArray): ByteArray
/** Verify Ed25519 signature — returns true if valid */
fun verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean
// ─── AES-256-GCM ──────────────────────────────────────────
/** Encrypt with AES-256-GCM. Generates random 12-byte nonce. */
fun aesGcmEncrypt(
key: ByteArray,
plaintext: ByteArray,
aad: ByteArray? = null,
): Pair<ByteArray, ByteArray> // (ciphertext, nonce)
/** Decrypt AES-256-GCM. Throws on authentication failure. */
fun aesGcmDecrypt(
key: ByteArray,
ciphertext: ByteArray,
nonce: ByteArray,
aad: ByteArray? = null,
): ByteArray
// ─── Key Derivation ────────────────────────────────────────
/** HKDF-SHA256: derive `length` bytes */
fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray
/** HMAC-SHA256: 32-byte MAC */
fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray
// ─── Random ────────────────────────────────────────────────
fun randomBytes(length: Int): ByteArray
fun randomUint32(): Int
// ─── Hardening ─────────────────────────────────────────────
/** Constant-time byte array comparison */
fun constantTimeEqual(a: ByteArray, b: ByteArray): Boolean
/** Overwrite a buffer with zeros */
fun zeroize(buf: ByteArray)
}

View File

@@ -0,0 +1,124 @@
package no.zyon.shade.crypto
import com.google.crypto.tink.subtle.Ed25519Sign
import com.google.crypto.tink.subtle.Ed25519Verify
import com.google.crypto.tink.subtle.Hkdf
import com.google.crypto.tink.subtle.X25519
import java.nio.ByteBuffer
import java.security.SecureRandom
import javax.crypto.Cipher
import javax.crypto.Mac
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/**
* CryptoProvider backed by Google Tink + javax.crypto.
*
* Must produce byte-identical output to @shade/crypto-web for the same
* inputs, otherwise cross-platform messaging breaks.
*/
class TinkProvider : CryptoProvider {
private val random = SecureRandom()
// ─── X25519 ────────────────────────────────────────────────
override fun generateX25519KeyPair(): Pair<ByteArray, ByteArray> {
val privateKey = X25519.generatePrivateKey()
val publicKey = X25519.publicFromPrivate(privateKey)
return publicKey to privateKey
}
override fun x25519(privateKey: ByteArray, publicKey: ByteArray): ByteArray {
return X25519.computeSharedSecret(privateKey, publicKey)
}
// ─── Ed25519 ───────────────────────────────────────────────
override fun generateEd25519KeyPair(): Pair<ByteArray, ByteArray> {
val keyPair = Ed25519Sign.KeyPair.newKeyPair()
return keyPair.publicKey to keyPair.privateKey
}
override fun sign(privateKey: ByteArray, message: ByteArray): ByteArray {
val signer = Ed25519Sign(privateKey)
return signer.sign(message)
}
override fun verify(publicKey: ByteArray, message: ByteArray, signature: ByteArray): Boolean {
return try {
Ed25519Verify(publicKey).verify(signature, message)
true
} catch (_: Exception) {
false
}
}
// ─── AES-256-GCM ──────────────────────────────────────────
override fun aesGcmEncrypt(
key: ByteArray,
plaintext: ByteArray,
aad: ByteArray?,
): Pair<ByteArray, ByteArray> {
val nonce = randomBytes(12)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(128, nonce)
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), spec)
if (aad != null) cipher.updateAAD(aad)
val ciphertext = cipher.doFinal(plaintext)
return ciphertext to nonce
}
override fun aesGcmDecrypt(
key: ByteArray,
ciphertext: ByteArray,
nonce: ByteArray,
aad: ByteArray?,
): ByteArray {
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(128, nonce)
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), spec)
if (aad != null) cipher.updateAAD(aad)
return cipher.doFinal(ciphertext)
}
// ─── Key Derivation ────────────────────────────────────────
override fun hkdf(ikm: ByteArray, salt: ByteArray, info: ByteArray, length: Int): ByteArray {
return Hkdf.computeHkdf("HMACSHA256", ikm, salt, info, length)
}
override fun hmacSha256(key: ByteArray, data: ByteArray): ByteArray {
val mac = Mac.getInstance("HmacSHA256")
mac.init(SecretKeySpec(key, "HmacSHA256"))
return mac.doFinal(data)
}
// ─── Random ────────────────────────────────────────────────
override fun randomBytes(length: Int): ByteArray {
val buf = ByteArray(length)
random.nextBytes(buf)
return buf
}
override fun randomUint32(): Int {
val buf = randomBytes(4)
return ByteBuffer.wrap(buf).int
}
// ─── Hardening ─────────────────────────────────────────────
override fun constantTimeEqual(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
}
override fun zeroize(buf: ByteArray) {
buf.fill(0)
}
}

View File

@@ -0,0 +1,40 @@
package no.zyon.shade.fingerprint
import no.zyon.shade.crypto.CryptoProvider
/**
* Safety number computation. Must produce byte-identical output
* to @shade/core/fingerprint.ts.
*
* Format: 12 groups of 5 decimal digits.
* Derived from: HKDF-SHA256(signingKey||dhKey, salt=32 zeros, info="ShadeFingerprint", 30)
* then interpret each 2-byte pair as a 16-bit unsigned int mod 10^5.
*
* Note: the TS version uses only the first 24 bytes (2 bytes × 12 groups),
* not all 30. We mirror that here.
*/
fun computeFingerprint(
crypto: CryptoProvider,
signingPublicKey: ByteArray,
dhPublicKey: ByteArray,
): String {
val combined = ByteArray(signingPublicKey.size + dhPublicKey.size)
signingPublicKey.copyInto(combined, 0)
dhPublicKey.copyInto(combined, signingPublicKey.size)
val salt = ByteArray(32)
val info = "ShadeFingerprint".toByteArray(Charsets.UTF_8)
val hash = crypto.hkdf(combined, salt, info, 30)
val groups = mutableListOf<String>()
for (i in 0 until 12) {
val offset = i * 2
val value = ((hash[offset].toInt() and 0xff) shl 8) or (hash[offset + 1].toInt() and 0xff)
groups.add(value.toString().padStart(5, '0'))
}
return groups.joinToString(" ")
}
fun shortFingerprint(full: String): String {
return full.split(" ").take(4).joinToString(" ")
}

View File

@@ -0,0 +1,77 @@
package no.zyon.shade.group
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.protocol.kdfChainKey
import java.nio.ByteBuffer
/**
* Group sender-keys (Sesame). Mirror @shade/core/sender-keys.ts.
*
* Each sender maintains a chain key that ratchets forward with `kdfChainKey`
* — same primitive the Double Ratchet uses for its symmetric chain. Per-message
* AEAD AAD binds (groupId, senderAddress, iteration) so a captured ciphertext
* cannot be replayed under a different sender or group:
*
* aad = u16_be(groupIdLen) || groupId || u16_be(senderAddrLen) || senderAddr || u32_be(iteration)
*
* Each ciphertext is signed by the sender's Ed25519 key over `aad || ciphertext`,
* which is what receivers verify before advancing their chain.
*/
data class SenderKeyMessage(
val senderAddress: String,
val iteration: Int,
val ciphertext: ByteArray,
val nonce: ByteArray,
val signature: ByteArray,
)
fun encodeSenderHeader(groupId: String, senderAddress: String, iteration: Int): ByteArray {
val gBytes = groupId.toByteArray(Charsets.UTF_8)
val sBytes = senderAddress.toByteArray(Charsets.UTF_8)
require(gBytes.size <= 0xFFFF) { "groupId too long (>65535 UTF-8 bytes)" }
require(sBytes.size <= 0xFFFF) { "senderAddress too long (>65535 UTF-8 bytes)" }
val out = ByteArray(2 + gBytes.size + 2 + sBytes.size + 4)
val buf = ByteBuffer.wrap(out)
buf.putShort(gBytes.size.toShort())
buf.put(gBytes)
buf.putShort(sBytes.size.toShort())
buf.put(sBytes)
buf.putInt(iteration)
return out
}
/**
* Compute (newChainKey, messageKey, aad) for the next group message.
* Pure function; caller is responsible for state advancement and the AEAD/sign
* steps (which need access to the signing private key not exposed here).
*/
data class SenderStepResult(
val newChainKey: ByteArray,
val messageKey: ByteArray,
val aad: ByteArray,
)
fun senderKeyStep(
crypto: CryptoProvider,
chainKey: ByteArray,
groupId: String,
senderAddress: String,
iteration: Int,
): SenderStepResult {
val r = kdfChainKey(crypto, chainKey)
val aad = encodeSenderHeader(groupId, senderAddress, iteration)
return SenderStepResult(newChainKey = r.newChainKey, messageKey = r.messageKey, aad = aad)
}
/**
* Concatenate `aad || ciphertext` — the byte string the sender signs and the
* receiver verifies. Exposed as a helper so vector parity can pin both sides.
*/
fun senderSignedBytes(aad: ByteArray, ciphertext: ByteArray): ByteArray {
val out = ByteArray(aad.size + ciphertext.size)
aad.copyInto(out, 0)
ciphertext.copyInto(out, aad.size)
return out
}

View File

@@ -0,0 +1,82 @@
package no.zyon.shade.media
import no.zyon.shade.serialization.stringifyJson
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.nio.ByteBuffer
import java.nio.charset.CharacterCodingException
import java.nio.charset.CodingErrorAction
/**
* Albums — mirror of `@shade/media/src/album.ts`. An album is a sealed file
* whose plaintext lists grants (films, pictures, nested albums, live
* channels), so one link opens them all and the relay cannot tell it from
* any other file.
*/
const val ALBUM_KIND = "shade.album/v1"
const val ALBUM_MIME = "application/vnd.shade.album+json"
const val MAX_ALBUM_ITEMS = 10_000
private const val MAX_TITLE = 512
private const val MAX_ALBUM_BYTES = 16L * 1024 * 1024
class Album(val title: String, val items: List<Grant>)
object Albums {
/** An album's plaintext, byte for byte what TS `encodeAlbum` writes. */
fun encode(album: Album): ByteArray {
if (album.title.length > MAX_TITLE) throw MediaFormatException("album title longer than $MAX_TITLE characters")
if (album.items.size > MAX_ALBUM_ITEMS) throw MediaFormatException("album holds more than $MAX_ALBUM_ITEMS items")
val o = LinkedHashMap<String, Any>()
o["kind"] = ALBUM_KIND
o["title"] = album.title
o["items"] = album.items.map { it.toJsonMap() }
return stringifyJson(o).toByteArray(Charsets.UTF_8)
}
/** The meta an album is sealed with: its type, and the title as its name. */
fun meta(title: String) = MediaMeta(mime = ALBUM_MIME, name = title)
/** Parse an album's plaintext, strictly: every item must be a valid grant. */
fun parse(bytes: ByteArray): Album {
val text = try {
Charsets.UTF_8.newDecoder()
.onMalformedInput(CodingErrorAction.REPORT)
.onUnmappableCharacter(CodingErrorAction.REPORT)
.decode(ByteBuffer.wrap(bytes)).toString()
} catch (e: CharacterCodingException) {
throw MediaFormatException("album is not UTF-8")
}
val o = try { JSONObject(text) } catch (e: JSONException) { throw MediaFormatException("album is not a JSON object") }
if (o.opt("kind") != ALBUM_KIND) throw MediaFormatException("not an album (kind ${o.opt("kind")})")
val title = o.opt("title") as? String ?: throw MediaFormatException("album.title must be a string")
if (title.length > MAX_TITLE) throw MediaFormatException("album title longer than $MAX_TITLE characters")
val items = o.opt("items") as? JSONArray ?: throw MediaFormatException("album.items must be an array")
if (items.length() > MAX_ALBUM_ITEMS) throw MediaFormatException("album holds more than $MAX_ALBUM_ITEMS items")
return Album(
title,
(0 until items.length()).map { i ->
val item = items.opt(i) as? JSONObject ?: throw MediaFormatException("album item $i is not a grant")
try {
Grants.parse(item.toString())
} catch (e: MediaFormatException) {
throw MediaFormatException("album item $i: ${e.message}")
}
},
)
}
/** The items of an album already opened as a reader. */
fun read(reader: MediaReader): Album {
if (reader.meta.mime != ALBUM_MIME) throw MediaFormatException("not an album (${reader.meta.mime ?: "no type"})")
if (reader.size > MAX_ALBUM_BYTES) throw MediaFormatException("album larger than 16 MiB")
return parse(reader.read(0, reader.size.toInt()))
}
/** Does this grant's meta preview name an album? */
fun isAlbum(grant: Grant): Boolean = when (grant) {
is MediaGrant -> grant.meta?.mime == ALBUM_MIME
is LiveGrant -> false
}
}

View File

@@ -0,0 +1,338 @@
package no.zyon.shade.media
import com.google.crypto.tink.subtle.Ed25519Sign
import com.google.crypto.tink.subtle.Ed25519Verify
import com.google.crypto.tink.subtle.Hkdf
import java.nio.ByteBuffer
import java.security.GeneralSecurityException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
/**
* Live channels — mirror of `@shade/media/src/live/{frame,channel}.ts`.
*
* SLF1 frame: 48-byte header ("SLF1", ver, flags, 0 0, channelId(16),
* epoch u32, seq u64, timestamp u64, ctLen u32) ‖ AES-256-GCM(ct‖tag, aad =
* header) ‖ Ed25519 signature over everything before it.
*
* Keys: Sender Keys. ck[0]/stickyKey from the epoch seed; mk[i] = HMAC(ck[i],
* 01) used once; ck[i+1] = HMAC(ck[i], 02). Every frame is signed by the
* channel key, so a viewer (who holds the chain) cannot forge to another.
*/
class LiveKeyException(message: String) : Exception(message)
const val SLF_HEADER_BYTES = 48
const val SLF_SIGNATURE_BYTES = 64
const val FLAG_STICKY = 0x01
const val FLAG_KEYFRAME = 0x02
const val FLAG_END = 0x04
const val LIVE_MAX_SKIP = 100_000L
const val LIVE_MAX_SKIPPED_KEYS = 2_000
const val LIVE_MAX_FRAME_PAYLOAD = 16 * 1024 * 1024
private val SLF_MAGIC = byteArrayOf(0x53, 0x4c, 0x46, 0x31)
private val INFO_CHAIN = "shade-live/v1\u0000chain".toByteArray(Charsets.UTF_8)
private val INFO_STICKY = "shade-live/v1\u0000sticky".toByteArray(Charsets.UTF_8)
private val INFO_EPOCH = "shade-live/v1\u0000epoch".toByteArray(Charsets.UTF_8)
class EpochKeys(val chainKey: ByteArray, val stickyKey: ByteArray)
fun epochKeys(epochSeed: ByteArray, channelId: ByteArray, epoch: Long): EpochKeys {
val salt = channelId + u32(epoch)
return EpochKeys(
Hkdf.computeHkdf("HMACSHA256", epochSeed, salt, INFO_CHAIN, 32),
Hkdf.computeHkdf("HMACSHA256", epochSeed, salt, INFO_STICKY, 32),
)
}
fun linkEpochSeed(channelSecret: ByteArray, channelId: ByteArray, epoch: Long): ByteArray =
Hkdf.computeHkdf("HMACSHA256", channelSecret, channelId, INFO_EPOCH + u32(epoch), 32)
private fun hmac(key: ByteArray, data: ByteArray): ByteArray =
Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data)
/** One chain step: (message key for this seq, chain key for the next). */
fun chainStep(ck: ByteArray): Pair<ByteArray, ByteArray> = hmac(ck, byteArrayOf(1)) to hmac(ck, byteArrayOf(2))
fun frameNonce(epoch: Long, seq: Long): ByteArray = u32(epoch) + u64(seq)
/** What a frame carries — mirror of the TS `LiveContent` union. */
sealed class LiveContent {
data class Text(val text: String) : LiveContent()
class Binary(val bytes: ByteArray) : LiveContent()
class Init(val mime: String, val bytes: ByteArray) : LiveContent()
class Chunk(val bytes: ByteArray) : LiveContent()
class Image(val mime: String, val bytes: ByteArray) : LiveContent()
data class Meta(val meta: MediaMeta) : LiveContent()
object End : LiveContent()
fun encode(): ByteArray = when (this) {
is Text -> byteArrayOf(1) + text.toByteArray(Charsets.UTF_8)
is Binary -> byteArrayOf(2) + bytes
is Init -> withMime(3, mime, bytes)
is Chunk -> byteArrayOf(4) + bytes
is Image -> withMime(5, mime, bytes)
is Meta -> byteArrayOf(6) + MediaMeta.validate(meta).toJson().toByteArray(Charsets.UTF_8)
End -> byteArrayOf(7)
}
companion object {
private fun withMime(kind: Int, mime: String, bytes: ByteArray): ByteArray {
val m = mime.toByteArray(Charsets.UTF_8)
if (m.isEmpty() || m.size > 255) throw MediaFormatException("mime must be 1–255 bytes")
return byteArrayOf(kind.toByte(), m.size.toByte()) + m + bytes
}
fun decode(p: ByteArray): LiveContent {
if (p.isEmpty()) throw MediaFormatException("empty live payload")
val body = p.copyOfRange(1, p.size)
fun mimeBody(): Pair<String, ByteArray> {
val n = body.firstOrNull()?.toInt()?.and(0xff) ?: throw MediaFormatException("bad mime prefix")
if (n == 0 || body.size < 1 + n) throw MediaFormatException("bad mime prefix")
return String(body, 1, n, Charsets.UTF_8) to body.copyOfRange(1 + n, body.size)
}
return when (p[0].toInt()) {
1 -> Text(String(body, Charsets.UTF_8))
2 -> Binary(body)
3 -> mimeBody().let { Init(it.first, it.second) }
4 -> Chunk(body)
5 -> mimeBody().let { Image(it.first, it.second) }
6 -> Meta(MediaMeta.fromJson(String(body, Charsets.UTF_8)))
7 -> End
else -> throw MediaFormatException("unknown live content kind ${p[0]}")
}
}
}
}
class FrameHeader(val flags: Int, val channelId: ByteArray, val epoch: Long, val seq: Long, val timestamp: Long, val ctLen: Int) {
fun encode(): ByteArray = ByteBuffer.allocate(SLF_HEADER_BYTES)
.put(SLF_MAGIC).put(1).put(flags.toByte()).put(0).put(0)
.put(channelId).putInt(epoch.toInt()).putLong(seq).putLong(timestamp).putInt(ctLen)
.array()
}
class DecodedFrame(val header: FrameHeader, val headerBytes: ByteArray, val ciphertext: ByteArray, val signed: ByteArray, val signature: ByteArray)
fun decodeFrame(frame: ByteArray): DecodedFrame {
if (frame.size < SLF_HEADER_BYTES + TAG_BYTES + SLF_SIGNATURE_BYTES) throw MediaFormatException("live frame too short")
if (!frame.copyOfRange(0, 4).contentEquals(SLF_MAGIC)) throw MediaFormatException("not an SLF1 frame")
if (frame[4].toInt() != 1) throw MediaFormatException("unsupported SLF version ${frame[4]}")
val flags = frame[5].toInt() and 0xff
if (flags and (FLAG_STICKY or FLAG_KEYFRAME or FLAG_END).inv() != 0 || frame[6].toInt() != 0 || frame[7].toInt() != 0) {
throw MediaFormatException("unknown SLF flags or reserved bytes")
}
val bb = ByteBuffer.wrap(frame)
val ctLen = bb.getInt(44)
if (ctLen < TAG_BYTES || ctLen > LIVE_MAX_FRAME_PAYLOAD + 17) throw MediaFormatException("bad ctLen")
if (frame.size != SLF_HEADER_BYTES + ctLen + SLF_SIGNATURE_BYTES) throw MediaFormatException("live frame length does not match its header")
val seq = bb.getLong(28)
val ts = bb.getLong(36)
if (seq < 0 || seq > (1L shl 53) || ts < 0) throw MediaFormatException("u64 field exceeds 2^53")
return DecodedFrame(
FrameHeader(flags, frame.copyOfRange(8, 24), bb.getInt(24).toLong() and 0xffff_ffffL, seq, ts, ctLen),
frame.copyOfRange(0, SLF_HEADER_BYTES),
frame.copyOfRange(SLF_HEADER_BYTES, SLF_HEADER_BYTES + ctLen),
frame.copyOfRange(0, SLF_HEADER_BYTES + ctLen),
frame.copyOfRange(SLF_HEADER_BYTES + ctLen, frame.size),
)
}
class ReceivedFrame(val epoch: Long, val seq: Long, val timestamp: Long, val sticky: Boolean, val keyframe: Boolean, val content: LiveContent)
/**
* Viewing side. Feed frames in any order; each is returned once, or `null`
* for a harmless drop (a duplicate, or backlog before the grant's start).
* Throws on a forgery. Not thread-safe: call from one thread (the socket's).
*/
class LiveSubscriber(grant: LiveGrant) {
val channelId: ByteArray = grant.channelId
val signingKey: ByteArray = grant.signingKey
private val verifier = Ed25519Verify(grant.signingKey)
private class EpochState(val stickyKey: ByteArray, var nextSeq: Long, var chainKey: ByteArray) {
val skipped = LinkedHashMap<Long, ByteArray>()
val stickySeen = HashSet<Long>()
}
private val epochs = HashMap<Long, EpochState>()
private var link: Pair<ByteArray, Long>? = null
init {
addGrant(grant)
}
fun addGrant(g: LiveGrant) {
if (!g.channelId.contentEquals(channelId)) throw MediaFormatException("grant is for another channel")
if (!g.signingKey.contentEquals(signingKey)) throw MediaIntegrityException("grant changes the channel signing key")
g.channelSecret?.let { s -> if (link == null || g.epoch < link!!.second) link = s.copyOf() to g.epoch }
val existing = epochs[g.epoch]
if (existing != null && existing.nextSeq <= g.seq) return
epochs[g.epoch] = EpochState(g.stickyKey.copyOf(), g.seq, g.chainKey.copyOf())
}
fun forgetBefore(epoch: Long) {
val it = epochs.entries.iterator()
while (it.hasNext()) {
val (e, st) = it.next()
if (e < epoch) {
st.chainKey.fill(0)
st.stickyKey.fill(0)
st.skipped.values.forEach { k -> k.fill(0) }
it.remove()
}
}
}
/** Wipe every key held; the subscriber opens nothing afterwards. */
fun close() {
forgetBefore(Long.MAX_VALUE)
link?.first?.fill(0)
link = null
}
private fun epochState(epoch: Long): EpochState? {
epochs[epoch]?.let { return it }
val (secret, from) = link ?: return null
if (epoch < from) return null
val k = epochKeys(linkEpochSeed(secret, channelId, epoch), channelId, epoch)
val st = EpochState(k.stickyKey, 0, k.chainKey)
epochs[epoch] = st
forgetBefore(epoch)
return st
}
fun open(frame: ByteArray): ReceivedFrame? {
val f = decodeFrame(frame)
val h = f.header
if (!h.channelId.contentEquals(channelId)) throw MediaFormatException("frame is for another channel")
try {
verifier.verify(f.signature, f.signed)
} catch (e: GeneralSecurityException) {
throw MediaIntegrityException("live frame signature does not verify")
}
val st = epochState(h.epoch) ?: throw LiveKeyException("no grant for epoch ${h.epoch}")
val sticky = h.flags and FLAG_STICKY != 0
val nonce = frameNonce(h.epoch, h.seq)
val plain = if (sticky) {
if (!st.stickySeen.add(h.seq)) return null
gcmOpen(st.stickyKey, nonce, f.ciphertext, f.headerBytes)
} else {
val mk = messageKey(st, h.seq) ?: return null
try {
gcmOpen(mk, nonce, f.ciphertext, f.headerBytes)
} finally {
mk.fill(0)
}
}
return ReceivedFrame(h.epoch, h.seq, h.timestamp, sticky, h.flags and FLAG_KEYFRAME != 0, LiveContent.decode(plain))
}
private fun messageKey(st: EpochState, seq: Long): ByteArray? {
if (seq < st.nextSeq) return st.skipped.remove(seq)
if (seq - st.nextSeq > LIVE_MAX_SKIP) throw LiveKeyException("frame $seq is ${seq - st.nextSeq} ahead — beyond MAX_SKIP")
var ck = st.chainKey
for (s in st.nextSeq until seq) {
val (mk, next) = chainStep(ck)
ck.fill(0)
ck = next
if (seq - s <= LIVE_MAX_SKIPPED_KEYS) {
st.skipped[s] = mk
if (st.skipped.size > LIVE_MAX_SKIPPED_KEYS) {
val oldest = st.skipped.keys.first()
st.skipped.remove(oldest)?.fill(0)
}
} else {
mk.fill(0)
}
}
val (mk, next) = chainStep(ck)
ck.fill(0)
st.chainKey = next
st.nextSeq = seq + 1
return mk
}
}
/**
* Sending side — a phone streaming its camera or its own logs. Mirror of the
* TS `LivePublisher` (link mode supported). Not thread-safe; frames are
* numbered in call order.
*/
class LivePublisher(
val channelId: ByteArray,
private val signingSeed: ByteArray,
private val channelSecret: ByteArray?,
startEpoch: Long = 0,
private val snapshotLimit: Int = 64,
) {
private val signer = Ed25519Sign(signingSeed)
val signingKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(signingSeed).publicKey
var epoch: Long = startEpoch
private set
private var seq = 0L
private var chainKey: ByteArray
private var stickyKey: ByteArray
private val snapshots = ArrayDeque<Pair<Long, ByteArray>>()
private val stickyContent = ArrayList<Pair<LiveContent, Boolean>>()
init {
require(channelId.size == 16) { "channelId must be 16 bytes" }
val k = epochKeys(seedFor(epoch), channelId, epoch)
chainKey = k.chainKey
stickyKey = k.stickyKey
}
private fun seedFor(e: Long): ByteArray =
channelSecret?.let { linkEpochSeed(it, channelId, e) } ?: ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }
fun frame(content: LiveContent, keyframe: Boolean = false, sticky: Boolean = false, timestamp: Long = System.currentTimeMillis()): ByteArray {
val plain = content.encode()
if (plain.size > LIVE_MAX_FRAME_PAYLOAD) throw MediaFormatException("live frame payload too large")
val s = seq++
var flags = 0
if (sticky) flags = flags or FLAG_STICKY
if (keyframe) flags = flags or FLAG_KEYFRAME
if (content is LiveContent.End) flags = flags or FLAG_END
if (keyframe && !sticky) {
snapshots.addLast(s to chainKey.copyOf())
while (snapshots.size > snapshotLimit) snapshots.removeFirst().second.fill(0)
}
val (mk, next) = chainStep(chainKey)
chainKey.fill(0)
chainKey = next
val header = FrameHeader(flags, channelId, epoch, s, timestamp, plain.size + TAG_BYTES).encode()
val ct = gcmSeal(if (sticky) stickyKey else mk, frameNonce(epoch, s), plain, header)
mk.fill(0)
val signed = header + ct
if (sticky) stickyContent += content to keyframe
return signed + signer.sign(signed)
}
fun grant(from: String = "oldest", link: Boolean = false, url: String? = null, readToken: ByteArray? = null): LiveGrant {
val (s, ck) = when {
from == "now" || snapshots.isEmpty() -> seq to chainKey
from == "latest" -> snapshots.last()
else -> snapshots.first()
}
if (link && channelSecret == null) throw IllegalStateException("link grants need a channelSecret")
return LiveGrant(channelId, signingKey, epoch, s, ck.copyOf(), stickyKey.copyOf(), url, readToken, null, if (link) channelSecret!!.copyOf() else null)
}
/** New epoch; returns the sticky frames resealed for it — send them first. */
fun rotate(timestamp: Long = System.currentTimeMillis()): List<ByteArray> {
epoch++
seq = 0
snapshots.forEach { it.second.fill(0) }
snapshots.clear()
chainKey.fill(0)
stickyKey.fill(0)
val k = epochKeys(seedFor(epoch), channelId, epoch)
chainKey = k.chainKey
stickyKey = k.stickyKey
val content = stickyContent.toList()
stickyContent.clear()
return content.map { (c, kf) -> frame(c, keyframe = kf, sticky = true, timestamp = timestamp) }
}
}

View File

@@ -0,0 +1,330 @@
package no.zyon.shade.media
import com.google.crypto.tink.subtle.Hkdf
import no.zyon.shade.serialization.stringifyJson
import org.json.JSONException
import org.json.JSONObject
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.security.SecureRandom
import javax.crypto.AEADBadTagException
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/**
* SMF1 — Shade Media Format v1, mirror of `@shade/media/src/sealed.ts`.
* The cross-language contract is `docs/media.md`; vectors in
* `test-vectors/media.json`.
*
* segment[0] … segment[n-1] AES-256-GCM, `segmentSize` plaintext each
* meta AES-256-GCM over UTF-8 JSON
* table n × SHA-256(segment bytes)
* footer (64) "SMF1" · ver · flags · 0 0 · segSize u32 ·
* plainSize u64 · metaLen u32 · mediaId(16) ·
* 20 × 0 · "SMF1"
*/
class MediaFormatException(message: String) : Exception(message)
/** Bytes failed authentication — a store or another key holder changed them. */
class MediaIntegrityException(message: String) : Exception(message)
val SMF_MAGIC = byteArrayOf(0x53, 0x4d, 0x46, 0x31)
const val SMF_VERSION = 1
const val FOOTER_BYTES = 64
const val DIGEST_BYTES = 32
const val TAG_BYTES = 16
const val MEDIA_ID_BYTES = 16
const val MEDIA_KEY_BYTES = 32
const val DEFAULT_SEGMENT_SIZE = 1024 * 1024
const val MIN_SEGMENT_SIZE = 4 * 1024
const val MAX_SEGMENT_SIZE = 16 * 1024 * 1024
const val MAX_META_BYTES = 64 * 1024
private val INFO_SEGMENT = "shade-media/v1\u0000segment".toByteArray(Charsets.UTF_8)
private val INFO_META = "shade-media/v1\u0000meta".toByteArray(Charsets.UTF_8)
private val AAD_META_PREFIX = "SMF1-meta".toByteArray(Charsets.UTF_8)
/**
* Sealed metadata. Numbers are whole (milliseconds, pixels): the TS writer
* would accept a fraction, but JSON number formatting is not something two
* languages agree on byte for byte, and nothing here needs one.
*/
data class MediaMeta(
val mime: String? = null,
val name: String? = null,
val durationMs: Long? = null,
val width: Long? = null,
val height: Long? = null,
val createdAt: Long? = null,
val extra: Map<String, String>? = null,
) {
/** `JSON.stringify` of the TS-validated object — same key order, same bytes. */
fun toJson(): String = stringifyJson(toJsonMap())
/** The fields in `toJson`'s order, for embedding in a larger JSON (a grant). */
internal fun toJsonMap(): Map<String, Any> {
val m = LinkedHashMap<String, Any>()
mime?.let { m["mime"] = it }
name?.let { m["name"] = it }
durationMs?.let { m["durationMs"] = it }
width?.let { m["width"] = it }
height?.let { m["height"] = it }
createdAt?.let { m["createdAt"] = it }
extra?.let { m["extra"] = LinkedHashMap(it) }
return m
}
companion object {
private val MIME_RE = Regex("""^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?:;[ -~]{0,200})?$""", RegexOption.IGNORE_CASE)
fun validate(m: MediaMeta): MediaMeta {
m.mime?.let { if (!MIME_RE.matches(it)) throw MediaFormatException("bad mime") }
m.name?.let { n ->
if (n.length > 1024 || n.any { it.code < 0x20 || it.code == 0x7f }) throw MediaFormatException("bad name")
}
listOf(m.durationMs, m.width, m.height, m.createdAt).forEach {
if (it != null && it < 0) throw MediaFormatException("negative number in meta")
}
return m
}
/** Parse strictly, like the TS reader: unknown shapes are refused, unknown keys ignored. */
fun fromJson(json: String): MediaMeta {
val o = try { JSONObject(json) } catch (e: JSONException) { throw MediaFormatException("meta is not a JSON object") }
fun str(k: String): String? = if (!o.has(k)) null else (o.get(k) as? String ?: throw MediaFormatException("bad $k"))
fun num(k: String): Long? {
if (!o.has(k)) return null
val v = o.get(k) as? Number ?: throw MediaFormatException("bad $k")
val d = v.toDouble()
if (d < 0 || d.isNaN() || d.isInfinite()) throw MediaFormatException("bad $k")
return v.toLong()
}
val extra = if (!o.has("extra")) null else {
val e = o.get("extra") as? JSONObject ?: throw MediaFormatException("extra must be an object of strings")
val out = LinkedHashMap<String, String>()
for (k in e.keys()) out[k] = e.get(k) as? String ?: throw MediaFormatException("extra values must be strings")
out
}
return validate(MediaMeta(str("mime"), str("name"), num("durationMs"), num("width"), num("height"), num("createdAt"), extra))
}
}
}
/** Raw subkeys of a media item: segment key and meta key. */
class MediaSubkeys(val segmentKey: ByteArray, val metaKey: ByteArray)
fun deriveMediaSubkeys(mediaKey: ByteArray, mediaId: ByteArray): MediaSubkeys {
if (mediaKey.size != MEDIA_KEY_BYTES) throw MediaFormatException("mediaKey must be 32 bytes")
if (mediaId.size != MEDIA_ID_BYTES) throw MediaFormatException("mediaId must be 16 bytes")
return MediaSubkeys(
Hkdf.computeHkdf("HMACSHA256", mediaKey, mediaId, INFO_SEGMENT, 32),
Hkdf.computeHkdf("HMACSHA256", mediaKey, mediaId, INFO_META, 32),
)
}
internal fun u32(n: Long): ByteArray = ByteBuffer.allocate(4).putInt(n.toInt()).array()
internal fun u64(n: Long): ByteArray = ByteBuffer.allocate(8).putLong(n).array()
fun segmentNonce(index: Long): ByteArray = u32(0) + u64(index)
internal val META_NONCE: ByteArray = u32(1) + u64(0)
fun segmentAad(mediaId: ByteArray, index: Long, last: Boolean): ByteArray =
SMF_MAGIC + mediaId + u64(index) + byteArrayOf(if (last) 1 else 0)
internal fun metaAad(mediaId: ByteArray): ByteArray = AAD_META_PREFIX + mediaId
internal fun sha256(b: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(b)
/** AES-256-GCM with a caller-supplied nonce; returns ct‖tag (no nonce prefix). */
internal fun gcmSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {
val c = Cipher.getInstance("AES/GCM/NoPadding")
c.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
c.updateAAD(aad)
return c.doFinal(plaintext)
}
internal fun gcmOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray {
val c = Cipher.getInstance("AES/GCM/NoPadding")
c.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
c.updateAAD(aad)
return try {
c.doFinal(ciphertext)
} catch (e: AEADBadTagException) {
throw MediaIntegrityException("AEAD authentication failed")
}
}
internal fun ctEquals(a: ByteArray, b: ByteArray): Boolean = MessageDigest.isEqual(a, b)
class Footer(val segmentSize: Int, val plaintextSize: Long, val metaLen: Int, val mediaId: ByteArray) {
val segmentCount: Long get() = segmentCountFor(plaintextSize, segmentSize)
/** Offset and sealed length of segment `i`. */
fun span(i: Long): Pair<Long, Int> {
val n = segmentCount
val plain = if (i < n - 1) segmentSize.toLong() else plaintextSize - (n - 1) * segmentSize
return i * (segmentSize + TAG_BYTES) to (plain + TAG_BYTES).toInt()
}
val sealedSize: Long
get() = plaintextSize + segmentCount * TAG_BYTES + metaLen + segmentCount * DIGEST_BYTES + FOOTER_BYTES
fun encode(): ByteArray {
val b = ByteBuffer.allocate(FOOTER_BYTES)
b.put(SMF_MAGIC).put(SMF_VERSION.toByte()).put(0).put(0).put(0)
b.putInt(segmentSize).putLong(plaintextSize).putInt(metaLen).put(mediaId)
b.put(ByteArray(20)).put(SMF_MAGIC)
return b.array()
}
companion object {
fun decode(b: ByteArray): Footer {
if (b.size != FOOTER_BYTES) throw MediaFormatException("footer must be 64 bytes")
if (!b.copyOfRange(0, 4).contentEquals(SMF_MAGIC) || !b.copyOfRange(60, 64).contentEquals(SMF_MAGIC)) {
throw MediaFormatException("not an SMF1 file (bad magic)")
}
if (b[4].toInt() != SMF_VERSION) throw MediaFormatException("unsupported SMF version ${b[4]}")
if (b[5].toInt() != 0 || b[6].toInt() != 0 || b[7].toInt() != 0 || (40 until 60).any { b[it].toInt() != 0 }) {
throw MediaFormatException("unknown SMF flags or non-zero reserved bytes")
}
val bb = ByteBuffer.wrap(b)
val seg = bb.getInt(8)
if (seg < MIN_SEGMENT_SIZE || seg > MAX_SEGMENT_SIZE) throw MediaFormatException("segmentSize out of range: $seg")
val plain = bb.getLong(12)
if (plain < 0 || plain > (1L shl 53)) throw MediaFormatException("plaintext size out of range")
val metaLen = bb.getInt(20)
if (metaLen < TAG_BYTES || metaLen > MAX_META_BYTES + TAG_BYTES) throw MediaFormatException("metaLen out of range: $metaLen")
return Footer(seg, plain, metaLen, b.copyOfRange(24, 40))
}
}
}
fun segmentCountFor(plaintextSize: Long, segmentSize: Int): Long =
maxOf(1L, (plaintextSize + segmentSize - 1) / segmentSize)
class SealResult(
val mediaId: ByteArray,
val mediaKey: ByteArray,
val rootDigest: ByteArray,
val plaintextSize: Long,
val sealedSize: Long,
val segmentSize: Int,
val segmentCount: Long,
)
/**
* Incremental sealer — feed plaintext in any chunking, write out what it
* returns, in order. Constant memory (one segment). Mirror of the TS
* `MediaSealer`: a segment is held back until more input proves it is not
* the last one, because "last" is in its AAD.
*/
class MediaSealer private constructor(
val mediaId: ByteArray,
val mediaKey: ByteArray,
val segmentSize: Int,
meta: MediaMeta,
) {
constructor(meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE) :
this(random(MEDIA_ID_BYTES), random(MEDIA_KEY_BYTES), segmentSize, meta)
private val keys = deriveMediaSubkeys(mediaKey, mediaId)
private val metaJson = MediaMeta.validate(meta).toJson().toByteArray(Charsets.UTF_8)
private val pending = java.io.ByteArrayOutputStream()
private val digests = java.io.ByteArrayOutputStream()
private var index = 0L
private var plaintextSize = 0L
private var sealedSize = 0L
private var finished = false
init {
if (segmentSize < MIN_SEGMENT_SIZE || segmentSize > MAX_SEGMENT_SIZE) {
throw MediaFormatException("segmentSize out of range: $segmentSize")
}
if (metaJson.size > MAX_META_BYTES) throw MediaFormatException("meta too large")
}
fun push(chunk: ByteArray): List<ByteArray> {
check(!finished) { "push after finish" }
pending.write(chunk)
plaintextSize += chunk.size
val out = ArrayList<ByteArray>()
if (pending.size() > segmentSize) {
val all = pending.toByteArray()
var off = 0
while (all.size - off > segmentSize) {
out += sealSegment(all.copyOfRange(off, off + segmentSize), false)
off += segmentSize
}
pending.reset()
pending.write(all, off, all.size - off)
}
return out
}
fun finish(): Pair<List<ByteArray>, SealResult> {
check(!finished) { "finish called twice" }
finished = true
val last = sealSegment(pending.toByteArray(), true)
val metaBlock = gcmSeal(keys.metaKey, META_NONCE, metaJson, metaAad(mediaId))
val footer = Footer(segmentSize, plaintextSize, metaBlock.size, mediaId).encode()
val trailer = metaBlock + digests.toByteArray() + footer
sealedSize += trailer.size
keys.segmentKey.fill(0)
keys.metaKey.fill(0)
return listOf(last, trailer) to SealResult(mediaId, mediaKey, sha256(trailer), plaintextSize, sealedSize, segmentSize, index)
}
private fun sealSegment(plain: ByteArray, last: Boolean): ByteArray {
val i = index++
val sealed = gcmSeal(keys.segmentKey, segmentNonce(i), plain, segmentAad(mediaId, i, last))
digests.write(sha256(sealed))
sealedSize += sealed.size
return sealed
}
companion object {
private val rng = SecureRandom()
private fun random(n: Int) = ByteArray(n).also { rng.nextBytes(it) }
/** Pinned key and id — for cross-language vectors ONLY (nonces are per key). */
internal fun withPinnedKeys(mediaId: ByteArray, mediaKey: ByteArray, meta: MediaMeta, segmentSize: Int) =
MediaSealer(mediaId, mediaKey, segmentSize, meta)
/**
* Seal a stream (a film from the gallery, a recording) to `out`, one
* segment in memory at a time. Neither stream is closed.
*/
fun sealStream(
input: java.io.InputStream,
out: java.io.OutputStream,
meta: MediaMeta = MediaMeta(),
segmentSize: Int = DEFAULT_SEGMENT_SIZE,
): SealResult {
val sealer = MediaSealer(meta, segmentSize)
val buf = ByteArray(segmentSize)
while (true) {
val n = input.read(buf)
if (n < 0) break
if (n > 0) sealer.push(buf.copyOf(n)).forEach { out.write(it) }
}
val (rest, result) = sealer.finish()
rest.forEach { out.write(it) }
out.flush()
return result
}
/** Seal bytes already in memory. */
fun sealBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE): Pair<ByteArray, SealResult> =
MediaSealer(meta, segmentSize).sealAll(plaintext)
}
internal fun sealAll(plaintext: ByteArray): Pair<ByteArray, SealResult> {
val out = java.io.ByteArrayOutputStream()
push(plaintext).forEach { out.write(it) }
val (rest, result) = finish()
rest.forEach { out.write(it) }
return out.toByteArray() to result
}
}

View File

@@ -0,0 +1,158 @@
package no.zyon.shade.media
import no.zyon.shade.serialization.stringifyJson
import org.json.JSONException
import org.json.JSONObject
import java.net.URI
import java.util.Base64
/**
* Grants — mirror of `@shade/media/src/grant.ts`. A grant travels as a
* message over an existing Shade session, or in the `#shade=` fragment of a
* capability link. Parsing is strict: a field of the wrong size or shape is
* refused, never guessed at.
*/
const val MEDIA_GRANT_KIND = "shade.media-grant/v1"
const val LIVE_GRANT_KIND = "shade.live-grant/v1"
sealed class Grant {
/** The wire fields in TS `encodeGrant`'s order. */
internal abstract fun toJsonMap(): Map<String, Any>
/** Wire JSON, byte for byte what TS `encodeGrant` writes (field order fixed, meta canonical). */
fun encode(): String = stringifyJson(toJsonMap())
/** `pageUrl#shade=<base64url(json)>`: the link that opens it, the key in the fragment (never sent to a server). */
fun capabilityUrl(pageUrl: String): String =
"${pageUrl.substringBefore('#')}#shade=${b64u(encode().toByteArray(Charsets.UTF_8))}"
}
class MediaGrant(
val mediaId: ByteArray,
val mediaKey: ByteArray,
val rootDigest: ByteArray,
val url: String? = null,
val readToken: ByteArray? = null,
val meta: MediaMeta? = null,
) : Grant() {
fun keys() = MediaKeys(mediaId, mediaKey, rootDigest)
/** Range source for the granted file, with the read token attached. */
fun source(): HttpRangeSource {
val u = url ?: throw MediaFormatException("grant has no URL")
return HttpRangeSource(u, readToken?.let { mapOf("x-shade-read" to b64u(it)) } ?: emptyMap())
}
fun open(): MediaReader = MediaReader.open(source(), keys())
override fun toJsonMap(): Map<String, Any> {
val o = LinkedHashMap<String, Any>()
o["kind"] = MEDIA_GRANT_KIND
o["mediaId"] = b64u(mediaId)
o["key"] = b64u(mediaKey)
o["root"] = rootDigest.joinToString("") { "%02x".format(it) }
url?.let { o["url"] = it }
readToken?.let { o["token"] = b64u(it) }
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
return o
}
companion object {
/** The grant for a file just sealed (and uploaded to `url`). */
fun of(r: SealResult, url: String? = null, readToken: ByteArray? = null, meta: MediaMeta? = null) =
MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url, readToken, meta)
}
}
class LiveGrant(
val channelId: ByteArray,
val signingKey: ByteArray,
val epoch: Long,
val seq: Long,
val chainKey: ByteArray,
val stickyKey: ByteArray,
val url: String? = null,
val readToken: ByteArray? = null,
val meta: MediaMeta? = null,
/** Link mode: reads this epoch and every later one, unaided. */
val channelSecret: ByteArray? = null,
) : Grant() {
override fun toJsonMap(): Map<String, Any> {
val o = LinkedHashMap<String, Any>()
o["kind"] = LIVE_GRANT_KIND
o["channelId"] = b64u(channelId)
o["signingKey"] = b64u(signingKey)
o["epoch"] = epoch
o["seq"] = seq
o["chainKey"] = b64u(chainKey)
o["stickyKey"] = b64u(stickyKey)
channelSecret?.let { o["channelSecret"] = b64u(it) }
url?.let { o["url"] = it }
readToken?.let { o["token"] = b64u(it) }
meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() }
return o
}
}
internal fun b64u(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
internal fun fromB64u(s: String, expected: Int? = null): ByteArray {
if (!Regex("^[A-Za-z0-9_-]*$").matches(s)) throw MediaFormatException("not base64url")
val b = try { Base64.getUrlDecoder().decode(s) } catch (e: IllegalArgumentException) { throw MediaFormatException("not base64url") }
if (expected != null && b.size != expected) throw MediaFormatException("expected $expected bytes, got ${b.size}")
return b
}
internal fun fromHexStrict(s: String, expected: Int): ByteArray {
if (!Regex("^(?:[0-9a-f]{2})*$").matches(s) || s.length != expected * 2) throw MediaFormatException("bad hex")
return ByteArray(expected) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
}
object Grants {
fun parse(json: String): Grant {
val o = try { JSONObject(json) } catch (e: JSONException) { throw MediaFormatException("grant is not JSON") }
fun str(k: String): String = o.opt(k) as? String ?: throw MediaFormatException("grant.$k must be a string")
fun optStr(k: String): String? = if (!o.has(k)) null else str(k)
fun int(k: String, max: Long): Long {
val v = o.opt(k) as? Number ?: throw MediaFormatException("grant.$k must be an integer")
val l = v.toLong()
if (l.toDouble() != v.toDouble() || l < 0 || l > max) throw MediaFormatException("grant.$k out of range")
return l
}
val url = optStr("url")?.also {
val scheme = try { URI(it).scheme } catch (e: Exception) { null }
if (scheme !in setOf("http", "https", "ws", "wss")) throw MediaFormatException("grant.url must be http(s) or ws(s)")
}
val token = optStr("token")?.let { fromB64u(it) }?.also {
if (it.size < 16 || it.size > 64) throw MediaFormatException("grant.token must be 16–64 bytes")
}
val meta = (o.opt("meta") as? JSONObject)?.let { MediaMeta.fromJson(it.toString()) }
return when (o.opt("kind")) {
MEDIA_GRANT_KIND -> MediaGrant(
fromB64u(str("mediaId"), MEDIA_ID_BYTES),
fromB64u(str("key"), MEDIA_KEY_BYTES),
fromHexStrict(str("root"), DIGEST_BYTES),
url, token, meta,
)
LIVE_GRANT_KIND -> LiveGrant(
fromB64u(str("channelId"), 16),
fromB64u(str("signingKey"), 32),
int("epoch", 0xffff_ffffL),
int("seq", (1L shl 53) - 1),
fromB64u(str("chainKey"), 32),
fromB64u(str("stickyKey"), 32),
url, token, meta,
optStr("channelSecret")?.let { fromB64u(it, 32) },
)
else -> throw MediaFormatException("unknown grant kind ${o.opt("kind")}")
}
}
/** Grant from a capability link `…#shade=<base64url(json)>`. */
fun fromCapabilityUrl(link: String): Grant {
val frag = link.substringAfter('#', link)
val m = Regex("(?:^|&)shade=([A-Za-z0-9_-]+)").find(frag) ?: throw MediaFormatException("link carries no #shade= grant")
return parse(String(fromB64u(m.groupValues[1]), Charsets.UTF_8))
}
}

View File

@@ -0,0 +1,63 @@
package no.zyon.shade.media
import com.google.crypto.tink.subtle.Ed25519Sign
import java.security.SecureRandom
/**
* Who may upload to a relay and delete from it: an Ed25519 key and nothing
* else (mirror of `@shade/media` owner.ts). Requests are signed over a fixed
* string naming the operation, so a signature for one request cannot be
* replayed as another, and over a timestamp the relay accepts within ten
* minutes of its own clock.
*/
class MediaOwner(seed: ByteArray) {
private val seed = seed.copyOf()
private val signer = Ed25519Sign(seed)
val publicKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey
init {
require(seed.size == 32) { "owner seed must be 32 bytes" }
}
/** The key as a relay's owner lists name it (`--owners`, `SHADE_MEDIA_OWNERS`). */
val id: String get() = b64u(publicKey)
/** The seed, for keeping — in the Keystore-backed storage, never in plain prefs. */
fun exportSeed(): ByteArray = seed.copyOf()
fun headers(op: OwnerOp, at: Long = System.currentTimeMillis()): Map<String, String> = mapOf(
OWNER_HEADER to id,
AT_HEADER to at.toString(),
SIGNATURE_HEADER to b64u(signer.sign(message(op, at))),
)
companion object {
const val OWNER_HEADER = "x-shade-owner"
const val AT_HEADER = "x-shade-at"
const val SIGNATURE_HEADER = "x-shade-signature"
const val READ_HASH_HEADER = "x-shade-read-hash"
const val READ_TOKEN_HEADER = "x-shade-read"
fun generate(): MediaOwner = MediaOwner(ByteArray(32).also { SecureRandom().nextBytes(it) })
/** The exact bytes signed for `op` at `at` — shared with TS through `test-vectors/media.json`. */
fun message(op: OwnerOp, at: Long): ByteArray = when (op) {
is OwnerOp.Put -> "shade.media-put/v1|${op.id}|${op.size}|${op.readTokenHash}|$at"
is OwnerOp.Upload -> "shade.media-upload/v1|${op.id}|${op.size}|${op.readTokenHash}|$at"
is OwnerOp.Piece -> "shade.media-piece/v1|${op.id}|${op.offset}|${op.length}|$at"
is OwnerOp.Abort -> "shade.media-abort/v1|${op.id}|$at"
is OwnerOp.Delete -> "shade.media-delete/v1|${op.id}|$at"
OwnerOp.List -> "shade.media-list/v1|$at"
}.toByteArray(Charsets.UTF_8)
}
}
/** What an owner signs. `readTokenHash` is the hex SHA-256 of the read token, or "" for public ciphertext. */
sealed class OwnerOp {
data class Put(val id: String, val size: Long, val readTokenHash: String) : OwnerOp()
data class Upload(val id: String, val size: Long, val readTokenHash: String) : OwnerOp()
data class Piece(val id: String, val offset: Long, val length: Long) : OwnerOp()
data class Abort(val id: String) : OwnerOp()
data class Delete(val id: String) : OwnerOp()
object List : OwnerOp()
}

View File

@@ -0,0 +1,255 @@
package no.zyon.shade.media
import java.io.Closeable
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
import java.nio.ByteBuffer
import java.nio.channels.FileChannel
import java.nio.file.StandardOpenOption
/** Where sealed bytes come from: a size and byte ranges, nothing else. */
interface RangeSource {
fun size(): Long
/** Exactly `length` bytes from `offset` (fewer only past the end). */
fun read(offset: Long, length: Int): ByteArray
}
class ByteArraySource(private val bytes: ByteArray) : RangeSource {
override fun size(): Long = bytes.size.toLong()
override fun read(offset: Long, length: Int): ByteArray {
val start = offset.toInt().coerceAtMost(bytes.size)
return bytes.copyOfRange(start, (start + length).coerceAtMost(bytes.size))
}
}
/** A sealed file on disk — a film too large to hold, uploaded a piece at a time. Safe to read from several threads. */
class FileRangeSource(file: File) : RangeSource, Closeable {
private val ch = FileChannel.open(file.toPath(), StandardOpenOption.READ)
override fun size(): Long = ch.size()
override fun read(offset: Long, length: Int): ByteArray {
val buf = ByteBuffer.allocate(length.coerceAtMost((size() - offset).coerceAtLeast(0).toInt()))
while (buf.hasRemaining()) {
if (ch.read(buf, offset + buf.position()) < 0) break
}
return if (buf.hasRemaining()) buf.array().copyOf(buf.position()) else buf.array()
}
override fun close() = ch.close()
}
/**
* HTTP Range reads against the Shade media routes (or any Range-capable
* server). The read token, when the grant carries one, rides in
* `x-shade-read`. Retries network errors and 5xx; a 4xx is final.
*/
class HttpRangeSource(
private val url: String,
private val headers: Map<String, String> = emptyMap(),
private val retries: Int = 3,
private val timeoutMs: Int = 15_000,
) : RangeSource {
@Volatile private var knownSize: Long = -1
override fun size(): Long {
if (knownSize >= 0) return knownSize
val len = attempt {
val c = open("HEAD", null)
try {
check4xx(c)
c.getHeaderField("content-length")?.toLongOrNull() ?: throw MediaFormatException("HEAD $url gave no Content-Length")
} finally {
c.disconnect()
}
}
knownSize = len
return len
}
override fun read(offset: Long, length: Int): ByteArray {
if (length == 0) return ByteArray(0)
return attempt {
val c = open("GET", "bytes=$offset-${offset + length - 1}")
try {
check4xx(c)
val body = c.inputStream.use { it.readBytes() }
when (c.responseCode) {
206 -> body
// A server that ignores Range sends everything; correct, if wasteful.
200 -> if (body.size >= offset + length) body.copyOfRange(offset.toInt(), (offset + length).toInt()) else throw MediaFormatException("short 200 body")
else -> throw MediaFormatException("GET $url answered ${c.responseCode} to a Range request")
}
} finally {
c.disconnect()
}
}
}
private fun open(method: String, range: String?): HttpURLConnection {
val c = URL(url).openConnection() as HttpURLConnection
c.requestMethod = method
c.connectTimeout = timeoutMs
c.readTimeout = timeoutMs
for ((k, v) in headers) c.setRequestProperty(k, v)
if (range != null) c.setRequestProperty("Range", range)
return c
}
private fun check4xx(c: HttpURLConnection) {
val code = c.responseCode
if (code in 400..499) throw MediaFormatException("HTTP $code from $url")
if (code >= 500) throw IOException("HTTP $code from $url")
}
private fun <T> attempt(run: () -> T): T {
var last: Exception? = null
repeat(retries.coerceAtLeast(1)) { i ->
try {
return run()
} catch (e: MediaFormatException) {
throw e
} catch (e: IOException) {
last = e
Thread.sleep(150L shl i)
}
}
throw last ?: IOException("unreachable")
}
}
/** What a reader needs: the secret half of a grant. */
class MediaKeys(val mediaId: ByteArray, val mediaKey: ByteArray, val rootDigest: ByteArray? = null)
/**
* Random-access reader over a sealed file — mirror of the TS `MediaReader`.
* `open` checks the trailer against the root digest; every `read` then
* fetches only the segments under the range (neighbours in one request) and
* checks each against the digest table before decrypting it.
*
* Thread-safe: ExoPlayer reads from its loader thread while the UI may seek.
*/
class MediaReader private constructor(
private val source: RangeSource,
private val footer: Footer,
private val table: ByteArray,
private val segmentKey: ByteArray,
val meta: MediaMeta,
private val cacheSegments: Int,
private val maxSegmentsPerFetch: Int,
) : AutoCloseable {
val size: Long get() = footer.plaintextSize
val segmentSize: Int get() = footer.segmentSize
val segmentCount: Long get() = footer.segmentCount
private val cache = object : LinkedHashMap<Long, ByteArray>(16, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?) = size > cacheSegments
}
companion object {
fun open(source: RangeSource, keys: MediaKeys, cacheSegments: Int = 8, maxSegmentsPerFetch: Int = 8): MediaReader {
val total = source.size()
if (total < FOOTER_BYTES) throw MediaFormatException("file too short to be SMF1")
val footer = Footer.decode(source.read(total - FOOTER_BYTES, FOOTER_BYTES))
if (!ctEquals(footer.mediaId, keys.mediaId)) throw MediaIntegrityException("file is a different media item than the grant names")
if (footer.sealedSize != total) throw MediaIntegrityException("size mismatch: footer implies ${footer.sealedSize}, file has $total")
val n = footer.segmentCount
val trailerLen = footer.metaLen + n * DIGEST_BYTES + FOOTER_BYTES
if (trailerLen > Int.MAX_VALUE) throw MediaFormatException("trailer too large")
val trailer = source.read(total - trailerLen, trailerLen.toInt())
if (keys.rootDigest != null && !ctEquals(sha256(trailer), keys.rootDigest)) {
throw MediaIntegrityException("trailer does not match the root digest in the grant")
}
val sub = deriveMediaSubkeys(keys.mediaKey, keys.mediaId)
val metaPlain = gcmOpen(sub.metaKey, META_NONCE, trailer.copyOfRange(0, footer.metaLen), metaAad(keys.mediaId))
sub.metaKey.fill(0)
val meta = MediaMeta.fromJson(String(metaPlain, Charsets.UTF_8))
val table = trailer.copyOfRange(footer.metaLen, footer.metaLen + (n * DIGEST_BYTES).toInt())
return MediaReader(source, footer, table, sub.segmentKey, meta, cacheSegments, maxSegmentsPerFetch.coerceAtLeast(1))
}
}
/** Plaintext `[offset, offset+length)`, clamped to the end. */
fun read(offset: Long, length: Int): ByteArray {
require(offset >= 0 && length >= 0) { "offset and length must be non-negative" }
val end = minOf(size, offset + length)
if (offset >= end) return ByteArray(0)
val first = offset / segmentSize
val last = (end - 1) / segmentSize
val out = ByteArray((end - offset).toInt())
var w = 0
for ((i, seg) in segments(first, last).withIndex()) {
val segStart = (first + i) * segmentSize
val from = maxOf(offset, segStart) - segStart
val to = minOf(end, segStart + seg.size) - segStart
System.arraycopy(seg, from.toInt(), out, w, (to - from).toInt())
w += (to - from).toInt()
}
return out
}
/** A plain InputStream over `[start, end)` — for players and file copies. */
fun inputStream(start: Long = 0, end: Long = size): InputStream = object : InputStream() {
private var pos = start
override fun read(): Int {
val b = ByteArray(1)
return if (read(b, 0, 1) <= 0) -1 else b[0].toInt() and 0xff
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (pos >= end) return -1
val n = minOf(len.toLong(), end - pos, segmentSize.toLong() * maxSegmentsPerFetch).toInt()
val bytes = this@MediaReader.read(pos, n)
System.arraycopy(bytes, 0, b, off, bytes.size)
pos += bytes.size
return bytes.size
}
override fun skip(n: Long): Long {
val s = minOf(n, end - pos).coerceAtLeast(0)
pos += s
return s
}
}
private fun segments(first: Long, last: Long): List<ByteArray> {
if (first < 0 || last >= segmentCount || first > last) throw IndexOutOfBoundsException("segments $first..$last")
val out = ArrayList<ByteArray>()
var i = first
while (i <= last) {
val cached = synchronized(cache) { cache[i] }
if (cached != null) {
out += cached
i++
continue
}
var j = i
while (j + 1 <= last && j + 1 - i < maxSegmentsPerFetch && synchronized(cache) { !cache.containsKey(j + 1) }) j++
val run = fetchRun(i, j)
synchronized(cache) { run.forEachIndexed { k, s -> cache[i + k] = s } }
out += run
i = j + 1
}
return out
}
private fun fetchRun(first: Long, last: Long): List<ByteArray> {
val (aOff, _) = footer.span(first)
val (bOff, bLen) = footer.span(last)
val len = bOff + bLen - aOff
if (len > Int.MAX_VALUE) throw MediaFormatException("range too large")
val bytes = source.read(aOff, len.toInt())
if (bytes.size.toLong() != len) throw MediaIntegrityException("short read from media source")
return (first..last).map { i ->
val (off, l) = footer.span(i)
val sealed = bytes.copyOfRange((off - aOff).toInt(), (off - aOff).toInt() + l)
val want = table.copyOfRange((i * DIGEST_BYTES).toInt(), ((i + 1) * DIGEST_BYTES).toInt())
if (!ctEquals(sha256(sealed), want)) throw MediaIntegrityException("segment $i does not match its digest")
gcmOpen(segmentKey, segmentNonce(i), sealed, segmentAad(footer.mediaId, i, i == segmentCount - 1))
}
}
override fun close() {
synchronized(cache) { cache.clear() }
segmentKey.fill(0)
}
}

View File

@@ -0,0 +1,391 @@
package no.zyon.shade.media
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL
import java.security.MessageDigest
import java.security.SecureRandom
import java.util.ArrayDeque
import java.util.TreeSet
import java.util.concurrent.ExecutorCompletionService
import java.util.concurrent.Executors
/** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */
const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024
const val OFFSET_HEADER = "x-shade-offset"
const val MAX_PIECE_BYTES = 64L * 1024 * 1024
/** Most pieces kept in flight, whatever window a relay offers. */
const val MAX_CLIENT_WINDOW = 16
/** Failed tries in a row before a resumable upload gives up. */
private const val MAX_TRIES = 8
/** The relay is restarting, overloaded or the network dropped: try again. */
private class Transient(message: String) : IOException(message)
class MediaUploadException(message: String) : IOException(message)
/**
* Upload sealed files to a Shade relay — mirror of the TS `MediaClient`, so a
* phone can share a film or a video it recorded. Blocking: call it off the
* main thread.
*
* A file above [DEFAULT_CHUNK_BYTES] goes in pieces, up to the relay's
* window of them in flight. A dropped connection or a relay restart costs
* the pieces in flight, not the upload: a failed piece is sent again after
* asking the relay whether it landed after all. Calling [putSealed] again
* with the same seal result and the same sealed file (after the app was
* killed, say) resumes where the relay got to, since the media id is the same.
*/
class MediaUploader(
server: String,
private val owner: MediaOwner,
private val timeoutMs: Int = 60_000,
) {
val server = server.trimEnd('/')
fun mediaUrl(mediaId: ByteArray): String = "$server/v1/media/${hex(mediaId)}"
/**
* Upload an already sealed file; `body` must be exactly `result.sealedSize`
* bytes. `readToken`: what viewers must present — a fresh random one by
* default, `null` for public ciphertext. `onProgress(acked, total)` after
* each piece the relay has.
*/
fun putSealed(
result: SealResult,
body: RangeSource,
readToken: ByteArray? = newReadToken(),
meta: MediaMeta? = null,
onProgress: ((Long, Long) -> Unit)? = null,
): MediaGrant {
val size = body.size()
if (size != result.sealedSize) throw MediaFormatException("body is $size bytes, the seal produced ${result.sealedSize}")
val readTokenHash = readToken?.let { hex(MessageDigest.getInstance("SHA-256").digest(it)) } ?: ""
val id = hex(result.mediaId)
val url = mediaUrl(result.mediaId)
if (size <= DEFAULT_CHUNK_BYTES) {
val bytes = body.read(0, size.toInt())
val headers = owner.headers(OwnerOp.Put(id, size, readTokenHash)) +
mapOf("content-type" to "application/vnd.shade.smf1") +
(if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap())
val res = try {
request("PUT", url, headers, bytes)
} catch (e: IOException) {
throw MediaUploadException("upload failed: ${e.message}")
}
if (res.status != 201) throw MediaUploadException("upload failed: HTTP ${res.status} ${res.text()}")
onProgress?.invoke(size, size)
} else {
Pieces("$url/upload", id, size, readTokenHash, body, onProgress).run()
}
return MediaGrant.of(result, url, readToken, meta)
}
/** Seal in memory and upload — a photo, a short clip, a document. */
fun uploadBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), readToken: ByteArray? = newReadToken()): MediaGrant {
val (sealed, result) = MediaSealer.sealBytes(plaintext, meta)
return putSealed(result, ByteArraySource(sealed), readToken, meta)
}
/** Seal and upload an album; the grant opens every item in it (a season, the photos of a trip). */
fun uploadAlbum(album: Album, readToken: ByteArray? = newReadToken()): MediaGrant =
uploadBytes(Albums.encode(album), Albums.meta(album.title), readToken)
/**
* Seal `input` into `sealedFile` and upload it — a film without holding it
* in memory. The sealed copy is the caller's: keep it (with the returned
* seal result) until this returns, to resume with [putSealed] if it fails.
*/
fun uploadStream(
input: java.io.InputStream,
sealedFile: File,
meta: MediaMeta = MediaMeta(),
readToken: ByteArray? = newReadToken(),
onProgress: ((Long, Long) -> Unit)? = null,
): MediaGrant {
val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) }
return FileRangeSource(sealedFile).use { putSealed(result, it, readToken, meta, onProgress) }
}
/**
* Upload `source` as the job `key` in `jobs`, so that a run cut short (the
* app killed, the phone out of signal for an hour) is resumed by calling
* this again: sealed once, into the job's directory, then put with the
* same media id. A job already done gives its grant again while the relay
* still serves it — sharing the same video twice is one upload, one link.
* `open` is only called when the file must be sealed.
*/
fun upload(
jobs: UploadJobs,
key: String,
source: String,
meta: MediaMeta,
open: () -> java.io.InputStream,
readToken: ByteArray? = newReadToken(),
onProgress: ((Long, Long) -> Unit)? = null,
): MediaGrant = jobs.claim(key).use {
var job = jobs.load(key)
job?.grant?.let { g ->
if (!gone(g)) return@use g
jobs.reset(key) // deleted from the relay since: a new upload
job = null
}
val j = job ?: run {
val sealed = jobs.sealedFile(key)
val result = open().use { input -> sealed.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) } }
UploadJobs.Job(result, readToken, meta, source, server = server).also { jobs.save(key, it) }
}
val grant = FileRangeSource(jobs.sealedFile(key)).use { putSealed(j.result, it, j.readToken, j.meta, onProgress) }
jobs.done(key, j, grant)
grant
}
/**
* Whether the relay says the file a grant opens is gone (deleted since).
* A relay that cannot be reached has not said so: its link still stands.
*/
fun gone(grant: MediaGrant): Boolean {
val u = grant.url ?: return true
return try {
request("HEAD", u, grant.readToken?.let { mapOf(MediaOwner.READ_TOKEN_HEADER to b64u(it)) } ?: emptyMap(), null).status in setOf(404, 410)
} catch (e: IOException) {
false
}
}
/** Remove one of your files from the relay; false if it was not there. */
fun delete(mediaId: ByteArray): Boolean {
val res = request("DELETE", mediaUrl(mediaId), owner.headers(OwnerOp.Delete(hex(mediaId))), null)
if (res.status == 404) return false
if (res.status !in 200..299) throw MediaUploadException("delete failed: HTTP ${res.status} ${res.text()}")
return true
}
private inner class Pieces(
private val at: String,
private val id: String,
private val size: Long,
private val readTokenHash: String,
private val body: RangeSource,
private val onProgress: ((Long, Long) -> Unit)?,
) {
/**
* How far the relay got. Checked before it is trusted (mirror of TS
* `statusProblem`): a zero chunk would never get through the file, a
* huge one would hold it all in memory, a huge window a thread per piece.
*/
private inner class Status(json: JSONObject) {
val complete = json.optBoolean("complete", false)
val chunk = if (complete) 0L else json.optLong("chunk", -1)
val window = json.optInt("window", 1)
val received = if (complete) size else json.optLong("received", -1)
val landed: Set<Long> = if (complete) emptySet() else json.optJSONArray("landed")?.let { a ->
(0 until a.length()).map { i -> (a.opt(i) as? Number)?.toLong()?.takeIf { it >= 0 } ?: unusable("landed is not a list of piece numbers") }.toSet()
} ?: emptySet()
init {
if (!complete) {
if (chunk < 1024 * 1024 || chunk > MAX_PIECE_BYTES) unusable("chunk $chunk out of range")
if (window < 1) unusable("window $window out of range")
if (received < 0 || received > size) unusable("received $received out of range")
}
}
fun has(offset: Long) = offset < received || (offset / chunk) in landed
}
private fun unusable(why: String): Nothing = throw MediaUploadException("upload failed: the relay's upload status is unusable: $why")
/** A request that got no answer (refused, reset, timed out) is worth repeating. */
private fun send(method: String, headers: Map<String, String>, body: ByteArray?): Answer =
try {
request(method, at, headers, body)
} catch (e: IOException) {
throw Transient(e.message ?: e.javaClass.simpleName)
}
private fun fail(res: Answer, what: String): Nothing {
if (res.status >= 500 || res.status == 429) throw Transient("$what: HTTP ${res.status} ${res.text()}")
throw MediaUploadException("upload failed: $what: HTTP ${res.status} ${res.text()}")
}
/** Retry `fn` while it fails transiently, with backoff; `fn` learns which try it is. */
private fun <T> retrying(fn: (attempt: Int) -> T): T {
var attempt = 0
while (true) {
try {
return fn(attempt)
} catch (e: Transient) {
if (attempt + 1 >= MAX_TRIES) throw MediaUploadException("upload failed after $MAX_TRIES tries: ${e.message}")
attempt++
Thread.sleep(minOf(30_000L, 500L shl attempt))
}
}
}
/** Start the upload, or learn how far it got. */
private fun status(): Status {
val headers = owner.headers(OwnerOp.Upload(id, size, readTokenHash)) +
mapOf("x-shade-size" to size.toString()) +
(if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap())
val res = send("POST", headers, ByteArray(0))
if (res.status != 200 && res.status != 201) fail(res, "start")
return try {
Status(JSONObject(res.body))
} catch (e: JSONException) {
throw Transient("start: the relay's answer is not JSON")
}
}
private var chunk = 0L
/** One piece until the relay has it; true once the relay stored the whole file. */
private fun sendPiece(offset: Long): Boolean = retrying { attempt ->
if (attempt > 0) {
// It may have landed before the connection dropped: ask before sending it again.
val st = status()
if (st.complete) return@retrying true
if (st.has(offset)) return@retrying false
}
val length = minOf(chunk, size - offset)
val piece = body.read(offset, length.toInt())
if (piece.size.toLong() != length) throw MediaFormatException("the file shrank: read ${piece.size} of $length bytes at $offset")
val res = send(
"PUT",
owner.headers(OwnerOp.Piece(id, offset, length)) +
mapOf("content-type" to "application/octet-stream", OFFSET_HEADER to offset.toString()),
piece,
)
when (res.status) {
201 -> true
200 -> false
// Ahead of the window (pieces before it are still on the way): later.
409 -> {
val error = try { JSONObject(res.body).optString("error") } catch (e: JSONException) { "" }
if (error == "OFFSET") throw Transient("piece ahead of the upload")
throw MediaUploadException("upload failed: HTTP 409 ${res.text()}")
}
else -> fail(res, "piece at $offset")
}
}
private inner class Outcome(val offset: Long, val done: Boolean, val error: Throwable?)
fun run() {
val opened = retrying { status() }
if (opened.complete) {
onProgress?.invoke(size, size)
return
}
chunk = opened.chunk
val window = opened.window.coerceAtMost(MAX_CLIENT_WINDOW)
var acked = 0L
var complete = false
val todo = ArrayDeque<Long>()
var off = 0L
while (off < size) {
if (opened.has(off)) acked += minOf(chunk, size - off) else todo.add(off)
off += chunk
}
onProgress?.invoke(acked, size)
val pool = Executors.newFixedThreadPool(window) { r -> Thread(r, "shade-upload").apply { isDaemon = true } }
val done = ExecutorCompletionService<Outcome>(pool)
val flying = TreeSet<Long>()
var failure: Throwable? = null
/**
* The relay takes `window` pieces past what it has from the start, so a
* piece is only sent within `window` of the first one not yet answered:
* one slow piece holds the window, rather than pieces past it bouncing.
*/
fun mayLaunch(): Boolean {
if (todo.isEmpty() || flying.size >= window) return false
val lowest = if (flying.isEmpty()) todo.first() else minOf(todo.first(), flying.first())
return todo.first() < lowest + window * chunk
}
try {
while (!complete && failure == null && (todo.isNotEmpty() || flying.isNotEmpty())) {
while (mayLaunch()) {
val o = todo.removeFirst()
flying.add(o)
done.submit {
try {
Outcome(o, sendPiece(o), null)
} catch (e: Throwable) {
Outcome(o, false, e)
}
}
}
val r = done.take().get()
flying.remove(r.offset)
if (r.error != null) {
failure = failure ?: r.error
continue
}
if (r.done) complete = true
acked += minOf(chunk, size - r.offset)
if (!complete) onProgress?.invoke(acked, size)
}
while (flying.isNotEmpty()) flying.remove(done.take().get().offset)
} finally {
pool.shutdownNow()
}
failure?.let { throw it }
if (!complete) {
// Every piece is in but no answer said so (they crossed a completion
// that failed and was retried): an empty piece at the end finishes it.
retrying {
val res = send("PUT", owner.headers(OwnerOp.Piece(id, size, 0)) + mapOf(OFFSET_HEADER to size.toString()), ByteArray(0))
if (res.status != 201) fail(res, "finish")
}
}
onProgress?.invoke(size, size)
}
}
private class Answer(val status: Int, val body: String, private val contentType: String) {
/**
* What a refusal says, for an error message: the relay's JSON as it is,
* but not an HTML error page (a proxy's) poured into a log.
*/
fun text(): String {
if (contentType.contains("text/html") || body.trimStart().startsWith("<")) return ""
return if (body.length > 300) "${body.take(300)}…" else body
}
}
private fun request(method: String, url: String, headers: Map<String, String>, body: ByteArray?): Answer {
val c = java.net.URI(url).toURL().openConnection() as HttpURLConnection
try {
c.requestMethod = method
c.connectTimeout = timeoutMs
c.readTimeout = timeoutMs
c.useCaches = false
for ((k, v) in headers) c.setRequestProperty(k, v)
if (body != null) {
c.doOutput = true
c.setFixedLengthStreamingMode(body.size)
c.outputStream.use { it.write(body) }
}
val status = c.responseCode
val stream = if (status >= 400) c.errorStream else c.inputStream
val text = stream?.use { String(it.readBytes(), Charsets.UTF_8) } ?: ""
return Answer(status, text, c.contentType ?: "")
} finally {
c.disconnect()
}
}
companion object {
private val rng = SecureRandom()
fun newReadToken(): ByteArray = ByteArray(32).also { rng.nextBytes(it) }
private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
}
}

View File

@@ -0,0 +1,36 @@
package no.zyon.shade.media
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
/**
* Subtitles — mirror of `@shade/media/src/subtitles.ts`. A film carries the
* grants of its sealed subtitle files in its own sealed meta, under
* `extra["shade.subtitles"]`: `[{"lang":"no","label":"…","grant":{…}}, …]`.
*/
const val SUBTITLES_KEY = "shade.subtitles"
private const val MAX_TRACKS = 64
private val LANG_RE = Regex("^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{2,8})*$")
class SubtitleTrack(val grant: MediaGrant, val lang: String? = null, val label: String? = null)
object Subtitles {
/** The subtitle tracks a film's meta names, strictly; none if it names none. */
fun of(meta: MediaMeta?): List<SubtitleTrack> {
val raw = meta?.extra?.get(SUBTITLES_KEY) ?: return emptyList()
val list = try { JSONArray(raw) } catch (e: JSONException) { throw MediaFormatException("subtitles are not a JSON array") }
if (list.length() > MAX_TRACKS) throw MediaFormatException("more than $MAX_TRACKS subtitle tracks")
return (0 until list.length()).map { i ->
val o = list.opt(i) as? JSONObject ?: throw MediaFormatException("subtitle $i is not an object")
val g = Grants.parse((o.opt("grant") as? JSONObject ?: throw MediaFormatException("subtitle $i has no grant")).toString())
if (g !is MediaGrant) throw MediaFormatException("subtitle $i is not a sealed file")
val lang = if (!o.has("lang")) null else (o.opt("lang") as? String)?.takeIf { LANG_RE.matches(it) }
?: throw MediaFormatException("subtitle $i: bad lang")
val label = if (!o.has("label")) null else (o.opt("label") as? String)?.takeIf { it.length <= 200 }
?: throw MediaFormatException("subtitle $i: bad label")
SubtitleTrack(g, lang, label)
}
}
}

View File

@@ -0,0 +1,197 @@
package no.zyon.shade.media
import org.json.JSONException
import org.json.JSONObject
import java.io.File
import java.nio.channels.FileChannel
import java.nio.channels.FileLock
import java.nio.channels.OverlappingFileLockException
import java.nio.file.StandardOpenOption
import java.security.MessageDigest
/**
* Uploads that outlive the app — mirror of `@shade/media` put-jobs.ts. A
* phone kills an app that uploads for long (a film over mobile data); this is
* what lets the next start send the same file again, with the same media id,
* so the relay already has most of it. Each upload has a directory:
*
* sealed.smf the sealed copy, kept until the relay has all of it
* job.json the seal result (with the file key), the read token, the
* meta, and the grant once the relay stored it. Keep the
* directory app-private (`filesDir`): it holds keys.
* lock held (an OS file lock) by whoever is uploading it
*
* A job is keyed by what identifies the source (the relay, a content URI,
* its size and name, …), so sharing the same video twice is one upload and
* gives the same link. Jobs untouched for 30 days are removed.
*/
class UploadJobs(private val dir: File) {
class Job(
val result: SealResult,
/** Null for public ciphertext. */
val readToken: ByteArray?,
val meta: MediaMeta,
/** What the job is of, for listing (a file name, a URI). */
val source: String,
/** Set once the relay stored the file. */
val grant: MediaGrant? = null,
/** The relay it goes to, for resuming it after a restart. */
val server: String = "",
)
class BusyException(message: String) : Exception(message)
/** The job for a source identified by `parts` (the relay URL first). */
fun key(vararg parts: String): String {
val md = MessageDigest.getInstance("SHA-256")
for (p in parts) {
val b = p.toByteArray(Charsets.UTF_8)
md.update(byteArrayOf((b.size ushr 24).toByte(), (b.size ushr 16).toByte(), (b.size ushr 8).toByte(), b.size.toByte()))
md.update(b)
}
return md.digest().copyOf(16).joinToString("") { "%02x".format(it) }
}
private fun jobDir(key: String): File {
require(KEY_RE.matches(key)) { "not a job key: $key" }
return File(dir, key)
}
fun sealedFile(key: String): File = File(jobDir(key), "sealed.smf")
/**
* Take the job for this upload; release with `close()`. Throws
* [BusyException] while another thread or process has it. A lock left by a
* process that died is released by the OS, so it never needs clearing.
*/
fun claim(key: String): AutoCloseable {
val d = jobDir(key).also { it.mkdirs() }
val ch = FileChannel.open(File(d, "lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE)
val lock: FileLock? = try {
ch.tryLock()
} catch (e: OverlappingFileLockException) {
null
}
if (lock == null) {
ch.close()
throw BusyException("this file is already being uploaded")
}
return AutoCloseable {
lock.release()
ch.close()
}
}
/** The job, if an earlier run got as far as sealing — and its sealed copy is whole, unless it is done. */
fun load(key: String): Job? {
val o = try {
JSONObject(File(jobDir(key), "job.json").readText())
} catch (e: java.io.IOException) {
return null
} catch (e: JSONException) {
return null
}
if (o.optInt("v") != 1) return null
val job = try {
val r = o.getJSONObject("result")
Job(
SealResult(
fromB64u(r.getString("mediaId"), MEDIA_ID_BYTES),
fromB64u(r.getString("mediaKey"), MEDIA_KEY_BYTES),
fromB64u(r.getString("rootDigest"), DIGEST_BYTES),
r.getLong("plaintextSize"),
r.getLong("sealedSize"),
r.getInt("segmentSize"),
r.getLong("segmentCount"),
),
if (o.isNull("readToken")) null else fromB64u(o.getString("readToken")),
MediaMeta.fromJson(o.getString("meta")),
o.optString("source"),
if (o.has("grant")) Grants.parse(o.getString("grant")) as? MediaGrant else null,
o.optString("server"),
)
} catch (e: JSONException) {
return null
} catch (e: MediaFormatException) {
return null
}
if (job.grant != null) return job
return if (sealedFile(key).length() == job.result.sealedSize) job else null
}
fun save(key: String, job: Job) {
val r = job.result
val o = JSONObject()
.put("v", 1)
.put("source", job.source)
.put("server", job.server)
.put(
"result",
JSONObject()
.put("mediaId", b64u(r.mediaId))
.put("mediaKey", b64u(r.mediaKey))
.put("rootDigest", b64u(r.rootDigest))
.put("plaintextSize", r.plaintextSize)
.put("sealedSize", r.sealedSize)
.put("segmentSize", r.segmentSize)
.put("segmentCount", r.segmentCount),
)
.put("readToken", job.readToken?.let { b64u(it) } ?: JSONObject.NULL)
.put("meta", job.meta.toJson())
job.grant?.let { o.put("grant", it.encode()) }
val d = jobDir(key).also { it.mkdirs() }
val tmp = File(d, "job.json.tmp")
tmp.writeText(o.toString())
if (!tmp.renameTo(File(d, "job.json"))) throw java.io.IOException("cannot write the job for $key")
}
/** The relay has it: keep the grant, drop the sealed copy. */
fun done(key: String, job: Job, grant: MediaGrant): Job {
val finished = Job(job.result, job.readToken, job.meta, job.source, grant, job.server)
save(key, finished)
sealedFile(key).delete()
return finished
}
/** Start the job over (its file was deleted from the relay), keeping the claim. */
fun reset(key: String) {
File(jobDir(key), "job.json").delete()
sealedFile(key).delete()
}
fun forget(key: String) {
jobDir(key).deleteRecursively()
}
/** Jobs not yet done whose sealed copy is whole: what to resume after a restart. */
fun unfinished(): List<Pair<String, Job>> =
(dir.list() ?: emptyArray()).filter { KEY_RE.matches(it) }
.mapNotNull { k -> load(k)?.takeIf { it.grant == null }?.let { k to it } }
/** Remove jobs nobody touched for 30 days, and half-sealed leftovers after an hour. */
fun prune(now: Long = System.currentTimeMillis()): Int {
var n = 0
for (k in dir.list() ?: emptyArray()) {
if (!KEY_RE.matches(k)) continue
val jobFile = File(jobDir(k), "job.json")
val touched = if (jobFile.exists()) jobFile.lastModified() else jobDir(k).lastModified()
val stale = now - touched > MAX_AGE_MS || (!jobFile.exists() && now - touched > 3_600_000L)
if (!stale) continue
val held = try {
claim(k)
} catch (e: BusyException) {
continue
}
held.close()
forget(k)
n++
}
return n
}
private companion object {
val KEY_RE = Regex("^[0-9a-f]{32}$")
const val MAX_AGE_MS = 30L * 24 * 3600 * 1000
}
}

View File

@@ -0,0 +1,237 @@
package no.zyon.shade.protocol
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.types.ChainState
import no.zyon.shade.types.Constants
import no.zyon.shade.types.KeyPair
import no.zyon.shade.types.RatchetMessage
import no.zyon.shade.types.SessionState
import java.nio.ByteBuffer
/**
* Double Ratchet implementation. Mirrors @shade/core/ratchet.ts.
*
* Must produce byte-identical ciphertext to the TypeScript version
* for the same inputs.
*/
// ─── Session initialization ─────────────────────────────────
fun initSenderSession(
crypto: CryptoProvider,
rootKey: ByteArray,
remoteIdentityKey: ByteArray,
remoteDHPublicKey: ByteArray,
): SessionState {
val (dhSendPub, dhSendPriv) = crypto.generateX25519KeyPair()
val dhOutput = crypto.x25519(dhSendPriv, remoteDHPublicKey)
val (newRootKey, chainKey) = kdfRootKey(crypto, rootKey, dhOutput).let {
it.newRootKey to it.chainKey
}
return SessionState(
remoteIdentityKey = remoteIdentityKey,
rootKey = newRootKey,
sendChain = ChainState(chainKey = chainKey, counter = 0),
receiveChain = null,
dhSend = KeyPair(publicKey = dhSendPub, privateKey = dhSendPriv),
dhReceive = remoteDHPublicKey,
previousSendCounter = 0,
skippedKeys = mutableMapOf(),
)
}
fun initReceiverSession(
rootKey: ByteArray,
remoteIdentityKey: ByteArray,
localDHKeyPair: KeyPair,
): SessionState {
return SessionState(
remoteIdentityKey = remoteIdentityKey,
rootKey = rootKey,
sendChain = ChainState(chainKey = ByteArray(32), counter = 0),
receiveChain = null,
dhSend = localDHKeyPair,
dhReceive = null,
previousSendCounter = 0,
skippedKeys = mutableMapOf(),
)
}
// ─── Header encoding (for AES-GCM AAD) ──────────────────────
private fun encodeHeader(
dhPublicKey: ByteArray,
previousCounter: Int,
counter: Int,
): ByteArray {
val buf = ByteBuffer.allocate(40)
buf.put(dhPublicKey)
buf.putInt(previousCounter) // big-endian by default in ByteBuffer
buf.putInt(counter)
return buf.array()
}
// ─── Encrypt ─────────────────────────────────────────────────
fun ratchetEncrypt(
crypto: CryptoProvider,
session: SessionState,
plaintext: ByteArray,
): RatchetMessage {
val oldChainKey = session.sendChain.chainKey
val (newChainKey, messageKey) = kdfChainKey(crypto, oldChainKey).let {
it.newChainKey to it.messageKey
}
crypto.zeroize(oldChainKey)
val counter = session.sendChain.counter
val header = encodeHeader(session.dhSend.publicKey, session.previousSendCounter, counter)
val (ciphertext, nonce) = crypto.aesGcmEncrypt(messageKey, plaintext, header)
crypto.zeroize(messageKey)
session.sendChain.chainKey = newChainKey
session.sendChain.counter = counter + 1
return RatchetMessage(
dhPublicKey = session.dhSend.publicKey,
previousCounter = session.previousSendCounter,
counter = counter,
ciphertext = ciphertext,
nonce = nonce,
)
}
// ─── Decrypt ─────────────────────────────────────────────────
private fun skippedKeyId(dhPublicKey: ByteArray, counter: Int): String {
return dhPublicKey.joinToString("") { "%02x".format(it) } + ":" + counter
}
fun ratchetDecrypt(
crypto: CryptoProvider,
session: SessionState,
message: RatchetMessage,
): ByteArray {
// Case 1: skipped key
val skipId = skippedKeyId(message.dhPublicKey, message.counter)
val skippedKey = session.skippedKeys[skipId]
if (skippedKey != null) {
session.skippedKeys.remove(skipId)
try {
return decryptWithKey(crypto, skippedKey, message)
} finally {
crypto.zeroize(skippedKey)
}
}
// Case 2 or 3: DH ratchet check
val isNewRatchet = session.dhReceive == null ||
!message.dhPublicKey.contentEquals(session.dhReceive!!)
if (isNewRatchet) {
if (session.receiveChain != null && session.dhReceive != null) {
skipMessageKeys(
crypto,
session,
session.dhReceive!!,
session.receiveChain!!,
message.previousCounter,
)
}
performDHRatchetStep(crypto, session, message.dhPublicKey)
}
val receiveChain = session.receiveChain
?: throw IllegalStateException("No receiving chain available")
skipMessageKeys(crypto, session, message.dhPublicKey, receiveChain, message.counter)
val oldChainKey = receiveChain.chainKey
val (newChainKey, messageKey) = kdfChainKey(crypto, oldChainKey).let {
it.newChainKey to it.messageKey
}
crypto.zeroize(oldChainKey)
receiveChain.chainKey = newChainKey
receiveChain.counter = message.counter + 1
try {
return decryptWithKey(crypto, messageKey, message)
} finally {
crypto.zeroize(messageKey)
}
}
private fun performDHRatchetStep(
crypto: CryptoProvider,
session: SessionState,
remoteDHKey: ByteArray,
) {
session.previousSendCounter = session.sendChain.counter
session.dhReceive = remoteDHKey
// DH with current send key → new receiving chain
val dh1 = crypto.x25519(session.dhSend.privateKey, remoteDHKey)
val oldRootKey1 = session.rootKey
val recv = kdfRootKey(crypto, oldRootKey1, dh1)
crypto.zeroize(oldRootKey1)
crypto.zeroize(dh1)
session.rootKey = recv.newRootKey
session.receiveChain = ChainState(chainKey = recv.chainKey, counter = 0)
// Generate new DH keypair, zero old private
val oldDhPrivate = session.dhSend.privateKey
val (newDhPub, newDhPriv) = crypto.generateX25519KeyPair()
session.dhSend = KeyPair(publicKey = newDhPub, privateKey = newDhPriv)
crypto.zeroize(oldDhPrivate)
// DH with new send key → new sending chain
val dh2 = crypto.x25519(newDhPriv, remoteDHKey)
val oldRootKey2 = session.rootKey
val send = kdfRootKey(crypto, oldRootKey2, dh2)
crypto.zeroize(oldRootKey2)
crypto.zeroize(dh2)
session.rootKey = send.newRootKey
if (session.sendChain.chainKey.isNotEmpty()) {
crypto.zeroize(session.sendChain.chainKey)
}
session.sendChain = ChainState(chainKey = send.chainKey, counter = 0)
}
private fun skipMessageKeys(
crypto: CryptoProvider,
session: SessionState,
dhPublicKey: ByteArray,
chain: ChainState,
untilCounter: Int,
) {
val toSkip = untilCounter - chain.counter
if (toSkip < 0) return
if (toSkip > Constants.MAX_SKIP) {
throw IllegalStateException("Cannot skip $toSkip messages (max: ${Constants.MAX_SKIP})")
}
for (i in chain.counter until untilCounter) {
val (newChainKey, messageKey) = kdfChainKey(crypto, chain.chainKey).let {
it.newChainKey to it.messageKey
}
val id = skippedKeyId(dhPublicKey, i)
session.skippedKeys[id] = messageKey
chain.chainKey = newChainKey
chain.counter = i + 1
while (session.skippedKeys.size > Constants.MAX_CACHED_SKIPPED_KEYS) {
val firstKey = session.skippedKeys.keys.first()
session.skippedKeys.remove(firstKey)
}
}
}
private fun decryptWithKey(
crypto: CryptoProvider,
messageKey: ByteArray,
message: RatchetMessage,
): ByteArray {
val aad = encodeHeader(message.dhPublicKey, message.previousCounter, message.counter)
return crypto.aesGcmDecrypt(messageKey, message.ciphertext, message.nonce, aad)
}

View File

@@ -0,0 +1,60 @@
package no.zyon.shade.protocol
import no.zyon.shade.crypto.CryptoProvider
/**
* KDF chain functions for the Signal Protocol ratchet.
*
* MUST produce byte-identical output to @shade/core/keys.ts.
* Info strings and salts are fixed constants and must not change.
*/
// Must match the TypeScript version EXACTLY
private val ROOT_KDF_INFO = "ShadeRootRatchet".toByteArray(Charsets.UTF_8)
private val CHAIN_KEY_CONSTANT = byteArrayOf(0x01)
private val MESSAGE_KEY_CONSTANT = byteArrayOf(0x02)
private val X3DH_INFO = "ShadeX3DH".toByteArray(Charsets.UTF_8)
private val X3DH_SALT = ByteArray(32) // 32 zero bytes
data class RootKdfResult(val newRootKey: ByteArray, val chainKey: ByteArray)
data class ChainKdfResult(val newChainKey: ByteArray, val messageKey: ByteArray)
/**
* Root key ratchet step.
* HKDF(ikm=dhOutput, salt=rootKey, info="ShadeRootRatchet", length=64)
* → first 32 bytes = new root key, last 32 bytes = chain key
*/
fun kdfRootKey(crypto: CryptoProvider, rootKey: ByteArray, dhOutput: ByteArray): RootKdfResult {
val derived = crypto.hkdf(dhOutput, rootKey, ROOT_KDF_INFO, 64)
return RootKdfResult(
newRootKey = derived.copyOfRange(0, 32),
chainKey = derived.copyOfRange(32, 64),
)
}
/**
* Chain key ratchet step.
* HMAC(chainKey, 0x01) = new chain key
* HMAC(chainKey, 0x02) = message key (used once)
*/
fun kdfChainKey(crypto: CryptoProvider, chainKey: ByteArray): ChainKdfResult {
val newChainKey = crypto.hmacSha256(chainKey, CHAIN_KEY_CONSTANT)
val messageKey = crypto.hmacSha256(chainKey, MESSAGE_KEY_CONSTANT)
return ChainKdfResult(newChainKey, messageKey)
}
/**
* Derive the initial root key from concatenated X3DH DH outputs.
* HKDF(ikm=DH1||DH2||DH3[||DH4], salt=32 zeros, info="ShadeX3DH", length=32)
*/
fun deriveInitialRootKey(crypto: CryptoProvider, sharedSecrets: List<ByteArray>): ByteArray {
val total = sharedSecrets.sumOf { it.size }
val ikm = ByteArray(total)
var offset = 0
for (secret in sharedSecrets) {
secret.copyInto(ikm, offset)
offset += secret.size
}
return crypto.hkdf(ikm, X3DH_SALT, X3DH_INFO, 32)
}

View File

@@ -0,0 +1,181 @@
package no.zyon.shade.protocol
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.types.IdentityKeyPair
import no.zyon.shade.types.KeyPair
import no.zyon.shade.types.OneTimePreKey
import no.zyon.shade.types.PreKeyBundle
import no.zyon.shade.types.PreKeyMessage
import no.zyon.shade.types.SignedPreKey
/**
* X3DH key agreement. Mirrors @shade/core/x3dh.ts.
*
* Identity keys: separate Ed25519 (signing) + X25519 (DH) keypairs stored together.
*/
/** Generate a new identity keypair (Ed25519 + X25519) */
fun generateIdentityKeyPair(crypto: CryptoProvider): IdentityKeyPair {
val (signPub, signPriv) = crypto.generateEd25519KeyPair()
val (dhPub, dhPriv) = crypto.generateX25519KeyPair()
return IdentityKeyPair(
signingPublicKey = signPub,
signingPrivateKey = signPriv,
dhPublicKey = dhPub,
dhPrivateKey = dhPriv,
)
}
/** Generate a signed prekey (X25519 keypair + Ed25519 signature over public key) */
fun generateSignedPreKey(
crypto: CryptoProvider,
identity: IdentityKeyPair,
keyId: Int,
): SignedPreKey {
val (pub, priv) = crypto.generateX25519KeyPair()
val signature = crypto.sign(identity.signingPrivateKey, pub)
return SignedPreKey(
keyId = keyId,
keyPair = KeyPair(publicKey = pub, privateKey = priv),
signature = signature,
timestamp = System.currentTimeMillis(),
)
}
/** Generate a batch of one-time prekeys */
fun generateOneTimePreKeys(
crypto: CryptoProvider,
startId: Int,
count: Int,
): List<OneTimePreKey> {
val keys = mutableListOf<OneTimePreKey>()
for (i in 0 until count) {
val (pub, priv) = crypto.generateX25519KeyPair()
keys.add(OneTimePreKey(keyId = startId + i, keyPair = KeyPair(pub, priv)))
}
return keys
}
fun createPreKeyBundle(
registrationId: Int,
identity: IdentityKeyPair,
signedPreKey: SignedPreKey,
oneTimePreKey: OneTimePreKey? = null,
): PreKeyBundle {
return PreKeyBundle(
registrationId = registrationId,
identitySigningKey = identity.signingPublicKey,
identityDHKey = identity.dhPublicKey,
signedPreKey = PreKeyBundle.BundleSignedPreKey(
keyId = signedPreKey.keyId,
publicKey = signedPreKey.keyPair.publicKey,
signature = signedPreKey.signature,
),
oneTimePreKey = oneTimePreKey?.let {
PreKeyBundle.BundleOneTimePreKey(it.keyId, it.keyPair.publicKey)
},
)
}
/** Result of processing a prekey bundle (Alice's side) */
data class X3DHInitResult(
val rootKey: ByteArray,
val ephemeralPublicKey: ByteArray,
val signedPreKeyId: Int,
val preKeyId: Int?,
val remoteIdentityKey: ByteArray,
val remoteSignedPreKey: ByteArray,
)
/**
* Alice processes Bob's prekey bundle to establish a session.
*
* Steps:
* 1. Verify the signed prekey signature
* 2. Generate an ephemeral X25519 keypair
* 3. Compute DH1 = DH(Alice identity DH, Bob signed prekey)
* 4. Compute DH2 = DH(Alice ephemeral, Bob identity DH)
* 5. Compute DH3 = DH(Alice ephemeral, Bob signed prekey)
* 6. Compute DH4 = DH(Alice ephemeral, Bob one-time prekey) if available
* 7. Derive initial root key from concatenated DH outputs
*/
fun processPreKeyBundle(
crypto: CryptoProvider,
identity: IdentityKeyPair,
bundle: PreKeyBundle,
): X3DHInitResult {
// 1. Verify signed prekey signature
val valid = crypto.verify(
bundle.identitySigningKey,
bundle.signedPreKey.publicKey,
bundle.signedPreKey.signature,
)
if (!valid) throw SecurityException("Signed prekey signature is invalid")
// 2. Ephemeral keypair
val (ephPub, ephPriv) = crypto.generateX25519KeyPair()
// 3-6. DH computations
val dh1 = crypto.x25519(identity.dhPrivateKey, bundle.signedPreKey.publicKey)
val dh2 = crypto.x25519(ephPriv, bundle.identityDHKey)
val dh3 = crypto.x25519(ephPriv, bundle.signedPreKey.publicKey)
val secrets = mutableListOf(dh1, dh2, dh3)
var preKeyId: Int? = null
if (bundle.oneTimePreKey != null) {
val dh4 = crypto.x25519(ephPriv, bundle.oneTimePreKey.publicKey)
secrets.add(dh4)
preKeyId = bundle.oneTimePreKey.keyId
}
// 7. Derive root key
val rootKey = deriveInitialRootKey(crypto, secrets)
return X3DHInitResult(
rootKey = rootKey,
ephemeralPublicKey = ephPub,
signedPreKeyId = bundle.signedPreKey.keyId,
preKeyId = preKeyId,
remoteIdentityKey = bundle.identityDHKey,
remoteSignedPreKey = bundle.signedPreKey.publicKey,
)
}
/** Result of processing an incoming PreKeyMessage (Bob's side) */
data class X3DHResponseResult(
val rootKey: ByteArray,
val remoteIdentityKey: ByteArray,
val remoteEphemeralKey: ByteArray,
)
/**
* Bob processes an incoming PreKeyMessage to establish a session.
* Mirrors Alice's DH computations from Bob's perspective.
*
* Caller is responsible for looking up the signed prekey and (if present)
* the one-time prekey from storage.
*/
fun processPreKeyMessage(
crypto: CryptoProvider,
identity: IdentityKeyPair,
signedPreKeyPrivate: ByteArray,
oneTimePreKeyPrivate: ByteArray?,
message: PreKeyMessage,
): X3DHResponseResult {
val dh1 = crypto.x25519(signedPreKeyPrivate, message.identityDHKey)
val dh2 = crypto.x25519(identity.dhPrivateKey, message.ephemeralKey)
val dh3 = crypto.x25519(signedPreKeyPrivate, message.ephemeralKey)
val secrets = mutableListOf(dh1, dh2, dh3)
if (oneTimePreKeyPrivate != null) {
val dh4 = crypto.x25519(oneTimePreKeyPrivate, message.ephemeralKey)
secrets.add(dh4)
}
val rootKey = deriveInitialRootKey(crypto, secrets)
return X3DHResponseResult(
rootKey = rootKey,
remoteIdentityKey = message.identityDHKey,
remoteEphemeralKey = message.ephemeralKey,
)
}

View File

@@ -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('"')
}

View File

@@ -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)
}

View File

@@ -0,0 +1,145 @@
package no.zyon.shade.serialization
import no.zyon.shade.streams.StreamConstants
import java.nio.ByteBuffer
/**
* Wire-decoded stream-chunk envelope (type 0x11).
*
* Mirror @shade/proto/wire.ts `StreamChunkWire`. The nonce is deterministic
* (derived from `(laneId, seq)` on both sides) but is also serialized over
* the wire for self-description and validated by the receiver.
*
* `seq` is unsigned-u64 on the wire; on the JVM we keep it as Long. The
* encode/decode helpers operate on the raw 8-byte big-endian representation,
* so values past Long.MAX_VALUE roundtrip via `Long.toULong()`.
*/
data class StreamChunkWire(
val streamId: ByteArray,
val laneId: Long,
val seq: Long,
val isLast: Boolean,
val nonce: ByteArray,
val aad: ByteArray,
val ciphertext: ByteArray,
) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is StreamChunkWire) return false
return streamId.contentEquals(other.streamId) &&
laneId == other.laneId &&
seq == other.seq &&
isLast == other.isLast &&
nonce.contentEquals(other.nonce) &&
aad.contentEquals(other.aad) &&
ciphertext.contentEquals(other.ciphertext)
}
override fun hashCode(): Int {
var result = streamId.contentHashCode()
result = 31 * result + laneId.hashCode()
result = 31 * result + seq.hashCode()
result = 31 * result + isLast.hashCode()
result = 31 * result + nonce.contentHashCode()
result = 31 * result + aad.contentHashCode()
result = 31 * result + ciphertext.contentHashCode()
return result
}
}
/** Stream-chunk wire codec. Mirror @shade/proto/wire.ts `encodeStreamChunk`/`decodeStreamChunk`. */
object StreamChunkWireFormat {
private const val VERSION: Byte = 0x02
const val TYPE_STREAM_CHUNK: Byte = 0x11
fun encodeStreamChunk(c: StreamChunkWire): ByteArray {
require(c.streamId.size == StreamConstants.STREAM_ID_BYTES) {
"streamId must be ${StreamConstants.STREAM_ID_BYTES} bytes"
}
require(c.nonce.size == StreamConstants.STREAM_NONCE_BYTES) {
"nonce must be ${StreamConstants.STREAM_NONCE_BYTES} bytes"
}
require(c.laneId in 0L..0xFFFFFFFFL) { "laneId out of u32 range: ${c.laneId}" }
// c.seq is unsigned-u64; negative signed longs encode as the high half
// of the u64 range. ByteBuffer.putLong writes the raw 8-byte pattern.
val headerSize =
1 + 1 +
StreamConstants.STREAM_ID_BYTES +
4 + 8 + 1 +
StreamConstants.STREAM_NONCE_BYTES +
4 + c.aad.size +
4
val out = ByteArray(headerSize + c.ciphertext.size)
val buf = ByteBuffer.wrap(out)
buf.put(VERSION)
buf.put(TYPE_STREAM_CHUNK)
buf.put(c.streamId)
buf.putInt(c.laneId.toInt())
buf.putLong(c.seq)
buf.put(if (c.isLast) 0x01.toByte() else 0x00.toByte())
buf.put(c.nonce)
buf.putInt(c.aad.size)
buf.put(c.aad)
buf.putInt(c.ciphertext.size)
buf.put(c.ciphertext)
return out
}
fun decodeStreamChunk(data: ByteArray): StreamChunkWire {
val minHeaderSize = 2 +
StreamConstants.STREAM_ID_BYTES +
4 + 8 + 1 +
StreamConstants.STREAM_NONCE_BYTES +
4 + 4
require(data.size >= minHeaderSize) {
"stream-chunk too short: ${data.size} < $minHeaderSize"
}
require(data[0] == VERSION) { "Unknown version: ${data[0]}" }
require(data[1] == TYPE_STREAM_CHUNK) { "Not a stream-chunk: type=${data[1]}" }
val buf = ByteBuffer.wrap(data)
buf.position(2)
val streamId = ByteArray(StreamConstants.STREAM_ID_BYTES)
buf.get(streamId)
val laneId = buf.int.toLong() and 0xFFFFFFFFL
val seq = buf.long
val isLast = buf.get() == 0x01.toByte()
val nonce = ByteArray(StreamConstants.STREAM_NONCE_BYTES)
buf.get(nonce)
val aadLen = buf.int
require(buf.position() + aadLen + 4 <= data.size) {
"stream-chunk truncated in aad/ctLen"
}
val aad = ByteArray(aadLen)
buf.get(aad)
val ctLen = buf.int
require(buf.position() + ctLen == data.size) {
"stream-chunk length mismatch: declared ${buf.position() + ctLen}, actual ${data.size}"
}
val ciphertext = ByteArray(ctLen)
buf.get(ciphertext)
return StreamChunkWire(streamId, laneId, seq, isLast, nonce, aad, ciphertext)
}
/** Inspect the type tag without full parsing. Mirror @shade/proto/wire.ts. */
enum class EnvelopeKind { PREKEY, RATCHET, STREAM_CHUNK, UNKNOWN }
fun inspectEnvelopeType(data: ByteArray): EnvelopeKind {
if (data.size < 2 || data[0] != VERSION) return EnvelopeKind.UNKNOWN
return when (data[1]) {
0x01.toByte() -> EnvelopeKind.PREKEY
0x02.toByte() -> EnvelopeKind.RATCHET
TYPE_STREAM_CHUNK -> EnvelopeKind.STREAM_CHUNK
else -> EnvelopeKind.UNKNOWN
}
}
}

View File

@@ -0,0 +1,172 @@
package no.zyon.shade.serialization
import no.zyon.shade.types.PreKeyMessage
import no.zyon.shade.types.RatchetMessage
import no.zyon.shade.types.ShadeEnvelope
import java.nio.ByteBuffer
/**
* Compact binary wire format. MUST match @shade/proto/wire.ts byte-for-byte.
*
* Format: [version:1][type:1][payload...]
* Types: 0x01 = PreKeyMessage, 0x02 = RatchetMessage
* Integers: big-endian
* Byte arrays: 4-byte (u32) length prefix + data (since wire VERSION 0x02).
*
* VERSION 0x01 used a 2-byte length prefix and was capped at 64 KiB
* payloads — incompatible with inline file ops up to 256 KiB.
*/
object WireFormat {
private const val VERSION: Byte = 0x02
private const val TYPE_PREKEY: Byte = 0x01
private const val TYPE_RATCHET: Byte = 0x02
private const val PREKEY_NONE: Long = 0xFFFFFFFFL
// ─── Encode ──────────────────────────────────────────────
fun encodeEnvelope(envelope: ShadeEnvelope): ByteArray {
return when (envelope.type) {
ShadeEnvelope.EnvelopeType.PREKEY ->
encodePreKeyMessage(envelope.content as PreKeyMessage)
ShadeEnvelope.EnvelopeType.RATCHET ->
encodeRatchetMessage(envelope.content as RatchetMessage)
}
}
fun encodePreKeyMessage(msg: PreKeyMessage): ByteArray {
val ratchetBytes = encodeRatchetInner(msg.message)
val parts = mutableListOf<ByteArray>()
parts.add(byteArrayOf(VERSION, TYPE_PREKEY))
parts.add(uint32(msg.registrationId.toLong()))
parts.add(uint32(msg.preKeyId?.toLong() ?: PREKEY_NONE))
parts.add(uint32(msg.signedPreKeyId.toLong()))
parts.add(lpBytes(msg.ephemeralKey))
parts.add(lpBytes(msg.identityDHKey))
parts.add(lpBytes(ratchetBytes))
return concat(parts)
}
fun encodeRatchetMessage(msg: RatchetMessage): ByteArray {
val parts = mutableListOf<ByteArray>()
parts.add(byteArrayOf(VERSION, TYPE_RATCHET))
parts.add(encodeRatchetInner(msg))
return concat(parts)
}
private fun encodeRatchetInner(msg: RatchetMessage): ByteArray {
val parts = mutableListOf<ByteArray>()
parts.add(lpBytes(msg.dhPublicKey))
parts.add(uint32(msg.previousCounter.toLong()))
parts.add(uint32(msg.counter.toLong()))
parts.add(lpBytes(msg.ciphertext))
parts.add(lpBytes(msg.nonce))
return concat(parts)
}
// ─── Decode ──────────────────────────────────────────────
fun decodeEnvelope(data: ByteArray): ShadeEnvelope {
if (data.size < 2) throw IllegalArgumentException("Too short")
val version = data[0]
if (version != VERSION) throw IllegalArgumentException("Unknown version: $version")
val type = data[1]
val payload = data.copyOfRange(2, data.size)
return when (type) {
TYPE_PREKEY -> ShadeEnvelope(
type = ShadeEnvelope.EnvelopeType.PREKEY,
content = decodePreKeyMessageInner(payload),
timestamp = 0,
senderAddress = "",
)
TYPE_RATCHET -> {
val (msg, _) = decodeRatchetInner(payload, 0)
ShadeEnvelope(
type = ShadeEnvelope.EnvelopeType.RATCHET,
content = msg,
timestamp = 0,
senderAddress = "",
)
}
else -> throw IllegalArgumentException("Unknown type: $type")
}
}
private fun decodePreKeyMessageInner(data: ByteArray): PreKeyMessage {
var offset = 0
val registrationId = readUint32(data, offset).toInt(); offset += 4
val preKeyIdRaw = readUint32(data, offset); offset += 4
val preKeyId = if (preKeyIdRaw == PREKEY_NONE) null else preKeyIdRaw.toInt()
val signedPreKeyId = readUint32(data, offset).toInt(); offset += 4
val ephemeral = readLP(data, offset); offset = ephemeral.second
val identityDH = readLP(data, offset); offset = identityDH.second
val ratchetData = readLP(data, offset); offset = ratchetData.second
val (ratchet, _) = decodeRatchetInner(ratchetData.first, 0)
return PreKeyMessage(
registrationId = registrationId,
preKeyId = preKeyId,
signedPreKeyId = signedPreKeyId,
ephemeralKey = ephemeral.first,
identityDHKey = identityDH.first,
message = ratchet,
)
}
private fun decodeRatchetInner(data: ByteArray, startOffset: Int): Pair<RatchetMessage, Int> {
var offset = startOffset
val dhPub = readLP(data, offset); offset = dhPub.second
val prevCounter = readUint32(data, offset).toInt(); offset += 4
val counter = readUint32(data, offset).toInt(); offset += 4
val ciphertext = readLP(data, offset); offset = ciphertext.second
val nonce = readLP(data, offset); offset = nonce.second
return RatchetMessage(
dhPublicKey = dhPub.first,
previousCounter = prevCounter,
counter = counter,
ciphertext = ciphertext.first,
nonce = nonce.first,
) to offset
}
// ─── Helpers ─────────────────────────────────────────────
private fun uint32(n: Long): ByteArray {
val buf = ByteBuffer.allocate(4)
buf.putInt(n.toInt())
return buf.array()
}
private fun lpBytes(data: ByteArray): ByteArray {
val len = ByteBuffer.allocate(4)
len.putInt(data.size)
return concat(listOf(len.array(), data))
}
private fun readUint32(data: ByteArray, offset: Int): Long {
return ((data[offset].toLong() and 0xff) shl 24) or
((data[offset + 1].toLong() and 0xff) shl 16) or
((data[offset + 2].toLong() and 0xff) shl 8) or
(data[offset + 3].toLong() and 0xff)
}
private fun readLP(data: ByteArray, offset: Int): Pair<ByteArray, Int> {
val len = readUint32(data, offset).toInt()
val value = data.copyOfRange(offset + 4, offset + 4 + len)
return value to (offset + 4 + len)
}
private fun concat(parts: List<ByteArray>): ByteArray {
val total = parts.sumOf { it.size }
val result = ByteArray(total)
var offset = 0
for (p in parts) {
p.copyInto(result, offset)
offset += p.size
}
return result
}
}

View File

@@ -0,0 +1,47 @@
package no.zyon.shade.storage
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.types.IdentityKeyPair
import no.zyon.shade.types.OneTimePreKey
import no.zyon.shade.types.SessionState
import no.zyon.shade.types.SignedPreKey
/**
* In-memory storage for tests and embedded use.
* Mirrors MemoryStorage in @shade/crypto-web.
*/
class MemoryStorage(private val crypto: CryptoProvider) : StorageProvider {
private var identity: IdentityKeyPair? = null
private var registrationId: Int = 0
private val signedPreKeys = mutableMapOf<Int, SignedPreKey>()
private val oneTimePreKeys = mutableMapOf<Int, OneTimePreKey>()
private val sessions = mutableMapOf<String, SessionState>()
private val trustedIdentities = mutableMapOf<String, ByteArray>()
override suspend fun getIdentityKeyPair(): IdentityKeyPair? = identity
override suspend fun saveIdentityKeyPair(keyPair: IdentityKeyPair) { identity = keyPair }
override suspend fun getLocalRegistrationId(): Int = registrationId
override suspend fun saveLocalRegistrationId(id: Int) { registrationId = id }
override suspend fun getSignedPreKey(keyId: Int): SignedPreKey? = signedPreKeys[keyId]
override suspend fun saveSignedPreKey(key: SignedPreKey) { signedPreKeys[key.keyId] = key }
override suspend fun removeSignedPreKey(keyId: Int) { signedPreKeys.remove(keyId) }
override suspend fun getOneTimePreKey(keyId: Int): OneTimePreKey? = oneTimePreKeys[keyId]
override suspend fun saveOneTimePreKey(key: OneTimePreKey) { oneTimePreKeys[key.keyId] = key }
override suspend fun removeOneTimePreKey(keyId: Int) { oneTimePreKeys.remove(keyId) }
override suspend fun getOneTimePreKeyCount(): Int = oneTimePreKeys.size
override suspend fun getSession(address: String): SessionState? = sessions[address]
override suspend fun saveSession(address: String, state: SessionState) { sessions[address] = state }
override suspend fun removeSession(address: String) { sessions.remove(address) }
override suspend fun isTrustedIdentity(address: String, identityKey: ByteArray): Boolean {
val stored = trustedIdentities[address] ?: return true // TOFU
return crypto.constantTimeEqual(stored, identityKey)
}
override suspend fun saveTrustedIdentity(address: String, identityKey: ByteArray) {
trustedIdentities[address] = identityKey
}
}

Some files were not shown because too many files have changed in this diff Show More