63 Commits

Author SHA1 Message Date
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
261 changed files with 29237 additions and 272 deletions

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

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

View File

@@ -5,6 +5,295 @@ All notable changes to Shade are documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
## [4.15.0] — 2026-10-18 — Media: films, video, images, audio and live streams, end to end
New package **`@shade/media`** — see `docs/media.md`.
- **Sealed media (SMF1).** A film, video, song or image is sealed once
(streaming, constant memory, ~300 MiB/s) into a file any Range-capable
store can serve. Readers fetch only the segments under the playhead; every
segment is checked against a digest table pinned by the grant's root
digest, so neither the store nor another key holder can substitute bytes.
Seek over HTTP: ~4 ms to the first decrypted byte (localhost).
- **Live channels (SLF1).** Logs, text, live video/audio and images from one
publisher to many viewers through a relay. Sender-Keys hash chain (each
frame key used once), every frame Ed25519-signed, sticky init frames and
keyframe snapshots so a viewer can join late, epoch rotation to remove a
viewer, and link mode so a capability link survives publisher restarts.
200 viewers: 100 % delivered, p50 28 ms.
- **Grants** carry the keys over an existing Shade session —
`shade.shareMedia(peer, grant)` / `shade.onMediaGrant(handler)` in the SDK —
or in a `#shade=` link fragment that never reaches a server.
- **Browser.** A Service Worker plays sealed files in native
`<video>`/`<audio>`/`<img>` with seeking; `LivePlayer` plays live WebM or
fragmented MP4 (H.264/HEVC/AV1 + AAC/Opus) via MSE; the relay serves a `/watch/` page that opens any link.
- **Server.** `createMediaService`: disk-backed sealed store with signed
owner uploads and immutable objects, a WebSocket live relay with bounded
backlog and slow-viewer shedding, and the watch page. Mounted by the
container when `SHADE_MEDIA_DIR` is set (no in-memory fallback);
`SHADE_MEDIA_OWNERS` lists who may upload and open channels.
- **CLI.** `shade media serve|put|get|ls|rm|whoami`,
`shade live text|video|watch` (`tail -f … | shade live text`,
`ffmpeg … -f webm - | shade live video`, or `-f mp4 -movflags
frag_keyframe+empty_moov` for H.264/AAC; the container is detected).
`MediaSplitter`, `WebmSplitter` and `Fmp4Splitter` are exported for apps
that publish from their own source.
- **Albums.** One link for a season, a photo album or a camera wall: an
album is a sealed file listing grants (`shade.album/v1`), so the relay
cannot tell it from a film. `shade media put dir/` uploads every file
and prints the album's link (subdirectories become nested albums, in
natural order); `shade media get` downloads an album back into a
directory; `/watch/` shows it as a grid with decrypted previews.
`uploadAlbum`, `openAlbum`, `Albums.read` (Kotlin), and a shared vector.
- **Subtitles.** `shade media put Film.mkv` seals `Film.srt`,
`Film.no.srt`, `Film.en.vtt` … beside it and carries their grants in the
film's sealed meta; `/watch/` shows them as `<track>`s (SRT converted to
VTT, the viewer's language on), `media get` writes them back, and
Android plays them as side-loaded ExoPlayer text tracks
(`ShadeMedia.openFilm`).
- **`media put --web`.** Films with AC-3/DTS audio or HEVC video (Chromium
refuses them outright) are converted before sealing: what browsers play
is copied, the rest becomes H.264/AAC, embedded text subtitles become
subtitle tracks, all in one ffmpeg pass. Without the flag, `put` warns
when ffprobe sees streams browsers will not play.
- **Shared media library.** `SHADE_MEDIA_S3_URL` + `SHADE_MEDIA_PG_URL` (or
`media serve --s3 --pg`): sealed films in any S3 bucket, records and live
pins in Postgres, so several relay instances serve one library.
`ObjectMediaStore` streams uploads as multipart with bounded memory, decides
racing uploads by the Postgres primary key, and sweeps orphaned objects and
dead multipart uploads. `S3Bucket` is a small SigV4 client of Shade's own
(Bun 1.3.5's `S3Client` buffers whole uploads). `PostgresMediaIndex`,
`PostgresLivePinStore`, `createSharedMediaBackend` in
`@shade/storage-postgres`. A live pin can no longer change key, even between
instances (`LivePinTakenError`).
- **Uploads in pieces, resumable.** A sealed file over 16 MiB goes up as
`POST /v1/media/:id/upload` + 16 MiB `PUT` pieces (each signed over its
offset), up to 4 in flight and landing in any order. 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 under way survive restarts (`uploads/` on disk, `shade_media_uploads`
beside the S3 multipart upload), count against quota and are swept after
24 h without a piece. `media put` shows progress, and resumes across runs:
after Ctrl-C or a long outage the same command goes on with the same
media id (sealed copy and job under `$XDG_CONFIG_HOME/shade/media-pending/`),
and a file already up gives its link again instead of a second copy. Above all, a relay's
memory no longer grows with the film (see Fixed).
- **`shade live record <link>`**: a channel to files until it ends: text,
seekable WebM/MP4 (ffmpeg `-c copy`, clock from 0:00), pictures. `--put`
seals and uploads the recording under the channel's name, so a broadcast
can be watched later (`LiveRecorder` in `@shade/media/node`). `live
video` now sends its name as a sticky `meta` frame like the other kinds.
- **`shade live video --input`** a film, `/dev/video0` or `rtsp://…`: ffmpeg is
run for you, H.264/AAC copied (a camera's own encoder) and anything else
encoded to H.264 (keyframe every 2 s) and AAC, as low-latency fMP4.
- **`shade live images`.** A channel of pictures: JPEG/PNG piped in (a
webcam through `ffmpeg -f image2pipe`), a slideshow of files, or each new
picture landing in a watched folder. `ImageStreamSplitter` walks JPEG
markers and PNG chunks. The Android demo shows live and sealed pictures.
- **Live channels across relay instances.** `LiveRelayOptions.mesh` with a
`LivePublisherLocator` (`PostgresLivePublisherLocator`;
`SHADE_MEDIA_RELAY_URL` / `media serve --advertise`): a relay with viewers
of a channel published elsewhere follows the relay that has the publisher,
verifying every frame against the pin, and viewers follow a publisher that
moves. Viewers get a `state` message when a channel goes live or quiet.
`LiveRelay.stop()` / `MediaService.stop()` now resolve once the relay's
claims are released; the container and `media serve` (SIGINT/SIGTERM) wait
for it and close the Postgres pool, so a redeploy does not leave other
instances pointing at a relay that is gone.
- **Library.** `media put` records each upload and its grant in
`$XDG_CONFIG_HOME/shade/media-library.jsonl` (0600, append-only); `media
ls` shows names, `media link <name|id>` prints a link again. Grants now
encode their meta canonically, so one grant is always one link.
- **Kotlin.** `no.zyon.shade.media`: SMF1 reader and sealer, grants, live
subscriber and publisher — byte-for-byte against `test-vectors/media.json`.
`:shade-android-media` plays sealed files in Media3/ExoPlayer
(`ShadeMediaDataSource`, `ShadeMedia.mediaSource(reader)`), and
`:shade-media-demo` is a player app that opens a shared watch link.
Live channels on Android: `LiveWatcher` (OkHttp) and
`ShadeMedia.liveMediaSource(grant)` play live WebM/fMP4 in ExoPlayer,
with late joining from a keyframe, gap recovery and the timeline rebased
to 0:00.
- **Uploads from Kotlin.** `MediaUploader` puts sealed files on a relay from
a phone: one PUT up to 16 MiB, larger ones in pieces with the relay's
window, retries and a resync after a lost answer — the same protocol as
`media put`. `MediaOwner` signs owner requests (byte for byte against the
new owner vector), `MediaSealer.sealStream` seals a film to a file, and
`MediaGrant.encode()` / `capabilityUrl(page)` make the link to share
(against a new grant-encode vector). `scripts/media-live-kotlin.ts` runs it
against a real TS relay with a lost answer and a refused piece injected;
TS reads the film back byte for byte.
- **Share to Shade (Android).** `UploadJobs` lets an upload survive the app
being killed (sealed once, resumed with the same media id, one link per
shared file); `ShadeUpload` seals a shared `content://` URI with its name,
type, duration and picture size; `KeystoreSecretFile` keeps the owner seed
under a Keystore key. The demo app takes shares from the gallery, uploads
them in a foreground service with progress, and offers the link to play or
share. Several files shared at once become one album link
(`MediaUploader.uploadAlbum`, `Albums.encode`, `Grant.encode` for live
grants too — the album vector now resealed byte for byte from Kotlin), and
the demo player lists an album's items and opens them in place.
Its minSdk is now 28.
### Fixed
- An uploader (TS and Kotlin) trusted the relay's upload status: a `chunk` of
0 looped forever, a huge one held the film in memory, a huge `window` opened
a request (a thread, on Kotlin) per piece. The status is now checked
(`statusProblem`) and the window capped at 16.
- `MediaClient` waited between retries with `Bun.sleep`, so a retry threw in
a browser or Node; it uses `setTimeout` now (the browser bundle of
`@shade/media` has no `Bun.*` left).
- `shade media get` used the sealed file's `meta.name` as the output path,
so whoever sealed a file chose where it was written (`../../.bashrc`).
Names are now reduced to one safe path component.
- A relay test raced: `flush()` means sent, not received, so a viewer could
join mid-burst and (correctly) get an older backlog. The relay now counts
`framesIn` in `stats()`, and the test waits on it.
- The live relay never noticed its publisher leave: Hono hands each event its
own `WSContext`, and the close handler compared them by identity. A channel
stayed "live" with nobody publishing, and a replaced publisher's socket was
never closed. They are compared by the socket underneath now.
- `shade live video` labelled every stream `video/…`, so a live radio stream
(Opus or AAC alone) played sound in a black video box. The meta now carries
the init segment's type, and the page gives sound an audio player.
- `FileMediaStore` on a directory it could not use rejected at start with no
handler (an unhandled rejection). Now every call fails with the reason.
- The container refused every request body over 128 MiB (Bun's default),
which would have made every film a 413. Films now go up in pieces of at
most 64 MiB, so the cap stays, and every route has an explicit 128 MiB
body limit.
- An upload put the whole film in the relay's memory whenever the store was
slower than the client: Bun.serve reads a request body as fast as it
arrives, whether the handler takes it or not. One `PUT` of a 512 MiB film
peaked at 762 MiB (disk) and 1011 MiB (S3). In pieces it stays the same at
512 MiB and 1.5 GiB (`bench/media-store.ts`).
- The media sweep ran only for the S3 store, from two copies of the timer
(container and `media serve`). It is now part of every store and of
`createMediaService` (`onSweep` reports it), hourly.
### Also in 4.15.0
- **`@shade/media/worker`: Shade's media handler inside an app's own Service
Worker.** A worker answers every request of the pages it controls, so an
installed PWA with a worker at `/` never let `media/<id>` reach Shade's
worker beside it. `installShadeMedia(self)`, `isShadeMediaRequest(req)` and
`shadeMediaResponse(req)` put it in the app's worker instead. The standalone
`browser/sw.ts` is now a thin wrapper around the same module.
- **`media put` records length and picture size.** Video, audio and images
are measured with ffprobe (after `--web`, so the numbers match the sealed
file) and sealed with `durationMs`, `width` and `height` in their meta. A
viewer can show a film's length on a tile and reserve its shape without
fetching a byte. Without ffprobe the fields are left out, as before.
- **Publishing.** `@shade/media` is in the publish order (first: it depends on
no other Shade package), so `@shade/server`, `@shade/sdk` and `@shade/cli`
no longer point at a package the registry does not have. `@shade/observer`
builds to `dist/` like the rest and is no longer published empty, and a
`bin` on `src/*.ts` is rewritten to `dist/*.js`, so `shade` runs after
install instead of failing on its first import.
## [4.14.1] — 2026-10-16 — Vault: `edit` for vaults two devices write
- `VaultClient.edit(change, at)` changes a few files against the head that
was actually read and commits `head + 1`; on `SEQ_CONFLICT` it re-reads and
calls `change` again. `push` publishes a whole collection and would drop a
file another device appended in between — right for a backup with one
writer, wrong for a queue a phone appends to while a PC drains it.
## [4.14.0] — 2026-10-16 — Vault v2: smaller, cheaper pushes, big files, retention
### Added
- **`@shade/vault`: compressed and multi-part entries.** A file is deflated
(raw, kept only if it saves ≥ 5 %, skipped for known compressed formats)
and split into 4 MiB parts. `VaultEntry` gains optional `enc` and `parts`;
`size` stays the plaintext length. Files over the relay's 8 MiB object limit
can now be backed up at all.
- **Manifest v2**: `"SVM2"` + deflate-raw(JSON). Push writes v2; readers
accept v1 and v2 and refuse anything else.
- **`VaultIndex`** — `push(files, at, message?, { index })` returns an `index`
to persist. With a fresh one, an unchanged file is recognised by plaintext
SHA-256 with no download, no seal and no upload (renames and copies too).
- **A push that changes nothing commits nothing** (`unchanged: true`), unless a
`message` asks for a version.
- **Lazy reads**: `VaultClient.manifest(seq?)` and `readEntry(entry)`; `pull`
is built on them. Exported helpers: `openEntryBytes`, `entryObjectHashes`,
`packEntry`, `sealEntry`, `encodeManifest`/`decodeManifest`, `vaultIndexFrom`.
- **Retention**: signed `POST /v1/vault/:id/prune` `{ keep }`,
`VaultClient.prune(keep)` → `{ removedVersions, removedObjects, freedBytes }`.
The relay records each commit's referenced hashes and collects objects no
remaining version uses. Versions from before this pin their objects until
they are pruned themselves. `VaultRoutesOptions.pruneGraceMs` (default 1 h)
protects uploads whose commit is still in flight.
- `VaultStore.prune` and an optional `refs` argument on `appendLog`;
`SqliteVaultStore` migrates its schema in place on open.
- `test-vectors/vault-v2.json` for the Kotlin port; `@shade/vault/testing`
(fixed-nonce sealing, vectors only).
### Changed
- Push without an index reads only the head manifest and downloads a previous
file only when its path and size match — it used to download every file of
the head. Freshly sealed objects are no longer have-checked (their names are
new by construction). A reused entry takes the file's current `mode`.
- `VaultTransport` has a required `prune` method; custom transports must add it.
## [4.13.2] — 2026-10-15 — No prekey-server call can hang an identity open
### Fixed
- **`@shade/transport`: every prekey-server request has a deadline**
(`requestTimeoutMs`, default 15 000; `DEFAULT_REQUEST_TIMEOUT_MS` exported).
A server that drops packets instead of refusing them held each call until
the kernel gave up on the TCP handshake — about two minutes on Linux.
Expiry throws a `NetworkError` naming the host.
- **`@shade/sdk`: a failed initial registration is actually retried** — with
backoff (5/15/30/60 s) until it succeeds, the identity rotates or is
restored, or `shutdown()` runs. The old log line promised a retry "on next
replenish", but replenish never registers: an identity that came up while
the server was unreachable stayed unregistered until the next restart.
### Added
- `ShadeConfig.registration: 'await' | 'background'` (default `'await'`, now
bounded by the timeout). `'background'` opens the identity without waiting
on the network — for apps whose unlock must be purely local.
- `ShadeConfig.requestTimeoutMs` and `ShadeConfig.fetch` (also on
`ShadeFetchTransport`): observe reachability, or stub the network in tests.
Found by Prism: with the relay unreachable, unlock — and with it the first
terminal — waited minutes on a register call.
## [4.13.1] — 2026-10-06 — Inbox keeps per-recipient order across retries
### Fixed
- **`@shade/inbox`: a failed PUT no longer lets the next message overtake it.**
`flushOnce` drained each recipient's bucket sequentially but carried on
past a failure, so entry N+1 was delivered in the same round and N only on
the retry — the recipient saw them reversed. For sender-key broadcasts that
is data loss, not cosmetics: a receiver that has advanced past iteration N
cannot open it. The bucket now stops at the first failure (head-of-line,
per recipient only; other recipients still drain in parallel). An entry
dropped at `maxAttempts` gives up its place. Found by Prism, where it
showed up as frozen terminal output on phones.
### Docs
- `senderKeyDecrypt` no longer claims a skipped-key cache it never had.
Out-of-order group messages still throw "Stale iteration"; senders must
deliver in iteration order (which the inbox fix above now guarantees).
## [4.11.2] — 2026-07-10 — Files pull-mode startup hotfix
**`@shade/files`**
- Fix a construction race in HTTP pull-mode clients: an immediate streamed
read/write now awaits asynchronous stream-bridge registration instead of
treating the not-yet-created queue drainer as proof that the client is
inline-only.
- Add a deterministic integration test that holds incoming-transfer
registration, starts a 512 KiB write immediately, and verifies that it
remains pending until streaming is ready.
- Add `publish-all.ts --only <pkg>` so isolated package hotfixes do not publish
unrelated workspace packages.
## [4.11.0] — 2026-05-15 — Streaming Double-Ratchet sub-sessions
Answers Vyvern FR `shade-ws-streaming-ratchet.md` (the last Phase-2

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

@@ -2,4 +2,5 @@ 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

@@ -21,3 +21,7 @@ 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 @@
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,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

@@ -49,6 +49,10 @@ dependencies {
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

@@ -1,6 +1,7 @@
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
@@ -187,62 +188,6 @@ class BlobClient(
}
}
/**
* Mirror of TS `signPayload`'s canonicalization: sorted keys, compact
* JSON, signature field absent. Only handles the subset of types we
* need (strings + longs + base64 strings) — keeping the implementation
* narrow so it can't accidentally diverge from `JSON.stringify` on
* structurally-different inputs.
*/
internal fun canonicalJson(map: Map<String, Any>): String {
val sb = StringBuilder()
sb.append('{')
var first = true
for ((key, value) in map.toSortedMap()) {
if (!first) sb.append(',')
first = false
appendJsonString(sb, key)
sb.append(':')
appendJsonValue(sb, value)
}
sb.append('}')
return sb.toString()
}
private fun appendJsonValue(sb: StringBuilder, value: Any) {
when (value) {
is String -> appendJsonString(sb, value)
is Long, is Int -> sb.append(value.toString())
is Boolean -> sb.append(value.toString())
else -> throw IllegalArgumentException(
"canonicalJson: unsupported value type ${value::class.java}",
)
}
}
private fun appendJsonString(sb: StringBuilder, s: String) {
sb.append('"')
for (c in s) {
when (c) {
'\\' -> sb.append("\\\\")
'"' -> sb.append("\\\"")
'\b' -> sb.append("\\b")
'\u000C' -> sb.append("\\f")
'\n' -> sb.append("\\n")
'\r' -> sb.append("\\r")
'\t' -> sb.append("\\t")
else -> {
if (c.code < 0x20) {
sb.append("\\u").append("%04x".format(c.code))
} else {
sb.append(c)
}
}
}
}
sb.append('"')
}
class BlobClientException(
val code: String,
val statusCode: Int,

View File

@@ -1,6 +1,6 @@
package no.zyon.shade.blob
import com.google.crypto.tink.subtle.Ed25519Sign
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
import no.zyon.shade.crypto.CryptoProvider
/**
@@ -72,13 +72,20 @@ fun deriveBlobSigningSeed(crypto: CryptoProvider, masterKey: ByteArray, app: Str
/**
* Recover the Ed25519 public key from a 32-byte seed. Mirrors
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`. Tink's
* `Ed25519Sign.KeyPair.newKeyPairFromSeed(seed)` exposes both halves;
* we discard the private half here.
* `@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 Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey
return Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
}
/** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */

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,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,223 @@
package no.zyon.shade.vault
import no.zyon.shade.crypto.CryptoProvider
import java.security.MessageDigest
import java.util.Base64
/** A file as the app sees it, before encryption. */
class VaultFile(val path: String, val bytes: ByteArray, val mode: String? = null)
/**
* A few files changed, for [VaultClient.edit] — mirror of TS `VaultEdit`.
*/
class VaultEdit(
/** Files to add, or to replace at the same path. Paths must be distinct. */
val put: List<VaultFile> = emptyList(),
/** Paths to drop. A path that is not there is ignored. */
val remove: List<String> = emptyList(),
)
/** What [VaultClient.edit] did. */
data class VaultEditResult(
/** The head after the edit: the new version, or the unchanged head. */
val seq: Long,
/** False when the edit changed nothing and no version was committed. */
val committed: Boolean,
)
/** A whole version, decrypted. */
class VaultPull(val manifest: VaultManifest, val files: Map<String, ByteArray>)
/**
* The client half of `@shade/vault` v2 for a phone: read a vault whose writer
* (the PC) may be switched off, and edit a vault several devices write to —
* such as a queue of changes the phone appends to and the PC drains.
*
* What it deliberately does not port is TS `push` (publish a whole
* collection from local files, with an index): a phone is not the source of
* truth for a workspace, and a whole-collection push from a stale view is
* exactly how another device's latest file gets lost. [edit] is the write
* primitive here.
*
* Blocking, like the transport: call from a background dispatcher.
*
* @param clock wall clock for `signedAt` — the relay rejects signatures older
* than five minutes, so this must be real time outside tests.
* @param chunkSize part size; tests only. Real writers use [VAULT_CHUNK_SIZE]
* so every implementation splits identically.
*/
class VaultClient(
private val crypto: CryptoProvider,
private val keys: VaultKeys,
private val transport: VaultTransport,
private val chunkSize: Int = VAULT_CHUNK_SIZE,
private val clock: () -> Long = System::currentTimeMillis,
) {
val vaultId: String get() = keys.vaultId
/** Version history, newest last. [limit] counts back from the head. */
fun log(limit: Int? = null): VaultLog = transport.log(keys.vaultId, limit)
/**
* Fetch and open just a version's manifest; defaults to the head. The
* cheap way to list a thousand-file workspace: one download, then
* [readEntry] only what the user opens.
*
* @throws VaultException `NOT_FOUND` when there is no such version
* (including the head of an empty vault — see [headManifest]).
*/
fun manifest(seq: Long? = null): VaultManifest {
// The head needs only the newest row; an older version needs the log
// to find its row, since `limit` counts back from the head.
val log = transport.log(keys.vaultId, if (seq == null) 1 else null)
val wanted = seq ?: log.head
val row = log.entries.firstOrNull { it.seq == wanted }
?: throw VaultException(VaultException.CODE_NOT_FOUND, 0, "vault has no version $wanted")
return openRow(row)
}
/** The head manifest, or null when nothing has ever been committed. */
fun headManifest(): VaultManifest? {
val log = transport.log(keys.vaultId, 1)
val row = log.entries.firstOrNull { it.seq == log.head } ?: return null
return openRow(row)
}
/** Fetch, verify, decrypt and reassemble one file of a manifest. */
fun readEntry(entry: VaultEntry): ByteArray {
val objects = entryObjectHashes(entry).map { transport.get(keys.vaultId, it) }
return openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, objects)
}
/** Fetch a version and decrypt all of it; defaults to the head. */
fun pull(seq: Long? = null): VaultPull {
val manifest = manifest(seq)
val files = LinkedHashMap<String, ByteArray>()
for (entry in manifest.entries) files[entry.path] = readEntry(entry)
return VaultPull(manifest, files)
}
/**
* Change a few files against the head that was actually read, and only it
* — mirror of TS `VaultClient.edit`.
*
* Reads the head, lets [change] decide from exactly that manifest (null
* for an empty vault), keeps every entry it did not touch as-is — same
* hash, same parts, never re-sealed — and commits `head + 1`. If another
* device committed in between, the relay answers SEQ_CONFLICT and this
* starts over from the new head, calling [change] again: it must be a
* pure decision about the manifest it is given.
*
* Returning null, or an edit with no puts that removes nothing present,
* commits nothing.
*
* One deliberate difference from TS: a file sealed in a lost attempt is
* not sealed again on the retry. Its objects are already on the relay
* (covered by the prune grace period), and on a phone the upload is the
* expensive part. The committed manifest is the same either way.
*
* @throws VaultException SEQ_CONFLICT after [maxAttempts] lost races, or
* any other relay refusal at once.
* @throws VaultFormatException when the head cannot be read — editing on
* top of a manifest this client cannot parse would drop its files.
*/
fun edit(at: Long, maxAttempts: Int = 5, change: (VaultManifest?) -> VaultEdit?): VaultEditResult {
val attempts = maxOf(1, maxAttempts)
// Plaintext digest + path → the entry its upload produced, across attempts.
val sealedThisEdit = HashMap<String, VaultEntry>()
var attempt = 1
while (true) {
val log = transport.log(keys.vaultId, 1)
val head = log.head
val row = log.entries.firstOrNull { it.seq == head }
val manifest = row?.let { openRow(it) }
val edit = change(manifest)
val put = edit?.put.orEmpty()
val remove = edit?.remove.orEmpty().toSet()
val current = manifest?.entries.orEmpty()
val replaced = put.map { it.path }.toSet()
require(replaced.size == put.size) { "VaultEdit.put lists the same path more than once" }
if (put.isEmpty() && current.none { it.path in remove }) {
return VaultEditResult(seq = head, committed = false)
}
val entries = current.filterTo(ArrayList()) { it.path !in remove && it.path !in replaced }
for (file in put) {
val key = sha256Hex(file.bytes) + "\u0000" + file.path
val located = sealedThisEdit.getOrPut(key) { upload(file) }
entries.add(located.copy(mode = file.mode))
}
try {
val seq = commitManifest(entries, head + 1, at)
return VaultEditResult(seq = seq, committed = true)
} catch (e: VaultException) {
// Only a lost race is worth another go; the manifest object
// just uploaded is an orphan the relay's GC will collect.
if (attempt >= attempts || !e.isSeqConflict) throw e
}
attempt++
}
}
/** Add or replace [files], keeping everything else — [edit] with only puts. */
fun append(files: List<VaultFile>, at: Long, maxAttempts: Int = 5): VaultEditResult =
edit(at, maxAttempts) { VaultEdit(put = files) }
/**
* Drop every version not in [keep] and let the relay delete objects only
* those versions used. [keep] must include the current head.
*/
fun prune(keep: List<Long>): VaultPruneResult =
transport.prune(keys.vaultId, sign(mapOf("keep" to keep)))
// ─── Internals ───────────────────────────────────────────
/** Seal one file into fresh objects and PUT them; the entry, without mode. */
private fun upload(file: VaultFile): VaultEntry {
val sealed = sealEntry(crypto, keys.contentKey, keys.vaultId, file.bytes, chunkSize)
// No have-check: every object was just sealed under a fresh nonce,
// so its name is new by construction.
for (obj in sealed.objects) {
transport.put(keys.vaultId, obj.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(obj.bytes))))
}
return VaultEntry(
path = file.path,
hash = sealed.locator.hash,
size = file.bytes.size.toLong(),
enc = sealed.locator.enc,
parts = sealed.locator.parts,
)
}
/**
* Seal and upload a v2 manifest naming [entries], then commit it as [seq].
* Every entry's objects must already be on the relay. `hashes` lists every
* part of every entry: the relay checks they exist, and records them as
* what the version references — a part left out may be pruned.
*/
private fun commitManifest(entries: List<VaultEntry>, seq: Long, at: Long): Long {
val manifest = VaultManifest(version = 2, seq = seq, at = at, entries = entries)
val sealed = sealManifest(crypto, keys.contentKey, keys.vaultId, manifest)
transport.put(keys.vaultId, sealed.hash, sign(mapOf("data" to Base64.getEncoder().encodeToString(sealed.bytes))))
val hashes = LinkedHashSet<String>().apply { entries.forEach { addAll(entryObjectHashes(it)) } }
return transport.commit(
keys.vaultId,
sign(
linkedMapOf(
"manifest" to sealed.hash,
"seq" to seq,
"at" to at,
"hashes" to hashes.toList(),
),
),
)
}
private fun sign(body: Map<String, Any>): String = signVaultBody(crypto, keys, body, clock()).json
private fun openRow(row: VaultLogEntry): VaultManifest =
openManifest(crypto, keys.contentKey, keys.vaultId, row.manifest, transport.get(keys.vaultId, row.manifest))
private fun sha256Hex(bytes: ByteArray): String = toHex(MessageDigest.getInstance("SHA-256").digest(bytes))
}

View File

@@ -0,0 +1,364 @@
package no.zyon.shade.vault
import no.zyon.shade.blob.aeadSeal
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.serialization.stringifyJson
import java.io.ByteArrayOutputStream
import java.security.GeneralSecurityException
import java.security.MessageDigest
import java.util.zip.DataFormatException
import java.util.zip.Deflater
import java.util.zip.Inflater
/**
* Sealing, naming, packing and manifest encoding — mirror of
* `@shade/vault/src/crypto.ts`. The cross-language contract is the
* "Format (v2)" section of `docs/vault.md`; vectors in
* `test-vectors/vault-v2.json`.
*
* Every object on the relay is `nonce(12) || ciphertext || tag(16)`, named by
* the lowercase hex SHA-256 of those bytes. Hashing the *ciphertext* is what
* lets the relay check an upload without holding a key; the price is that
* identical plaintext gets a new name on every seal (fresh nonce), so
* unchanged files must reuse their old entry instead of being re-sealed.
*/
private const val NONCE_LEN = 12
private const val TAG_LEN = 16
/**
* Largest stored (post-compression) slice sealed as one object: 4 MiB.
* Part of the wire contract — every writer splits at the same boundary.
*/
const val VAULT_CHUNK_SIZE = 4 * 1024 * 1024
/**
* Ceiling on an inflated manifest. Manifests are sealed under our own key, so
* a decompression bomb could only come from a device that holds it — but a
* corrupted write should fail with a message, not by exhausting the heap.
*/
private const val MAX_MANIFEST_BYTES = 256L * 1024 * 1024
/** ASCII "SVM2" — marks a compressed v2 manifest. */
private val MANIFEST_V2_MAGIC = byteArrayOf(0x53, 0x56, 0x4d, 0x32)
/** One sealed object: its relay name and its bytes. */
class SealedObject(val hash: String, val bytes: ByteArray)
/** Lowercase hex SHA-256 — the name of an object. */
fun objectHash(sealed: ByteArray): String =
toHex(MessageDigest.getInstance("SHA-256").digest(sealed))
/**
* AAD for an object: binds the vault, so a ciphertext lifted from one vault
* cannot be planted in another even by someone who can write to both. The
* content hash is deliberately not in it — it is derived from the very bytes
* being sealed.
*/
fun vaultObjectAad(vaultId: String): ByteArray =
"shade-vault-object-v1|$vaultId".toByteArray(Charsets.UTF_8)
/** Encrypt one object under a fresh random nonce and give it its name. */
fun sealObject(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, plaintext: ByteArray): SealedObject {
val (ciphertext, nonce) = crypto.aesGcmEncrypt(contentKey, plaintext, vaultObjectAad(vaultId))
val bytes = ByteArray(NONCE_LEN + ciphertext.size)
System.arraycopy(nonce, 0, bytes, 0, NONCE_LEN)
System.arraycopy(ciphertext, 0, bytes, NONCE_LEN, ciphertext.size)
return SealedObject(objectHash(bytes), bytes)
}
/**
* [sealObject] with a caller-chosen nonce — for cross-language vectors ONLY.
* Mirror of `@shade/vault/testing`'s `sealObjectWithNonce`. `internal` so it
* is reachable from this module's tests and from nowhere else: a nonce reused
* under one content key breaks AES-GCM outright.
*/
internal fun sealObjectWithNonce(contentKey: ByteArray, vaultId: String, plaintext: ByteArray, nonce: ByteArray): SealedObject {
val bytes = aeadSeal(contentKey, nonce, plaintext, vaultObjectAad(vaultId))
return SealedObject(objectHash(bytes), bytes)
}
/**
* Decrypt one object, verifying its name first: a relay that returned the
* wrong object would otherwise surface as an AEAD failure, which reads like
* key corruption and sends the user looking in the wrong place.
*/
fun openObject(
crypto: CryptoProvider,
contentKey: ByteArray,
vaultId: String,
expectedHash: String,
bytes: ByteArray,
): ByteArray {
if (bytes.size < NONCE_LEN + TAG_LEN) {
throw VaultFormatException("vault object too short to be a sealed object")
}
val actual = objectHash(bytes)
if (actual != expectedHash) {
throw VaultFormatException("vault object hash mismatch: expected $expectedHash, got $actual")
}
return try {
crypto.aesGcmDecrypt(
contentKey,
bytes.copyOfRange(NONCE_LEN, bytes.size),
bytes.copyOfRange(0, NONCE_LEN),
vaultObjectAad(vaultId),
)
} catch (e: GeneralSecurityException) {
// The hash matched, so the relay returned what was asked for; a tag
// failure now means a wrong key or an object from another vault.
throw VaultFormatException("vault object $expectedHash failed authentication (wrong key or vault?)", e)
}
}
// ─── Compression ─────────────────────────────────────────────
/**
* Raw DEFLATE (RFC 1951) at zlib's default level — what the TS side's
* `CompressionStream('deflate-raw')` produces. Readers never depend on the
* exact bytes, only on the stream inflating to the original.
*/
fun deflateRaw(bytes: ByteArray): ByteArray {
val deflater = Deflater(Deflater.DEFAULT_COMPRESSION, true)
try {
deflater.setInput(bytes)
deflater.finish()
val out = ByteArrayOutputStream(maxOf(64, bytes.size / 2))
val buf = ByteArray(64 * 1024)
while (!deflater.finished()) {
val n = deflater.deflate(buf)
out.write(buf, 0, n)
}
return out.toByteArray()
} finally {
deflater.end()
}
}
/**
* Inverse of [deflateRaw], refusing to produce more than [limit] bytes.
*
* Strict about the stream's end, like the TS `DecompressionStream`: a stream
* that stops before its final block is "truncated", and bytes after the final
* block are "trailing data" — both are corruption, not something to paper
* over by returning whatever inflated so far.
*/
fun inflateRaw(bytes: ByteArray, limit: Long): ByteArray {
val inflater = Inflater(true)
try {
// With `nowrap`, zlib may need one byte past the end of the stream
// before it reports `finished()` (documented on Inflater's
// constructor). Feed a dummy byte so a valid stream always finishes;
// it is never consumed, which is how trailing data is recognised below.
inflater.setInput(bytes.copyOf(bytes.size + 1))
val out = ByteArrayOutputStream()
val buf = ByteArray(64 * 1024)
var stalls = 0
while (!inflater.finished()) {
val n = try {
inflater.inflate(buf)
} catch (e: DataFormatException) {
throw VaultFormatException("vault inflate failed: ${e.message ?: "corrupt deflate stream"}", e)
}
if (n == 0) {
if (inflater.finished()) break
if (inflater.needsDictionary()) throw VaultFormatException("vault inflate failed: stream wants a preset dictionary")
if (inflater.needsInput()) throw VaultFormatException("vault inflate failed: truncated deflate stream")
// Neither progress nor a reason: never spin forever on it.
if (++stalls > 2) throw VaultFormatException("vault inflate failed: no progress")
continue
}
stalls = 0
if (out.size().toLong() + n > limit) throw VaultFormatException("vault inflate exceeded $limit bytes")
out.write(buf, 0, n)
}
if (inflater.remaining > 1) {
throw VaultFormatException("vault inflate failed: ${inflater.remaining - 1} byte(s) of trailing data")
}
return out.toByteArray()
} finally {
inflater.end()
}
}
/**
* Does this file start with the signature of an already-compressed format?
* Part of the contract so ports make the same `enc` choice: PNG, JPEG, WebP
* ("RIFF"…"WEBP"), MP4 family ("ftyp" at offset 4), GIF, gzip, zip ("PK",
* which also covers docx/xlsx/jar/apk).
*/
fun looksCompressed(b: ByteArray): Boolean {
fun at(offset: Int, vararg sig: Int): Boolean =
b.size >= offset + sig.size && sig.indices.all { (b[offset + it].toInt() and 0xff) == sig[it] }
return at(0, 0x89, 0x50, 0x4e, 0x47) || // PNG
at(0, 0xff, 0xd8, 0xff) || // JPEG
(at(0, 0x52, 0x49, 0x46, 0x46) && at(8, 0x57, 0x45, 0x42, 0x50)) || // RIFF....WEBP
at(4, 0x66, 0x74, 0x79, 0x70) || // ....ftyp
at(0, 0x47, 0x49, 0x46, 0x38) || // GIF8
at(0, 0x1f, 0x8b) || // gzip
at(0, 0x50, 0x4b) // PK
}
// ─── Entries ─────────────────────────────────────────────────
/** A file's bytes as they will be stored, before sealing. */
class PackedEntry(
/** [VAULT_ENC_DEFLATE_RAW] when the stored bytes are compressed, else null. */
val enc: String?,
/** The plaintext, or its deflate-raw. */
val stored: ByteArray,
/** [stored] in slices of at most the chunk size. Never empty. */
val chunks: List<ByteArray>,
)
/**
* Turn a file's plaintext into the slices that get sealed.
*
* Compression is kept only when it saves at least 5 %, as the integer test
* `compressed * 20 <= plain * 19` so no port disagrees over rounding. The
* whole file is compressed first and THEN split: a reader concatenates the
* opened parts and inflates once, so parts carry no framing of their own.
*
* [chunkSize] exists for tests and vectors; real writers use the default.
*/
fun packEntry(plaintext: ByteArray, chunkSize: Int = VAULT_CHUNK_SIZE): PackedEntry {
require(chunkSize >= 1) { "vault chunk size must be a positive integer, got $chunkSize" }
var stored = plaintext
var enc: String? = null
if (plaintext.isNotEmpty() && !looksCompressed(plaintext)) {
val deflated = deflateRaw(plaintext)
if (deflated.size.toLong() * 20 <= plaintext.size.toLong() * 19) {
stored = deflated
enc = VAULT_ENC_DEFLATE_RAW
}
}
// An empty file is still one (empty) object: an entry always names
// something the relay holds, so a reader never special-cases.
val chunks = ArrayList<ByteArray>()
var i = 0
while (i < stored.size || chunks.isEmpty()) {
chunks.add(stored.copyOfRange(i, minOf(stored.size, i + chunkSize)))
i += chunkSize
}
return PackedEntry(enc, stored, chunks)
}
/** The manifest fields that locate a file's ciphertext. */
data class EntryLocator(val hash: String, val parts: List<String>? = null, val enc: String? = null)
/** Shape an entry's locator from its sealed parts (one part → no `parts`). */
fun entryLocator(packed: PackedEntry, sealed: List<SealedObject>): EntryLocator {
require(sealed.isNotEmpty()) { "an entry has at least one object" }
return EntryLocator(
hash = sealed[0].hash,
parts = if (sealed.size > 1) sealed.map { it.hash } else null,
enc = packed.enc,
)
}
/** The locator for a file's manifest entry, and the objects to upload. */
class SealedEntry(val locator: EntryLocator, val objects: List<SealedObject>)
/** Pack and seal one file. */
fun sealEntry(
crypto: CryptoProvider,
contentKey: ByteArray,
vaultId: String,
plaintext: ByteArray,
chunkSize: Int = VAULT_CHUNK_SIZE,
): SealedEntry {
val packed = packEntry(plaintext, chunkSize)
val objects = packed.chunks.map { sealObject(crypto, contentKey, vaultId, it) }
return SealedEntry(entryLocator(packed, objects), objects)
}
/**
* Every object an entry needs, in read order — also exactly what a commit's
* signed `hashes` must list, or a part may be collected by the next prune.
*/
fun entryObjectHashes(entry: VaultEntry): List<String> =
if (!entry.parts.isNullOrEmpty()) entry.parts else listOf(entry.hash)
/**
* Reassemble a file from its fetched objects, in [entryObjectHashes] order:
* verify and open each part, concatenate, inflate if `enc`, check the size.
*
* The size check is what catches a part list that lost or gained an element
* — every part authenticates on its own, so such an entry would otherwise
* open cleanly into a truncated or padded file.
*/
fun openEntryBytes(
crypto: CryptoProvider,
contentKey: ByteArray,
vaultId: String,
entry: VaultEntry,
objects: List<ByteArray>,
): ByteArray {
val hashes = entryObjectHashes(entry)
if (!entry.parts.isNullOrEmpty() && entry.parts[0] != entry.hash) {
throw VaultFormatException("vault entry ${entry.path}: hash must equal parts[0]")
}
if (objects.size != hashes.size) {
throw VaultFormatException("vault entry ${entry.path}: expected ${hashes.size} object(s), got ${objects.size}")
}
if (entry.size < 0 || entry.size > Int.MAX_VALUE - 8) {
throw VaultFormatException("vault entry ${entry.path}: size ${entry.size} cannot be held in memory")
}
val stored = ByteArrayOutputStream()
for (i in hashes.indices) {
stored.write(openObject(crypto, contentKey, vaultId, hashes[i], objects[i]))
}
val plaintext = when (entry.enc) {
null -> stored.toByteArray()
VAULT_ENC_DEFLATE_RAW -> inflateRaw(stored.toByteArray(), entry.size)
// Guessing would hand back bytes that look like the file and are not.
else -> throw VaultFormatException("vault entry ${entry.path}: unsupported encoding ${entry.enc}")
}
if (plaintext.size.toLong() != entry.size) {
throw VaultFormatException(
"vault entry ${entry.path}: size mismatch, manifest says ${entry.size}, got ${plaintext.size}",
)
}
return plaintext
}
// ─── Manifests ───────────────────────────────────────────────
/**
* A manifest's plaintext before sealing: v1 is bare UTF-8 JSON, v2 is "SVM2"
* + deflate-raw of it. The version field decides the container.
*/
fun encodeManifest(manifest: VaultManifest): ByteArray {
require(manifest.version == 1 || manifest.version == 2) {
"unsupported vault manifest version: ${manifest.version}"
}
val json = stringifyJson(manifest.toJsonMap()).toByteArray(Charsets.UTF_8)
if (manifest.version == 1) return json
return MANIFEST_V2_MAGIC + deflateRaw(json)
}
/** Parse a manifest's plaintext, v1 or v2, refusing any other version. */
fun decodeManifest(plain: ByteArray): VaultManifest {
val isV2 = plain.size >= MANIFEST_V2_MAGIC.size &&
MANIFEST_V2_MAGIC.indices.all { plain[it] == MANIFEST_V2_MAGIC[it] }
val json = if (isV2) {
inflateRaw(plain.copyOfRange(MANIFEST_V2_MAGIC.size, plain.size), MAX_MANIFEST_BYTES)
} else {
plain
}
return parseManifestJson(String(json, Charsets.UTF_8))
}
/** A manifest is stored as an ordinary object; this is the encoding step around it. */
fun sealManifest(crypto: CryptoProvider, contentKey: ByteArray, vaultId: String, manifest: VaultManifest): SealedObject =
sealObject(crypto, contentKey, vaultId, encodeManifest(manifest))
fun openManifest(
crypto: CryptoProvider,
contentKey: ByteArray,
vaultId: String,
expectedHash: String,
bytes: ByteArray,
): VaultManifest = decodeManifest(openObject(crypto, contentKey, vaultId, expectedHash, bytes))

View File

@@ -0,0 +1,44 @@
package no.zyon.shade.vault
/**
* The relay refused a request. [code] is the relay's own error code
* (`BAD_REQUEST`, `UNAUTHORIZED`, `NOT_FOUND`, `SEQ_CONFLICT`, `TOO_LARGE`,
* `MISSING_OBJECTS`), or `SHADE_NETWORK` when the response carried none.
*
* Kept apart from [VaultFormatException] because the reactions differ: a
* relay refusal may be retried or shown as "offline / rejected", while a
* format failure means the bytes themselves are wrong and retrying is futile.
*/
class VaultException(
val code: String,
/** HTTP status, or 0 when the failure is local (e.g. a missing version). */
val statusCode: Int,
message: String,
/** The relay's head, sent along with `SEQ_CONFLICT`. */
val head: Long? = null,
/** Up to 20 hashes the relay reported missing with `MISSING_OBJECTS`. */
val missing: List<String> = emptyList(),
cause: Throwable? = null,
) : RuntimeException("[$code @ $statusCode] $message", cause) {
/**
* Two devices committed from the same head and this one lost. The answer
* is to re-read the head and rebuild the edit on top of it — never to
* resend the same commit, which would just lose again.
*/
val isSeqConflict: Boolean get() = code == CODE_SEQ_CONFLICT
companion object {
const val CODE_SEQ_CONFLICT = "SEQ_CONFLICT"
const val CODE_NOT_FOUND = "NOT_FOUND"
const val CODE_MISSING_OBJECTS = "MISSING_OBJECTS"
const val CODE_NETWORK = "SHADE_NETWORK"
}
}
/**
* Bytes that do not decode to what the vault format promises: a hash
* mismatch, a failed AEAD tag, corrupt or oversized deflate, an unknown
* manifest version or entry encoding, a size that does not add up.
*/
class VaultFormatException(message: String, cause: Throwable? = null) : RuntimeException(message, cause)

View File

@@ -0,0 +1,80 @@
package no.zyon.shade.vault
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
import no.zyon.shade.crypto.CryptoProvider
/**
* Everything a vault needs, derived from the account master key.
*
* Mirror of `@shade/vault`'s `VaultKeys` / `deriveVaultKeys`, and of the three
* `deriveVault*` functions in `@shade/storage-encrypted/crypto/kdf.ts`:
*
* vaultId = hex(HKDF(masterKey, info=`shade-vault-id-v1:<app>`)) // relay-visible opaque id
* contentKey = HKDF(masterKey, info=`shade-vault-content-v1:<app>`) // AES-256-GCM key for every object
* signingSeed = HKDF(masterKey, info=`shade-vault-sig-v1:<app>`) // Ed25519 seed, TOFU-pinned by the relay
* publicKey = Ed25519 public key of signingSeed
*
* This is what makes recovery "username and password": a phone that can
* derive the profile master can derive these too, and read a vault whose
* writer — the PC — is switched off.
*
* Its own HKDF branch rather than a reuse of `shade-blob-*-v1`: whoever holds
* a vault key reads every file, so it must not be derivable from the profile
* blob's key or vice versa. Reference vectors: `test-vectors/vault-v2.json`
* ("vault-v2 keys").
*/
class VaultKeys(
/** Lowercase hex (64 chars) — the id in every relay URL. */
val vaultId: String,
val contentKey: ByteArray,
val signingSeed: ByteArray,
val publicKey: ByteArray,
)
private const val VAULT_ID_INFO_PREFIX = "shade-vault-id-v1:"
private const val VAULT_CONTENT_INFO_PREFIX = "shade-vault-content-v1:"
private const val VAULT_SIG_INFO_PREFIX = "shade-vault-sig-v1:"
private const val DERIVED_LEN = 32
/**
* Derive a vault's keys for namespace [app] (e.g. `"scaffold"`). Distinct
* collections under one master MUST use distinct `app` strings — the phone's
* outgoing change queue is a second vault with its own `app`, not a path
* prefix inside the first, so the two never contend for one `seq`.
*
* No HKDF salt: the TS side passes `undefined`, which RFC 5869 (and
* `@noble/hashes`) turn into 32 zero bytes — exactly what Tink does with an
* empty salt. The vectors pin it.
*/
fun deriveVaultKeys(crypto: CryptoProvider, masterKey: ByteArray, app: String): VaultKeys {
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
require(app.isNotEmpty()) { "app namespace must be non-empty" }
fun derive(prefix: String): ByteArray =
crypto.hkdf(masterKey, ByteArray(0), (prefix + app).toByteArray(Charsets.UTF_8), DERIVED_LEN)
val signingSeed = derive(VAULT_SIG_INFO_PREFIX)
return VaultKeys(
vaultId = toHex(derive(VAULT_ID_INFO_PREFIX)),
contentKey = derive(VAULT_CONTENT_INFO_PREFIX),
signingSeed = signingSeed,
publicKey = ed25519PublicKeyFromSeed(signingSeed),
)
}
/** Lowercase hex — the encoding of vault ids and object names on the wire. */
fun toHex(bytes: ByteArray): String {
val out = CharArray(bytes.size * 2)
val digits = "0123456789abcdef"
for (i in bytes.indices) {
val v = bytes[i].toInt() and 0xff
out[i * 2] = digits[v ushr 4]
out[i * 2 + 1] = digits[v and 0x0f]
}
return String(out)
}
private val HEX64 = Regex("^[0-9a-f]{64}$")
/** True for a 64-char lowercase hex string — a vault id or an object name. */
internal fun isHex64(s: String): Boolean = HEX64.matches(s)

View File

@@ -0,0 +1,183 @@
package no.zyon.shade.vault
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
/**
* The vault's data model — mirror of `@shade/vault/src/types.ts`.
*
* Objects are content-addressed (named by the SHA-256 of their ciphertext), a
* manifest names the collection (paths live only inside it, encrypted), and
* the log is append-only. See `docs/vault.md` for why.
*/
/** The only entry encoding v2 defines: RFC 1951 raw DEFLATE, no zlib/gzip header. */
const val VAULT_ENC_DEFLATE_RAW = "deflate-raw"
/**
* One file in a manifest.
*
* [enc] is kept as a raw string rather than an enum on purpose: a manifest
* written by a newer client may name an encoding this one does not know, and
* the right reaction is to refuse *reading that file* (see [openEntryBytes]),
* not to refuse the whole manifest — every other file is still readable.
*/
data class VaultEntry(
/** Path within the collection, as the app understands it. */
val path: String,
/** Lowercase hex SHA-256 of the (first) ciphertext object. */
val hash: String,
/** PLAINTEXT byte length — before compression, whatever [enc] says. */
val size: Long,
/** Optional app-defined mode/metadata, opaque to the vault. */
val mode: String? = null,
/** Present only when the stored bytes are compressed. */
val enc: String? = null,
/** Present only when there is more than one object; `parts[0] == hash`. */
val parts: List<String>? = null,
)
/** The full contents of a collection at one point in time. */
data class VaultManifest(
/** 1: bare JSON. 2: "SVM2" + deflate-raw(JSON). Writers emit 2; readers accept both. */
val version: Int,
/** Monotonic, assigned by the client and checked by the relay. */
val seq: Long,
/** Epoch millis when the commit was made. */
val at: Long,
/** Optional human note, e.g. "nattlig backup". */
val message: String? = null,
val entries: List<VaultEntry>,
)
/** One row of the append-only log. */
data class VaultLogEntry(
val seq: Long,
/** Hash of the encrypted manifest object. */
val manifest: String,
val at: Long,
/** Total bytes of all objects the manifest references, for quota display. */
val bytes: Long,
)
/** What `GET /v1/vault/:id/log` returns. */
data class VaultLog(
val entries: List<VaultLogEntry>,
/** Highest seq the relay holds; `0` when the vault is empty. */
val head: Long,
)
/** What `POST /v1/vault/:id/prune` returns. */
data class VaultPruneResult(
val removedVersions: Long,
val removedObjects: Long,
val freedBytes: Long,
)
// ─── JSON ────────────────────────────────────────────────────
/**
* The entry as an insertion-ordered map, in the order TS builds it
* (`{ path, ...locator, size }`, then `mode`), so `JSON.stringify` on either
* side yields the same bytes. Key order is not part of the contract — readers
* never depend on it — but matching it keeps the manifest vector exact.
* Absent optionals are left out, as `JSON.stringify` drops `undefined`.
*/
internal fun VaultEntry.toJsonMap(): Map<String, Any> {
val m = LinkedHashMap<String, Any>()
m["path"] = path
m["hash"] = hash
if (parts != null) m["parts"] = parts
if (enc != null) m["enc"] = enc
m["size"] = size
if (mode != null) m["mode"] = mode
return m
}
internal fun VaultManifest.toJsonMap(): Map<String, Any> {
val m = LinkedHashMap<String, Any>()
m["version"] = version
m["seq"] = seq
m["at"] = at
m["entries"] = entries.map { it.toJsonMap() }
if (message != null) m["message"] = message
return m
}
/**
* Parse a manifest's JSON. Malformed structure surfaces as
* [VaultFormatException], never as a raw `JSONException` — a caller showing
* "the backup could not be read" should not have to know which parser ran.
*/
internal fun parseManifestJson(text: String): VaultManifest {
try {
val o = JSONObject(text)
// Strict like TS `version !== 1 && version !== 2`: "2" or 2.5 are refused.
val version = when ((o.opt("version") as? Number)?.toDouble()) {
1.0 -> 1
2.0 -> 2
else -> -1
}
if (version != 1 && version != 2) {
// Refusing beats guessing: a future manifest may describe a file
// this reader cannot represent, and committing on top of a
// half-understood head would drop it.
throw VaultFormatException(
"unsupported vault manifest version: ${if (o.has("version")) o.get("version") else "undefined"}",
)
}
val arr = o.getJSONArray("entries")
val entries = ArrayList<VaultEntry>(arr.length())
for (i in 0 until arr.length()) entries.add(parseEntryJson(arr.getJSONObject(i)))
return VaultManifest(
version = version,
seq = o.getLong("seq"),
at = o.getLong("at"),
message = optString(o, "message"),
entries = entries,
)
} catch (e: JSONException) {
throw VaultFormatException("vault manifest is not valid JSON: ${e.message}", e)
}
}
private fun parseEntryJson(o: JSONObject): VaultEntry {
val parts = if (o.has("parts") && !o.isNull("parts")) {
val a = o.getJSONArray("parts")
List(a.length()) { a.getString(it) }
} else {
null
}
return VaultEntry(
path = o.getString("path"),
hash = o.getString("hash"),
size = o.getLong("size"),
mode = optString(o, "mode"),
enc = optString(o, "enc"),
parts = parts,
)
}
/** `org.json`'s `optString` turns null into "null" and numbers into strings; this does not. */
private fun optString(o: JSONObject, key: String): String? =
if (o.has(key) && !o.isNull(key)) o.getString(key) else null
internal fun parseLogJson(text: String): VaultLog {
try {
val o = JSONObject(text)
val arr: JSONArray = o.getJSONArray("entries")
val entries = List(arr.length()) { i ->
val e = arr.getJSONObject(i)
VaultLogEntry(
seq = e.getLong("seq"),
manifest = e.getString("manifest"),
at = e.getLong("at"),
bytes = e.optLong("bytes", 0L),
)
}
return VaultLog(entries = entries, head = o.getLong("head"))
} catch (e: JSONException) {
throw VaultFormatException("vault log response is malformed: ${e.message}", e)
}
}

View File

@@ -0,0 +1,67 @@
package no.zyon.shade.vault
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.serialization.canonicalJson
import no.zyon.shade.serialization.stringifyJson
import java.util.Base64
/**
* A request body signed the way the relay verifies it.
*
* [canonical] is kept alongside the wire JSON so tests can compare it with
* the TS bytes directly instead of reverse-engineering a failing signature.
*/
class SignedPayload(
/** The JSON to send: the payload fields + `signedAt` + `signature`. */
val json: String,
/** The exact bytes the signature covers. */
val canonical: ByteArray,
val signedAt: Long,
val signature: ByteArray,
)
/**
* Mirror of `@shade/server`'s `signPayload`: Ed25519 over `JSON.stringify` of
* every field except `signature` (with `signedAt` added), top-level keys
* sorted, nested values as-is; the wire body then carries `signedAt` and the
* signature in standard base64.
*
* [signedAt] is a parameter so the vectors can pin it; the relay rejects a
* value more than five minutes old or one minute in the future, so real
* callers pass the current wall clock.
*/
fun signPayload(
crypto: CryptoProvider,
signingSeed: ByteArray,
payload: Map<String, Any>,
signedAt: Long,
): SignedPayload {
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
require("signature" !in payload && "signedAt" !in payload) {
"payload must not carry signature/signedAt — they are added here"
}
val withTime = LinkedHashMap(payload).apply { put("signedAt", signedAt) }
val canonical = canonicalJson(withTime).toByteArray(Charsets.UTF_8)
val signature = crypto.sign(signingSeed, canonical)
val wire = LinkedHashMap<String, Any>(withTime).apply {
put("signature", Base64.getEncoder().encodeToString(signature))
}
return SignedPayload(stringifyJson(wire), canonical, signedAt, signature)
}
/**
* Sign a vault request body with the vault's key, the pubkey INSIDE the
* signed payload — appended afterwards it would not be covered, and could be
* swapped in transit on the first (TOFU-pinning) write.
*/
fun signVaultBody(
crypto: CryptoProvider,
keys: VaultKeys,
body: Map<String, Any>,
signedAt: Long,
): SignedPayload {
val withKey = LinkedHashMap(body).apply {
put("publicKey", Base64.getEncoder().encodeToString(keys.publicKey))
}
return signPayload(crypto, keys.signingSeed, withKey, signedAt)
}

View File

@@ -0,0 +1,167 @@
package no.zyon.shade.vault
import org.json.JSONException
import org.json.JSONObject
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
/**
* How a [VaultClient] reaches the relay — mirror of `@shade/vault`'s
* `VaultTransport`. Bodies arrive already signed (as JSON text): the
* transport moves bytes and maps errors, it never holds a key.
*
* Blocking by design, like [no.zyon.shade.blob.BlobClient]: call it from a
* background dispatcher (`Dispatchers.IO`), never from the main thread.
*/
interface VaultTransport {
/** Does the relay already hold this object? */
fun has(vaultId: String, hash: String): Boolean
fun put(vaultId: String, hash: String, signedBody: String)
/** The raw sealed object. */
fun get(vaultId: String, hash: String): ByteArray
fun log(vaultId: String, limit: Int? = null): VaultLog
/** Returns the committed seq. Throws [VaultException] with `SEQ_CONFLICT` when beaten to it. */
fun commit(vaultId: String, signedBody: String): Long
fun prune(vaultId: String, signedBody: String): VaultPruneResult
}
/**
* Plain HTTP against a relay running `createVaultRoutes`.
*
* Built on `HttpURLConnection` rather than `java.net.http.HttpClient` (which
* [no.zyon.shade.blob.BlobClient] uses): `java.net.http` does not exist on
* Android at any API level, and this client exists for a phone. OkHttp would
* also work but would add a dependency to a library that has none for HTTP;
* `HttpURLConnection` is on both the JVM (tests) and Android.
*/
class VaultHttpTransport(
baseUrl: String,
private val connectTimeoutMs: Int = 15_000,
/** Generous: one object is up to 4 MiB, and phones sit on slow uplinks. */
private val readTimeoutMs: Int = 60_000,
) : VaultTransport {
private val base = baseUrl.trimEnd('/')
override fun has(vaultId: String, hash: String): Boolean {
val res = request("HEAD", objectPath(vaultId, hash), null)
return when (res.status) {
200 -> true
404 -> false
else -> fail(res, "have-check")
}
}
override fun put(vaultId: String, hash: String, signedBody: String) {
val res = request("PUT", objectPath(vaultId, hash), signedBody)
if (res.status !in 200..299) fail(res, "upload")
}
override fun get(vaultId: String, hash: String): ByteArray {
val res = request("GET", objectPath(vaultId, hash), null)
if (res.status !in 200..299) fail(res, "download")
return res.body
}
override fun log(vaultId: String, limit: Int?): VaultLog {
val q = if (limit == null) "" else "?limit=$limit"
val res = request("GET", "${vaultPath(vaultId)}/log$q", null)
if (res.status !in 200..299) fail(res, "log")
return parseLogJson(res.body.toString(Charsets.UTF_8))
}
override fun commit(vaultId: String, signedBody: String): Long {
val res = request("POST", "${vaultPath(vaultId)}/commit", signedBody)
if (res.status !in 200..299) fail(res, "commit")
return jsonBody(res, "commit").getLong("seq")
}
override fun prune(vaultId: String, signedBody: String): VaultPruneResult {
val res = request("POST", "${vaultPath(vaultId)}/prune", signedBody)
if (res.status !in 200..299) fail(res, "prune")
val o = jsonBody(res, "prune")
return VaultPruneResult(
removedVersions = o.getLong("removedVersions"),
removedObjects = o.getLong("removedObjects"),
freedBytes = o.getLong("freedBytes"),
)
}
// ─── Plumbing ────────────────────────────────────────────
private class Response(val status: Int, val body: ByteArray)
/** Ids are validated before they reach a URL, so nothing can smuggle a path. */
private fun vaultPath(vaultId: String): String {
require(isHex64(vaultId)) { "vaultId must be 64 lowercase hex chars" }
return "/v1/vault/$vaultId"
}
private fun objectPath(vaultId: String, hash: String): String {
require(isHex64(hash)) { "object hash must be 64 lowercase hex chars" }
return "${vaultPath(vaultId)}/object/$hash"
}
private fun request(method: String, path: String, jsonBody: String?): Response {
val conn = try {
URL(base + path).openConnection() as HttpURLConnection
} catch (e: IOException) {
throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e)
}
try {
conn.requestMethod = method
conn.connectTimeout = connectTimeoutMs
conn.readTimeout = readTimeoutMs
conn.useCaches = false
if (jsonBody != null) {
val bytes = jsonBody.toByteArray(Charsets.UTF_8)
conn.doOutput = true
conn.setRequestProperty("content-type", "application/json")
conn.setFixedLengthStreamingMode(bytes.size)
conn.outputStream.use { it.write(bytes) }
}
val status = conn.responseCode
// A non-2xx body is on the error stream; HEAD has neither.
val stream: InputStream? = if (status >= 400) conn.errorStream else if (method == "HEAD") null else conn.inputStream
val body = stream?.use { it.readBytes() } ?: ByteArray(0)
return Response(status, body)
} catch (e: IOException) {
throw VaultException(VaultException.CODE_NETWORK, 0, "vault $method $path: ${e.message}", cause = e)
} finally {
conn.disconnect()
}
}
private fun jsonBody(res: Response, what: String): JSONObject = try {
JSONObject(res.body.toString(Charsets.UTF_8))
} catch (e: JSONException) {
throw VaultException(VaultException.CODE_NETWORK, res.status, "vault $what response not JSON", cause = e)
}
/** Turn a non-2xx into a [VaultException] that carries the relay's own code. */
private fun fail(res: Response, what: String): Nothing {
var code = VaultException.CODE_NETWORK
var detail = "HTTP ${res.status}"
var head: Long? = null
var missing = emptyList<String>()
try {
val o = JSONObject(res.body.toString(Charsets.UTF_8))
o.optJSONObject("error")?.let { err ->
code = err.optString("code", code)
detail = err.optString("message", detail)
}
if (o.has("head") && !o.isNull("head")) head = o.getLong("head")
o.optJSONArray("missing")?.let { a -> missing = List(a.length()) { a.getString(it) } }
} catch (_: JSONException) {
// Non-JSON error body (a proxy's HTML page): the status is all we have.
}
throw VaultException(code, res.status, "vault $what failed — $detail", head = head, missing = missing)
}
}

View File

@@ -0,0 +1,132 @@
package no.zyon.shade
import no.zyon.shade.media.Album
import no.zyon.shade.media.Albums
import no.zyon.shade.media.FileRangeSource
import no.zyon.shade.media.Grants
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import java.security.MessageDigest
import java.security.SecureRandom
/**
* Live cross-check of [MediaUploader] against the real TS relay — skipped
* unless `SHADE_MEDIA_LIVE_SPEC` points at the spec file a TS driver wrote.
*
* Run it via `bun run scripts/media-live-kotlin.ts`: the driver serves
* `createMediaService` with two faults injected on the pieces, uploads a file
* with the TS client and writes `{ url, seed, tsLink, tsSha256, scratch,
* kotlinOut }`. This test opens the TS file, uploads a film in pieces and a
* photo in one PUT, and records the links in `kotlinOut`; the driver then
* reads the film back with the TS reader.
*/
class MediaLiveTest {
private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) }
private fun fromHex(s: String) =
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
@Test
fun uploadsInPiecesThroughFaultsForTsToRead() {
val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC")
assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
val spec = JSONObject(File(specPath!!).readText())
val uploader = MediaUploader(spec.getString("url"), MediaOwner(fromHex(spec.getString("seed"))))
// Read what TS uploaded, from its link.
val tsGrant = Grants.fromCapabilityUrl(spec.getString("tsLink")) as MediaGrant
tsGrant.open().use { r -> assertEquals(spec.getString("tsSha256"), sha256(r.read(0, r.size.toInt()))) }
// A film from the phone: sealed to a file, up in three pieces (16 MiB each),
// through a lost answer on the second and a refusal of the third.
val plain = ByteArray(40 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
val sealedFile = File(spec.getString("scratch"), "film.smf")
val meta = MediaMeta(name = "Fra telefonen — «Kveld».mp4", mime = "video/mp4", durationMs = 61_500, width = 1080, height = 1920)
val progress = mutableListOf<Long>()
val token = MediaUploader.newReadToken()
val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(plain.inputStream(), it, meta) }
val film = FileRangeSource(sealedFile).use { body ->
uploader.putSealed(result, body, token, meta) { acked, total ->
synchronized(progress) { progress += acked }
assertEquals(result.sealedSize, total)
}
}
assertEquals(result.sealedSize, progress.last())
assertTrue("progress only grows: $progress", progress.zipWithNext().all { (a, b) -> a <= b })
film.open().use { r -> assertEquals(sha256(plain), sha256(r.read(0, r.size.toInt()))) }
// The same film again (the app was killed after the upload): the relay
// already has it, nothing is sent, the link is the same.
val again = FileRangeSource(sealedFile).use { uploader.putSealed(result, it, token, meta) }
assertEquals(film.capabilityUrl("https://watch.example/"), again.capabilityUrl("https://watch.example/"))
// A shared video as an upload job: the app is killed after the first
// piece; the next start resumes past it, and sharing it a third time
// sends nothing and gives the same link.
val jobs = UploadJobs(File(spec.getString("scratch"), "jobs"))
val video = ByteArray(36 * 1024 * 1024).also { SecureRandom().nextBytes(it) }
val key = jobs.key(spec.getString("url"), "content://media/external/video/42", video.size.toString())
val videoMeta = MediaMeta(name = "VID_0042.mp4", mime = "video/mp4")
var opened = 0
val open = { opened++; video.inputStream() }
class Killed : RuntimeException()
try {
uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (acked > 0) throw Killed() }
error("the upload should have been cut short")
} catch (e: Killed) {
// as if the app was killed mid-upload
}
assertEquals(1, jobs.unfinished().size)
var firstSeen = -1L
val resumed = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open) { acked, _ -> if (firstSeen < 0) firstSeen = acked }
assertTrue("resumed from $firstSeen", firstSeen > 0)
assertEquals("sealed once", 1, opened)
resumed.open().use { r -> assertEquals(sha256(video), sha256(r.read(0, r.size.toInt()))) }
val third = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open)
assertEquals(resumed.encode(), third.encode())
assertEquals(1, opened)
assertTrue(jobs.unfinished().isEmpty())
// Deleted from the relay since: the next share is a new upload with a new link.
assertTrue(uploader.delete(resumed.mediaId))
val fresh = uploader.upload(jobs, key, "VID_0042.mp4", videoMeta, open)
assertNotEquals(resumed.encode(), fresh.encode())
assertEquals(2, opened)
// A photo: one PUT; then deleted.
val photo = uploader.uploadBytes(ByteArray(300_000).also { SecureRandom().nextBytes(it) }, MediaMeta(name = "IMG_0001.jpg", mime = "image/jpeg"))
photo.open().use { assertEquals("IMG_0001.jpg", it.meta.name) }
assertTrue(uploader.delete(photo.mediaId))
assertFalse(uploader.delete(photo.mediaId))
// The photos of a trip, shared at once: one album link for all of them.
val album = uploader.uploadAlbum(Album("Tur — «Lofoten»", listOf(film, fresh)))
album.open().use { r ->
val back = Albums.read(r)
assertEquals("Tur — «Lofoten»", back.title)
assertEquals(listOf(film.encode(), fresh.encode()), back.items.map { it.encode() })
}
File(spec.getString("kotlinOut")).writeText(
JSONObject()
.put("film", JSONObject().put("link", film.capabilityUrl("https://watch.example/")).put("sha256", sha256(plain)).put("size", plain.size))
.put("again", again.capabilityUrl("https://watch.example/"))
.put("photo", JSONObject().put("url", photo.url))
.put("album", album.capabilityUrl("https://watch.example/"))
.toString(),
)
sealedFile.delete()
}
}

View File

@@ -0,0 +1,55 @@
package no.zyon.shade
import com.sun.net.httpserver.HttpServer
import no.zyon.shade.media.ByteArraySource
import no.zyon.shade.media.DEFAULT_CHUNK_BYTES
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.MediaUploadException
import no.zyon.shade.media.MediaUploader
import org.junit.Assert.assertEquals
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.InetSocketAddress
import java.util.concurrent.atomic.AtomicInteger
/** What the uploader does with a relay that answers nonsense; the real conversation is `MediaLiveTest`. */
class MediaUploaderTest {
private fun relay(answer: String, calls: AtomicInteger): HttpServer =
HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0).apply {
createContext("/") { ex ->
calls.incrementAndGet()
ex.requestBody.readBytes()
val b = answer.toByteArray()
ex.responseHeaders.add("content-type", "application/json")
ex.sendResponseHeaders(201, b.size.toLong())
ex.responseBody.use { it.write(b) }
}
start()
}
@Test
fun anUnusableUploadStatusIsRefusedAtOnceNotLoopedOn() {
val (sealed, result) = MediaSealer.sealBytes(ByteArray(DEFAULT_CHUNK_BYTES.toInt() + 4096))
for (bad in listOf(
"""{"chunk":0,"received":0}""",
"""{"chunk":${64L * 1024 * 1024 * 4},"received":0}""",
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":-1}""",
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"window":0}""",
"""{"chunk":${DEFAULT_CHUNK_BYTES},"received":0,"landed":["x"]}""",
)) {
val calls = AtomicInteger()
val server = relay(bad, calls)
try {
val up = MediaUploader("http://127.0.0.1:${server.address.port}", MediaOwner.generate())
val e = assertThrows(MediaUploadException::class.java) { up.putSealed(result, ByteArraySource(sealed)) }
assertTrue(bad, e.message!!.contains("unusable"))
assertEquals(bad, 1, calls.get())
} finally {
server.stop(0)
}
}
}
}

View File

@@ -0,0 +1,283 @@
package no.zyon.shade
import no.zyon.shade.media.ALBUM_MIME
import no.zyon.shade.media.Albums
import no.zyon.shade.media.ByteArraySource
import no.zyon.shade.media.FOOTER_BYTES
import no.zyon.shade.media.Grants
import no.zyon.shade.media.LIVE_GRANT_KIND
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.LiveKeyException
import no.zyon.shade.media.LivePublisher
import no.zyon.shade.media.LiveSubscriber
import no.zyon.shade.media.MEDIA_GRANT_KIND
import no.zyon.shade.media.MediaFormatException
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaIntegrityException
import no.zyon.shade.media.MediaKeys
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.OwnerOp
import no.zyon.shade.media.Subtitles
import no.zyon.shade.media.chainStep
import no.zyon.shade.media.decodeFrame
import no.zyon.shade.media.deriveMediaSubkeys
import no.zyon.shade.media.epochKeys
import no.zyon.shade.media.linkEpochSeed
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
/**
* `@shade/media` against `test-vectors/media.json` — SMF1 sealed files and
* SLF1 live frames, byte for byte. Generated by
* `bun run scripts/generate-vectors.ts media.json`.
*/
class MediaVectorTest {
private val vectors: JSONArray = run {
val obj = JSONObject(File("../../test-vectors/media.json").readText())
assertEquals("media.json schema version", 2, obj.getInt("version"))
obj.getJSONArray("vectors")
}
private fun byPrefix(prefix: String): List<JSONObject> =
(0 until vectors.length()).map { vectors.getJSONObject(it) }
.filter { it.getString("description").startsWith(prefix) }
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
private fun hex(s: String): ByteArray =
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
private fun toHex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
private val keys = byPrefix("smf1 keys").single()
private val mediaId = hex(keys.getString("mediaId"))
private val mediaKey = hex(keys.getString("mediaKey"))
@Test
fun subkeys() {
val k = deriveMediaSubkeys(mediaKey, mediaId)
assertEquals(keys.getString("segmentKey"), toHex(k.segmentKey))
assertEquals(keys.getString("metaKey"), toHex(k.metaKey))
}
@Test
fun sealedFilesReadAndResealByteForByte() {
for (v in byPrefix("smf1 file")) {
val sealed = hex(v.getString("sealed"))
val plain = hex(v.getString("plaintext"))
val reader = MediaReader.open(ByteArraySource(sealed), MediaKeys(mediaId, mediaKey, hex(v.getString("rootDigest"))))
assertArrayEquals(v.getString("description"), plain, reader.read(0, plain.size))
val meta = MediaMeta.fromJson(v.getString("metaJson"))
assertEquals(meta, reader.meta)
// Writer parity: the same key, id and input give the same bytes.
val (resealed, result) = MediaSealer.withPinnedKeys(mediaId, mediaKey, meta, v.getInt("segmentSize")).sealAll(plain)
assertEquals(v.getString("description"), v.getString("sealed"), toHex(resealed))
assertEquals(v.getString("rootDigest"), toHex(result.rootDigest))
assertEquals(v.getLong("segmentCount"), result.segmentCount)
}
}
@Test
fun randomAccessAndStreaming() {
val v = byPrefix("smf1 file: three segments").single()
val plain = hex(v.getString("plaintext"))
val reader = MediaReader.open(ByteArraySource(hex(v.getString("sealed"))), MediaKeys(mediaId, mediaKey), cacheSegments = 0)
for (off in listOf(0, 1, 4095, 4096, 4097, 8191, 8192, plain.size - 1)) {
for (len in listOf(1, 100, 4096, 9000)) {
assertArrayEquals("at $off+$len", plain.copyOfRange(off, minOf(plain.size, off + len)), reader.read(off.toLong(), len))
}
}
assertArrayEquals(plain, reader.inputStream().readBytes())
assertArrayEquals(plain.copyOfRange(5000, 9000), reader.inputStream(5000, 9000).readBytes())
}
@Test
fun tamperedSegmentAndTrailerAreRefused() {
val v = byPrefix("smf1 file: three segments").single()
val sealed = hex(v.getString("sealed"))
val root = hex(v.getString("rootDigest"))
val bad = sealed.copyOf().also { it[5000] = (it[5000].toInt() xor 1).toByte() }
val r = MediaReader.open(ByteArraySource(bad), MediaKeys(mediaId, mediaKey, root))
assertThrows(MediaIntegrityException::class.java) { r.read(4096, 10) }
val badTable = sealed.copyOf().also { it[it.size - FOOTER_BYTES - 1] = (it[it.size - FOOTER_BYTES - 1].toInt() xor 1).toByte() }
assertThrows(MediaIntegrityException::class.java) { MediaReader.open(ByteArraySource(badTable), MediaKeys(mediaId, mediaKey, root)) }
}
@Test
fun liveKeySchedule() {
val k = byPrefix("live keys").single()
val channelId = hex(k.getString("channelId"))
val seed = linkEpochSeed(hex(k.getString("channelSecret")), channelId, 0)
assertEquals(k.getString("epochSeed"), toHex(seed))
assertEquals(k.getString("epochSeed1"), toHex(linkEpochSeed(hex(k.getString("channelSecret")), channelId, 1)))
val ek = epochKeys(seed, channelId, 0)
assertEquals(k.getString("chainKey0"), toHex(ek.chainKey))
assertEquals(k.getString("stickyKey"), toHex(ek.stickyKey))
val (mk0, ck1) = chainStep(ek.chainKey)
assertEquals(k.getString("messageKey0"), toHex(mk0))
assertEquals(k.getString("chainKey1"), toHex(ck1))
assertEquals(k.getString("messageKey1"), toHex(chainStep(ck1).first))
}
@Test
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
assertNotNull(g.channelSecret)
assertEquals(byPrefix("live grant").single().getString("json"), g.encode())
val sub = LiveSubscriber(g)
for (v in byPrefix("live frame")) {
val f = sub.open(hex(v.getString("wire")))
assertNotNull(v.getString("description"), f)
assertEquals(v.getLong("seq"), f!!.seq)
assertEquals(v.getString("payload"), toHex(f.content.encode()))
// Replays are dropped quietly.
assertNull(sub.open(hex(v.getString("wire"))))
}
}
@Test
fun livePublisherReproducesTheWireBytes() {
val k = byPrefix("live keys").single()
val pub = LivePublisher(hex(k.getString("channelId")), hex(k.getString("signingSecret")), hex(k.getString("channelSecret")))
assertEquals(k.getString("signingKey"), toHex(pub.signingKey))
val frames = byPrefix("live frame: seq")
for ((i, v) in frames.withIndex()) {
val content = LiveContent.decode(hex(v.getString("payload")))
val sticky = v.getString("description").contains("sticky")
val keyframe = decodeFrame(hex(v.getString("wire"))).header.flags and 0x02 != 0
val wire = pub.frame(content, keyframe = keyframe, sticky = sticky, timestamp = 1_786_600_000_000L + i * 100)
assertEquals(v.getString("description"), v.getString("wire"), toHex(wire))
}
}
@Test
fun forgedFramesAndForeignEpochsAreRefused() {
val k = byPrefix("live keys").single()
val channelId = hex(k.getString("channelId"))
val pub = LivePublisher(channelId, ByteArray(32) { 7 }, null)
val sub = LiveSubscriber(pub.grant(from = "now"))
val good = pub.frame(LiveContent.Text("hei"))
val mallory = LivePublisher(channelId, ByteArray(32) { 9 }, null)
assertThrows(MediaIntegrityException::class.java) { sub.open(mallory.frame(LiveContent.Text("falsk"))) }
assertEquals(LiveContent.Text("hei"), sub.open(good)!!.content)
pub.rotate()
assertThrows(LiveKeyException::class.java) { sub.open(pub.frame(LiveContent.Text("etter"))) }
}
@Test
fun mediaGrantParses() {
val g = Grants.parse(
"""{"kind":"shade.media-grant/v1","mediaId":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaId)}","key":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaKey)}","root":"${"ab".repeat(32)}","url":"https://relay.example/v1/media/x","token":"${"A".repeat(43)}"}""",
) as MediaGrant
assertArrayEquals(mediaId, g.mediaId)
assertThrows(Exception::class.java) { Grants.parse("""{"kind":"shade.media-grant/v1","mediaId":"AA","key":"AA","root":"ab"}""") }
}
@Test
fun albumOpensFromTheSealedVector() {
val v = byPrefix("album:").single()
val reader = MediaReader.open(ByteArraySource(hex(v.getString("sealed"))), MediaKeys(mediaId, mediaKey, hex(v.getString("rootDigest"))))
assertEquals(ALBUM_MIME, reader.meta.mime)
val album = Albums.read(reader)
assertEquals(v.getString("title"), album.title)
// And written back: the same plaintext, sealed to the same bytes.
val plain = Albums.encode(album)
assertEquals(v.getString("plaintext"), String(plain, Charsets.UTF_8))
val (resealed, _) = MediaSealer.withPinnedKeys(mediaId, mediaKey, Albums.meta(album.title), 4096).sealAll(plain)
assertEquals(v.getString("sealed"), toHex(resealed))
val kinds = v.getJSONArray("itemKinds")
val names = v.getJSONArray("itemNames")
assertEquals(kinds.length(), album.items.size)
album.items.forEachIndexed { i, g ->
assertEquals(kinds.getString(i), if (g is MediaGrant) MEDIA_GRANT_KIND else LIVE_GRANT_KIND)
val meta = when (g) {
is MediaGrant -> g.meta
is LiveGrant -> g.meta
}
assertEquals(names.getString(i), meta?.name)
}
assertTrue(Albums.isAlbum(album.items[1]))
assertFalse(Albums.isAlbum(album.items[0]))
// Strict: a bad item, the wrong kind, invalid UTF-8.
assertThrows(MediaFormatException::class.java) { Albums.parse("""{"kind":"shade.album/v1","title":"","items":[{"kind":"x"}]}""".toByteArray()) }
assertThrows(MediaFormatException::class.java) { Albums.parse("""{"kind":"shade.album/v2","title":"","items":[]}""".toByteArray()) }
assertThrows(MediaFormatException::class.java) { Albums.parse(byteArrayOf(0xff.toByte(), 0xfe.toByte())) }
}
@Test
fun subtitlesInAFilmsMetaParse() {
val v = byPrefix("subtitles:").single()
val tracks = Subtitles.of(MediaMeta.fromJson(v.getString("meta")))
val langs = v.getJSONArray("langs")
val labels = v.getJSONArray("labels")
val ids = v.getJSONArray("mediaIds")
assertEquals(langs.length(), tracks.size)
tracks.forEachIndexed { i, t ->
assertEquals(langs.getString(i), t.lang)
assertEquals(if (labels.isNull(i)) null else labels.getString(i), t.label)
assertEquals(ids.getString(i), toHex(t.grant.mediaId))
}
assertEquals(emptyList<Any>(), Subtitles.of(MediaMeta(name = "no subtitles")))
assertThrows(MediaFormatException::class.java) {
Subtitles.of(MediaMeta(extra = mapOf("shade.subtitles" to """[{"lang":"no; x","grant":{}}]""")))
}
}
@Test
fun ownerSignaturesMatchTheRelaysByteForByte() {
val v = byPrefix("owner:").single()
val owner = MediaOwner(hex(v.getString("seed")))
assertEquals(v.getString("owner"), owner.id)
val at = v.getLong("at")
val requests = v.getJSONArray("requests")
for (i in 0 until requests.length()) {
val r = requests.getJSONObject(i)
val op = when (r.getString("op")) {
"put" -> OwnerOp.Put(r.getString("id"), r.getLong("size"), r.getString("readTokenHash"))
"upload" -> OwnerOp.Upload(r.getString("id"), r.getLong("size"), r.getString("readTokenHash"))
"piece" -> OwnerOp.Piece(r.getString("id"), r.getLong("offset"), r.getLong("length"))
"abort" -> OwnerOp.Abort(r.getString("id"))
"delete" -> OwnerOp.Delete(r.getString("id"))
"list" -> OwnerOp.List
else -> error("unknown op ${r.getString("op")}")
}
assertEquals(r.getString("message"), String(MediaOwner.message(op, at)))
val want = r.getJSONObject("headers")
val got = owner.headers(op, at)
assertEquals(want.keySet(), got.keys)
for (k in got.keys) assertEquals("${r.getString("op")} $k", want.getString(k), got[k])
}
}
@Test
fun grantsEncodeToTheSameJsonAndLinkAsTs() {
val v = byPrefix("grant encode:").single()
val g = MediaGrant(
hex(v.getString("mediaId")),
hex(v.getString("mediaKey")),
hex(v.getString("rootDigest")),
v.getString("url"),
hex(v.getString("readToken")),
MediaMeta.fromJson(v.getString("meta")),
)
assertEquals(v.getString("json"), g.encode())
assertEquals(v.getString("link"), g.capabilityUrl(v.getString("pageUrl")))
// And back.
val back = Grants.fromCapabilityUrl(v.getString("link")) as MediaGrant
assertEquals(v.getString("json"), back.encode())
}
}

View File

@@ -0,0 +1,101 @@
package no.zyon.shade
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.UploadJobs
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Rule
import org.junit.Test
import org.junit.rules.TemporaryFolder
class UploadJobsTest {
@get:Rule val tmp = TemporaryFolder()
private fun sealed(jobs: UploadJobs, key: String, meta: MediaMeta = MediaMeta(name = "Kveld.mp4")): UploadJobs.Job {
val result = jobs.sealedFile(key).also { it.parentFile.mkdirs() }.outputStream().use {
MediaSealer.sealStream(ByteArray(200_000) { i -> i.toByte() }.inputStream(), it, meta)
}
return UploadJobs.Job(result, ByteArray(32) { 9 }, meta, "content://media/1", server = "https://relay")
}
@Test
fun keysAreTheSourceAndTheRelay() {
val jobs = UploadJobs(tmp.root)
val k = jobs.key("https://relay", "content://media/1", "1234", "Kveld.mp4")
assertEquals(k, jobs.key("https://relay", "content://media/1", "1234", "Kveld.mp4"))
assertNotEquals(k, jobs.key("https://other", "content://media/1", "1234", "Kveld.mp4"))
// Parts are length-prefixed: moving a separator is another job.
assertNotEquals(jobs.key("ab", "c"), jobs.key("a", "bc"))
assertTrue(Regex("^[0-9a-f]{32}$").matches(k))
}
@Test
fun resumableOnlyWithAWholeSealedCopyAndDoneKeepsTheGrant() {
val jobs = UploadJobs(tmp.root)
val key = jobs.key("r", "s")
jobs.claim(key).use {
val job = sealed(jobs, key)
jobs.save(key, job)
val back = jobs.load(key)!!
assertArrayEquals(job.result.mediaKey, back.result.mediaKey)
assertArrayEquals(job.readToken, back.readToken)
assertEquals("Kveld.mp4", back.meta.name)
assertEquals("https://relay", back.server)
assertEquals(listOf(key), jobs.unfinished().map { it.first })
// Cut short: not resumable.
val f = jobs.sealedFile(key)
val whole = f.readBytes()
f.writeBytes(whole.copyOf(whole.size - 1))
assertNull(jobs.load(key))
f.writeBytes(whole)
val grant = MediaGrant.of(job.result, "http://relay/v1/media/x", job.readToken, job.meta)
jobs.done(key, job, grant)
assertFalse(f.exists())
assertEquals(grant.encode(), jobs.load(key)!!.grant!!.encode())
assertTrue(jobs.unfinished().isEmpty())
jobs.reset(key)
assertNull(jobs.load(key))
}
}
@Test
fun oneUploadPerJobAndTheLockGoesWithItsHolder() {
val jobs = UploadJobs(tmp.root)
val key = jobs.key("r", "busy")
val held = jobs.claim(key)
assertThrows(UploadJobs.BusyException::class.java) { jobs.claim(key) }
held.close()
jobs.claim(key).close()
}
@Test
fun pruneOldJobsAndHalfSealedLeftoversButNotOnesInUse() {
val jobs = UploadJobs(tmp.root)
val now = System.currentTimeMillis()
val old = jobs.key("old")
val fresh = jobs.key("fresh")
val half = jobs.key("half")
val busy = jobs.key("busy")
for (k in listOf(old, fresh, busy)) jobs.claim(k).use { jobs.save(k, sealed(jobs, k)) }
jobs.claim(half).close()
java.io.File(tmp.root, "$old/job.json").setLastModified(now - 31L * 86_400_000)
java.io.File(tmp.root, "$busy/job.json").setLastModified(now - 31L * 86_400_000)
java.io.File(tmp.root, half).setLastModified(now - 7_200_000)
jobs.claim(busy).use { assertEquals(2, jobs.prune(now)) }
assertNotNull(jobs.load(fresh))
assertNotNull(jobs.load(busy))
assertFalse(java.io.File(tmp.root, old).exists())
assertFalse(java.io.File(tmp.root, half).exists())
}
}

View File

@@ -0,0 +1,280 @@
package no.zyon.shade
import com.sun.net.httpserver.HttpServer
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.serialization.canonicalJson
import no.zyon.shade.vault.VaultClient
import no.zyon.shade.vault.VaultEdit
import no.zyon.shade.vault.VaultException
import no.zyon.shade.vault.VaultFile
import no.zyon.shade.vault.VaultFormatException
import no.zyon.shade.vault.VaultHttpTransport
import no.zyon.shade.vault.VaultKeys
import no.zyon.shade.vault.VaultLog
import no.zyon.shade.vault.VaultLogEntry
import no.zyon.shade.vault.VaultManifest
import no.zyon.shade.vault.VaultPruneResult
import no.zyon.shade.vault.VaultTransport
import no.zyon.shade.vault.deriveVaultKeys
import no.zyon.shade.vault.entryObjectHashes
import no.zyon.shade.vault.objectHash
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.net.InetSocketAddress
import java.util.Base64
/**
* [VaultClient.edit] and friends against an in-memory relay that enforces
* what the real routes enforce: hash-checked uploads, TOFU Ed25519 over the
* canonical body, `seq == head + 1`, and every referenced object present.
* A signature or hash the TS relay would refuse fails here too.
*/
class VaultClientTest {
private val crypto = TinkProvider()
private val master = ByteArray(32) { (it * 7 + 3).toByte() }
private val keys = deriveVaultKeys(crypto, master, "prism-queue-test")
private val at = 1_786_600_000_000L
/** The relay, minus HTTP. */
private class MemoryRelay(private val crypto: CryptoProvider) : VaultTransport {
val objects = HashMap<String, ByteArray>()
val log = ArrayList<VaultLogEntry>()
val committedHashes = HashMap<Long, List<String>>()
var pinned: ByteArray? = null
var puts = 0
/** Runs just before a commit is checked — the "other device" hook. */
var beforeCommit: (() -> Unit)? = null
private fun authorize(body: JSONObject) {
val sig = Base64.getDecoder().decode(body.getString("signature"))
val fields = LinkedHashMap<String, Any>()
for (k in body.keys()) if (k != "signature") fields[k] = plain(body.get(k))
val canonical = canonicalJson(fields).toByteArray()
val key = pinned ?: Base64.getDecoder().decode(body.getString("publicKey")).also { pinned = it }
if (!crypto.verify(key, canonical, sig)) throw VaultException("UNAUTHORIZED", 401, "bad signature")
}
private fun plain(v: Any): Any = when (v) {
is JSONArray -> List(v.length()) { plain(v.get(it)) }
is Int -> v.toLong()
else -> v
}
private fun head() = log.lastOrNull()?.seq ?: 0L
override fun has(vaultId: String, hash: String) = hash in objects
override fun put(vaultId: String, hash: String, signedBody: String) {
val body = JSONObject(signedBody)
authorize(body)
val data = Base64.getDecoder().decode(body.getString("data"))
if (objectHash(data) != hash) throw VaultException("BAD_REQUEST", 400, "hash mismatch")
objects[hash] = data
puts++
}
override fun get(vaultId: String, hash: String) =
objects[hash] ?: throw VaultException("NOT_FOUND", 404, "no such object")
override fun log(vaultId: String, limit: Int?) =
VaultLog(if (limit == null) log.toList() else log.takeLast(limit), head())
override fun commit(vaultId: String, signedBody: String): Long {
beforeCommit?.let { beforeCommit = null; it() }
val body = JSONObject(signedBody)
authorize(body)
val seq = body.getLong("seq")
if (seq != head() + 1) throw VaultException("SEQ_CONFLICT", 409, "expected seq ${head() + 1}, got $seq", head = head())
val hashes = List(body.getJSONArray("hashes").length()) { body.getJSONArray("hashes").getString(it) }
val manifest = body.getString("manifest")
if (manifest !in objects || hashes.any { it !in objects }) throw VaultException("MISSING_OBJECTS", 409, "missing")
log.add(VaultLogEntry(seq, manifest, body.getLong("at"), 0))
committedHashes[seq] = hashes
return seq
}
override fun prune(vaultId: String, signedBody: String) = VaultPruneResult(0, 0, 0)
}
private fun text(s: String) = s.toByteArray()
@Test
fun emptyVaultAndNoOpEditsCommitNothing() {
val relay = MemoryRelay(crypto)
val client = VaultClient(crypto, keys, relay)
assertNull(client.headManifest())
assertThrows(VaultException::class.java) { client.manifest() }
var seen: VaultManifest? = VaultManifest(2, 99, 0, null, emptyList())
assertEquals(0L, client.edit(at) { seen = it; null }.seq)
assertNull(seen)
val noop = client.edit(at) { VaultEdit(remove = listOf("not-there")) }
assertFalse(noop.committed)
assertEquals(0, relay.puts)
}
@Test
fun appendThenEditKeepsUntouchedEntriesByteForByte() {
val relay = MemoryRelay(crypto)
val client = VaultClient(crypto, keys, relay, chunkSize = 64)
val big = ByteArray(1000).also { java.util.Random(1).nextBytes(it) } // 16 parts, incompressible
val note = text("# Plan\n" + "- [ ] gjør noe\n".repeat(40))
val r1 = client.append(
listOf(VaultFile("big.bin", big), VaultFile("plan.md", note, mode = "644"), VaultFile("empty", ByteArray(0))),
at,
)
assertEquals(1L, r1.seq)
assertTrue(r1.committed)
val m1 = client.manifest()
assertEquals(2, m1.version)
val bigEntry = m1.entries.single { it.path == "big.bin" }
assertEquals(16, bigEntry.parts!!.size)
assertEquals(bigEntry.parts!![0], bigEntry.hash)
assertNull(bigEntry.enc)
val planEntry = m1.entries.single { it.path == "plan.md" }
assertEquals("deflate-raw", planEntry.enc)
assertEquals("644", planEntry.mode)
assertArrayEquals(big, client.readEntry(bigEntry))
assertArrayEquals(note, client.readEntry(planEntry))
assertArrayEquals(ByteArray(0), client.readEntry(m1.entries.single { it.path == "empty" }))
// Commit lists every part of every entry.
assertEquals(m1.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[1L]!!.toSet())
val putsBefore = relay.puts
val r2 = client.edit(at + 1) { head ->
assertEquals(1L, head!!.seq)
VaultEdit(put = listOf(VaultFile("queue/001.json", text("""{"op":"check"}"""))), remove = listOf("empty"))
}
assertEquals(2L, r2.seq)
assertEquals(2, relay.puts - putsBefore) // one new object + the manifest; nothing re-sealed
val m2 = client.manifest()
assertEquals(listOf("big.bin", "plan.md", "queue/001.json"), m2.entries.map { it.path })
assertEquals(bigEntry, m2.entries[0])
assertEquals(planEntry, m2.entries[1])
assertEquals(m2.entries.flatMap { entryObjectHashes(it) }.toSet(), relay.committedHashes[2L]!!.toSet())
// Old versions stay readable; pull decrypts everything.
assertEquals(3, client.manifest(1).entries.size)
val pulled = client.pull()
assertArrayEquals(text("""{"op":"check"}"""), pulled.files["queue/001.json"])
assertEquals(2L, client.log().head)
}
@Test
fun seqConflictRereadsTheHeadAndRetries() {
val relay = MemoryRelay(crypto)
val phone = VaultClient(crypto, keys, relay)
val pc = VaultClient(crypto, keys, relay)
phone.append(listOf(VaultFile("a.txt", text("a"))), at)
// The PC drains the queue between the phone's read and its commit.
relay.beforeCommit = { pc.edit(at) { VaultEdit(remove = listOf("a.txt"), put = listOf(VaultFile("pc.txt", text("pc")))) } }
val heads = ArrayList<Long?>()
val putsBefore = relay.puts
val r = phone.edit(at + 5) { head ->
heads.add(head?.seq)
VaultEdit(put = listOf(VaultFile("b.txt", text("b"))))
}
assertEquals(listOf<Long?>(1L, 2L), heads) // change() saw the new head on the retry
assertEquals(3L, r.seq)
assertTrue(r.committed)
val m = phone.manifest()
assertEquals(setOf("pc.txt", "b.txt"), m.entries.map { it.path }.toSet()) // the PC's edit survived
assertArrayEquals(text("b"), phone.readEntry(m.entries.single { it.path == "b.txt" }))
// Phone: b.txt sealed once + two manifests. PC: pc.txt + its manifest.
assertEquals(5, relay.puts - putsBefore)
}
@Test
fun givesUpAfterMaxAttemptsAndPassesOtherErrorsThrough() {
val relay = MemoryRelay(crypto)
val client = VaultClient(crypto, keys, relay)
val other = VaultClient(crypto, keys, relay)
var calls = 0
val loseEveryRace = object : VaultTransport by relay {
override fun commit(vaultId: String, signedBody: String): Long {
other.append(listOf(VaultFile("x${calls++}", text("x"))), at)
return relay.commit(vaultId, signedBody)
}
}
val e = assertThrows(VaultException::class.java) {
VaultClient(crypto, keys, loseEveryRace).edit(at, maxAttempts = 3) { VaultEdit(put = listOf(VaultFile("p", text("p")))) }
}
assertTrue(e.isSeqConflict)
assertEquals(3, calls)
val refusing = object : VaultTransport by relay {
override fun commit(vaultId: String, signedBody: String): Long =
throw VaultException("MISSING_OBJECTS", 409, "missing")
}
var attempts = 0
val e2 = assertThrows(VaultException::class.java) {
VaultClient(crypto, keys, refusing).edit(at) { attempts++; VaultEdit(put = listOf(VaultFile("q", text("q")))) }
}
assertEquals("MISSING_OBJECTS", e2.code)
assertEquals(1, attempts)
assertTrue(client.headManifest() != null)
}
@Test
fun refusesToEditOnTopOfAnUnreadableHead() {
val relay = MemoryRelay(crypto)
VaultClient(crypto, keys, relay).append(listOf(VaultFile("a", text("a"))), at)
val wrongKey = VaultKeys(keys.vaultId, ByteArray(32) { 9 }, keys.signingSeed, keys.publicKey)
assertThrows(VaultFormatException::class.java) {
VaultClient(crypto, wrongKey, relay).edit(at) { VaultEdit(put = listOf(VaultFile("b", text("b")))) }
}
assertEquals(1L, relay.log.size.toLong())
}
@Test
fun httpTransportMapsRelayErrors() {
val server = HttpServer.create(InetSocketAddress("127.0.0.1", 0), 0)
server.createContext("/") { ex ->
val path = ex.requestURI.path
val (status, body) = when {
path.endsWith("/commit") -> 409 to """{"error":{"code":"SEQ_CONFLICT","message":"expected seq 4, got 3"},"head":3}"""
path.endsWith("/log") -> 200 to """{"entries":[{"seq":3,"manifest":"${"a".repeat(64)}","at":5,"bytes":10}],"head":3}"""
ex.requestMethod == "HEAD" -> 404 to ""
ex.requestMethod == "GET" -> 200 to "raw-bytes"
else -> 502 to "<html>bad gateway</html>"
}
val bytes = body.toByteArray()
ex.sendResponseHeaders(status, if (ex.requestMethod == "HEAD" || bytes.isEmpty()) -1 else bytes.size.toLong())
if (bytes.isNotEmpty() && ex.requestMethod != "HEAD") ex.responseBody.use { it.write(bytes) }
ex.close()
}
server.start()
try {
val t = VaultHttpTransport("http://127.0.0.1:${server.address.port}/")
val id = keys.vaultId
val hash = "b".repeat(64)
assertEquals(3L, t.log(id, 1).head)
assertEquals(10L, t.log(id).entries.single().bytes)
assertFalse(t.has(id, hash))
assertArrayEquals("raw-bytes".toByteArray(), t.get(id, hash))
val e = assertThrows(VaultException::class.java) { t.commit(id, "{}") }
assertTrue(e.isSeqConflict)
assertEquals(409, e.statusCode)
assertEquals(3L, e.head)
val e2 = assertThrows(VaultException::class.java) { t.put(id, hash, "{}") }
assertEquals(VaultException.CODE_NETWORK, e2.code)
assertEquals(502, e2.statusCode)
assertThrows(IllegalArgumentException::class.java) { t.get(id, "../../etc/passwd") }
} finally {
server.stop(0)
}
}
}

View File

@@ -0,0 +1,73 @@
package no.zyon.shade
import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.vault.VaultClient
import no.zyon.shade.vault.VaultEdit
import no.zyon.shade.vault.VaultFile
import no.zyon.shade.vault.VaultHttpTransport
import no.zyon.shade.vault.deriveVaultKeys
import no.zyon.shade.vault.toHex
import org.json.JSONObject
import org.junit.Assert.assertEquals
import org.junit.Assert.assertTrue
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import java.security.MessageDigest
/**
* Live cross-check against the real TS vault routes — skipped unless
* `SHADE_VAULT_LIVE_SPEC` points at the spec file a TS driver wrote.
*
* Run it via `bun run scripts/vault-live-kotlin.ts`: the driver serves `createVaultRoutes`
* on a local port, pushes files with the TS client and writes
* `{ url, masterKey, app, files: {path: sha256}, kotlinOut }`. This test reads
* every file back, then edits the vault from Kotlin and records what it wrote
* in `kotlinOut`; the driver then reads that back with the TS client.
*/
class VaultLiveTest {
private fun sha256(b: ByteArray) = toHex(MessageDigest.getInstance("SHA-256").digest(b))
private fun fromHex(s: String) =
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
@Test
fun readsTsWritesAndAppendsForTs() {
val specPath = System.getenv("SHADE_VAULT_LIVE_SPEC")
assumeTrue("SHADE_VAULT_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty())
val spec = JSONObject(File(specPath!!).readText())
val crypto = TinkProvider()
val keys = deriveVaultKeys(crypto, fromHex(spec.getString("masterKey")), spec.getString("app"))
val client = VaultClient(crypto, keys, VaultHttpTransport(spec.getString("url")))
// Read what TS pushed.
val head = client.manifest()
val want = spec.getJSONObject("files")
assertEquals(want.keySet(), head.entries.map { it.path }.toSet())
for (entry in head.entries) {
assertEquals(entry.path, want.getString(entry.path), sha256(client.readEntry(entry)))
}
assertTrue("TS pushed a multi-part file", head.entries.any { (it.parts?.size ?: 0) > 1 })
assertTrue("TS pushed a compressed file", head.entries.any { it.enc == "deflate-raw" })
// Append from Kotlin: a compressible note, a 2-part binary, a removal.
val note = ("# Fra telefonen\n" + "- [x] lest workspace mens PC-en var av\n".repeat(200)).toByteArray()
val big = ByteArray(5 * 1024 * 1024).also { java.util.Random(42).nextBytes(it) }
val result = client.edit(System.currentTimeMillis()) { h ->
assertEquals(head.seq, h!!.seq)
VaultEdit(
put = listOf(VaultFile("from-kotlin/note.md", note, mode = "644"), VaultFile("from-kotlin/big.bin", big)),
remove = listOf("hello.txt"),
)
}
assertTrue(result.committed)
assertEquals(head.seq + 1, result.seq)
val out = JSONObject()
.put("seq", result.seq)
.put("removed", "hello.txt")
.put("files", JSONObject().put("from-kotlin/note.md", sha256(note)).put("from-kotlin/big.bin", sha256(big)))
File(spec.getString("kotlinOut")).writeText(out.toString())
}
}

View File

@@ -0,0 +1,333 @@
package no.zyon.shade
import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.vault.VAULT_CHUNK_SIZE
import no.zyon.shade.vault.VaultEntry
import no.zyon.shade.vault.VaultFormatException
import no.zyon.shade.vault.VaultKeys
import no.zyon.shade.vault.VaultManifest
import no.zyon.shade.vault.decodeManifest
import no.zyon.shade.vault.deflateRaw
import no.zyon.shade.vault.deriveVaultKeys
import no.zyon.shade.vault.encodeManifest
import no.zyon.shade.vault.entryLocator
import no.zyon.shade.vault.entryObjectHashes
import no.zyon.shade.vault.inflateRaw
import no.zyon.shade.vault.looksCompressed
import no.zyon.shade.vault.openEntryBytes
import no.zyon.shade.vault.openManifest
import no.zyon.shade.vault.openObject
import no.zyon.shade.vault.packEntry
import no.zyon.shade.vault.sealObject
import no.zyon.shade.vault.sealObjectWithNonce
import no.zyon.shade.vault.signPayload
import no.zyon.shade.vault.signVaultBody
import no.zyon.shade.vault.toHex
import no.zyon.shade.vault.vaultObjectAad
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
import java.util.Base64
/**
* `@shade/vault` v2 against `test-vectors/vault-v2.json` — the cross-language
* contract in `docs/vault.md`. Every byte a reader or signer depends on is
* compared exactly; generated by `scripts/generate-vectors.ts vault-v2.json`.
*/
class VaultVectorTest {
private val crypto = TinkProvider()
private val vectors: JSONArray = run {
val obj = JSONObject(File("../../test-vectors/vault-v2.json").readText())
assertEquals("vault-v2.json schema version", 2, obj.getInt("version"))
obj.getJSONArray("vectors")
}
private fun byPrefix(prefix: String): List<JSONObject> =
(0 until vectors.length()).map { vectors.getJSONObject(it) }
.filter { it.getString("description").startsWith(prefix) }
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
private fun fromHex(s: String): ByteArray =
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
private val keyVector = byPrefix("vault-v2 keys").single()
private val keys: VaultKeys = deriveVaultKeys(crypto, fromHex(keyVector.getString("masterKey")), keyVector.getString("app"))
private fun entryFrom(o: JSONObject): VaultEntry = VaultEntry(
path = o.getString("path"),
hash = o.getString("hash"),
size = o.getLong("size"),
mode = if (o.has("mode")) o.getString("mode") else null,
enc = if (o.has("enc") && !o.isNull("enc")) o.getString("enc") else null,
parts = o.optJSONArray("parts")?.let { a -> List(a.length()) { a.getString(it) } },
)
private fun manifestFrom(o: JSONObject): VaultManifest {
val a = o.getJSONArray("entries")
return VaultManifest(
version = o.getInt("version"),
seq = o.getLong("seq"),
at = o.getLong("at"),
message = if (o.has("message")) o.getString("message") else null,
entries = List(a.length()) { entryFrom(a.getJSONObject(it)) },
)
}
/** Vector JSON → plain Kotlin values, keeping key order (org.json does not, but only top-level is sorted anyway). */
private fun toKotlin(v: Any?): Any = when (v) {
is JSONObject -> LinkedHashMap<String, Any>().apply { for (k in v.keys()) put(k, toKotlin(v.get(k))) }
is JSONArray -> List(v.length()) { toKotlin(v.get(it)) }
is Int -> v.toLong()
is Long, is String, is Boolean -> v
else -> error("unexpected vector value ${v?.javaClass}")
}
// ─── Keys ────────────────────────────────────────────────
@Test
fun keysMatchVector() {
assertEquals(keyVector.getString("vaultId"), keys.vaultId)
assertEquals(keyVector.getString("contentKey"), toHex(keys.contentKey))
assertEquals(keyVector.getString("signingSeed"), toHex(keys.signingSeed))
assertEquals(keyVector.getString("publicKey"), toHex(keys.publicKey))
assertEquals(keyVector.getString("objectAad"), toHex(vaultObjectAad(keys.vaultId)))
assertEquals(keyVector.getString("objectAadUtf8"), String(vaultObjectAad(keys.vaultId), Charsets.UTF_8))
}
// ─── Entries ─────────────────────────────────────────────
@Test
fun entryPackingMatchesVectors() {
for (v in byPrefix("vault-v2 entry")) {
val what = v.getString("description")
val plaintext = fromHex(v.getString("plaintext"))
val chunkSize = v.getInt("chunkSize")
val packed = packEntry(plaintext, chunkSize)
val wantEnc = if (v.isNull("enc")) null else v.getString("enc")
assertEquals("$what: enc", wantEnc, packed.enc)
// Compressed bytes need not match zlib-for-zlib (readers never
// depend on them; the JDK's zlib and Bun's diverge on longer
// inputs) — but ours must inflate back, and the vector's must too.
if (packed.enc != null) {
assertArrayEquals("$what: own stored inflates", plaintext, inflateRaw(packed.stored, plaintext.size.toLong()))
assertArrayEquals("$what: vector stored inflates", plaintext, inflateRaw(fromHex(v.getString("stored")), plaintext.size.toLong()))
} else {
assertEquals("$what: stored", v.getString("stored"), toHex(packed.stored))
}
// Splitting and sealing are exact: chunk the vector's stored bytes
// the way packEntry does and seal each slice under the pinned nonce.
val stored = fromHex(v.getString("stored"))
val chunks = stored.toList().chunked(chunkSize).map { it.toByteArray() }.ifEmpty { listOf(ByteArray(0)) }
val parts = v.getJSONArray("parts")
assertEquals("$what: part count", parts.length(), chunks.size)
val sealed = (0 until parts.length()).map { i ->
val p = parts.getJSONObject(i)
assertEquals("$what: part $i plaintext", p.getString("plaintext"), toHex(chunks[i]))
val obj = sealObjectWithNonce(keys.contentKey, keys.vaultId, chunks[i], fromHex(p.getString("nonce")))
assertEquals("$what: part $i wire", p.getString("wire"), toHex(obj.bytes))
assertEquals("$what: part $i hash", p.getString("hash"), obj.hash)
obj
}
val vectorPacked = no.zyon.shade.vault.PackedEntry(wantEnc, stored, chunks)
val want = entryFrom(v.getJSONObject("entry"))
val loc = entryLocator(vectorPacked, sealed)
assertEquals("$what: hash", want.hash, loc.hash)
assertEquals("$what: parts", want.parts, loc.parts)
assertEquals("$what: locator enc", want.enc, loc.enc)
assertEquals("$what: object hashes", sealed.map { it.hash }, entryObjectHashes(want))
}
}
@Test
fun entryReadsBackFromWire() {
for (v in byPrefix("vault-v2 entry")) {
val entry = entryFrom(v.getJSONObject("entry"))
val parts = v.getJSONArray("parts")
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
val plain = openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, wires)
assertEquals(v.getString("description"), v.getString("plaintext"), toHex(plain))
}
}
@Test
fun entryReadRefusesWhatDoesNotAddUp() {
val v = byPrefix("vault-v2 entry: multi-part").single()
val entry = entryFrom(v.getJSONObject("entry"))
val parts = v.getJSONArray("parts")
val wires = List(parts.length()) { fromHex(parts.getJSONObject(it).getString("wire")) }
// Parts swapped: each fetched object must hash to its slot.
assertThrows(VaultFormatException::class.java) {
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry, listOf(wires[1], wires[0]) + wires.drop(2))
}
// A part dropped from the list (consistently, so every hash checks out).
val shorter = entry.copy(parts = entry.parts!!.dropLast(1))
assertThrows(VaultFormatException::class.java) {
openEntryBytes(crypto, keys.contentKey, keys.vaultId, shorter, wires.dropLast(1))
}
// Size lies.
assertThrows(VaultFormatException::class.java) {
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(size = entry.size + 1), wires)
}
// An encoding this reader does not know is refused, not guessed.
assertThrows(VaultFormatException::class.java) {
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(enc = "zstd"), wires)
}
// hash must equal parts[0].
assertThrows(VaultFormatException::class.java) {
openEntryBytes(crypto, keys.contentKey, keys.vaultId, entry.copy(hash = entry.parts!![1]), wires)
}
// A flipped ciphertext bit no longer matches its name.
val tampered = wires[0].copyOf().also { it[20] = (it[20].toInt() xor 1).toByte() }
assertThrows(VaultFormatException::class.java) {
openObject(crypto, keys.contentKey, keys.vaultId, entry.parts!![0], tampered)
}
// Right name, wrong vault: the AAD binds the vaultId.
assertThrows(VaultFormatException::class.java) {
openObject(crypto, keys.contentKey, "0".repeat(64), entry.parts!![0], wires[0])
}
}
// ─── Manifests ───────────────────────────────────────────
@Test
fun manifestsDecodeFromWire() {
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
val v = byPrefix(prefix).single()
val want = manifestFrom(v.getJSONObject("manifest"))
val got = openManifest(crypto, keys.contentKey, keys.vaultId, v.getString("hash"), fromHex(v.getString("wire")))
assertEquals(prefix, want, got)
}
}
@Test
fun manifestsEncodeLikeTypeScript() {
for (prefix in listOf("vault-v2 manifest v2", "vault-v2 manifest v1")) {
val v = byPrefix(prefix).single()
val m = manifestFrom(v.getJSONObject("manifest"))
val plain = encodeManifest(m)
// Key order is not contract, but writing it in TS order makes the
// JSON identical; v1 is that JSON, so its whole plaintext matches.
val ownJson = if (m.version == 2) String(inflateRaw(plain.copyOfRange(4, plain.size), 1L shl 20)) else String(plain)
assertEquals("$prefix: json", v.getString("json"), ownJson)
assertArrayEquals("$prefix: magic", if (m.version == 2) "SVM2".toByteArray() else "{\"v".toByteArray(), plain.copyOf(if (m.version == 2) 4 else 3))
if (m.version == 1) assertEquals("$prefix: plaintext", v.getString("plaintext"), toHex(plain))
val sealed = sealObjectWithNonce(keys.contentKey, keys.vaultId, fromHex(v.getString("plaintext")), fromHex(v.getString("nonce")))
assertEquals("$prefix: wire", v.getString("wire"), toHex(sealed.bytes))
assertEquals("$prefix: hash", v.getString("hash"), sealed.hash)
assertEquals("$prefix: round trip", m, decodeManifest(plain))
}
val v2 = byPrefix("vault-v2 manifest v2").single()
val json = String(inflateRaw(fromHex(v2.getString("plaintext")).copyOfRange(4, fromHex(v2.getString("plaintext")).size), 1 shl 20))
assertEquals(v2.getString("json"), json)
}
@Test
fun manifestRefusesUnknownVersion() {
for (bad in listOf("""{"version":3,"seq":1,"at":1,"entries":[]}""", """{"version":"2","seq":1,"at":1,"entries":[]}""", """{"seq":1,"at":1,"entries":[]}""")) {
assertThrows(bad, VaultFormatException::class.java) { decodeManifest(bad.toByteArray()) }
}
val v3 = byteArrayOf(0x53, 0x56, 0x4d, 0x32) + deflateRaw("""{"version":3,"seq":1,"at":1,"entries":[]}""".toByteArray())
assertThrows(VaultFormatException::class.java) { decodeManifest(v3) }
}
@Test
fun freshSealOpensAndRoundTripsAManifest() {
val m = manifestFrom(byPrefix("vault-v2 manifest v2").single().getJSONObject("manifest"))
val a = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
val b = sealObject(crypto, keys.contentKey, keys.vaultId, encodeManifest(m))
// Fresh nonce: same plaintext, different names — why unchanged entries are reused, not re-sealed.
assertFalse(a.hash == b.hash)
assertEquals(m, openManifest(crypto, keys.contentKey, keys.vaultId, a.hash, a.bytes))
}
// ─── Signing ─────────────────────────────────────────────
@Test
fun signedBodiesMatchVectors() {
for (v in byPrefix("vault-v2 signed")) {
val what = v.getString("description")
@Suppress("UNCHECKED_CAST")
val body = toKotlin(v.getJSONObject("body")) as Map<String, Any>
val signed = signPayload(crypto, keys.signingSeed, body, v.getLong("signedAt"))
assertEquals("$what: canonical", v.getString("canonical"), String(signed.canonical, Charsets.UTF_8))
assertEquals("$what: canonicalHex", v.getString("canonicalHex"), toHex(signed.canonical))
assertEquals("$what: signature", v.getString("signature"), toHex(signed.signature))
val wire = JSONObject(signed.json)
assertEquals(v.getString("signatureBase64"), wire.getString("signature"))
assertEquals(v.getLong("signedAt"), wire.getLong("signedAt"))
assertTrue(crypto.verify(keys.publicKey, signed.canonical, Base64.getDecoder().decode(wire.getString("signature"))))
// The vault helper adds publicKey itself and must land on the same bytes.
val withoutKey = body.filterKeys { it != "publicKey" }
val viaKeys = signVaultBody(crypto, keys, withoutKey, v.getLong("signedAt"))
assertArrayEquals("$what: signVaultBody", signed.canonical, viaKeys.canonical)
assertArrayEquals(signed.signature, viaKeys.signature)
}
}
// ─── Packing rules ───────────────────────────────────────
@Test
fun packingRules() {
// Empty file: one empty part, never compressed.
val empty = packEntry(ByteArray(0))
assertNull(empty.enc)
assertEquals(1, empty.chunks.size)
assertEquals(0, empty.chunks[0].size)
// Random bytes do not shrink ≥5 %: stored as-is.
val random = ByteArray(10_000).also { java.util.Random(7).nextBytes(it) }
assertNull(packEntry(random).enc)
// Exactly at a chunk boundary: no trailing empty part.
val twoChunks = packEntry(random, chunkSize = 5_000)
assertEquals(2, twoChunks.chunks.size)
assertEquals(VAULT_CHUNK_SIZE, 4 * 1024 * 1024)
// Compressible text compresses and inflates back.
val text = "hei hei hei hei\n".repeat(500).toByteArray()
val p = packEntry(text)
assertEquals("deflate-raw", p.enc)
assertArrayEquals(text, inflateRaw(p.stored, text.size.toLong()))
val magics = listOf(
byteArrayOf(0x89.toByte(), 0x50, 0x4e, 0x47),
byteArrayOf(0xff.toByte(), 0xd8.toByte(), 0xff.toByte()),
"RIFF\u0000\u0000\u0000\u0000WEBP".toByteArray(),
"\u0000\u0000\u0000\u0018ftypmp42".toByteArray(),
"GIF89a".toByteArray(),
byteArrayOf(0x1f, 0x8b.toByte()),
"PK\u0003\u0004".toByteArray(),
)
for (m in magics) {
assertTrue(toHex(m), looksCompressed(m))
assertNull(packEntry(m + ByteArray(4000)).enc)
}
assertFalse(looksCompressed("RIFF\u0000\u0000\u0000\u0000WAVE".toByteArray()))
assertFalse(looksCompressed("P".toByteArray()))
}
@Test
fun inflateIsStrictAboutTheStreamEnd() {
val text = "abcabcabc-".repeat(1000).toByteArray()
val d = deflateRaw(text)
assertArrayEquals(text, inflateRaw(d, text.size.toLong()))
assertThrows(VaultFormatException::class.java) { inflateRaw(d.copyOf(d.size - 3), text.size.toLong()) }
assertThrows(VaultFormatException::class.java) { inflateRaw(d + byteArrayOf(1, 2, 3), text.size.toLong()) }
assertThrows(VaultFormatException::class.java) { inflateRaw(d, text.size.toLong() - 1) }
assertThrows(VaultFormatException::class.java) { inflateRaw(byteArrayOf(0xff.toByte(), 0xff.toByte(), 0xff.toByte()), 100) }
assertArrayEquals(ByteArray(0), inflateRaw(deflateRaw(ByteArray(0)), 0))
}
}

View File

@@ -0,0 +1,46 @@
plugins {
id("com.android.application")
kotlin("android")
}
// Demo player for sealed Shade media: open a `…/watch/#shade=…` link and
// play it with ExoPlayer through `ShadeMediaDataSource`. Debug-signed, for
// the dev phone; not a product.
android {
namespace = "no.zyon.shade.mediademo"
compileSdk = 35
defaultConfig {
applicationId = "no.zyon.shade.mediademo"
minSdk = 28 // the owner key lives in the Keystore (:shade-android-keystore)
targetSdk = 35
versionCode = 1
versionName = "4.15.0"
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildTypes {
release {
isMinifyEnabled = false
}
}
packaging {
resources.excludes += setOf("META-INF/versions/9/OSGI-INF/MANIFEST.MF")
}
}
dependencies {
implementation(project(":shade-android-media"))
implementation(project(":shade-android-keystore"))
implementation("androidx.media3:media3-ui:1.5.1")
}

View File

@@ -0,0 +1,54 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<!-- Uploading a film runs in the foreground, with its progress shown. -->
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<!-- Cleartext is allowed so the demo can reach a relay on the LAN
(`shade media serve` speaks plain HTTP). The media is sealed end to
end either way; TLS would hide only which file is fetched. -->
<application
android:label="Shade Media"
android:usesCleartextTraffic="true"
android:theme="@android:style/Theme.Material.NoActionBar">
<activity
android:name=".PlayerActivity"
android:exported="true"
android:configChanges="orientation|screenSize|screenLayout|keyboardHidden">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Share a watch link to the app from any browser or chat. -->
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/plain" />
</intent-filter>
</activity>
<!-- Share a video, photo, song or document: sealed here, uploaded to your relay. -->
<activity
android:name=".ShareActivity"
android:exported="true"
android:label="Share to Shade"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.SEND" />
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="video/*" />
<data android:mimeType="image/*" />
<data android:mimeType="audio/*" />
<data android:mimeType="application/*" />
</intent-filter>
</activity>
<service
android:name=".UploadService"
android:exported="false"
android:foregroundServiceType="dataSync" />
</application>
</manifest>

View File

@@ -0,0 +1,363 @@
package no.zyon.shade.mediademo
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Button
import android.widget.EditText
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.ScrollView
import android.widget.TextView
import androidx.annotation.OptIn
import androidx.media3.common.PlaybackException
import androidx.media3.common.Player
import androidx.media3.common.util.UnstableApi
import androidx.media3.exoplayer.ExoPlayer
import androidx.media3.ui.PlayerView
import no.zyon.shade.media.ALBUM_MIME
import no.zyon.shade.media.Album
import no.zyon.shade.media.Albums
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.ReceivedFrame
import no.zyon.shade.media.android.LiveWatcher
import no.zyon.shade.media.android.ShadeFilm
import no.zyon.shade.media.android.ShadeMedia
import java.util.concurrent.Executors
/**
* Plays a sealed Shade film, video, song or picture, or watches a live
* channel: live video/audio through ExoPlayer, a live log as scrolling text,
* live pictures (a webcam, a watched folder) one after another.
*
* The link comes from a share (`ACTION_SEND` text), from an upload's
* notification (see [ShareActivity]), from
* `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`,
* or is pasted into the field. Opening the reader fetches the footer and
* trailer over the network, so it runs off the main thread.
*/
@OptIn(UnstableApi::class)
class PlayerActivity : Activity() {
private val io = Executors.newSingleThreadExecutor()
private var player: ExoPlayer? = null
private var film: ShadeFilm? = null
private var watcher: LiveWatcher? = null
private lateinit var status: TextView
private lateinit var view: PlayerView
private lateinit var log: TextView
private lateinit var logScroll: ScrollView
private lateinit var picture: ImageView
private lateinit var share: Button
private lateinit var albumList: LinearLayout
private lateinit var albumScroll: ScrollView
/** The album the item on screen came from, to go back to. */
private var album: Album? = null
/** The link playing now, to hand on. */
private var current: String? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val field = EditText(this).apply {
hint = "https://…/watch/#shade=…"
setSingleLine()
}
val open = Button(this).apply {
text = "Open"
setOnClickListener { play(field.text.toString().trim()) }
}
status = TextView(this).apply {
setTextColor(Color.LTGRAY)
setPadding(24, 12, 24, 12)
}
view = PlayerView(this).apply { setBackgroundColor(Color.BLACK) }
log = TextView(this).apply {
setTextColor(Color.rgb(214, 219, 225))
typeface = android.graphics.Typeface.MONOSPACE
textSize = 11f
setPadding(24, 12, 24, 12)
}
logScroll = ScrollView(this).apply {
addView(log)
visibility = android.view.View.GONE
}
picture = ImageView(this).apply {
scaleType = ImageView.ScaleType.FIT_CENTER
setBackgroundColor(Color.BLACK)
visibility = android.view.View.GONE
}
share = Button(this).apply {
text = "Share"
visibility = android.view.View.GONE
setOnClickListener {
current?.let { link ->
startActivity(Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, link), "Share link"))
}
}
}
albumList = LinearLayout(this).apply { orientation = LinearLayout.VERTICAL }
albumScroll = ScrollView(this).apply {
addView(albumList)
visibility = android.view.View.GONE
}
val bar = LinearLayout(this).apply {
orientation = LinearLayout.HORIZONTAL
gravity = Gravity.CENTER_VERTICAL
addView(field, LinearLayout.LayoutParams(0, WRAP_CONTENT, 1f))
addView(open)
addView(share)
}
setContentView(
LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.rgb(15, 17, 21))
addView(bar, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(status, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
addView(view, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(logScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(picture, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
addView(albumScroll, LinearLayout.LayoutParams(MATCH_PARENT, 0, 1f))
},
)
linkFrom(intent)?.let {
field.setText(it)
play(it)
}
}
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
linkFrom(intent)?.let { play(it) }
}
private fun linkFrom(intent: Intent?): String? = when (intent?.action) {
Intent.ACTION_SEND -> intent.getStringExtra(Intent.EXTRA_TEXT)
else -> intent?.getStringExtra("link")
}?.let { text -> Regex("\\S*#\\S*shade=[A-Za-z0-9_-]+").find(text)?.value }
private fun play(link: String) {
if (link.isEmpty()) return
stop()
val grant = runCatching { ShadeMedia.grant(link) }.getOrElse {
status.text = "Not a Shade link: ${it.message}"
return
}
current = link
share.visibility = android.view.View.VISIBLE
album = null
open(grant)
}
/** Open a grant: from a link, or an item of the album on screen. */
private fun open(grant: no.zyon.shade.media.Grant) {
stop()
when (grant) {
is LiveGrant -> watch(grant)
is MediaGrant -> {
status.text = "Opening…"
io.execute {
val opened = runCatching { ShadeMedia.openFilm(grant) }
runOnUiThread {
opened.fold(
onSuccess = { start(it) },
onFailure = { status.text = "Cannot open: ${it.message}" },
)
}
}
}
}
}
private fun watch(g: LiveGrant) {
val name = g.meta?.name ?: "live channel"
val mime = g.meta?.mime ?: ""
if (mime.startsWith("video/") || mime.startsWith("audio/")) {
show(View.PLAYER)
val p = newPlayer()
status.text = "$name · live · end-to-end encrypted"
p.setMediaSource(ShadeMedia.liveMediaSource(g))
p.prepare()
p.play()
return
}
// Text and images: follow the channel directly.
show(if (mime.startsWith("image/")) View.PICTURE else View.LOG)
log.text = ""
status.text = "$name · connecting…"
watcher = LiveWatcher(g, object : LiveWatcher.Listener {
override fun onFrame(frame: ReceivedFrame) {
val c = frame.content
runOnUiThread {
when (c) {
is LiveContent.Text -> {
show(View.LOG)
appendLog(c.text)
}
is LiveContent.Image -> showPicture(c.bytes)
is LiveContent.End -> status.text = "$name · the broadcast has ended"
else -> Unit
}
}
}
override fun onState(state: LiveWatcher.State) {
runOnUiThread { status.text = "$name · ${state.name.lowercase()} · end-to-end encrypted" }
}
})
}
private fun appendLog(text: String) {
val atBottom = !logScroll.canScrollVertically(1)
log.append(text)
// Bound the view: a log channel runs for days.
if (log.length() > MAX_LOG_CHARS) log.text = log.text.subSequence(log.length() - MAX_LOG_CHARS / 2, log.length())
if (atBottom) logScroll.post { logScroll.fullScroll(android.view.View.FOCUS_DOWN) }
}
/**
* An album: its items as a list, each opening in place. Back returns to
* the list. Read already (it is small), so this needs no network.
*/
private fun showAlbum(a: Album) {
album = a
show(View.ALBUM)
status.text = "${a.title} · ${a.items.size} item(s) · end-to-end encrypted"
albumList.removeAllViews()
a.items.forEachIndexed { i, g ->
val meta = when (g) {
is MediaGrant -> g.meta
is LiveGrant -> g.meta
}
val kind = when {
g is LiveGrant -> "live"
Albums.isAlbum(g) -> "album"
else -> meta?.mime?.substringBefore('/') ?: "file"
}
albumList.addView(Button(this).apply {
text = "${meta?.name ?: "item ${i + 1}"} · $kind"
isAllCaps = false
gravity = Gravity.START or Gravity.CENTER_VERTICAL
setOnClickListener { open(g) }
})
}
}
@Deprecated("Activity.onBackPressed")
override fun onBackPressed() {
val a = album
if (a != null && albumScroll.visibility != android.view.View.VISIBLE) {
stop()
showAlbum(a)
return
}
@Suppress("DEPRECATION")
super.onBackPressed()
}
private enum class View { PLAYER, LOG, PICTURE, ALBUM }
private fun show(which: View) {
fun vis(on: Boolean) = if (on) android.view.View.VISIBLE else android.view.View.GONE
view.visibility = vis(which == View.PLAYER)
logScroll.visibility = vis(which == View.LOG)
picture.visibility = vis(which == View.PICTURE)
albumScroll.visibility = vis(which == View.ALBUM)
}
/**
* Decode off the UI thread, scaled to the screen: a 40-megapixel photo
* decoded whole is 160 MB of bitmap. A picture that will not decode is
* reported and skipped — the next one may.
*/
private fun showPicture(bytes: ByteArray) {
show(View.PICTURE)
val target = maxOf(resources.displayMetrics.widthPixels, resources.displayMetrics.heightPixels)
io.execute {
val bounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
BitmapFactory.decodeByteArray(bytes, 0, bytes.size, bounds)
var sample = 1
while (maxOf(bounds.outWidth, bounds.outHeight) / (sample * 2) >= target) sample *= 2
val bmp: Bitmap? = BitmapFactory.decodeByteArray(bytes, 0, bytes.size, BitmapFactory.Options().apply { inSampleSize = sample })
runOnUiThread {
if (bmp == null) status.text = "${status.text} · a picture could not be decoded" else picture.setImageBitmap(bmp)
}
}
}
private fun newPlayer(): ExoPlayer {
val p = ExoPlayer.Builder(this).build()
player = p
view.player = p
p.addListener(object : Player.Listener {
override fun onPlayerError(error: PlaybackException) {
status.text = "Playback failed: ${error.cause?.message ?: error.message}"
}
})
return p
}
private fun start(f: ShadeFilm) {
film = f
val meta0 = f.reader.meta
if (meta0.mime == ALBUM_MIME) {
val read = runCatching { Albums.read(f.reader) }
read.fold(onSuccess = { showAlbum(it) }, onFailure = { status.text = "Cannot read the album: ${it.message}" })
return
}
if (meta0.mime?.startsWith("image/") == true) {
status.text = "${meta0.name ?: "picture"} · ${meta0.mime} · ${f.reader.size / 1024} KiB · end-to-end encrypted"
if (f.reader.size > MAX_PICTURE_BYTES) {
status.text = "${status.text} · too large to show here"
return
}
show(View.PICTURE)
io.execute {
val bytes = runCatching { f.reader.read(0, f.reader.size.toInt()) }
runOnUiThread { bytes.fold(onSuccess = { showPicture(it) }, onFailure = { status.text = "Cannot read: ${it.message}" }) }
}
return
}
show(View.PLAYER)
val p = newPlayer()
val meta = f.reader.meta
val subs = if (f.subtitles.isEmpty()) "" else " · ${f.subtitles.size} subtitle track(s)"
status.text = "${meta.name ?: "sealed file"} · ${meta.mime ?: "?"} · ${f.reader.size / 1024} KiB$subs · end-to-end encrypted"
p.setMediaSource(ShadeMedia.mediaSource(f))
p.prepare()
p.play()
}
private fun stop() {
picture.setImageDrawable(null)
watcher?.close()
watcher = null
view.player = null
player?.release()
player = null
film?.close()
film = null
}
override fun onStop() {
super.onStop()
player?.pause()
}
override fun onDestroy() {
stop()
io.shutdown()
super.onDestroy()
}
private companion object {
const val MAX_LOG_CHARS = 200_000
const val MAX_PICTURE_BYTES = 64L * 1024 * 1024
}
}

View File

@@ -0,0 +1,139 @@
package no.zyon.shade.mediademo
import android.Manifest
import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.provider.OpenableColumns
import android.view.ViewGroup.LayoutParams.MATCH_PARENT
import android.view.ViewGroup.LayoutParams.WRAP_CONTENT
import android.widget.Button
import android.widget.EditText
import android.widget.LinearLayout
import android.widget.TextView
import java.util.concurrent.Executors
/**
* «Share to Shade»: a video, photo, song or document shared from the gallery
* or a file manager is sealed on the phone and uploaded to your relay; the
* link to it comes back as a notification. The first time, enter the relay
* and add the owner id shown here to its owners
* (`shade media serve --owners <id>`).
*/
class ShareActivity : Activity() {
private val io = Executors.newSingleThreadExecutor()
private var album = "Shared"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val uris = UploadService.urisOf(intent)
val pad = (16 * resources.displayMetrics.density).toInt()
fun label(t: String, size: Float = 14f, color: Int = Color.LTGRAY) = TextView(this).apply {
text = t
textSize = size
setTextColor(color)
setPadding(0, pad / 2, 0, pad / 2)
}
val files = label(if (uris.isEmpty()) "Nothing to upload" else "${uris.size} file(s)", 16f, Color.WHITE)
val relay = EditText(this).apply {
hint = "http://192.168.1.10:3900"
setSingleLine()
setText(Uploads.relay(this@ShareActivity) ?: "")
setTextColor(Color.WHITE)
}
val albumTitle = EditText(this).apply {
hint = "Album title"
setSingleLine()
setText("Shared ${java.text.DateFormat.getDateInstance().format(java.util.Date())}")
setTextColor(Color.WHITE)
}
val ownerId = label("Owner key: …", 12f)
val copy = Button(this).apply { text = "Copy owner id"; isEnabled = false }
val upload = Button(this).apply { text = "Seal and upload"; isEnabled = uris.isNotEmpty() }
val note = label("Sealed on this phone: the relay stores only ciphertext, and the key travels in the link.", 12f)
setContentView(
LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
setBackgroundColor(Color.rgb(15, 17, 21))
setPadding(pad, pad, pad, pad)
addView(label("Share to Shade", 22f, Color.WHITE))
addView(files)
addView(label("Relay"))
addView(relay, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
if (uris.size > 1) {
addView(label("One link for all of them: an album"))
addView(albumTitle, LinearLayout.LayoutParams(MATCH_PARENT, WRAP_CONTENT))
}
addView(ownerId)
addView(copy)
addView(upload)
addView(note)
},
)
// Off the main thread: the Keystore may be a StrongBox chip, and names come from a provider.
io.execute {
val owner = runCatching { Uploads.owner(this) }
val names = uris.map { uri ->
runCatching {
contentResolver.query(uri, arrayOf(OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE), null, null, null)?.use { c ->
if (!c.moveToFirst()) null else "${c.getString(0)} · ${"%.1f".format(c.getLong(1) / 1048576.0)} MiB"
}
}.getOrNull() ?: uri.lastPathSegment ?: "file"
}
runOnUiThread {
if (names.isNotEmpty()) files.text = names.joinToString("\n")
owner.fold(
onSuccess = { o ->
ownerId.text = "Owner key (add to the relay's owners):\n${o.id}"
copy.isEnabled = true
copy.setOnClickListener {
getSystemService(ClipboardManager::class.java).setPrimaryClip(ClipData.newPlainText("Shade owner id", o.id))
}
},
onFailure = { ownerId.text = "No owner key: ${it.message}"; upload.isEnabled = false },
)
}
}
upload.setOnClickListener {
val url = relay.text.toString().trim()
if (!Regex("^https?://[^\\s/]+.*$").matches(url)) {
relay.error = "http(s)://host:port"
return@setOnClickListener
}
Uploads.setRelay(this, url)
album = albumTitle.text.toString().trim().ifEmpty { "Shared" }.take(512)
if (Build.VERSION.SDK_INT >= 33 && checkSelfPermission(Manifest.permission.POST_NOTIFICATIONS) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
requestPermissions(arrayOf(Manifest.permission.POST_NOTIFICATIONS), 1)
} else {
send(uris)
}
}
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
// Without notifications the upload still runs; only its progress and link are not shown.
send(UploadService.urisOf(intent))
}
private fun send(uris: List<android.net.Uri>) {
val clip = ClipData.newRawUri("shared", uris.first()).apply { uris.drop(1).forEach { addItem(ClipData.Item(it)) } }
val svc = Intent(this, UploadService::class.java).apply {
clipData = clip
addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
if (uris.size > 1) putExtra(UploadService.EXTRA_ALBUM, album)
}
startForegroundService(svc)
finish()
}
override fun onDestroy() {
io.shutdown()
super.onDestroy()
}
}

View File

@@ -0,0 +1,219 @@
package no.zyon.shade.mediademo
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.app.Service
import android.content.Intent
import android.content.pm.ServiceInfo
import android.net.Uri
import android.os.Build
import android.os.Handler
import android.os.IBinder
import android.os.Looper
import android.os.PowerManager
import no.zyon.shade.media.Album
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.UploadJobs
import no.zyon.shade.media.android.ShadeUpload
import java.util.concurrent.Executors
import java.util.concurrent.atomic.AtomicInteger
/**
* Seals and uploads shared files one after another, in the foreground (with
* a progress notification) so Android lets a film finish. A file that was
* sealed before the app was killed is resumed when the service starts again;
* one that was still being sealed is started over the next time it is shared.
* Several files shared at once become one album (one link for the photos of
* a trip). When a file is up, a notification opens it, or shares its link.
*/
class UploadService : Service() {
private val worker = Executors.newSingleThreadExecutor()
private val pending = AtomicInteger(0)
private val ids = AtomicInteger(100)
private val main = Handler(Looper.getMainLooper())
/** Jobs queued or running in this run, so a redelivered share is not done twice. Main thread only. */
private val queued = HashSet<String>()
private var lastStart = 0
private lateinit var nm: NotificationManager
override fun onBind(intent: Intent?): IBinder? = null
override fun onCreate() {
super.onCreate()
nm = getSystemService(NotificationManager::class.java)
nm.createNotificationChannel(NotificationChannel(PROGRESS, "Uploads", NotificationManager.IMPORTANCE_LOW))
nm.createNotificationChannel(NotificationChannel(DONE, "Uploaded", NotificationManager.IMPORTANCE_DEFAULT))
goForeground(progress("Shade", "Preparing…", 0, 0))
// What an earlier run sealed but did not get up.
val jobs = Uploads.jobs(this)
jobs.prune()
for ((key, job) in jobs.unfinished()) {
if (job.server.isEmpty()) continue
val name = job.meta.name ?: "file"
enqueue(key, name) { progress ->
Uploads.uploader(this, job.server).upload(jobs, key, job.source, job.meta, {
throw IllegalStateException("sealed copy missing")
}) { acked, total -> progress(name, acked, total) }
}
}
}
override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
lastStart = startId
val relay = Uploads.relay(this)
val uris = intent?.let(::urisOf).orEmpty()
if (relay != null && uris.isNotEmpty()) {
val uploader = Uploads.uploader(this, relay)
val jobs = Uploads.jobs(this)
// Described now, while the share's read permission still holds.
val items = uris.mapNotNull { uri ->
try {
ShadeUpload.describe(this, uri)
} catch (e: Exception) {
failed(uri.lastPathSegment ?: "file", e)
null
}
}
val album = intent?.getStringExtra(EXTRA_ALBUM)
if (album != null && items.size > 1) {
// One link for all of them: each file is its own job, then the album of their grants.
val keys = items.map { ShadeUpload.jobKey(jobs, uploader, it) }
enqueue(keys.joinToString(","), album) { progress ->
val grants = items.mapIndexed { i, item ->
val label = "${i + 1}/${items.size} · ${item.meta.name ?: "file"}"
ShadeUpload.upload(this, uploader, jobs, item) { acked, total -> progress(label, acked, total) }
}
uploader.uploadAlbum(Album(album, grants))
}
} else {
for (item in items) {
val name = item.meta.name ?: "file"
enqueue(ShadeUpload.jobKey(jobs, uploader, item), name) { progress ->
ShadeUpload.upload(this, uploader, jobs, item) { acked, total -> progress(name, acked, total) }
}
}
}
}
if (pending.get() == 0) stopSelf(startId)
return START_REDELIVER_INTENT
}
/** `run` reports progress as (what, acked, total). */
private fun enqueue(key: String, name: String, run: ((String, Long, Long) -> Unit) -> MediaGrant) {
if (!queued.add(key)) return
pending.incrementAndGet()
worker.execute {
val wake = getSystemService(PowerManager::class.java).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "shade:upload")
wake.acquire(6 * 3600_000L)
var shown = ""
try {
val grant = run { what, acked, total ->
val pct = if (total > 0) (acked * 100 / total).toInt() else 0
if ("$what $pct" != shown) {
shown = "$what $pct"
nm.notify(FOREGROUND_ID, progress(what, "${mib(acked)} of ${mib(total)} MiB", pct, 100))
}
}
uploaded(name, grant)
} catch (e: UploadJobs.BusyException) {
// Already on its way in this run.
} catch (e: Exception) {
failed(name, e)
} finally {
wake.release()
pending.decrementAndGet()
// On the main thread, after any share that came in meanwhile has queued its files.
main.post {
queued.remove(key)
if (pending.get() == 0) stopSelf(lastStart)
}
}
}
}
private fun uploaded(name: String, grant: MediaGrant) {
val link = grant.capabilityUrl(watchPage(grant))
val open = PendingIntent.getActivity(
this, ids.get(),
Intent(this, PlayerActivity::class.java).putExtra("link", link).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val share = PendingIntent.getActivity(
this, ids.get() + 1,
Intent.createChooser(Intent(Intent.ACTION_SEND).setType("text/plain").putExtra(Intent.EXTRA_TEXT, link), "Share $name"),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
)
val n = builder(DONE)
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setContentTitle(name)
.setContentText("Uploaded, end-to-end encrypted — tap to play")
.setContentIntent(open)
.setAutoCancel(true)
.addAction(Notification.Action.Builder(null, "Share link", share).build())
.build()
nm.notify(ids.getAndAdd(2), n)
}
private fun failed(name: String, e: Throwable) {
val n = builder(DONE)
.setSmallIcon(android.R.drawable.stat_notify_error)
.setContentTitle("$name was not uploaded")
.setContentText(e.message ?: e.javaClass.simpleName)
.setStyle(Notification.BigTextStyle().bigText(e.message ?: e.javaClass.simpleName))
.build()
nm.notify(ids.getAndAdd(2), n)
}
private fun progress(title: String, text: String, value: Int, max: Int): Notification =
builder(PROGRESS)
.setSmallIcon(android.R.drawable.stat_sys_upload)
.setContentTitle(title)
.setContentText(text)
.setOngoing(true)
.setProgress(max, value, max == 0)
.build()
private fun builder(channel: String): Notification.Builder = Notification.Builder(this, channel)
private fun goForeground(n: Notification) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
startForeground(FOREGROUND_ID, n, ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC)
} else {
startForeground(FOREGROUND_ID, n)
}
}
override fun onDestroy() {
worker.shutdownNow()
super.onDestroy()
}
companion object {
private const val PROGRESS = "uploads"
private const val DONE = "uploaded"
private const val FOREGROUND_ID = 1
/** A share of several files becomes one album with this title. */
const val EXTRA_ALBUM = "no.zyon.shade.mediademo.ALBUM"
private fun mib(b: Long) = "%.1f".format(b / 1048576.0)
/** The relay's own watch page opens the link in a browser too. */
fun watchPage(grant: MediaGrant): String = grant.url!!.substringBefore("/v1/media/") + "/watch/"
fun urisOf(intent: Intent): List<Uri> {
val out = LinkedHashSet<Uri>()
intent.data?.let(out::add)
intent.clipData?.let { c -> for (i in 0 until c.itemCount) c.getItemAt(i).uri?.let(out::add) }
// A share names its files in EXTRA_STREAM (Android usually mirrors them into the clip).
@Suppress("DEPRECATION")
when (intent.action) {
Intent.ACTION_SEND -> (intent.getParcelableExtra(Intent.EXTRA_STREAM) as? Uri)?.let(out::add)
Intent.ACTION_SEND_MULTIPLE -> intent.getParcelableArrayListExtra<Uri>(Intent.EXTRA_STREAM)?.let(out::addAll)
}
return out.toList()
}
}
}

View File

@@ -0,0 +1,49 @@
package no.zyon.shade.mediademo
import android.content.Context
import no.zyon.shade.keystore.KeystoreSecretFile
import no.zyon.shade.media.MediaOwner
import no.zyon.shade.media.MediaUploader
import no.zyon.shade.media.UploadJobs
import java.io.File
/**
* Where the demo uploads to and as whom. The relay URL is not a secret and
* lives in prefs; the owner seed signs every upload and lives in a
* Keystore-encrypted file. The relay must list [owner]'s id among its owners
* (`shade media serve --owners <id>`), which the share screen shows to copy.
*/
object Uploads {
private const val PREFS = "shade-media-demo"
private const val RELAY = "relay"
fun relay(context: Context): String? =
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).getString(RELAY, null)?.takeIf { it.isNotBlank() }
fun setRelay(context: Context, url: String) {
context.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit().putString(RELAY, url.trim().trimEnd('/')).apply()
}
private fun secret(context: Context) = KeystoreSecretFile(File(context.filesDir, "media-owner.sks"), "shade-media-owner")
/**
* The owner key, made on first use. If its Keystore key is gone (the app's
* data restored onto another phone), a new owner is made: the relay must
* then be told the new id — the old one cannot be recovered by design.
*/
@Synchronized
fun owner(context: Context): MediaOwner {
val s = secret(context)
val seed = try {
s.getOrCreate(32)
} catch (e: KeystoreSecretFile.SecretLostException) {
s.destroy()
s.getOrCreate(32)
}
return MediaOwner(seed).also { seed.fill(0) }
}
fun jobs(context: Context) = UploadJobs(File(context.filesDir, "media-uploads"))
fun uploader(context: Context, relay: String) = MediaUploader(relay, owner(context))
}

7
bench/media-relay.ts Normal file
View File

@@ -0,0 +1,7 @@
/** A live relay in its own process for bench/media.ts; prints its port. */
import { websocket } from 'hono/bun';
import { createLiveRelay, MemoryLivePinStore } from '../packages/shade-media/src/server.js';
const relay = createLiveRelay({ pins: new MemoryLivePinStore(), viewerHighWater: 32 * 1024 * 1024 });
const server = Bun.serve({ port: 0, fetch: (req, srv) => relay.app.fetch(req, { server: srv }), websocket, idleTimeout: 0 });
console.log(server.port);

67
bench/media-results.json Normal file
View File

@@ -0,0 +1,67 @@
{
"at": "2026-10-18T19:15:13.188Z",
"bun": "1.3.5",
"bigMiB": 1024,
"seal": {
"mibPerSec": 259.1,
"ms": 3951.4,
"overheadPct": 0.0046
},
"readDisk": {
"mibPerSec": 480.2,
"ms": 2132.4
},
"upload": {
"mibPerSec": 50.9
},
"readHttp": {
"mibPerSec": 209.5,
"ms": 4889
},
"open": {
"p50": 3.28,
"p95": 6.58
},
"seek": {
"p50": 3.98,
"p95": 8.21,
"max": 16.08
},
"live": [
{
"viewers": 1,
"delivered": 100,
"p50": 3,
"p95": 12,
"max": 14
},
{
"viewers": 10,
"delivered": 100,
"p50": 6,
"p95": 20,
"max": 49
},
{
"viewers": 50,
"delivered": 100,
"p50": 22,
"p95": 58,
"max": 213
},
{
"viewers": 100,
"delivered": 100,
"p50": 15,
"p95": 72,
"max": 255
},
{
"viewers": 200,
"delivered": 100,
"p50": 28,
"p95": 151,
"max": 443
}
]
}

View File

@@ -0,0 +1,26 @@
/**
* Media routes over one store, in their own process, for bench/media-store.ts
* (so the relay's memory is measured alone). Prints its port.
*
* bun bench/media-store-relay.ts file <dir>
* bun bench/media-store-relay.ts s3 <s3 url> [<postgres url>]
*/
import { createMediaRoutes, FileMediaStore, MemoryMediaIndex, ObjectMediaStore, S3Bucket, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
import type { MediaIndex, MediaStore } from '../packages/shade-media/src/server.js';
const [kind, where, pg] = process.argv.slice(2);
let store: MediaStore;
if (kind === 'file') {
store = new FileMediaStore(where!);
} else {
const { bucket, prefix } = S3Bucket.fromUrl(where!);
let index: MediaIndex = new MemoryMediaIndex();
if (pg !== undefined) {
const { PostgresMediaIndex } = await import('../packages/shade-storage-postgres/src/index.js');
index = await PostgresMediaIndex.create(pg);
}
store = new ObjectMediaStore(bucket, index, { prefix });
}
const app = createMediaRoutes(store);
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req), idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() });
console.log(server.port);

View File

@@ -0,0 +1,42 @@
{
"sizesMiB": [
512,
1536
],
"runs": 3,
"bun": "1.3.5",
"results": {
"512": {
"disk (FileMediaStore)": {
"uploadMiBs": 171,
"readMiBs": 239.5,
"seekP50": 3.78,
"seekP95": 7.03,
"peakRssMiB": 330
},
"S3 + Postgres (ObjectMediaStore)": {
"uploadMiBs": 179.9,
"readMiBs": 146.3,
"seekP50": 15.96,
"seekP95": 28.66,
"peakRssMiB": 360
}
},
"1536": {
"disk (FileMediaStore)": {
"uploadMiBs": 286.6,
"readMiBs": 199.6,
"seekP50": 9.05,
"seekP95": 19.37,
"peakRssMiB": 369
},
"S3 + Postgres (ObjectMediaStore)": {
"uploadMiBs": 79.3,
"readMiBs": 107.4,
"seekP50": 20.37,
"seekP95": 31.89,
"peakRssMiB": 358
}
}
}
}

View File

@@ -0,0 +1,125 @@
[
{
"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": "media-store-results.json"
},
"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
]
]
}
]
},
{
"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": "media-store-results.json"
},
"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
]
]
}
]
},
{
"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": "media-store-results.json"
},
"series": [
{
"name": "disk (FileMediaStore)",
"data": [
[
"p50",
9.05
],
[
"p95",
19.37
]
]
},
{
"name": "S3 + Postgres (ObjectMediaStore)",
"data": [
[
"p50",
20.37
],
[
"p95",
31.89
]
]
}
]
}
]

174
bench/media-store.ts Normal file
View File

@@ -0,0 +1,174 @@
/**
* Where sealed films live: the disk store against the S3 store
* (ObjectMediaStore), through the real media routes, each relay in its own
* process.
*
* Run: SHADE_BENCH_S3_URL=http://key:secret@127.0.0.1:58333/bench \
* [SHADE_BENCH_PG_URL=postgres://…] bun bench/media-store.ts [--mib 512,1536]
*
* Per store: upload (a sealed file in pieces, as `media put` sends it), full read + verify over
* Range, seek latency (64 KiB at random offsets, fresh reader each), and the
* relay's own peak memory during the upload (VmHWM − VmRSS before) — at
* each film size, to show it does not grow with the film.
* Writes bench/media-store-results.json and bench/media-store.chart.json.
*/
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { sealFile } from '../packages/shade-media/src/node.js';
import { MediaClient, openGrant } from '../packages/shade-media/src/client.js';
import { OwnerKey } from '../packages/shade-media/src/owner.js';
const args = process.argv.slice(2);
const SIZES = (args.includes('--mib') ? args[args.indexOf('--mib') + 1]! : '512,1536').split(',').map(Number);
if (SIZES.some((n) => !Number.isInteger(n) || n < 1)) throw new Error('--mib takes sizes in MiB, comma-separated');
// Disk and bucket speed swing with whatever else the machine does: median of several runs.
const RUNS = args.includes('--runs') ? Number(args[args.indexOf('--runs') + 1]) : 3;
const S3 = process.env.SHADE_BENCH_S3_URL;
const PG = process.env.SHADE_BENCH_PG_URL;
if (S3 === undefined) throw new Error('set SHADE_BENCH_S3_URL (a bucket that may be written to)');
const MiB = 1024 * 1024;
const pct = (xs: number[], p: number) => {
const s = [...xs].sort((a, b) => a - b);
return Math.round(s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]! * 100) / 100;
};
const kib = async (pid: number, field: 'VmRSS' | 'VmHWM') =>
Number(new RegExp(`${field}:\\s+(\\d+) kB`).exec(await readFile(`/proc/${pid}/status`, 'utf8'))![1]);
async function relay(argv: string[]) {
const proc = Bun.spawn(['bun', join(import.meta.dir, 'media-store-relay.ts'), ...argv], { stdout: 'pipe', stderr: 'inherit' });
const reader = proc.stdout.getReader();
const { value } = await reader.read();
const port = Number(new TextDecoder().decode(value).trim());
return { proc, base: `http://localhost:${port}` };
}
type Result = { uploadMiBs: number; readMiBs: number; seekP50: number; seekP95: number; peakRssMiB: number };
const S3_NAME = PG !== undefined ? 'S3 + Postgres (ObjectMediaStore)' : 'S3 (ObjectMediaStore)';
const DISK_NAME = 'disk (FileMediaStore)';
/** One film of `mib` MiB through each store. */
async function run(mib: number, work: string): Promise<Record<string, Result>> {
const plain = join(work, 'film.bin');
const sealed = join(work, 'film.smf');
{
const f = Bun.file(plain).writer();
const chunk = new Uint8Array(MiB);
for (let i = 0; i < mib; i++) {
crypto.getRandomValues(chunk.subarray(0, 65536));
for (let o = 65536; o < MiB; o += 65536) chunk.copyWithin(o, 0, 65536);
chunk[0] = i & 0xff;
f.write(chunk);
}
await f.end();
}
const sealResult = await sealFile(plain, sealed, { meta: { name: 'bench.bin' } });
await rm(plain);
const sealedSize = Bun.file(sealed).size;
const stores: [string, string[]][] = [
[DISK_NAME, ['file', join(work, `store-${mib}`)]],
[S3_NAME, ['s3', `${S3!.replace(/\/$/, '')}/bench-${Date.now().toString(36)}`, ...(PG !== undefined ? [PG] : [])]],
];
const results: Record<string, Result> = {};
for (const [name, argv] of stores) {
const runs: Result[] = [];
for (let i = 0; i < RUNS; i++) {
// A fresh relay per run: its high-water mark is this upload's alone.
const { proc, base } = await relay(argv);
try {
const client = new MediaClient(base, OwnerKey.generate());
await Bun.sleep(300);
const rssBefore = await kib(proc.pid, 'VmRSS');
let t = performance.now();
const grant = await client.putSealed(sealResult, Bun.file(sealed));
const upSec = (performance.now() - t) / 1000;
const peak = (await kib(proc.pid, 'VmHWM')) - rssBefore;
const reader = await openGrant(grant);
t = performance.now();
for (let off = 0; off < reader.size; off += 8 * MiB) await reader.read(off, Math.min(8 * MiB, reader.size - off));
const readSec = (performance.now() - t) / 1000;
const seeks: number[] = [];
for (let j = 0; j < 50; j++) {
const r = await openGrant(grant);
const at = Math.floor(Math.random() * (r.size - 65536));
const s = performance.now();
await r.read(at, 65536);
seeks.push(performance.now() - s);
}
runs.push({
uploadMiBs: sealedSize / MiB / upSec,
readMiBs: mib / readSec,
seekP50: pct(seeks, 50),
seekP95: pct(seeks, 95),
peakRssMiB: peak / 1024,
});
await client.delete(grant.mediaId);
} finally {
proc.kill();
await proc.exited;
}
}
const median = (k: keyof Result) => pct(runs.map((r) => r[k]), 50);
results[name] = {
uploadMiBs: Math.round(median('uploadMiBs') * 10) / 10,
readMiBs: Math.round(median('readMiBs') * 10) / 10,
seekP50: median('seekP50'),
seekP95: median('seekP95'),
// Memory is a bound, not a typical value: the worst run.
peakRssMiB: Math.round(Math.max(...runs.map((r) => r.peakRssMiB))),
};
console.log(`${mib} MiB`, name, results[name], `(${RUNS} runs; upload ${runs.map((r) => r.uploadMiBs.toFixed(0)).join('/')} MiB/s)`);
}
await rm(sealed);
await rm(join(work, `store-${mib}`), { recursive: true, force: true });
return results;
}
const work = await mkdtemp(join(tmpdir(), 'shade-bench-store-'));
try {
const bySize: Record<string, Record<string, Result>> = {};
for (const mib of SIZES) bySize[mib] = await run(mib, work);
await writeFile(
join(import.meta.dir, 'media-store-results.json'),
`${JSON.stringify({ sizesMiB: SIZES, runs: RUNS, bun: Bun.version, results: bySize }, null, 2)}\n`,
);
const largest = Math.max(...SIZES);
const results = bySize[largest]!;
const names = [DISK_NAME, S3_NAME];
const charts = [
{
type: 'bar',
title: 'Sealed film store: disk vs S3 (MiB/s)',
subtitle: `${largest} MiB film through the real media routes, median of ${RUNS} runs; relay in its own process; S3 = local SeaweedFS`,
y: { label: 'MiB/s', min: 0 },
note: `Bun ${Bun.version}. 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: 'media-store-results.json' },
series: names.map((n) => ({ name: n, data: [['upload (pieces)', results[n]!.uploadMiBs], ['read + verify (Range)', results[n]!.readMiBs]] })),
},
{
type: 'bar',
title: 'Relay memory does not grow with the film',
subtitle: `Peak relay RSS growth during one upload (VmHWM − RSS before), worst of ${RUNS} 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: 'media-store-results.json' },
series: names.map((n) => ({ name: n, data: SIZES.map((mib) => [`${mib} MiB film`, bySize[mib]![n]!.peakRssMiB]) })),
},
{
type: 'bar',
title: 'Seek latency, disk vs S3 (ms)',
subtitle: `64 KiB at a random offset of the ${largest} MiB film, fresh reader each (n = 50 per run, median of ${RUNS} runs)`,
y: { label: 'ms', min: 0 },
note: 'Includes opening: footer + trailer + root check, then the range.',
source: { path: 'media-store-results.json' },
series: names.map((n) => ({ name: n, data: [['p50', results[n]!.seekP50], ['p95', results[n]!.seekP95]] })),
},
];
await writeFile(join(import.meta.dir, 'media-store.chart.json'), `${JSON.stringify(charts, null, 2)}\n`);
console.log('wrote bench/media-store-results.json and bench/media-store.chart.json');
} finally {
await rm(work, { recursive: true, force: true });
}

147
bench/media.chart.json Normal file
View File

@@ -0,0 +1,147 @@
[
{
"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": "media-results.json"
},
"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
]
]
}
]
},
{
"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": "media-results.json"
},
"series": [
{
"name": "p50",
"data": [
[
"open",
3.28
],
[
"seek",
3.98
]
]
},
{
"name": "p95",
"data": [
[
"open",
6.58
],
[
"seek",
8.21
]
]
}
]
},
{
"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": "media-results.json"
},
"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
]
]
}
]
}
]

236
bench/media.ts Normal file
View File

@@ -0,0 +1,236 @@
/**
* @shade/media benchmarks — what streaming under Shade costs.
*
* Run: bun bench/media.ts [--big-mib 1024] [--viewers 1,10,50,200]
*
* 1. Seal and read throughput, sealed file on disk (1 MiB segments).
* 2. The same read over HTTP Range from the real media routes.
* 3. Seek: time to the first decrypted byte at a random offset over HTTP.
* 4. Live fan-out: one publisher, N viewers, relay in its own process —
* delivered fraction and end-to-end latency (publish → decrypted).
*
* Writes bench/media-results.json (raw numbers) and bench/media.chart.json
* (charts for the log post, `scaffold-agent chart block`).
*/
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { createWriteStream } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { Hono } from 'hono';
import { websocket } from 'hono/bun';
import { sealFile, FileSource } from '../packages/shade-media/src/node.js';
import { MediaReader } from '../packages/shade-media/src/sealed.js';
import { createMediaRoutes, FileMediaStore, mediaMaxRequestBody } from '../packages/shade-media/src/server.js';
import { MediaClient, openGrant } from '../packages/shade-media/src/client.js';
import { OwnerKey } from '../packages/shade-media/src/owner.js';
import { LivePublisher } from '../packages/shade-media/src/live/channel.js';
import { LivePublishClient, LiveWatchClient } from '../packages/shade-media/src/live/client.js';
const args = process.argv.slice(2);
const flag = (k: string, d: string) => {
const i = args.indexOf(`--${k}`);
return i >= 0 ? args[i + 1]! : d;
};
const BIG_MIB = Number(flag('big-mib', '1024'));
const VIEWERS = flag('viewers', '1,10,50,200').split(',').map(Number);
const MiB = 1024 * 1024;
const now = () => performance.now();
const pct = (xs: number[], p: number) => {
const s = [...xs].sort((a, b) => a - b);
return s[Math.min(s.length - 1, Math.floor((p / 100) * s.length))]!;
};
const round = (x: number, d = 1) => Math.round(x * 10 ** d) / 10 ** d;
async function writeRandomFile(path: string, mib: number): Promise<void> {
// Random bytes (incompressible, like video). One 1 MiB block reused with a
// counter stamped in, so generation is not the thing being measured.
const block = new Uint8Array(MiB);
globalThis.crypto.getRandomValues(block.subarray(0, 65536));
for (let i = 65536; i < MiB; i += 65536) block.copyWithin(i, 0, 65536);
const ws = createWriteStream(path);
for (let i = 0; i < mib; i++) {
new DataView(block.buffer).setUint32(0, i);
if (!ws.write(Buffer.from(block))) await new Promise<void>((r) => ws.once('drain', () => r()));
}
await new Promise<void>((r) => ws.end(() => r()));
}
async function main() {
const dir = await mkdtemp(join(tmpdir(), 'shade-media-bench-'));
const results: Record<string, unknown> = { at: new Date().toISOString(), bun: Bun.version, bigMiB: BIG_MIB };
try {
// ─── 1. Seal + local read ──────────────────────────────────
const plain = join(dir, 'film.bin');
const sealedPath = join(dir, 'film.smf');
await writeRandomFile(plain, BIG_MIB);
let t = now();
const res = await sealFile(plain, sealedPath, { meta: { mime: 'video/mp4', name: 'film.bin' } });
const sealMs = now() - t;
const keys = { mediaId: res.mediaId, mediaKey: res.mediaKey, rootDigest: res.rootDigest };
t = now();
const reader = await MediaReader.open(new FileSource(sealedPath), keys, { cacheSegments: 0, maxSegmentsPerFetch: 8 });
let n = 0;
for await (const c of reader.stream()) n += c.length;
const readMs = now() - t;
if (n !== BIG_MIB * MiB) throw new Error(`read ${n} bytes`);
const overhead = (res.sealedSize - res.plaintextSize) / res.plaintextSize;
results.seal = { mibPerSec: round((BIG_MIB / sealMs) * 1000), ms: round(sealMs), overheadPct: round(overhead * 100, 4) };
results.readDisk = { mibPerSec: round((BIG_MIB / readMs) * 1000), ms: round(readMs) };
console.log(`seal ${BIG_MIB} MiB: ${round((BIG_MIB / sealMs) * 1000)} MiB/s size overhead ${round(overhead * 100, 4)} %`);
console.log(`read ${BIG_MIB} MiB (disk): ${round((BIG_MIB / readMs) * 1000)} MiB/s`);
// ─── 2 + 3. Over HTTP ──────────────────────────────────────
const app = new Hono();
app.route('/', createMediaRoutes(new FileMediaStore(join(dir, 'store'))));
const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket, idleTimeout: 0, maxRequestBodySize: mediaMaxRequestBody() });
const base = `http://localhost:${server.port}`;
try {
const client = new MediaClient(base, OwnerKey.generate());
t = now();
const grant = await client.putSealed(res, Bun.file(sealedPath));
const uploadMs = now() - t;
t = now();
const hr = await openGrant(grant, { cacheSegments: 0, maxSegmentsPerFetch: 8 });
n = 0;
for await (const c of hr.stream()) n += c.length;
const httpMs = now() - t;
results.upload = { mibPerSec: round((BIG_MIB / uploadMs) * 1000) };
results.readHttp = { mibPerSec: round((BIG_MIB / httpMs) * 1000), ms: round(httpMs) };
console.log(`upload (localhost): ${round((BIG_MIB / uploadMs) * 1000)} MiB/s read over HTTP Range: ${round((BIG_MIB / httpMs) * 1000)} MiB/s`);
// Seek: a fresh reader per probe would measure open(); one reader with
// no cache measures what a seek in a playing film costs.
const opened: number[] = [];
for (let i = 0; i < 10; i++) {
t = now();
await openGrant(grant);
opened.push(now() - t);
}
const seeks: number[] = [];
const sr = await openGrant(grant, { cacheSegments: 0 });
for (let i = 0; i < 100; i++) {
const off = Math.floor(Math.random() * (BIG_MIB * MiB - 65536));
t = now();
await sr.read(off, 65536);
seeks.push(now() - t);
}
results.open = { p50: round(pct(opened, 50), 2), p95: round(pct(opened, 95), 2) };
results.seek = { p50: round(pct(seeks, 50), 2), p95: round(pct(seeks, 95), 2), max: round(Math.max(...seeks), 2) };
console.log(`open (footer+trailer): p50 ${round(pct(opened, 50), 2)} ms seek→first byte: p50 ${round(pct(seeks, 50), 2)} ms, p95 ${round(pct(seeks, 95), 2)} ms`);
} finally {
server.stop(true);
}
// ─── 4. Live fan-out ───────────────────────────────────────
const relayProc = Bun.spawn(['bun', join(import.meta.dir, 'media-relay.ts')], { stdout: 'pipe', stderr: 'inherit' });
const portLine = await new Response(relayProc.stdout).body!.getReader().read();
const relayBase = `http://localhost:${new TextDecoder().decode(portLine.value).trim()}`;
const live: Array<{ viewers: number; delivered: number; p50: number; p95: number; max: number }> = [];
try {
for (const v of VIEWERS) {
const fps = 10;
const frameBytes = 32 * 1024; // ≈ 2.6 Mbit/s, a 720p stream
const seconds = 6;
const pub = new LivePublisher();
const pc = new LivePublishClient({ relay: relayBase, publisher: pub, readToken: new Uint8Array(32).fill(1) });
await pc.whenReady();
const grant = pc.grant('now');
const lat: number[] = [];
let got = 0;
const viewers: LiveWatchClient[] = [];
let ready = 0;
for (let i = 0; i < v; i++) {
viewers.push(
new LiveWatchClient(grant, {
onState: (s) => {
if (s === 'live') ready++;
},
onFrame: (f) => {
got++;
lat.push(Date.now() - f.timestamp);
},
}),
);
}
while (ready < v) await Bun.sleep(20);
const payload = new Uint8Array(frameBytes);
globalThis.crypto.getRandomValues(payload.subarray(0, 65536 > frameBytes ? frameBytes : 65536));
const total = fps * seconds;
const start = Date.now();
for (let i = 0; i < total; i++) {
await pc.send({ type: 'chunk', bytes: payload }, { keyframe: i % fps === 0 });
const due = start + ((i + 1) * 1000) / fps;
const wait = due - Date.now();
if (wait > 0) await Bun.sleep(wait);
}
await Bun.sleep(1500);
const delivered = got / (total * v);
const row = { viewers: v, delivered: round(delivered * 100, 2), p50: pct(lat, 50), p95: pct(lat, 95), max: Math.max(...lat) };
live.push(row);
console.log(`live ${v} viewer(s): delivered ${row.delivered} %, latency p50 ${row.p50} ms, p95 ${row.p95} ms, max ${row.max} ms`);
for (const w of viewers) w.close();
pc.close();
await Bun.sleep(300);
}
} finally {
relayProc.kill();
}
results.live = live;
await writeFile(join(import.meta.dir, 'media-results.json'), `${JSON.stringify(results, null, 2)}\n`);
const r = results as any;
const charts = [
{
type: 'bar',
title: 'Sealed media throughput (MiB/s)',
subtitle: `${BIG_MIB} MiB of incompressible data, 1 MiB segments, one core`,
y: { label: 'MiB/s', min: 0 },
note: `Bun ${Bun.version}; HTTP is localhost through the real media routes; size overhead ${r.seal.overheadPct} %`,
source: { path: 'media-results.json' },
series: [
{
name: 'MiB/s',
data: [
['seal (disk → disk)', r.seal.mibPerSec],
['read + verify (disk)', r.readDisk.mibPerSec],
['upload (HTTP PUT)', r.upload.mibPerSec],
['read + verify (HTTP Range)', r.readHttp.mibPerSec],
],
},
],
},
{
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: 'media-results.json' },
series: [
{ name: 'p50', data: [['open', r.open.p50], ['seek', r.seek.p50]] },
{ name: 'p95', data: [['open', r.open.p95], ['seek', r.seek.p95]] },
],
},
{
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: ${live.map((l) => `${l.viewers} → ${l.delivered} %`).join(', ')}. 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: 'media-results.json' },
series: [
{ name: 'p50', data: live.map((l) => [l.viewers, l.p50]) },
{ name: 'p95', data: live.map((l) => [l.viewers, l.p95]) },
],
},
];
await writeFile(join(import.meta.dir, 'media.chart.json'), `${JSON.stringify(charts, null, 2)}\n`);
console.log('wrote bench/media-results.json and bench/media.chart.json');
} finally {
await rm(dir, { recursive: true, force: true });
}
}
await main();
process.exit(0);

144
bun.lock
View File

@@ -13,11 +13,12 @@
"devDependencies": {
"bun-types": "^1.3.11",
"fast-check": "^3.22.0",
"typescript": "7.0.2",
},
},
"packages/shade-cli": {
"name": "@shade/cli",
"version": "4.8.5",
"version": "4.15.0",
"bin": {
"shade": "src/cli.ts",
},
@@ -25,8 +26,10 @@
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
"@shade/keychain": "workspace:*",
"@shade/media": "workspace:*",
"@shade/sdk": "workspace:*",
"@shade/storage-encrypted": "workspace:*",
"@shade/storage-postgres": "workspace:*",
"@shade/storage-sqlite": "workspace:*",
"@shade/transport": "workspace:*",
},
@@ -36,7 +39,7 @@
},
"packages/shade-core": {
"name": "@shade/core",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/observability": "workspace:*",
},
@@ -49,7 +52,7 @@
},
"packages/shade-crypto-web": {
"name": "@shade/crypto-web",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@noble/curves": "^2.0.1",
"@noble/hashes": "^2.0.1",
@@ -59,7 +62,7 @@
},
"packages/shade-dashboard": {
"name": "@shade/dashboard",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/widgets": "workspace:*",
"react": "^19.0.0",
@@ -74,7 +77,7 @@
},
"packages/shade-files": {
"name": "@shade/files",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
@@ -101,7 +104,7 @@
},
"packages/shade-inbox": {
"name": "@shade/inbox",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/proto": "workspace:*",
@@ -114,7 +117,7 @@
},
"packages/shade-inbox-server": {
"name": "@shade/inbox-server",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/observability": "workspace:*",
@@ -132,7 +135,7 @@
},
"packages/shade-key-transparency": {
"name": "@shade/key-transparency",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@noble/hashes": "^2.0.1",
"@shade/core": "workspace:*",
@@ -144,11 +147,20 @@
},
"packages/shade-keychain": {
"name": "@shade/keychain",
"version": "4.8.5",
"version": "4.15.0",
},
"packages/shade-media": {
"name": "@shade/media",
"version": "4.15.0",
"dependencies": {
"@noble/curves": "^2.0.1",
"@noble/hashes": "^2.0.1",
"hono": "^4.12.18",
},
},
"packages/shade-observability": {
"name": "@shade/observability",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@noble/hashes": "^2.0.1",
},
@@ -166,7 +178,7 @@
},
"packages/shade-observer": {
"name": "@shade/observer",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/server": "workspace:*",
@@ -178,14 +190,14 @@
},
"packages/shade-proto": {
"name": "@shade/proto",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
},
},
"packages/shade-recovery": {
"name": "@shade/recovery",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
@@ -198,13 +210,14 @@
},
"packages/shade-sdk": {
"name": "@shade/sdk",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
"@shade/files": "workspace:*",
"@shade/inbox": "workspace:*",
"@shade/key-transparency": "workspace:*",
"@shade/media": "workspace:*",
"@shade/observability": "workspace:*",
"@shade/observer": "workspace:*",
"@shade/proto": "workspace:*",
@@ -228,12 +241,15 @@
},
"packages/shade-server": {
"name": "@shade/server",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/inbox-server": "workspace:*",
"@shade/key-transparency": "workspace:*",
"@shade/media": "workspace:*",
"@shade/observability": "workspace:*",
"@shade/storage-sqlite": "workspace:*",
"@shade/vault": "workspace:*",
"hono": "^4.12.12",
},
"devDependencies": {
@@ -248,7 +264,7 @@
},
"packages/shade-storage-encrypted": {
"name": "@shade/storage-encrypted",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@noble/hashes": "^2.0.1",
"@shade/core": "workspace:*",
@@ -270,7 +286,7 @@
},
"packages/shade-storage-indexeddb": {
"name": "@shade/storage-indexeddb",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"idb": "^8.0.3",
@@ -282,32 +298,37 @@
},
"packages/shade-storage-postgres": {
"name": "@shade/storage-postgres",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/inbox-server": "workspace:*",
"@shade/key-transparency": "workspace:*",
"@shade/media": "workspace:*",
"@shade/server": "workspace:*",
"drizzle-orm": "^0.45.2",
"postgres": "^3.4.9",
},
"devDependencies": {
"@shade/crypto-web": "workspace:*",
"hono": "^4.12.18",
},
},
"packages/shade-storage-sqlite": {
"name": "@shade/storage-sqlite",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
"@shade/inbox-server": "workspace:*",
"@shade/server": "workspace:*",
},
"devDependencies": {
"@shade/vault": "workspace:*",
},
},
"packages/shade-streams": {
"name": "@shade/streams",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@noble/hashes": "^2.0.1",
"@shade/core": "workspace:*",
@@ -319,7 +340,7 @@
},
"packages/shade-transfer": {
"name": "@shade/transfer",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
@@ -336,7 +357,7 @@
},
"packages/shade-transport": {
"name": "@shade/transport",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
@@ -347,7 +368,7 @@
},
"packages/shade-transport-bridge": {
"name": "@shade/transport-bridge",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/server": "workspace:*",
@@ -369,16 +390,29 @@
},
"packages/shade-transport-webrtc": {
"name": "@shade/transport-webrtc",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/core": "workspace:*",
"@shade/streams": "workspace:*",
"@shade/transfer": "workspace:*",
},
},
"packages/shade-vault": {
"name": "@shade/vault",
"version": "4.15.0",
"dependencies": {
"@noble/hashes": "^2.0.1",
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
"@shade/observability": "workspace:*",
"@shade/server": "workspace:*",
"@shade/storage-encrypted": "workspace:*",
"hono": "^4.12.18",
},
},
"packages/shade-widgets": {
"name": "@shade/widgets",
"version": "4.8.5",
"version": "4.15.0",
"dependencies": {
"@shade/recovery": "workspace:*",
"@shade/sdk": "workspace:*",
@@ -573,6 +607,8 @@
"@shade/keychain": ["@shade/keychain@workspace:packages/shade-keychain"],
"@shade/media": ["@shade/media@workspace:packages/shade-media"],
"@shade/observability": ["@shade/observability@workspace:packages/shade-observability"],
"@shade/observer": ["@shade/observer@workspace:packages/shade-observer"],
@@ -603,6 +639,8 @@
"@shade/transport-webrtc": ["@shade/transport-webrtc@workspace:packages/shade-transport-webrtc"],
"@shade/vault": ["@shade/vault@workspace:packages/shade-vault"],
"@shade/widgets": ["@shade/widgets@workspace:packages/shade-widgets"],
"@types/babel__core": ["@types/babel__core@7.20.5", "", { "dependencies": { "@babel/parser": "^7.20.7", "@babel/types": "^7.20.7", "@types/babel__generator": "*", "@types/babel__template": "*", "@types/babel__traverse": "*" } }, "sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA=="],
@@ -621,6 +659,46 @@
"@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
"@typescript/typescript-aix-ppc64": ["@typescript/typescript-aix-ppc64@7.0.2", "", { "os": "aix", "cpu": "ppc64" }, "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ=="],
"@typescript/typescript-darwin-arm64": ["@typescript/typescript-darwin-arm64@7.0.2", "", { "os": "darwin", "cpu": "arm64" }, "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA=="],
"@typescript/typescript-darwin-x64": ["@typescript/typescript-darwin-x64@7.0.2", "", { "os": "darwin", "cpu": "x64" }, "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA=="],
"@typescript/typescript-freebsd-arm64": ["@typescript/typescript-freebsd-arm64@7.0.2", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ=="],
"@typescript/typescript-freebsd-x64": ["@typescript/typescript-freebsd-x64@7.0.2", "", { "os": "freebsd", "cpu": "x64" }, "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw=="],
"@typescript/typescript-linux-arm": ["@typescript/typescript-linux-arm@7.0.2", "", { "os": "linux", "cpu": "arm" }, "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ=="],
"@typescript/typescript-linux-arm64": ["@typescript/typescript-linux-arm64@7.0.2", "", { "os": "linux", "cpu": "arm64" }, "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ=="],
"@typescript/typescript-linux-loong64": ["@typescript/typescript-linux-loong64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ=="],
"@typescript/typescript-linux-mips64el": ["@typescript/typescript-linux-mips64el@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA=="],
"@typescript/typescript-linux-ppc64": ["@typescript/typescript-linux-ppc64@7.0.2", "", { "os": "linux", "cpu": "ppc64" }, "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA=="],
"@typescript/typescript-linux-riscv64": ["@typescript/typescript-linux-riscv64@7.0.2", "", { "os": "linux", "cpu": "none" }, "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ=="],
"@typescript/typescript-linux-s390x": ["@typescript/typescript-linux-s390x@7.0.2", "", { "os": "linux", "cpu": "s390x" }, "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw=="],
"@typescript/typescript-linux-x64": ["@typescript/typescript-linux-x64@7.0.2", "", { "os": "linux", "cpu": "x64" }, "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A=="],
"@typescript/typescript-netbsd-arm64": ["@typescript/typescript-netbsd-arm64@7.0.2", "", { "os": "none", "cpu": "arm64" }, "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA=="],
"@typescript/typescript-netbsd-x64": ["@typescript/typescript-netbsd-x64@7.0.2", "", { "os": "none", "cpu": "x64" }, "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA=="],
"@typescript/typescript-openbsd-arm64": ["@typescript/typescript-openbsd-arm64@7.0.2", "", { "os": "openbsd", "cpu": "arm64" }, "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ=="],
"@typescript/typescript-openbsd-x64": ["@typescript/typescript-openbsd-x64@7.0.2", "", { "os": "openbsd", "cpu": "x64" }, "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg=="],
"@typescript/typescript-sunos-x64": ["@typescript/typescript-sunos-x64@7.0.2", "", { "os": "sunos", "cpu": "x64" }, "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g=="],
"@typescript/typescript-win32-arm64": ["@typescript/typescript-win32-arm64@7.0.2", "", { "os": "win32", "cpu": "arm64" }, "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ=="],
"@typescript/typescript-win32-x64": ["@typescript/typescript-win32-x64@7.0.2", "", { "os": "win32", "cpu": "x64" }, "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g=="],
"@vitejs/plugin-react": ["@vitejs/plugin-react@4.7.0", "", { "dependencies": { "@babel/core": "^7.28.0", "@babel/plugin-transform-react-jsx-self": "^7.27.1", "@babel/plugin-transform-react-jsx-source": "^7.27.1", "@rolldown/pluginutils": "1.0.0-beta.27", "@types/babel__core": "^7.20.5", "react-refresh": "^0.17.0" }, "peerDependencies": { "vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0" } }, "sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA=="],
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.17", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-HdrkN8eVG2CXxeifv/VdJ4A4RSra1DTW8dc/hdxzhGHN8QePs6gKaWM9pHPcpCoxYZJuOZ8drHmbdpLHjCYjLA=="],
@@ -703,6 +781,8 @@
"tinyglobby": ["tinyglobby@0.2.16", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
"typescript": ["typescript@7.0.2", "", { "optionalDependencies": { "@typescript/typescript-aix-ppc64": "7.0.2", "@typescript/typescript-darwin-arm64": "7.0.2", "@typescript/typescript-darwin-x64": "7.0.2", "@typescript/typescript-freebsd-arm64": "7.0.2", "@typescript/typescript-freebsd-x64": "7.0.2", "@typescript/typescript-linux-arm": "7.0.2", "@typescript/typescript-linux-arm64": "7.0.2", "@typescript/typescript-linux-loong64": "7.0.2", "@typescript/typescript-linux-mips64el": "7.0.2", "@typescript/typescript-linux-ppc64": "7.0.2", "@typescript/typescript-linux-riscv64": "7.0.2", "@typescript/typescript-linux-s390x": "7.0.2", "@typescript/typescript-linux-x64": "7.0.2", "@typescript/typescript-netbsd-arm64": "7.0.2", "@typescript/typescript-netbsd-x64": "7.0.2", "@typescript/typescript-openbsd-arm64": "7.0.2", "@typescript/typescript-openbsd-x64": "7.0.2", "@typescript/typescript-sunos-x64": "7.0.2", "@typescript/typescript-win32-arm64": "7.0.2", "@typescript/typescript-win32-x64": "7.0.2" }, "bin": { "tsc": "bin/tsc" } }, "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA=="],
"undici-types": ["undici-types@7.18.2", "", {}, "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w=="],
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
@@ -716,5 +796,19 @@
"yallist": ["yallist@3.1.1", "", {}, "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g=="],
"zod": ["zod@3.25.76", "", {}, "sha512-gzUt/qt81nXsFGKIFcC3YnfEAx5NkunCfnDlvuBSSFS02bcXu4Lmea0AFIUwbLWxWPx3d9p8S5QoaujKcNQxcQ=="],
"@shade/inbox-server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
"@shade/media/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
"@shade/observer/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
"@shade/server/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
"@shade/storage-postgres/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
"@shade/transport-bridge/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
"@shade/vault/hono": ["hono@4.13.2", "", {}, "sha512-JydRilDRkYBQMt9qR9U92mXxmbGqsqSn/IKOrh4e7/gEbn+0zSr8igTu0obwJoNGN4sez28DIql7FBHWydoJpA=="],
}
}

608
docs/media.md Normal file
View File

@@ -0,0 +1,608 @@
# `@shade/media` — streaming under Shade
V4.15. Films, videos, songs, images, and live streams of logs, text, video and
audio, all end-to-end encrypted. Whoever stores or relays the bytes cannot read
them, and whoever holds a key cannot forge them for anyone else.
There are two shapes, because "a film" and "a log" are different problems:
| | Sealed media (SMF1) | Live channel (SLF1) |
|---|---|---|
| What | a file that exists in full: film, episode, photo, song, document | a stream that is still being made: `tail -f`, a camera, a broadcast |
| Read how | random access over HTTP Range, so you can seek | in order over a WebSocket, joining late from a backlog |
| Stored where | any dumb store: the relay, nginx, S3, a USB disk | the relay holds minutes of ciphertext for late joiners, then lets it go |
| Keys | one random key per file | Sender Keys: a hash chain per epoch, every frame signed |
| Plays in | `<video>`/`<audio>`/`<img>` through a Service Worker; ExoPlayer via `MediaReader.inputStream` | `<video>` through Media Source Extensions; a log view; the terminal |
Both hand their keys to a viewer as a **grant**: a small JSON message sent over an
existing Shade session (Double Ratchet, so it is authenticated and forward-secret),
or carried in the `#shade=` fragment of a link for a device with no session.
## Quick start
```bash
# A relay: sealed store + live relay + the /watch page, on one port.
shade media serve --port 3910 --dir /srv/shade-media
# A film. Seals in one streaming pass, uploads, prints a watch link.
shade media put Film.mkv --server https://relay.example
# → https://relay.example/watch/#shade=eyJraW5kIjoic2hhZGUubWVkaWEtZ3JhbnQ…
# Back on disk, decrypted and verified.
shade media get '<link>' -o Film.mkv
# A season, a photo album: every file, plus one link that opens them all.
shade media put "Sesong 1/" --server https://relay.example
shade media get '<album link>' -o "Sesong 1" # the whole directory back
# Live logs.
tail -f /var/log/app.log | shade live text --server https://relay.example --name "api logs" --channel ~/.config/shade/api-logs.json
shade live watch '<link>' # in a terminal — or open the link in a browser
# Live video (and audio) from anything ffmpeg can read: WebM (VP8/VP9/AV1 + Opus) …
ffmpeg -re -i camera.mp4 -c:v libvpx -deadline realtime -g 30 -c:a libopus \
-f webm -live 1 -cluster_time_limit 1000 - \
| shade live video --server https://relay.example --name "Kamera 1"
# … or fragmented MP4 (H.264/HEVC/AV1 + AAC/Opus), what cameras, OBS and Safari speak.
ffmpeg -re -i camera.mp4 -c:v libx264 -tune zerolatency -g 30 -c:a aac \
-f mp4 -movflags frag_keyframe+empty_moov+default_base_moof -frag_duration 250000 - \
| shade live video --server https://relay.example --name "Kamera 1"
# Or let shade run ffmpeg: a film, a webcam, an IP camera. H.264/AAC is copied,
# anything else encoded (H.264 with a keyframe every 2 s, AAC); a file plays at its own pace.
shade live video --input rtsp://camera.local/stream1 --server https://relay.example --name "Inngang"
shade live video --input Film.mkv --server https://relay.example --name "Filmkveld"
# Live radio: the same, with sound only — the page and the app give it an audio player.
ffmpeg -re -i radio.mp3 -c:a libopus -f webm -live 1 -cluster_time_limit 1000 - \
| shade live video --server https://relay.example --name "Radio"
# Live pictures: a webcam at one picture a second …
ffmpeg -f v4l2 -i /dev/video0 -r 1 -c:v mjpeg -f image2pipe - \
| shade live images --server https://relay.example --name "Hytta"
# … a slideshow, or every new picture that lands in a folder.
shade live images Ferie/ --every 5 --server https://relay.example
shade live images --watch ~/Pictures/Screenshots --server https://relay.example
# Record a channel until it ends, and keep it as a sealed film with its own link.
shade live record '<link>' -o Kveldssending --put --server https://relay.example
```
`shade live video` recognises the container from the first bytes (`--format webm|fmp4`
pins it). A fragment is a starting point for late joiners when the first sample of its
video track is a sync sample, so fragments shorter than a GOP keep latency down without
breaking late joining.
`shade live images` splits a piped stream into whole JPEG/PNG pictures by walking
their markers and chunks (a JPEG's EXIF thumbnail is a whole JPEG and does not end the
picture). Each picture is a keyframe, so a late viewer opens on the latest. A watched
folder sends a file once its size has held still, because cameras write in pieces.
`shade live record` writes what the channel carries: text to `base.txt`, video or
sound to `base.webm`/`base.mp4` (the init segment, then every chunk, in the order they
were sent; a chunk that arrives after newer ones is left out and counted), pictures
to `base-images/`. If the publisher starts over with a different init, the recording
goes on in `base-2.…`. When the channel ends (or on Ctrl-C), ffmpeg, if present,
rewrites each recording without re-encoding: an index for seeking, the clock from
0:00. `--put` then seals and uploads it like `media put`, under the channel's name; a
recording of several files becomes an album. Every channel kind now sends its name as
a sticky `meta` frame, so a viewer without the grant's meta learns it too.
`--channel <file>` keeps a live channel's identity across restarts: the link keeps
working, and each run starts a new epoch.
The owner key (who may upload, delete and open live channels) is created the first
time it is needed, under `$XDG_CONFIG_HOME/shade/media-owner.key` (mode 0600).
`shade media whoami` prints its public half.
The relay knows ids and sizes, never names, and a link is printed once. So `media put`
also writes every upload, with its grant, to `$XDG_CONFIG_HOME/shade/media-library.jsonl`
(mode 0600: a grant is a key). `shade media ls` names your uploads from it, and
`shade media link <name or id>` prints a link again. The file is append-only, one JSON
line per change, so two uploads at once cannot lose each other's entries. A grant
always encodes to the same link: its meta is written in canonical order.
### In the Shade container
```
SHADE_MEDIA_DIR=/data/media # enables media; required (no in-memory fallback)
SHADE_MEDIA_OWNERS=<key>,<key> # who may upload / open channels (`shade media whoami`)
SHADE_DISABLE_MEDIA=1 # optional: off entirely
```
Routes: `/v1/media/:id`, `/v1/media/:id/upload`, `/v1/live/:channelId` (WebSocket), `/watch/`.
### Uploads go up in pieces
A sealed file larger than 16 MiB is not one request. `shade media put` (and
`MediaClient.putSealed`) starts an upload (`POST /v1/media/:id/upload`, signed over
id, size and read-token hash) and sends it in pieces of 16 MiB (`PUT`, each signed
over its offset and length), up to 4 at once. The relay keeps what landed on disk or
in the bucket, so:
- **A dropped connection costs the pieces in flight, not the film.** After a failure
the client asks the relay how far the upload got and sends only what is missing,
with backoff, for up to 8 tries in a row. A piece sent twice is the same bytes twice,
and the second is a no-op.
- **A relay restart, or the next piece landing on another instance, changes nothing.**
The upload is `uploads/<id>.part` + `.json` + `.log` on disk, or a row in
`shade_media_uploads` beside its S3 multipart upload. The log (or the row) names
only pieces already on stable storage, so a piece cut off by a crash is sent again.
- **The relay's memory is bounded by the window, not the film.** This is the reason
the protocol exists. Bun.serve does not hold back a request body the handler reads
slowly: one `PUT` of a 512 MiB film put 762 MiB (disk) and 1011 MiB (S3) into the
relay. In pieces, it stays around 350 MiB at 512 MiB and at 1.5 GiB alike
(`bench/media-store.ts`). Every route now takes at most 64 MiB per
request, so Bun's own 128 MiB cap stays in place.
- An upload counts against the owner's quota from its start. One with no new piece
for 24 hours is dropped by the sweep.
**Across runs, too.** Ctrl-C, a laptop that sleeps, or a relay gone for longer than
the retries wait: run the same `shade media put` again and it goes on with the same
media id. Each file being put has a job under `$XDG_CONFIG_HOME/shade/media-pending/`
(keyed by server, path, size, mtime and options) holding the sealed copy and what a
rerun needs (`job.json`, 0600: it holds the file key, like the library). Once the
relay has the file, the copy is removed and the grant is kept: putting the same file
again gives the same link while the relay still serves it. So running a season's put
again after it stopped at episode 7 sends only episodes 7 to 10. Jobs untouched for
30 days are removed.
A file of at most one piece still goes up as one `PUT /v1/media/:id`. The full exchange
is described in `packages/shade-media/src/upload.ts`.
**There is no in-memory fallback**, for the vault's reason: a library that lives in
RAM accepts every upload and loses all of it on the next redeploy, without anything
failing. With `SHADE_MEDIA_DIR` unset the routes are not mounted, and the log says so.
With `SHADE_MEDIA_OWNERS` empty, the relay serves what it has and accepts nothing new.
`*` admits every key, which is only safe on a private network.
### Several instances, one library (S3 + Postgres)
```
SHADE_MEDIA_S3_URL=https://<key>:<secret>@s3.eu-north-1.amazonaws.com/<bucket>[/<prefix>]
SHADE_MEDIA_PG_URL=postgres://… # falls back to SHADE_PREKEY_PG_URL
SHADE_MEDIA_RELAY_URL=http://10.0.0.5:3000 # this instance, as the others reach it (live channels)
```
(`shade media serve --s3 … --pg … --advertise URL` does the same outside the container.) Sealed
bytes go to the bucket, records and live-channel pins to Postgres, and any number of
instances behind one hostname serve one library. Any S3 API works (AWS, R2, MinIO,
SeaweedFS, Garage, B2); credentials left out of the URL come from
`AWS_ACCESS_KEY_ID`/`AWS_SECRET_ACCESS_KEY`, the region from an `amazonaws.com` host
or `?region=`. A bucket the credentials cannot use is reported at start; media stays
off and the rest of the server runs.
- **Uploads stream.** Each piece of an upload is one part of an S3 multipart upload,
and any instance may take the next one. Every part's payload is hashed into its
signature, so a part damaged in transit is refused. A file sent in one `PUT` goes up
part by part as it arrives, with at most three 16 MiB parts in memory.
- **Behind a load balancer**, let a request that cannot reach one instance go to the
next. A piece is a `PUT` (idempotent: sent twice, the second is a no-op), which
nginx already retries on the next upstream. The `POST` that starts an upload or asks
how far it got is just as safe to repeat, but nginx does not retry it by default:
`location ~ ^/v1/media/[0-9a-f]+/upload$ { proxy_next_upstream error timeout non_idempotent; … }`.
Without it the client still retries, but a balancer that keeps sending its
retries to a dead instance makes the run stop; running it again resumes.
- **Racing uploads of one id** (on any instances) each go to their own object key;
the primary key in Postgres admits one record, and the loser deletes its object.
Delete removes the record first, so a crash never brings a film back.
- **Sweeping.** Three kinds of leftovers are reclaimed after 24 hours: objects no
record points at, uploads with no new piece in that time, and multipart uploads no
upload owns (a crash mid-`PUT`). An upload still receiving pieces is spared, however
old its multipart upload is. The sweep runs a minute after start and then hourly,
for the disk store too, and every instance may sweep at once.
- **Live channels** are pinned in Postgres, so a channel cannot be pinned to two keys
by two instances. Each instance records which channels' publishers are connected to
it (`shade_live_publishers`, refreshed every 10 s). An instance whose viewers want a
channel published elsewhere subscribes to that instance once, with a viewer's own
read token, and fans the frames out locally. It verifies every frame against the pin
as if the publisher were its own, so a peer, or a poisoned locator row, cannot forge
one. Following an instance again replays its backlog; frames already passed on (by
`seq`) are not passed on twice. If the publisher moves (a deploy), viewers on every
instance follow it within a poll (2 s). What is sent while they look for it reaches
them the way a late joiner gets it, from a keyframe. A token that does not match the
pin held in memory is checked against the shared pin before it is refused, so a
publisher that comes back with a new read token is honoured everywhere. Without
`SHADE_MEDIA_RELAY_URL` an instance cannot be followed, and `/v1/live/*` must go to
one instance.
- Viewers now hear when a channel goes live or quiet after they joined: a
`{"type":"state","live":…}` message, in the browser, the TS client and Android.
- The bucket holds only sealed SMF1 bytes. No key, name or plaintext is in it or in
Postgres.
`S3Bucket` is Shade's own small S3 client (SigV4, checked against AWS's published
signature example and a server that validates signatures), not `Bun.S3Client`: in
Bun 1.3.5 its writer buffers everything written to it (512 MiB in, 543 MiB of RSS),
`end(error)` does not abort, and `slice(0, n).stream()` returned the whole object.
## In code
```ts
import { MediaClient, OwnerKey, openGrant, encodeGrant, parseGrant } from '@shade/media';
import { sealFile } from '@shade/media/node';
// Owner side: seal and upload, then grant a peer over the Shade session.
const sealed = await sealFile('Film.mkv', '/tmp/film.smf', { meta: { mime: 'video/x-matroska', name: 'Film' } });
const grant = await new MediaClient(relay, owner).putSealed(sealed, Bun.file('/tmp/film.smf'));
await shade.send('bob', encodeGrant(grant));
// Viewer side: open what was granted and read any range.
const g = parseGrant(await shade.receive('alice', envelope));
const film = await openGrant(g); // fetches the footer + trailer only
const bytes = await film.read(3_000_000_000, 1 << 20); // 1 MiB from 3 GB in
```
Live:
```ts
import { LivePublisher, LivePublishClient, LiveWatchClient } from '@shade/media';
const pub = new LivePublishClient({ relay, publisher: new LivePublisher({ meta: { name: 'logs' } }), readToken, owner });
await pub.whenReady();
await shade.send('bob', encodeGrant(pub.grant('oldest'))); // backlog from the oldest kept keyframe
await pub.send({ type: 'text', text: 'line\n' }, { keyframe: true });
// bob
new LiveWatchClient(grant, { onFrame: (f) => console.log(f.content) });
```
In a page, `installMediaWorker('/sw.js')` registers the decrypting worker, and
`keyring.add(grant)` returns a URL to put in `<video src>`. `new LivePlayer(video, grant)`
plays a live WebM or fragmented-MP4 channel; `MediaSplitter` cuts either container into
the frames a publisher sends (init once, sticky; then one frame per cluster or fragment). The relay serves a ready-made page at `/watch/` that does
both from a link.
On Android/JVM, `no.zyon.shade.media`: `Grants.fromCapabilityUrl(link)`,
`(grant as MediaGrant).open()` returns a `MediaReader` with `read(offset, len)` and
`inputStream()`. `LiveSubscriber(grant).open(frame)` handles live frames, and
`MediaSealer` and `LivePublisher` write both formats byte for byte the way TS does.
Uploading from a phone is `MediaUploader` (blocking; off the main thread):
```kotlin
val owner = MediaOwner(seed) // 32 bytes, kept in the Keystore-backed storage
val up = MediaUploader("https://relay.example", owner)
val grant = contentResolver.openInputStream(uri)!!.use { input ->
up.uploadStream(input, File(cacheDir, "film.smf"), MediaMeta(name = "Kveld.mp4", mime = "video/mp4")) { acked, total -> … }
}
share(grant.capabilityUrl("https://relay.example/watch/"))
```
It speaks the same piece protocol as `media put` (one PUT up to 16 MiB, then pieces
with the relay's window, retries and a resync after a lost answer). To survive the
app being killed, keep the sealed file and the `SealResult` and call `putSealed`
again: the media id is the same, so the relay picks up where it stopped, and a file it
already has gives the same link without sending anything. The relay must list
`owner.id` among its owners.
`UploadJobs` does that bookkeeping: `uploader.upload(jobs, key, …)` seals once into an
app-private job directory (sealed copy + seal result, file key included — keep it in
`filesDir`), resumes after a kill with the same media id, and gives a finished job's
grant again unless the relay says the file is gone. On Android, `ShadeUpload.describe(
context, uri)` turns a shared `content://` URI into the meta to seal (name, type, size,
duration, picture size as shown — nothing else, no location) and `ShadeUpload.upload`
runs it as a job. `KeystoreSecretFile` (`:shade-android-keystore`) keeps the owner seed
encrypted under a hardware-backed Keystore key.
The demo app shows the whole flow: share a video, photo, song or document to «Share to
Shade», enter the relay once and add the owner id it shows to the relay's
`--owners`; a foreground service seals and uploads with a progress notification, and
the finished notification plays the file or shares its link. Several files shared at
once become one album (`uploader.uploadAlbum(Album(title, grants))`), which the player
shows as a list. Android 15 limits
`dataSync` foreground services to 6 hours a day, which is a lot of film; a killed
upload resumes when the service starts again.
For playback, `:shade-android-media` hands a reader to Media3/ExoPlayer, so any
container ExoPlayer understands plays and seeks from a sealed file:
```kotlin
val reader = ShadeMedia.open(link) // blocking: footer + trailer over HTTP
player.setMediaSource(ShadeMedia.mediaSource(reader))
player.prepare()
```
`ShadeMediaDataSource` serves the plaintext ranges ExoPlayer asks for; a tampered
segment fails the read with a `DataSourceException` instead of reaching the decoder.
Live channels play too: `ShadeMedia.liveMediaSource(liveGrant)` connects a
`LiveWatcher` (OkHttp WebSocket, reconnects with backoff, the relay's backlog
deduplicated) and turns the frames into one endless WebM or fMP4 stream for
ExoPlayer's own extractors: the init, then media from the first keyframe, and after
any gap (a reconnect, the relay shedding a slow viewer) nothing until the next
keyframe. A late joiner's timeline starts at 0:00: fMP4 through a per-join
`TimestampAdjuster`, WebM by rewriting each cluster's Timecode in place. Otherwise a
viewer arriving an hour in would wait an hour for the first sample. A different init
mid-stream fails playback with a `ParserException`, which is not retried, rather than
feeding the decoder a spliced stream. `LiveWatcher` on its own follows text and image
channels.
`:shade-media-demo` is a small player app for the dev phone: share a watch link to it,
or start it with `adb shell am start -n no.zyon.shade.mediademo/.PlayerActivity --es link '<link>'`.
Against `shade media serve` on the PC, `adb reverse tcp:3910 tcp:3910` makes a
`http://localhost:3910/…` link work on the phone.
## SMF1 — the sealed file (cross-language contract)
All integers are big-endian.
```
segment[0] … segment[n-1] AES-256-GCM(segKey) of `segmentSize` plaintext bytes each;
the last holds the rest (0 … segmentSize). n ≥ 1.
meta AES-256-GCM(metaKey) of UTF-8 JSON (MediaMeta)
table n × SHA-256(sealed segment i)
footer (64 bytes) "SMF1" | 0x01 | flags=0 | 0 0 | segmentSize u32 |
plaintextSize u64 | metaLen u32 | mediaId (16) |
20 × 0 | "SMF1"
```
```
mediaKey 32 random bytes, fresh for every seal (never caller-chosen)
mediaId 16 random bytes
segKey = HKDF-SHA256(ikm = mediaKey, salt = mediaId, info = "shade-media/v1\0segment", 32)
metaKey = HKDF-SHA256(ikm = mediaKey, salt = mediaId, info = "shade-media/v1\0meta", 32)
nonce_i = u32(0) ‖ u64(i) aad_i = "SMF1" ‖ mediaId ‖ u64(i) ‖ u8(i == n-1)
nonce_meta = u32(1) ‖ u64(0) aad_meta = "SMF1-meta" ‖ mediaId
rootDigest = SHA-256(meta ‖ table ‖ footer)
```
- **The trailer is at the end** so a writer can seal a stream of unknown length in one
pass with one segment of memory, and upload as it goes. A reader fetches the last 64
bytes, then the trailer, which is about 130 KiB for a 4 GB film.
- **Deterministic nonces are safe** because no key is ever used for two files. The
sealer draws the key itself; the only way to pin one is `@shade/media/testing`, for
vectors.
- **`last` is in the AAD**, so truncation fails closed. Cutting the file makes a
segment that was not the last one claim to be.
- **Two layers of integrity.** AEAD protects against the store. The table, pinned by
`rootDigest` in the grant, also protects against *other key holders*. Without it,
a viewer who holds the key could re-encrypt forged segments and serve them to a
third viewer through a store it controls. The reader checks every segment's hash
before decrypting it.
- **Strict parsing.** Unknown flags, non-zero reserved bytes, a size that does not
match the footer, or a `metaLen` over 64 KiB are all refused, never guessed at.
- Default segment size is 1 MiB (allowed: 4 KiB to 16 MiB). The overhead is 48 bytes
per segment plus the trailer, about 0.005 %.
`MediaMeta` holds `mime`, `name`, `durationMs`, `width`, `height`, `createdAt` and
`extra` (string → string). It is validated on both sides, and a writer serialises it
in that key order so two languages produce the same bytes.
## SLF1 — the live frame (cross-language contract)
```
0..4 "SLF1"
4 version = 1
5 flags: 0x01 sticky · 0x02 keyframe · 0x04 end (other bits refused)
6..8 0
8..24 channelId
24..28 epoch u32
28..36 seq u64
36..44 timestamp ms u64 (publisher clock)
44..48 ctLen u32
48.. AES-256-GCM ciphertext ‖ tag (aad = bytes 0..48)
+64 Ed25519 signature over everything before it
```
Payload (inside the ciphertext): one kind byte, then `1` text (UTF-8), `2` binary,
`3` init (u8 mimeLen, mime, bytes), `4` media chunk, `5` image (mime-prefixed like
init), `6` meta (JSON), or `7` end.
Keys follow Signal's Sender Keys, per epoch:
```
ck[0] = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0chain")
stickyKey = HKDF(epochSeed, salt = channelId ‖ u32(epoch), "shade-live/v1\0sticky")
mk[i] = HMAC-SHA256(ck[i], 0x01) used for exactly one frame, then wiped
ck[i+1] = HMAC-SHA256(ck[i], 0x02) one-way: ck[i] cannot be recovered
nonce = u32(epoch) ‖ u64(seq)
```
- **Every frame is signed** with the channel's Ed25519 key. All viewers hold the
same chain, so without a signature any of them could forge frames to the others
through the relay. The signing key's public half travels in the grant, and the
grant travels over an authenticated Shade session; that is what ties a channel
to a person. The relay checks signatures too, against the key the channel was
pinned to on first use, so it never stores or forwards anything a viewer would
reject.
- **Sticky frames** (codec init, the channel's own description) are sealed under
`stickyKey`, not the chain. The relay keeps them for the whole epoch, so a viewer
who joins an hour in can still decode the init segment sent at second zero.
- **Joining late.** The publisher keeps chain snapshots at recent keyframes (64 by
default). A grant carries the chain key at one of them: `oldest` (the most backlog
the relay still has), `latest`, or `now`. A viewer can never derive anything before
its grant's point.
- **Out of order and gaps.** A subscriber derives forward up to 100 000 frames and
keeps keys for up to 2 000 skipped ones, evicting the oldest first. Replays are
dropped quietly.
- **Removing a viewer** means a new epoch: fresh seed, `seq` back to 0, and the sticky
frames resealed. Everyone who stays gets a new grant; anyone left out is out.
- **Link mode** (`channelSecret`): `epochSeed(e) = HKDF(channelSecret, salt =
channelId, "shade-live/v1\0epoch" ‖ u32(e))`. A grant made with `{ link: true }`
carries the secret, so its holder can follow every later epoch without a new grant.
That is how a link survives publisher restarts and the CLI's scheduled rotation
(every 20 000 frames, so catching up stays cheap). The trade-off is that there is
no forward secrecy against a link holder and no way to remove one short of a new
channel. Session grants never carry the secret, so they stay per-epoch either way.
## Grants
```jsonc
// sealed file
{ "kind": "shade.media-grant/v1", "mediaId": "<b64u 16>", "key": "<b64u 32>",
"root": "<hex 32>", "url": "https://…/v1/media/<hex id>", "token": "<b64u>", "meta": { … } }
// live channel
{ "kind": "shade.live-grant/v1", "channelId": "<b64u 16>", "signingKey": "<b64u 32>",
"epoch": 0, "seq": 1234, "chainKey": "<b64u 32>", "stickyKey": "<b64u 32>",
"channelSecret": "<b64u 32, link grants only>", "url": "wss://…", "token": "<b64u>" }
```
`token` is the relay's read token. It is a door, not a key: the relay stores only its
SHA-256 and answers a wrong token and a missing id with the same 404, so a prober
cannot tell which ids exist. A link is `…/watch/#shade=<b64u(grant JSON)>`. The
fragment is never sent to a server, and the page removes it from the address bar
once it has read it.
## Albums
An album is a sealed file like any other, with meta `mime`
`application/vnd.shade.album+json` and this plaintext:
```jsonc
{ "kind": "shade.album/v1", "title": "Sesong 1",
"items": [ { "kind": "shade.media-grant/v1", … }, { "kind": "shade.live-grant/v1", … }, … ] }
```
Items are grants in their wire form, so an album can hold films, pictures, live
channels and other albums (`shade media put dir/` turns subdirectories into nested
albums, in natural order). Parsing is strict on both sides: every item must be a
valid grant, at most 10 000 items, a title of at most 512 characters.
The relay stores an album as one more opaque object. It cannot tell an album from a
film, see its title, count its items or link it to them. Holding the album link means
holding every item's keys: deleting the album does not take them back from someone who
has already opened it. To revoke, delete the items.
Names in an album (and in any sealed file's meta) come from whoever sealed it, so
`shade media get` never uses them as paths: only the last path segment is kept,
without control characters or leading dots, and duplicates get a ` (2)` suffix.
`MediaClient.uploadAlbum`, `openAlbum` / `readAlbum` and `encodeAlbum` / `parseAlbum`
in TS, `Albums.parse` / `Albums.read` in Kotlin. The `/watch/` page shows an album as a
grid with decrypted previews, and Back returns from an item to its album. History
entries hold only a depth, never a grant.
## Films that play in any browser (`--web`)
Real films are often MKV with AC-3, E-AC-3 or DTS audio, or HEVC video. Browsers decode
none of those: Chromium refuses such a file outright ("no supported streams"). Since
sealing happens on the uploader's machine and the relay never sees the content, that is
the only place to fix it. `shade media put Film.mkv --web` runs ffmpeg first:
| In the file | Becomes |
|---|---|
| H.264, VP8, VP9, AV1 video | copied |
| other video (HEVC, MPEG-2, …) | H.264 (CRF 20), which takes a while |
| AAC, MP3, Opus audio | copied |
| other audio (AC-3, E-AC-3, DTS, TrueHD) | AAC, all tracks kept with their languages |
| text subtitles (SubRip, ASS, mov_text) | subtitle tracks (below), in the same pass |
| picture subtitles (PGS, DVD) | reported and skipped: they cannot become text |
The result is an MP4 with its index first. Without `--web`, `media put` uses ffprobe
(when it is installed) to say which streams browsers will not play.
## Subtitles
`shade media put Film.mkv` also seals and uploads the subtitle files next to it, named
the usual way: `Film.srt`, `Film.no.srt`, `Film.en-GB.vtt`. Their grants go into the
film's own sealed meta, under `extra["shade.subtitles"]`:
```jsonc
[{ "lang": "no", "label": "Norsk", "grant": { "kind": "shade.media-grant/v1", … } }, …]
```
So the subtitles travel with the film, shared alone or inside an album, and the relay
sees unrelated objects. In a directory, subtitles that belong to a video are not listed
as album items of their own. `shade media get` writes them back next to the film as
`Film.<lang>.srt`.
The `/watch/` page decrypts them through the worker, turns SubRip into WebVTT, and adds
them as `<track>`s with names in the viewer's language. The track in the browser's
language is on (Bokmål and Nynorsk match a `no` file), and only one is shown at a time.
On Android, `ShadeMedia.openFilm(grant)` opens the film and its subtitle files, and
`ShadeMedia.mediaSource(film)` gives them to ExoPlayer as side-loaded text tracks, the
one in the device's language marked default. A subtitle that cannot be opened is
skipped; the film plays without it. `withSubtitles` / `subtitlesOf` (TS) and
`Subtitles.of` (Kotlin) read and write the field, checked against a shared vector.
## What the relay learns
- **Sealed:** that an opaque id exists, its size (to within a segment), when it was
uploaded, which owner key uploaded it, and which ranges get fetched when. Range
patterns reveal viewing behaviour such as seeking and how far someone watched,
but not content.
- **Live:** that a channel is active, the frame sizes and timing (the bitrate
envelope of a video, the burstiness of a log), keyframe and sticky flags, epoch and
seq, and how many viewers are connected.
- **Never:** content, file names, titles, MIME types, or who a viewer is. Viewers
present a token, not an identity.
Padding sizes or frame timing would hide more, at a real cost in bandwidth. It is not
done in v1. A deployment that needs it can pad above this layer.
## Testing and vectors
- `packages/shade-media/tests/`: format round trips at every boundary, tamper
(flipped bytes, swapped segments, forged table, truncation), live chains (late
join, reordering, replay, forged frames from a key holder, rotation lock-out, link
mode across restarts), the HTTP routes and relay over real sockets, and the WebM
and fMP4 splitters on real ffmpeg output (keyframes inside a GOP, codec strings
for H.264, HEVC, AV1, VP9, AAC and Opus, CMAF `styp`/`prft` prefixes).
- `tests/object-store.test.ts` and `shade-storage-postgres/tests/postgres-media.test.ts`
run against a real S3 API and Postgres when `SHADE_TEST_S3_URL` /
`SHADE_TEST_PG_URL` are set (commands in the files): two relays over one bucket,
racing uploads and pins, sweeping, bounded memory.
- `test-vectors/media.json` (`bun run scripts/generate-vectors.ts media.json`): the
Kotlin port reads every vector and reproduces every sealed file and signed frame
byte for byte (`MediaVectorTest`), owner signatures and encoded grants included.
- `bun run scripts/media-live-kotlin.ts`: the Kotlin uploader against a real TS relay,
with a lost answer and a refused piece injected; TS reads the 40 MiB film back
byte for byte (`MediaLiveTest`, skipped without the driver). The same run kills an
upload job after its first piece and resumes it, and uploads a video shared by its
`content://` URI under Robolectric (`ShadeUploadTest`).
- `bench/media.ts`: throughput, seek latency and live fan-out, written as
`bench/media.chart.json`.
- `bench/media-store.ts`: disk store against S3 (+ Postgres) through the real routes,
each relay in its own process. Upload and read speed, seek latency, and the relay's
peak memory at two film sizes, median or worst of 3 runs
(`bench/media-store.chart.json`).
- `tests/upload.test.ts`: uploads in pieces on the memory and disk stores. Covers
dropped connections before and after the relay stored a piece, a restart with a
piece cut off mid-write, pieces out of order and twice at once, the window, signatures
per offset, a bad footer at the last piece, quota and sweep. `object-store.test.ts`
covers the same over S3 across two instances.
## Design notes
- **Why not HLS/DASH with AES-128?** Their key delivery is a URL the player fetches,
so whoever runs the key server can read everything, and segments are not
authenticated. SMF1 needs only a Range-capable store and puts the key in a grant.
Because the Service Worker presents the decrypted file as an ordinary one, the
browser's native player handles seeking, buffering and codecs.
- **Why not `ShadeStream` (V4.11) for broadcast?** ShadeStream is a pairwise Double
Ratchet, ideal for one server streaming a console to one client. A broadcast to N
viewers through a relay would need N encryptions per frame, and the relay could not
keep one backlog for late joiners. Sender Keys encrypt once and sign once. The
signature restores what the pairwise ratchet gave for free: only the publisher can
speak.
- **Chrome's WebM rule.** Chrome's MSE demuxer rejects a cluster in which any block,
on any track, has an earlier timecode than the block before it. ffmpeg's live
muxer writes exactly that when Opus timestamps round a millisecond below an
interleaved video frame. The splitter sorts blocks within each cluster (stable, so
each track keeps its order). The cluster keeps its size and every block keeps its
bytes.
- **fMP4 keyframes.** The splitter reads sync-ness the way MSE does:
`trun` first-sample flags, else per-sample flags, else `tfhd` defaults, else the
`trex` defaults from the init. The codec string comes from the sample entry
(`avcC`, `hvcC`, `av1C`, `vpcC`, `esds`), so the browser is asked for exactly what
the encoder wrote. CENC-encrypted tracks (`encv`/`enca`) are refused; Shade already
encrypts, and a second DRM layer would leave the viewer without keys.
- **Bun 1.3.5.** `new Response(Bun.file(p).slice(a, b))` sent the whole file in
answer to a Range request when the file was large, so the store reads the range
itself. `fetch(url, { body: Bun.file(p).slice(a, b) })` never finishes sending, so
the client reads each piece itself. And Bun.serve buffers a request body without
limit when the handler reads it slower than the client sends, which is why uploads
go up in pieces.
## Limits (defaults)
| | |
|---|---|
| sealed file | 64 GiB per object, 256 GiB per owner, uploads under way included (`MediaRoutesOptions`) |
| one request | 64 MiB (`MAX_PIECE_BYTES`): a file larger than that goes up in pieces of 16 MiB (more for files over 156 GiB), 4 in flight |
| abandoned upload | dropped after 24 h without a new piece |
| metadata | 64 KiB |
| live frame payload | 16 MiB |
| live backlog | 3 keyframes, at most 32 MiB / 5000 frames per channel |
| slow viewer | over 8 MiB buffered: frames dropped until it drains and a keyframe comes |
| channels held | 1000 live channels per relay; pins idle for 30 days are dropped |

214
docs/vault.md Normal file
View File

@@ -0,0 +1,214 @@
# `@shade/vault` — server-side encrypted file store
V4.13. Where the blob primitive (V4.9) holds one small blob per account, a
vault holds a whole **collection** — a workspace, a mailbox, a drive folder —
as content-addressed objects plus an append-only log of manifests.
It is the piece Shade was missing to let an app offer backup, or to let a
client read data while the peer that owns it is switched off.
## The model
**Objects are content-addressed.** An object's name is the SHA-256 of its
*ciphertext*, so the relay can store, dedupe and verify without a key: it
recomputes the hash on upload and rejects anything mislabelled.
**A manifest names the collection.** Paths live inside the encrypted manifest,
never in object names — the relay must not learn that a user has a file called
`Projects/Divorce/plan.md`. The manifest is itself stored as an object.
**The log is append-only.** Each commit adds a row pointing at a manifest.
History, rollback and "what changed last Tuesday" all fall out of that.
## Keys
Three deterministic derivations off the account master key, in their own HKDF
branch:
```
vaultId = HKDF(masterKey, "shade-vault-id-v1:<app>")
contentKey = HKDF(masterKey, "shade-vault-content-v1:<app>")
sigSeed = HKDF(masterKey, "shade-vault-sig-v1:<app>")
```
Separate from `shade-blob-*-v1` on purpose: a vault key reads every file, a
profile-blob key reads a host list. Sharing a derivation would turn one
compromise into the other.
Because the derivation is deterministic, **recovery is credentials**. A fresh
device that can derive the profile master can derive these, and the relay hands
over ciphertext it has never been able to read. The flip side is that recovery
strength is password strength — see G1's argon2id item.
## Client
```ts
import { SubtleCryptoProvider } from '@shade/crypto-web';
import { VaultClient, HttpVaultTransport, deriveVaultKeys } from '@shade/vault';
const crypto = new SubtleCryptoProvider();
const keys = await deriveVaultKeys(masterKey, 'scaffold');
const client = new VaultClient(crypto, keys, new HttpVaultTransport('https://vault.example'));
// Back up. Unchanged files are not re-uploaded. Persist `res.index` and pass
// it to the next push: an unchanged file is then recognised locally, with no
// download at all.
const res = await client.push(files, Date.now(), undefined, { index: savedIndex });
// → { seq: 4, uploaded: 2, reused: 489, bytesUploaded: 1_204, unchanged: false, index }
// Restore — the newest, or any earlier version.
const { manifest, files: restored } = await client.pull();
const old = await client.pull(2);
// Lazy: list a version, then fetch only what is opened.
const m = await client.manifest();
const bytes = await client.readEntry(m.entries[0]);
// History, and retention.
const log = await client.history();
await client.prune([log.head - 1, log.head]); // → { removedVersions, removedObjects, freedBytes }
```
`push` takes `at` rather than reading the clock, so a queued backup records
when it was *taken* rather than when it finally reached the relay.
**A push that changes nothing commits nothing.** Same paths, same modes, every
file reused, no `message`: the result is `{ unchanged: true, seq: head }` and
the log does not grow. Pushes run on every workspace change; a version per
trigger would fill the log with empty commits. Pass a `message` to force one.
**The index** (`VaultIndex`, plain JSON) maps each path to its plaintext
SHA-256 and the entry it was stored as. It is trusted only when its `vaultId`
matches and its `seq` is still the relay's head; otherwise the push reads the
head manifest and downloads only same-path, same-size candidates to compare. It
holds plaintext hashes, so keep it with the files, never on the relay. After a
restore, `vaultIndexFrom(vaultId, manifest, files)` builds one, so the first
push from a fresh device is free too.
## Format (v2) — the cross-language contract
Every object is `nonce(12) || AES-256-GCM(contentKey, plaintext, aad)`, named
by the lowercase hex SHA-256 of those bytes, with
`aad = utf8("shade-vault-object-v1|" + vaultId)`.
**Entries.** A file's plaintext becomes its *stored* bytes, then *parts*:
1. Unless the plaintext is empty or starts with a known compressed signature —
PNG `89 50 4E 47`, JPEG `FF D8 FF`, WebP `"RIFF"` + `"WEBP"` at offset 8,
MP4 family `"ftyp"` at offset 4, GIF `"GIF8"`, gzip `1F 8B`, zip `"PK"` —
deflate it (raw RFC 1951, zlib default level). Keep the result, and set
`enc: "deflate-raw"`, only if `compressed * 20 <= plain * 19` (≤ 95 %, in
integers so no port rounds differently).
2. Split the stored bytes into slices of at most 4 MiB (4 194 304). An empty
file is one empty slice.
3. Seal each slice as its own object. One slice: `hash` names it and there is
no `parts`. Several: `parts` lists their hashes in order and
`hash = parts[0]`.
`size` is always the **plaintext** length. A reader fetches
`parts ?? [hash]`, verifies and opens each, concatenates, inflates if `enc`,
and checks the result against `size`. An unknown `enc` is refused.
**Manifests.** v2 plaintext is ASCII `"SVM2"` followed by deflate-raw of the
UTF-8 JSON; v1 is the bare JSON. A reader inflates when the magic is present,
parses, and accepts `version` 1 or 2 only — refusing beats guessing, since
silently dropping a field it cannot represent would lose data on its next
commit. JSON key order is not part of the contract. A v1-only reader fails on a
v2 manifest at JSON parse, loudly, rather than misreading it.
**Commits** list every part of every entry in the signed `hashes`. The relay
checks they exist and records them as what the version references; a part
left out may be collected by the next prune.
**Signed bodies** are canonicalised as JSON of every field except
`signature`, top-level keys sorted, nested values as-is; the signature is
Ed25519 over those bytes with the vault's signing seed, base64 on the wire.
Vectors for all of the above: `test-vectors/vault-v2.json` (regenerate with
`bun run scripts/generate-vectors.ts vault-v2.json`). Compressed bytes are
pinned (`stored`) for writer parity; a reader needs only `wire`.
## Server
```ts
import { createVaultRoutes } from '@shade/vault/server';
import { SqliteVaultStore } from '@shade/storage-sqlite';
app.route('/', createVaultRoutes(new SqliteVaultStore('/data/shade-vault.db'), crypto));
```
Routes:
| | |
|---|---|
| `GET /v1/vault/:id/log` | `{ entries, head }` |
| `HEAD /v1/vault/:id/object/:hash` | 200 / 404 — the have-check |
| `GET /v1/vault/:id/object/:hash` | raw ciphertext |
| `PUT /v1/vault/:id/object/:hash` | signed; verifies hash matches bytes |
| `POST /v1/vault/:id/commit` | signed; refuses a stale `seq` or a missing object |
| `POST /v1/vault/:id/prune` | signed `{ keep: number[] }`; must keep the head |
Auth is TOFU-Ed25519, as for blobs: the first signed write pins a pubkey, and
every later write must be signed by it. The pubkey travels **inside** the
signed payload — appended afterwards it would not be covered by the signature,
and could be swapped in transit on the pinning write.
### Configuration
```
SHADE_VAULT_DB_PATH=/data/shade-vault.db # required — no in-memory fallback
SHADE_DISABLE_VAULT=1 # optional: off entirely
```
**There is deliberately no in-memory fallback.** The blob store has one, and on
2026-08-12 a routine redeploy destroyed every profile because the path was
never set in compose: the fallback worked perfectly right up until the
container was recreated, and nothing ever failed loudly. A vault that forgets
is worse than no vault, so an unset path means the routes are simply not
mounted, with a warning that says why.
### Limits
Per object 8 MiB, per vault 512 MiB, both overridable via `VaultRoutesOptions`.
Files larger than an object are split into 4 MiB parts by the client, so the
per-object limit no longer caps file size.
### Retention
`prune` deletes every log entry not in `keep` and then every object no
remaining entry references. The client chooses the policy — only it can read
the manifests — and the relay executes it:
- `keep` must include the current head, or the request fails with
`SEQ_CONFLICT` (and the head). That is also what a keep-list computed before
another device's commit, or a replayed prune, runs into.
- Prune never pins an owner: on a vault with no owner it is a 404.
- An entry newer than the head the route checked is never removed, even if a
commit lands mid-request.
- An object no version has ever referenced (an upload whose commit is still
in flight) survives for `pruneGraceMs`, default one hour.
- **Versions committed before ref tracking** have no recorded hash list. Every
object present when such a version was written (for SQLite: when the
database was migrated) is pinned and never collected while any untracked
version remains. Once the last one is pruned, nothing has an unknown
reference set, and the pins are released.
`SqliteVaultStore` migrates in place on open: `refs_known` on the log,
`pinned` on objects, a `shade_vault_refs` table. No manual step.
## What the relay learns
Object sizes, how many objects there are, when commits happen, and that some
opaque 64-hex id is active. Not contents, not paths, not filenames, and not
which user a vaultId belongs to — the id is itself derived from a secret.
Deduplication is **within** a version chain, not across independent seals:
sealing uses a fresh nonce, so identical plaintext yields different names.
Convergent encryption would dedupe globally but leak which files two users
share, which is exactly what a blind store must not do.
## Status
Client, routes, `MemoryVaultStore` and `SqliteVaultStore` are implemented and
tested, v2 format and prune included, with cross-language vectors. Not yet: a
Postgres store, rate limiting on the vault routes, and the Kotlin port of v2.

View File

@@ -1,7 +1,9 @@
{
"name": "shade",
"private": true,
"workspaces": ["packages/*"],
"workspaces": [
"packages/*"
],
"scripts": {
"test": "bun test --recursive",
"test:core": "cd packages/shade-core && bun test",
@@ -25,7 +27,8 @@
},
"devDependencies": {
"bun-types": "^1.3.11",
"fast-check": "^3.22.0"
"fast-check": "^3.22.0",
"typescript": "7.0.2"
},
"dependencies": {
"@noble/curves": "^2.0.1",

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/cli",
"version": "4.11.0",
"version": "4.15.0",
"type": "module",
"main": "src/cli.ts",
"bin": {
@@ -10,8 +10,10 @@
"@shade/core": "workspace:*",
"@shade/crypto-web": "workspace:*",
"@shade/keychain": "workspace:*",
"@shade/media": "workspace:*",
"@shade/sdk": "workspace:*",
"@shade/storage-encrypted": "workspace:*",
"@shade/storage-postgres": "workspace:*",
"@shade/storage-sqlite": "workspace:*",
"@shade/transport": "workspace:*"
},

View File

@@ -56,6 +56,8 @@ Commands:
rotate-storage-key Re-key the encrypted SQLite store (V3.2)
--key-source / --passphrase / … (current key — same flags as migrate)
--new-key-source / --new-passphrase / … (target key)
media … / live … E2E-encrypted streaming of films, video, images, audio and logs
(run \`shade media\` or \`shade live\` for the subcommands)
help Show this message
Config:
@@ -127,6 +129,15 @@ async function main(): Promise<void> {
await rotateStorageKeyCommand(opts);
break;
}
case 'media':
case 'live': {
const { runMediaCli } = await import('@shade/media/cli');
process.exitCode = await runMediaCli(cmd, args.slice(1), {
// Loaded only by `media serve --s3 … --pg …`.
sharedBackend: async (o) => (await import('@shade/storage-postgres')).createSharedMediaBackend(o),
});
break;
}
case 'help':
case '--help':
case '-h':

View File

@@ -1,6 +1,6 @@
{
"name": "@shade/core",
"version": "4.11.0",
"version": "4.15.0",
"type": "module",
"main": "src/index.ts",
"types": "src/index.ts",

View File

@@ -138,8 +138,13 @@ export async function senderKeyEncrypt(
* Decrypt a sender key message. Verifies signature then advances the
* appropriate chain key.
*
* Handles out-of-order delivery via skipped-key cache (simpler than Double
* Ratchet since there's no DH ratchet).
* Out-of-order delivery is NOT handled: the chain only moves forward and
* the keys of skipped iterations are discarded, so a message that arrives
* after its successor throws "Stale iteration". (This comment used to
* claim a skipped-key cache that never existed.) Senders must therefore
* deliver in iteration order — `Inbox` keeps per-recipient order across
* retries for this reason. Prism's Android receiver keeps skipped keys;
* porting that here needs a `skippedKeys` field in every storage backend.
*/
export async function senderKeyDecrypt(
crypto: CryptoProvider,

View File

@@ -86,6 +86,14 @@ export class ShadeSessionManager {
* fully concurrent.
*/
private readonly peerOpChains = new Map<string, Promise<unknown>>();
/**
* Memoized `alias → canonical` lookups; `null` records "no alias" so a
* label without one costs a single storage read for the life of the
* process instead of one per encrypt/decrypt. Aliases change only via
* the mutators in this class, each of which clears the whole map — it
* holds at most one entry per peer, so rebuilding is cheap.
*/
private readonly aliasCache = new Map<string, string | null>();
constructor(
private readonly crypto: CryptoProvider,
@@ -151,6 +159,46 @@ export class ShadeSessionManager {
}
}
/**
* Map a session label onto the label its state actually lives under.
*
* `aliasSession` moves a session from a first-contact label (typically
* `fp:<hex>`) to the peer's canonical address, but the peer keeps
* sending under the old one. The persisted alias lets us follow that
* move across restarts — see the alias block in `StorageProvider`.
*
* A live session under `label` always wins: after a re-link the peer
* re-runs X3DH and a fresh session is established under the
* first-contact label again, and that new session — not the stale
* alias target — is the one that can decrypt what follows.
*
* Resolves one hop only. Aliases are always written pointing at a
* canonical label, so a chain would mean corrupt state; following it
* would risk a loop for no legitimate gain.
*
* MUST be called before taking the peer mutex: locking the alias while
* mutating the canonical session would let an aliased caller and a
* canonical caller ratchet the same state concurrently.
*/
private async resolveLabel(label: string): Promise<string> {
let canonical = this.aliasCache.get(label);
if (canonical === undefined) {
canonical = (await this.storage.getSessionAlias?.(label)) ?? null;
this.aliasCache.set(label, canonical);
}
if (canonical === null || canonical === label) return label;
if (await this.storage.getSession(label)) return label;
return canonical;
}
/**
* Public label resolution for callers that need to know where a
* peer's state lives (e.g. a transport routing an inbound frame).
*/
async resolveSessionLabel(label: string): Promise<string> {
return this.resolveLabel(label);
}
/** Get the event emitter (if observability is enabled) */
getEvents(): ShadeEventEmitter | undefined {
return this.events;
@@ -268,6 +316,11 @@ export class ShadeSessionManager {
*/
async resetSession(address: string): Promise<void> {
await this.storage.removeSession(address);
// Aliases pointing here are now dangling — drop them so the next
// first-contact frame resolves to its own label and establishes the
// fresh session this reset exists to force.
await this.storage.removeSessionAliasesFor?.(address);
this.aliasCache.clear();
this.events?.emit('session.removed', { address });
// Note: we keep the trusted identity; new session will verify against it.
}
@@ -336,6 +389,14 @@ export class ShadeSessionManager {
await this.storage.bumpPeerIdentityVersion(newLabel);
}
await this.storage.removeSession(oldLabel);
// Remember the move durably. The peer goes on sending under
// `oldLabel` — its transport derives the same first-contact label
// from our relay hint every time — so without this record every
// inbound frame after a restart resolves to a label whose session
// we just removed, and the peer (holding a valid session, never
// re-running X3DH) can never recover on its own.
await this.storage.saveSessionAlias?.(oldLabel, newLabel);
this.aliasCache.clear();
this.events?.emit('session.aliased', { oldLabel, newLabel });
}
@@ -349,6 +410,10 @@ export class ShadeSessionManager {
// because isTrustedIdentity() compares not retrieves; we just emit the new hash)
await this.storage.saveTrustedIdentity(address, newIdentityKey);
await this.storage.removeSession(address);
// The peer rotated identity — any alias into the old session is
// dangling and must not redirect frames meant for the new one.
await this.storage.removeSessionAliasesFor?.(address);
this.aliasCache.clear();
if (this.events) {
const newHash = await shortHash(this.crypto, newIdentityKey);
@@ -516,14 +581,19 @@ export class ShadeSessionManager {
* Subsequent messages are standard RatchetMessages.
*/
async encrypt(address: string, plaintext: string): Promise<ShadeEnvelope> {
return this.withSpan('encrypt', address, async () => {
const session = await this.storage.getSession(address);
if (!session) throw new NoSessionError(address);
// Follow a persisted alias so a caller still holding a first-contact
// label reaches the session that alias moved to — without this, a
// restarted host can decrypt a peer's frames but not reply to them.
// Resolved before the mutex so the lock lands on the canonical label.
const target = await this.resolveLabel(address);
return this.withSpan('encrypt', target, async () => {
const session = await this.storage.getSession(target);
if (!session) throw new NoSessionError(target);
const ratchetMsg = await ratchetEncrypt(this.crypto, session, enc.encode(plaintext));
this.events?.emit('message.encrypted', {
address,
address: target,
counter: ratchetMsg.counter,
ciphertextSize: ratchetMsg.ciphertext.length,
});
@@ -532,7 +602,7 @@ export class ShadeSessionManager {
const x3dh = (session as any).__x3dh;
if (x3dh) {
delete (session as any).__x3dh;
await this.storage.saveSession(address, session);
await this.storage.saveSession(target, session);
const preKeyMsg: PreKeyMessage = {
registrationId: x3dh.registrationId,
@@ -546,16 +616,16 @@ export class ShadeSessionManager {
type: 'prekey',
content: preKeyMsg,
timestamp: Date.now(),
senderAddress: address,
senderAddress: target,
};
}
await this.storage.saveSession(address, session);
await this.storage.saveSession(target, session);
return {
type: 'ratchet',
content: ratchetMsg,
timestamp: Date.now(),
senderAddress: address,
senderAddress: target,
};
});
}
@@ -564,11 +634,17 @@ export class ShadeSessionManager {
* Decrypt a message from a peer. Handles both PreKeyMessage and RatchetMessage.
*/
async decrypt(address: string, envelope: ShadeEnvelope): Promise<string> {
return this.withSpan('decrypt', address, async () => {
// A prekey envelope carries its own X3DH material and establishes a
// fresh session, which must land under the label it arrived on —
// that is exactly what a re-link looks like. Only ratchet envelopes,
// which need state that already exists, follow an alias.
const target =
envelope.type === 'prekey' ? address : await this.resolveLabel(address);
return this.withSpan('decrypt', target, async () => {
if (envelope.type === 'prekey') {
return this.decryptPreKeyMessage(address, envelope.content as PreKeyMessage);
return this.decryptPreKeyMessage(target, envelope.content as PreKeyMessage);
}
return this.decryptRatchetMessage(address, envelope.content as RatchetMessage);
return this.decryptRatchetMessage(target, envelope.content as RatchetMessage);
});
}

View File

@@ -165,6 +165,36 @@ export interface StorageProvider {
/** Remove session for a peer */
removeSession(address: string): Promise<void>;
// ─── Session label aliases (V4.12) ────────────────────────
//
// First contact forces the receiver to label a session by the only
// sender hint the relay surfaces — an 8-byte signing-key fingerprint
// (`fp:<hex>`). A later in-band announcement reveals the peer's
// canonical address and `aliasSession` moves the session there.
//
// The peer, however, keeps sending under whatever label its own
// transport derives — which for a fingerprint-hinted relay is still
// `fp:<hex>`. Before V4.12 that binding lived only in the consumer's
// memory: after a restart the alias was gone, inbound ratchet frames
// resolved to `fp:<hex>`, found no session there, and failed forever
// (the peer holds a valid session so it never re-runs X3DH).
//
// Persisting the alias makes the binding survive restarts, so
// `getSession` can follow it. Optional so third-party storage
// implementations keep compiling — they simply lose alias recovery.
/**
* Record that `alias` names the same peer session as `canonical`.
* Idempotent upsert on `alias`.
*/
saveSessionAlias?(alias: string, canonical: string): Promise<void>;
/** Resolve an alias to its canonical label (null when unaliased). */
getSessionAlias?(alias: string): Promise<string | null>;
/** Drop every alias pointing at `canonical` (session teardown). */
removeSessionAliasesFor?(canonical: string): Promise<void>;
/** Check if we trust a remote identity key (for TOFU or pinned keys) */
isTrustedIdentity(address: string, identityKey: Uint8Array): Promise<boolean>;

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