80 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
037f994572 release(v4.11.0): streaming Double-Ratchet sub-sessions (ShadeStream)
Some checks failed
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Test / test (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled
Answers Vyvern FR shade-ws-streaming-ratchet.md with a first-class
streaming-session API rather than the documented-contract fallback.
The Double-Ratchet crypto was already safe for high-frequency
one-directional use; the send/receive wrapper was not (per-frame
saveSession keystore write; shared per-peer mutex + single stored
session row coupling reuse to the HTTP path).

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

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

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

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

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

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

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

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

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

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

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

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

Two fixes:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 22:58:26 +02:00
348 changed files with 45215 additions and 375 deletions

View File

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

3
.gitignore vendored
View File

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

View File

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

24
.scaffold/log.md Normal file
View File

@@ -0,0 +1,24 @@
# Logg — Shade
## 2026-07-10 — Holistisk helsesjekk + gated plan mot V5.0
Fem parallelle analysepass (arkitektur, test/CI, kryptosikkerhet, Android-paritet, docs/DX), topp-funn kildeverifisert. Kjernen er reell og moden (1159 tester grønne, vektorer byte-pinnet, KT/recovery ekte implementasjoner) — men «GA-frosset og revisjonsklar» stemte ikke. Fire P0-blockere identifisert og lagt inn som blockers i plan.md + kort i tasks.yaml:
1. **AES-GCM nonce-gjenbruk** i at-rest storage (`storage-encrypted/src/crypto/kdf.ts:116`) — deterministisk nonce uten meldingsteller, `saveSession` re-krypterer hver ratchet-op → GCM forbidden attack mot §4. Reachable bekreftet; fiks er liten (tilfeldig nonce, wire lagrer den allerede i prefiks).
2. **@shade/observer@4.11.1 tomt på registry** — `outDir=dist-build` men publish shipper `dist/`; `dist-build/` er det untrackede git-avviket.
3. **Typecheck-gaten rød** — TS upinnet → `bunx tsc` henter 7.0.2 (fjernet `baseUrl`, brukt i consumer-strict); gaten kjøres aldri i CI.
4. **@shade/cli bin dingler** etter publish (bin ikke omskrevet til dist/).
P1: safety-number matcher aldri peerens eget (`session.ts:241`, MITM-forsvar ikke-funksjonelt); backup-KDF HKDF ikke argon2id (finnes allerede i repoet); hono <4.12.18; begge flaggskip-eksempler røde (accept-race `shade-transfer/engine.ts:1140`). Paritet: ShadeStream (v4.11) uvoktet selv på TS-siden, Kotlin stopper på v4.10.
Låst prinsipp: **V5.0-implementasjon er gated på G0–G4 grønne.** V5.0.md er idéskisse — modnes parallelt (wire-typer reconciled mot 0x31–0x33, Insertable Streams-mekanisme, ratchet-params). Full rapport: helsesjekk-artifact (claude.ai/code).
## 2026-07-09 — Adoptert Scaffold plan-kontrakt
Migrerte `docs/ROADMAP.md` og `android/shade-android/ROADMAP-ANDROID.md` til `.scaffold/`: nåbildet destillert inn i `plan.md`, originalene arkivert under `.scaffold/archive/` med opprinnelig mappestruktur. Versjonsdesigndokumentene (`docs/V5.0.md`, `docs/archive/V*.md`) er bevisst latt stå — de er spesifikasjoner, ikke planfiler.
## 2026-05-15 — v4.11: streaming Double-Ratchet sub-sessions
Siste post-GA-økning på 4.x-linjen: `ShadeStream` gir in-memory sub-sessions (seal/open uten keystore-I/O per frame) med nye wire-typer 0x31–0x33. Låst beslutning: stream-ratchets persisteres aldri — en droppet stream gjenåpnes, aldri gjenopptas.
## 2026-05-09 — Android M-Cross 1–4 fullført + Keystore-adapter
All kryptografisk paritet TS↔Kotlin grønn via delte test-vektorer: KDF-kjede, HKDF-labels, X3DH, ratchet-steg, fingerprint, wire 0x02 og 0x11 (streams), backup-HKDF, group sender-keys og storage-HKDF. Etterslepet fra Android-roadmapen landet samme dag: scrypt + argon2id via Bouncy Castle og `shade-android-keystore`-modulen (hardware-backed master key + `KeystoreStorage`). Gjenstår: socket-interop-test og instrumenterte Keystore-tester.
## 2026-05-03 — V4.0 GA: V3.x-konsolidering og audit-pakking
Alle fasene V3.1–V3.12 ferdige og merget: dokumentasjon/hardening, at-rest storage-kryptering, trust-UX, observability (OTel), Android-paritet, inbox (store-and-forward), transport-bridge, web workers-krypto, filmetadata, social key recovery, WebRTC P2P og key transparency. Wire-formatet låst — uendret fra 0.4.x, så 4.0-peers interopererer byte-for-byte med 0.4.x. Kjernen pakket for ekstern review. Låst beslutning: alt VOIP/video skilt ut til V5.0, bygget oppå den frosne 4.0-stacken via reserverte envelope-typer (ikke breaking).

View File

@@ -0,0 +1,41 @@
---
title: "G0: AES-GCM nonce-gjenbruk fjernet fra at-rest-lagringen"
date: 2026-08-13
author: Claude
---
Den første av de fire P0-ene fra helsesjekken 10. juli er borte. `row-codec` forsegler nå med tilfeldig nonce i stedet for en avledet.
## Hva som var galt
`deriveNonce()` laget nonce som en ren funksjon av `(fieldKey, table, pk)` — altså av radens identitet. Doc-kommentaren argumenterte for at det var trygt fordi «hver `(key, plaintext)`-kombinasjon opptrer høyst én gang», men det er nøyaktig omvendt av hva AES-GCM krever: det farlige er å gjenbruke `(key, nonce)` på tvers av *ulike* plaintekster. `saveSession` re-forsegler sesjonsraden ved hvert ratchet-steg, så paret gjentok seg per konstruksjon. Konsekvensen er ikke bare XOR av plaintekstene, men lekkasje av GHASH-subnøkkelen — «the forbidden attack» — som gir tag-forfalskning under den nøkkelen. Det gjaldt alle muterbare rader: sesjoner, config, prekey-state og trust.
## Fiksen
Fire kallesteder, som kartlagt: `sealString` og `sealBytes` (`row-codec.ts:67`/`:96`) tar nå `randomNonce()` fra `aead.ts`, og `openString`/`openBytes` (`:83`/`:112`) slutter å sende `expectedNonce`.
Tilfeldig ble valgt framfor en teller fordi codec-en er delt mellom SQLite og Postgres og ikke har noen varig per-rad skrivteller å støtte seg på. 96 bit holder collision-sannsynligheten neglisjerbar langt forbi et realistisk antall re-lagringer.
`deriveNonce` er beholdt og markert `@deprecated` framfor slettet — den er del av den publiserte flaten via både `index.ts` og `crypto.ts`. Ingen kaller den lenger inne i pakken, og et søk gjennom `packages/`, `android/` og `examples/` fant ingen andre konsumenter. `expectedNonce`-parameteren i `aeadOpen` er beholdt på samme vilkår, med dokumentasjon om hvorfor den ikke skal brukes: den ga ingen tuklingsdeteksjon som AEAD-taggen og `(table, column, pk)`-AAD-en ikke allerede gir.
`randomNonce` er eksportert fra `index.ts` og `crypto.ts`, så konsumenter som forsegler selv har den trygge kilden for hånden.
## Ingen migrering trengs
`aeadOpen` har alltid lest nonce fra blob-prefikset; `expectedNonce` var kun en valgfri ekstrasjekk. Eksisterende blobber åpnes derfor uendret etter fiksen. Todoen om en migreringssti er erstattet av en test som beviser det.
## Android var aldri rammet
Kryssplattform-vektoren «Storage HKDF: rowNonce» tester HKDF-funksjonen, ikke at forseglingen bruker den, så den består uendret — `deriveNonce` er fortsatt der med samme oppførsel. Og `KeystoreStorage` henter nonce fra `cipher.iv`, altså Android Keystores egen tilfeldige IV, som ikke lar seg overstyre. TS-siden er nå på linje med Kotlin, ikke omvendt.
## Verifisering
Ny `tests/nonce-reuse.test.ts` med ni tester i tre grupper: nonce-unikhet (inkludert 200 re-lagringer med 200 distinkte nonces), bakoverkompatibilitet (blob forseglet med den gamle avledningen åpnes, og nye og gamle blobber leses under samme nøkkel), og at tuklingsdeteksjonen overlevde — flippet nonce-byte og flyttet rad avvises fortsatt.
Testene ble bevist å ha verdi ved å reversere fiksen midlertidig: nøyaktig de tre som beskriver feilen falt, mens bakoverkompatibilitets- og tuklingstestene sto uendret.
87 tester grønne i `@shade/storage-encrypted`, typecheck ren, og de to avhengige pakkene kjørt: `@shade/cli` 15/15 og `@shade/sdk` 104/104. En enkelt sdk-feil i første kjøring var en flaky gjennomstrømningsmåling — tre påfølgende kjøringer er grønne.
## Ikke publisert
Fiksen ligger i kildetreet. Prism er pinnet på `@shade/storage-encrypted@4.12.0` og får den først ved en release, som er riktig rekkefølge: `prism-daemon` skal ikke restartes nå.

View File

@@ -0,0 +1,41 @@
---
title: "@shade/vault — server-side kryptert fillager (V4.13)"
date: 2026-08-14
author: Claude
---
Shade kunne flytte filer mellom peers (`@shade/files`) og lagre én liten profil-blob per konto (`/v1/blob/<slotId>`), men hadde ingen alltid-på lagring av krypterte filer. Uten den kan ingen Shade-app tilby backup, og ingen klient kan lese data mens peeren som eier dem er avslått. `@shade/vault` fyller det hullet.
## Modellen
Tre ideer, og formen følger av dem.
**Objekter er innholdsadresserte.** Et objekts navn er SHA-256 av *ciphertexten*, så relayen kan lagre, deduplisere og verifisere uten å forstå noe. Den regner om hashen ved opplasting og avviser et objekt som ikke er det det utgir seg for — uten å eie en nøkkel.
**Et manifest navngir samlingen.** Stier bor i manifestet, ikke i objektnavn: relayen skal ikke lære at brukeren har en fil som heter `Projects/Skilsmisse/plan.md`. Manifestet er selv kryptert og lagret som et objekt.
**Loggen er append-only.** Hver commit legger til en rad som peker på et manifest. Historikk, rollback og «hva endret seg sist tirsdag» faller ut av det — versjoneringshalvdelen av bestillingen.
## Valg verdt å begrunne
*Egen HKDF-gren* (`shade-vault-{id,content,sig}-v1`) ved siden av `shade-blob-*-v1`. En vault-nøkkel leser hver eneste fil; en profil-blob-nøkkel leser en vertsliste. Delt derivasjon ville gjort ett kompromiss om til det andre.
*Ingen konvergent kryptering.* Identisk klartekst gir ulike objektnavn fordi nonce er fersk. Dedupliseringen skjer derfor innenfor en versjonskjede — en uendret fil beholder hashen sin fordi klienten gjenbruker objektet den allerede lastet opp — ikke på tvers av uavhengige forseglinger. Konvergent kryptering ville lekket hvilke filer to brukere deler, som er nøyaktig det en blind butikk ikke skal.
*Commit verifiserer at objektene finnes.* Ellers ville loggen kunne publisere en versjon som ikke lar seg gjenopprette, og det er verdt en ekstra rundtur å utelukke.
*Pubkeyen er inne i signaturen.* Første forsøk la den på utenfor, som både brøt `verifyPayload` (den kanonikaliserer alle felt) og — hvis skjemaet hadde ignorert det — ville latt hvem som helst bytte identitet i transit på den TOFU-pinnende førsteskrivingen. Fanget av testene.
## Verifisering
16 tester, alle mot de ekte rutehåndtererne gjennom Honos `fetch` — ikke mot en mock-transport, som ville vært enig med klienten per konstruksjon og ikke bevist noe om wire-kontrakten.
Dekket: rundtur bit-for-bit; gjenoppretting på en fersk klient som bare har kontonøkkelen; feil master-nøkkel når ikke fram; tre versjoner med rollback til hver enkelt; en 50 KB uendret fil lastes ikke opp på nytt (`bytesUploaded` under 1 KB på andre push); slettet fil borte i ny versjon, intakt i gammel; lagrede objekter inneholder verken innhold eller sti; feilnavngitt objekt avvist; `SEQ_CONFLICT` ved commit fra utdatert head; `MISSING_OBJECTS` ved manglende referanse; fremmed nøkkel avvist mot en pinnet vault; usignert skriving avvist; og at vault-grenen er forskjellig fra blob-grenen.
Typecheck ren. `@shade/storage-encrypted` fortsatt 87/87 etter endringene i `kdf.ts`.
## Gjenstår
Ruting i `shade-server/src/standalone.ts` ved siden av `createBlobRoutes`, en varig `VaultStore` (SQLite/Postgres — bare `MemoryVaultStore` finnes), `docs/vault.md`, og deploy. Ingenting av det er gjort: deploy og publisering er utenfor mandatet for en uovervåket økt.
Arbeidet ligger ukommittert i arbeidstreet, sammen med de eksisterende endringene fra juli.

View File

@@ -0,0 +1,25 @@
---
title: "G0: typecheck-gaten pinnet og lagt i CI"
date: 2026-08-14
author: Claude
---
Tredje av de fire P0-ene fra helsesjekken 10. juli.
## Hva som faktisk var galt
Helsesjekken beskrev gaten som rød fordi TS 7.0.2 hadde fjernet `baseUrl`, som `consumer-strict` brukte. Det stemmer ikke lenger: `baseUrl` finnes ikke noe sted i repoet, og `bun run typecheck` er grønn for alle 26 pakker — inkludert den nye `shade-vault`.
Den ekte feilen står likevel, og er den viktigere av de to: `scripts/typecheck-all.ts` kjørte `bunx tsc`, som henter nyeste utgivelse ved hver kjøring. Gaten kunne altså gå rød — eller stille slutte å fange ting — fordi TypeScript hadde sluppet en versjon, ikke fordi repoet endret seg. Det er en gate som ikke måler det den utgir seg for å måle.
## Fiksen
`typescript` er pinnet til `7.0.2` i rotens `devDependencies`, og `typecheck-all.ts` kjører `node_modules/.bin/tsc` i stedet for `bunx`. Et `Typecheck`-steg er lagt inn i `.gitea/workflows/test.yml`, plassert før testene: en typefeil er billigere å lese enn kjøretidsfeilen den til slutt forårsaker.
## Verifisering
`bun run typecheck` med den pinnede kompilatoren: alle 26 pakker grønne, inkludert consumer-strict-røyktesten (`lib: DOM`, `exactOptionalPropertyTypes`, `paths → workspace`).
## Gjenstår i G0
De to siste P0-ene — `@shade/observer` tomt på registry og `@shade/cli` sin dinglende `bin` — krever begge publisering til npm. Det er en utadvendt handling, og ble ikke gjort i en uovervåket økt.

View File

@@ -0,0 +1,30 @@
---
title: "Register venter ikke lenger på en server som ikke svarer"
date: 2026-10-15
author: "Claude"
---
Prism ble stående med et tomt vindu i flere minutter 2026-10-15 mens zyon var nede.
En av grunnene lå her: `Shade.initialize()` ventet på `transport.register()` uten
tidsgrense. Når pakkene droppes i stedet for å avvises, betyr det ca. 2 minutter før kjernen
gir opp TCP-handshaken. Og feilmeldingen lovet «Will retry on next replenish», men
replenish registrerer aldri. En identitet som startet mens serveren var nede, forble
uregistrert til neste restart.
## Endret
- **`ShadeFetchTransport`**: alle forespørsler går gjennom én `request()` med tidsgrense (`requestTimeoutMs`, standard 15 000, `DEFAULT_REQUEST_TIMEOUT_MS` eksporteres) og en valgfri `fetch`-override. Når tidsgrensen nås, kommer en `NetworkError` med «No response from <host> within N ms».
- **`ShadeConfig`**: `registration: 'await' | 'background'`, `requestTimeoutMs`, `fetch`. Standard er `'await'`, så eksisterende brukere får fortsatt «registrert når `createShade` er ferdig», bare med tidsgrense. `'background'` er for apper der det å åpne identiteten skal være helt lokalt (Prisms unlock-port).
- **Ekte retry**: en register som feiler, prøves på nytt med backoff 5/15/30/60 s til den lykkes. Retryen avbrytes av `shutdown()`, `rotate()` og `importBackup()`, så en gammel identitet aldri publiseres etter rotasjon.
- De tre stedene som bygde `ShadeFetchTransport` bruker nå samme `makeTransport()`, så tidsgrense og fetch følger med ved rotasjon og restore.
## Verifisert
`tests/registration.test.ts` (5 nye) mot en fetch som aldri svarer: `'background'`
blir ferdig uten å vente, `'await'` gir opp ved tidsgrensen, en feilet register blir
prøvd på nytt etter 5 s, og `shutdown` stopper retryene. To nye transporttester for
tidsgrensen og fetch-overriden. Hele suiten: 1206 grønne, typecheck ren på alle 26 pakker.
> [!NOTE]
> Ikke publisert ennå. Registryet bor på `gt.zyon.no`, som var nede da dette ble skrevet.
> Neste steg er 4.13.2, og deretter at Prism bumper og setter `registration: 'background'` og `fetch: serverLink.fetch`.

View File

@@ -0,0 +1,20 @@
---
title: "Vault v2 og Kotlin-vaulten (4.14.0/4.14.1)"
date: 2026-10-16
author: "Claude"
---
Shade fikk det Scaffold-vaulten trengte for å bli telefonens kilde når PC-en er av, uten at serveren fylles opp.
- **4.14.0 — vault v2:**
- Filer komprimeres med deflate-raw når det lønner seg, og deles i forseglede biter på 4 MiB. Manifestene komprimeres også (`SVM2`).
- Push bruker en lokal indeks og laster ikke ned forrige versjon. En push uten endringer committer ingenting.
- Ny lat lesing med `manifest` og `readEntry`.
- Relayet registrerer hvilke objekter hver versjon refererer til, og har fått en signert `prune`-rute. SQLite-lageret migrerer seg selv.
- Kryss-språk-vektorene ligger i `test-vectors/vault-v2.json`.
- **4.14.1 — `edit`:** endrer noen få filer mot hodet som faktisk ble lest, og prøver igjen ved `SEQ_CONFLICT`. Dette er det en kø med to skrivere trenger. `push` publiserer hele samlingen, og ville mistet en fil som en annen enhet la til i mellomtiden.
- **Kotlin, `no.zyon.shade.vault`:** en full port av v2 (lese, forsegle, signere, `edit`).
- 71 Android-tester er grønne.
- Live kryss-sjekk TS↔Kotlin mot ekte vault-ruter (`scripts/vault-live-kotlin.ts`).
Verifisert: shade-vault 61, storage-sqlite 47 og shade-server 55 grønne, og typecheck er ren for alle 26 pakkene. Publisert til Gitea-registeret. Commitet lokalt og tagget (`v4.14.0`, `v4.14.1`), men ikke pushet til remote. Kotlin-filene i `android/` er ennå ikke commitet.

View File

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

View File

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

View File

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

Binary file not shown.

After

Width:  |  Height:  |  Size: 29 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 152 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 127 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 101 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 151 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 53 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 162 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 195 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 156 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 124 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 66 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 165 KiB

View File

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

66
.scaffold/plan.md Normal file
View File

@@ -0,0 +1,66 @@
---
project: "Shade"
phase: "Post-4.x GA — hardening til revisjonsklar (G0–G4) før V5.0-design"
updated: 2026-10-20
focus: "GCM-nonce-fiksen er levert (2026-08-13) og @shade/vault står ferdig og testet (2026-08-14), men er IKKE deployet eller publisert. 4.15.0 er publisert (2026-10-20) med observer- og cli-P0-ene fikset i publiseringsskriptet; G0 har CI-gaten igjen. Historikk: G0 fikk en andre bestiller: @shade/vault (server-side kryptert fillager, bestilt 2026-08-13 av Scaffold-backupen) bygger på at-rest-stacken, og skal ikke reise seg på en kjent GCM-svakhet. Nonce-fiksens migreringssti er verifisert gratis — aeadOpen leser alltid nonce fra prefiks, så eksisterende blobber åpnes uendret."
blockers: []
---
# Plan — Shade
## Mål
- E2EE-bibliotek som implementerer Signal-protokollen (X3DH + Double Ratchet) for TypeScript/Bun — drop-in for frontend, backend og mobil, med forward secrecy og post-compromise recovery.
- Byte-for-byte kryssplattform-paritet: Kotlin/Android-porten verifiseres kontinuerlig mot TS-referansen via delte test-vektorer i `test-vectors/`.
- Reelt revisjonsklar 4.x-kjerne som fundament (G0–G4 grønne); sanntid (V5.0) bygges oppå den låste stacken uten å røre kjernekrypto-revisjonen.
## Nå
Gated hardening — hard utgangsport per steg (full plan + funn: helsesjekk-artifact 2026-07-10, se log.md).
- [ ] **Publiser 4.13.2** (register med tidsgrense + ekte retry + `registration: 'background'`,
gjort 2026-10-15, se `logs/2026-10-15-register-venter-ikke-lenger-pa-en-server-som-ikke-svarer.md`).
Venter på at `gt.zyon.no` er oppe. UNCOMMITTED.
- [x] **G0 — Stopp blødningen (P0):** ~~tilfeldig nonce per skriving i
storage-encrypted~~ (gjort 2026-08-13 — 9 nye tester, ingen migrering nødvendig,
Android var aldri rammet; se `logs/2026-08-13-gcm-nonce-reuse-fikset.md`.
**Ikke publisert** — Prism er pinnet på 4.12.0); observer `outDir→dist` +
republiser 4.11.2 + gitignore `dist-build/`; ~~pin `typescript` + typecheck i CI~~
(gjort 2026-08-14 — pinnet 7.0.2, `typecheck-all.ts` bruker lokal binær i
stedet for `bunx` latest, steg lagt i `test.yml`; `baseUrl` var allerede
borte og alle 26 pakker er grønne); fiks `bin`-omskriving + tarball-verifisering i publish.
Port: typecheck grønn i CI, nonce-negativtest grønn, `bun pm pack` inneholder
main-fil for alle pakker.
Resten gjort 2026-10-20: observer bygger til `dist/`, `bin` omskrives til `dist/*.js`, og
`publish-all.ts` avviser en tarball som mangler en fil `main`/`types`/`bin`/`exports` peker på
(bevist mot den gamle observer-feilen). 4.15.0 publisert med alle 27 pakker.
- [ ] **G1 — Revisjonsklar kjerne (P1):** peer-signeringsnøkkel per sesjon → symmetrisk safety-number; argon2id i backup-KDF (TS+Kotlin); hono ≥4.12.18; håndhevende §4 at-rest-tuklingstest; bestill ekstern krypto-review + pentest. Port: `alice.verify(bob, bob.getIdentityFingerprint())`===true, `bun audit` ren.
- [ ] **G2 — CI som mur:** biome + coverage-terskel + soak:smoke i CI; fjern/synk `.github/workflows`; publish kjører `prepublish:check`; bryt server↔inbox-server-syklus; rydd sdk/cli/files-deps; `dashboard: private`; pin bun. Port: PR blokkeres ved brudd, alle 8 examples grønne i CI.
## Neste
- **Streaming (`@shade/media`, 4.15.0)** — levert 2026-10-18, se `branches/streaming.md`: forseglede filmer/bilder/lyd (SMF1) og live-strømmer (SLF1) E2E, TS + Kotlin; fMP4 + WebM live, ExoPlayer (Android), album, undertekster, `--web`, delt S3/Postgres-lager. Delte relay-instanser med live på tvers, gjenopptakbar opplasting i stykker, `live record`, og «Del til Shade» fra Android (album av flere filer). Gjenstår: demo-APK på enhet. Ikke publisert eller deployet.
- **V4.13 — `@shade/vault`: server-side kryptert fillager.** Klient, ruter,
`MemoryVaultStore`, `SqliteVaultStore`, ruting i `standalone.ts` og
`docs/vault.md` er levert natt til 2026-08-14 (auto-mode); 16 + 7 tester
grønne, og kjeden er kjørt mot en ekte HTTP-server med et ekte workspace:
491 filer bit-identiske etter gjenoppretting, andre push sendte 0 KB.
Gjenstår: Postgres-store, rate limiting på vault-rutene, GC av objekter
ingen manifest lenger refererer — og deploy. Bestilt 2026-08-13 av
Scaffold-backupen, men er en generell mangel: Shade kan flytte filer mellom peers
(`@shade/files`) og lagre én liten profil-blob per konto (`/v1/blob/<slotId>`, V4.9),
men har ingen **alltid-på lagring av krypterte filer på relayen**. Hver konsument
docs/files.md nevner (Dispatch, Mail, Drive-style apps) trenger det samme, så det
hører i Shade og ikke i den enkelte appen.
- *Form:* innholdsadressert lager — klienten krypterer og navngir etter hash av
ciphertext, serveren ser aldri klartekst og trenger ingen forståelse av innholdet.
- *Historikk:* append-only oplog per samling gir versjonering og rollback gratis;
det er «mini github»-halvdelen av Scaffold-bestillingen.
- *Nøkler:* egen HKDF-gren ved siden av `shade-blob-*-v1`, så et vault-kompromiss
ikke rører profil-slotten. Recovery er kontocredentials, som blob-primitivet —
med det forbeholdet at gjenopprettingsstyrken da er passordstyrken (se G1s
argon2id-punkt, som løfter nettopp den).
- *Gated på G0:* lageret bygger på at-rest-stacken, og skal ikke reise seg på en
kjent GCM forbidden attack.
- **G3 — Paritetslås:** ShadeStream-vektorer (3-DH, wire 0x31–0x33) konsumert av begge sider; Kotlin-port av v4.11; utvid cross-vectors path-filter; `PARITY-VERSION`-sjekk; symmetriser alle 14 vektorfiler; Robolectric-tester for KeystoreStorage; E2E socket-interop TS↔Kotlin. Port: begge sider verifiserer alle vektorer, minor-bump uten Android-ack ⇒ rød CI. Vilkår for «production»-label på Android.
- **G4 — Docs = sannhet:** README/MIGRATION/CHANGELOG/CONTRIBUTING → 4.11.x; fiks brutte lenker + riktig remote; legg indexeddb/ShadeStream/broadcast i README+SHADE-BY-SCENARIO; Postgres at-rest quick-start + salt-livssyklus; per-pakke README for de 6 viktigste.
## Senere
- **G5 — V5.0 (Voice/Video):** implementasjon gated på G0–G4 grønne. `docs/V5.0.md` er i dag idéskisse (135 linjer) — modnes parallelt: wire-type-allokering reconciled mot 0x31–0x33 (nå tatt av ShadeStream), browser-SFrame-mekanisme (RTCRtpScriptTransform/Insertable Streams), ratchet-parametre, API-flate, milepæler, intern konsistens (60fps/1080p vs 30fps-test). Godkjennes i diskusjon (Stian + Fable) før koding.
- Versjonsdesigndokumentene bor fortsatt i `docs/V5.0.md` og `docs/archive/V*.md` — de er spesifikasjoner, ikke planfiler.

421
.scaffold/tasks.yaml Normal file
View File

@@ -0,0 +1,421 @@
# Scaffold kanban-kort. Skjema per kort:
# - id: kort-slug # unik i fila
# title: ""
# description: ""
# status: todo # todo | doing | done | blocked
# column: todo # speiler status (kanban-kolonne)
# priority: medium # low | medium | high
# assignee: human # cursor | claude | human | any
# context: "" # valgfri: hvorfor/hvor i koden
# acceptance: "" # valgfri: hva «ferdig» betyr
# todos:
# - text: "Underoppgave"
# done: false
# created: 2026-07-09
# updated: 2026-07-09
# completed_at: null
tasks:
# ─────────────── G0 — Stopp blødningen (P0-blockere) ───────────────
- id: g0-gcm-nonce-reuse
title: "Fjern AES-GCM nonce-gjenbruk i at-rest storage"
description: >
deriveNonce() lager deterministisk nonce fra (fieldKey, tabell, pk) uten
meldingsteller. saveSession re-krypterer sesjonsraden ved hvert ratchet-steg,
så to DB-snapshots deler (key, nonce) over ulik plaintext = GCM forbidden
attack. Systemisk: gjelder alle muterbare rader (config, prekey-state, trust).
status: done
column: done
priority: high
assignee: claude
context: >
Kallesteder kartlagt 2026-08-13: kun row-codec.ts:67 og :96 lager nonce,
og :83/:112 tvinger den ved lesing. deriveNonce() er eksportert fra både
index.ts og crypto.ts, så den beholdes (deprecated) framfor å brekke
konsumenter. VERIFISERT: aeadOpen leser alltid nonce fra blob-prefiks
(aead.ts:72) og expectedNonce er kun en valgfri ekstrasjekk — eksisterende
blobber åpnes derfor uendret, og ingen migreringssti trengs.
acceptance: "Tilfeldig nonce per skriving; aeadOpen leser nonce fra prefiks (dropp expectedNonce-tvang). Negativ test: to session-snapshots ved ulik message-count deler ikke (key, nonce). Test som åpner en blob forseglet med gammel deterministisk nonce. Alle eksisterende tester grønne."
todos:
- text: "row-codec.ts:67/96 → tilfeldig 12-byte nonce, lagret i blob-prefiks"
done: true
- text: "Dropp expectedNonce-argumentet i row-codec.ts:83/112"
done: true
- text: "Negativ regresjonstest for nonce-unikhet på tvers av re-saves"
done: true
- text: "Bakoverkompatibilitetstest: blob med gammel deterministisk nonce åpnes"
done: true
- text: "Marker deriveNonce deprecated (fortsatt eksportert fra index/crypto)"
done: true
- text: "IKKE PUBLISERT — Prism er pinnet på 4.12.0 og får fiksen først ved release"
done: false
created: 2026-07-10
updated: 2026-08-13
completed_at: 2026-08-13
- id: g0-observer-publish
title: "Fiks @shade/observer publiserings-artefakt (tomt på registry)"
description: >
outDir=dist-build avviker fra alle andre pakker (dist). Publish kjører
rm -rf dist og shipper files:[dist] → tarballen mangler JS, main peker på
manglende fil. dist-build/ er det untrackede avviket i git status.
status: todo
column: todo
priority: high
assignee: claude
context: "packages/shade-observer/tsconfig.json (outDir), scripts/publish-all.ts:109/186-227, dashboard copy-to-observer.ts-konflikten"
acceptance: "outDir=dist; dashboard-SPA-konflikt løst eksplisitt; 4.11.2 republisert med verifisert tarball; dist-build/ i .gitignore."
todos:
- text: "tsconfig outDir → dist"
done: false
- text: "Løs dashboard-SPA vs publish-eierskap til dist/"
done: false
- text: "gitignore dist-build/ + fjern restene"
done: false
- text: "Republiser observer 4.11.2"
done: false
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: g0-typecheck-gate
title: "Pin TypeScript, fiks baseUrl, kjør typecheck i CI"
description: >
TS ikke pinnet noe sted → bunx tsc henter 7.0.2 som fjernet baseUrl (brukt i
consumer-strict). typecheck exit 1 nå → prepublish:check rød. Gaten kjøres
heller aldri i CI.
status: done
column: done
priority: high
assignee: claude
context: "tests/consumer-strict/tsconfig.json:17 (baseUrl), scripts/typecheck-all.ts (bruker upinnet bunx tsc), .gitea/workflows/test.yml"
acceptance: "typescript pinnet som devDependency og brukt av typecheck-all.ts; baseUrl fjernet; bun run typecheck grønn og kjøres i .gitea/workflows/test.yml."
todos:
- text: "Pin typescript i root devDependencies"
done: true
- text: "typecheck-all.ts bruker lokal tsc, ikke bunx latest"
done: true
- text: "Fjern baseUrl fra consumer-strict tsconfig (var allerede borte)"
done: true
- text: "Legg typecheck-steg i test.yml"
done: true
created: 2026-07-10
updated: 2026-08-14
completed_at: 2026-08-14
- id: g0-cli-bin-tarball-verify
title: "Fiks cli bin-omskriving + tarball-verifisering i publish"
description: >
bin.shade=src/cli.ts omskrives ikke til dist/ (rewriteEntryPointsForDist
dekker kun main/types/exports). npm i -g @shade/cli gir brutt binær. Samme
rot som observer: publish mangler integritetssjekk.
status: todo
column: todo
priority: high
assignee: claude
context: "scripts/publish-all.ts:186-196 (rewriteEntryPointsForDist), packages/shade-cli/package.json (bin)"
acceptance: "bin omskrives til dist/; publish asserterer at bun pm pack inneholder main-filen for hver pakke; npm i -g @shade/cli kjørbar."
todos:
- text: "Utvid rewriteEntryPointsForDist til pkgJson.bin"
done: false
- text: "Legg tarball-innhold-assert (bun pm pack) i publish-flyten"
done: false
created: 2026-07-10
updated: 2026-07-10
completed_at: null
# ─────────────── G1 — Revisjonsklar kjerne (P1-sikkerhet) ───────────────
- id: g1-symmetric-safety-number
title: "Symmetrisk safety-number (lagre peer-signeringsnøkkel per sesjon)"
description: >
getRemoteFingerprint sender remoteIdentityKey (DH) som begge argumenter →
H(dh‖dh) ≠ peerens egen H(sig‖dh). OOB-verifisering kan aldri matche →
primær MITM-forsvar ikke-funksjonelt.
status: todo
column: todo
priority: high
assignee: claude
context: "packages/shade-core/src/session.ts:238-245, SDK verify()/markPeerVerified()/isPeerVerified() shade.ts:590/649/659"
acceptance: "Peer-signeringsnøkkel lagres per sesjon; kanonisk symmetrisk safety-number; kryssparts-test alice.verify(bob, bob.getIdentityFingerprint())===true uten MITM."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: g1-argon2id-backup
title: "Koble argon2id inn i backup-KDF (TS + Kotlin)"
description: >
Backup-passord-KDF er HKDF → offline brute-force i HKDF-hastighet.
argon2idAsync fra @noble/hashes er allerede dependency og brukes i
storage-encrypted. Kotlin har deriveMasterKeyArgon2id via Bouncy Castle.
status: todo
column: todo
priority: high
assignee: claude
context: "packages/shade-sdk/src/backup.ts:112-119, android/.../backup/BackupKdf.kt:27-36, referanse: storage-encrypted/src/crypto/kdf.ts:73-91"
acceptance: "Backup-KDF = argon2id på begge plattformer; backup-vektor re-pinnet; cross-platform-vektortest grønn."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: g1-hono-upgrade-audit
title: "Oppgrader hono ≥4.12.18 + bun audit-gate"
description: >
hono <4.12.18 har bodyLimit-bypass (svekker §7 64 KiB body-cap), path
traversal i serve-static, IP-restriction-bypass. Dev/test: happy-dom
(critical VM-escape), vite, postcss.
status: todo
column: todo
priority: high
assignee: claude
context: "hono i shade-server/inbox-server/transfer/observer/transport-bridge; bun.lock pinner nåværende"
acceptance: "hono ≥4.12.18 overalt; bun audit uten runtime-high/critical; §7 DoS-cap re-evaluert."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: g1-at-rest-tamper-test
title: "Håndhevende §4 at-rest-tuklingstest + bestill ekstern review"
description: >
SECURITY.md-cellen «§4 at-rest session DB» er «none yet» → ikke håndhevet.
Ekstern krypto-review + pentest står «Pending V4.0» og må ikke skli forbi V5.0.
status: todo
column: todo
priority: high
assignee: any
context: "SECURITY.md:18 (celler uten testlenke ikke håndhevet), THREAT-MODEL §4"
acceptance: "Negativ test som beviser at at-rest-tukling fanges (AAD/tag); SECURITY.md-celle lenket. Ekstern review + pentest bestilt."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
# ─────────────── G2/G3-hoder (nedbrytes når G0/G1 nærmer seg) ───────────────
- id: g2-ci-wall
title: "G2: CI som mur — lint/format/coverage/soak + rydd .github + arkitektur"
description: >
biome (lint+format), coverage-terskel (gulv=dagens), soak:smoke i CI;
fjern/synk stale .github/workflows (7 pakker→npmjs); publish kjører
prepublish:check; bryt server↔inbox-server-syklus; rydd sdk/cli/files ubrukte
deps; dashboard private; pin bun i workflows; kjør alle 8 examples (fiks
accept-race i shade-transfer/engine.ts:1140).
status: todo
column: todo
priority: medium
assignee: claude
context: "Se helsesjekk-artifact 2026-07-10 (P2-arkitektur + CI-hull)"
acceptance: "PR blokkeres ved brudd på typecheck·lint·format·test·coverage; alle 8 examples grønne i CI; ingen udeklarert/ubrukt hard dep."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: g3-parity-lock
title: "G3: Paritetslås — ShadeStream-vektorer + Kotlin v4.11 + interop"
description: >
ShadeStream (v4.11) har null vektorer selv på TS-siden. Kotlin stopper på
v4.10. Lag vektorer (3-DH deriveStreamRootKey, wire 0x31-0x33, frame
seal/open) konsumert av begge; port ShadeStream til Kotlin; utvid
cross-vectors path-filter; PARITY-VERSION-sjekk; symmetriser alle 14
vektorfiler; Robolectric-tester for KeystoreStorage; E2E socket-interop.
status: todo
column: todo
priority: medium
assignee: claude
context: "packages/shade-core/src/stream.ts, scripts/generate-vectors.ts, .gitea/workflows/cross-vectors.yml, android/shade-android-keystore (0 tester)"
acceptance: "Begge sider verifiserer alle 14 vektorer + ShadeStream; minor-bump uten Android-ack ⇒ rød CI; E2E TS-server↔Kotlin-klient over socket grønn."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: g4-docs-truth
title: "G4: Docs = sannhet — oppdater til 4.11.x, fiks lenker/remote/eksempler"
description: >
README/MIGRATION/CHANGELOG/CONTRIBUTING frosset på 4.0. Riktig remote er
Gitea (ikke GitHub). Legg indexeddb/ShadeStream/broadcast i README+
SHADE-BY-SCENARIO; Postgres at-rest quick-start + salt-livssyklus; per-pakke
README for sdk/core/files/streams/storage-encrypted/transport.
status: todo
column: todo
priority: medium
assignee: claude
context: "README.md, MIGRATION.md, CHANGELOG.md, CONTRIBUTING.md, docs/SHADE-BY-SCENARIO.md"
acceptance: "Én sannhetskilde for versjon; ingen brutte doc-lenker (CI link-check); hvert ECOSYSTEM-scenario har kjørende CI-testet eksempel-sti."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
# ─────────────── Åpne beslutninger (Stian avgjør i plandiskusjon) ───────────────
- id: decision-g3-vs-g4-order
title: "BESLUTNING: rekkefølge G3 (paritetslås) vs G4 (docs)"
description: >
Foreslått G3 før G4 fordi «production»-label på Android henger på paritet.
Men hvis Prism/Vyvern trenger docs-sannhet raskere, kan de bytte plass.
status: blocked
column: blocked
priority: medium
assignee: human
acceptance: "Rekkefølge bestemt; plan.md Neste-seksjon speiler valget."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: decision-external-review-timing
title: "BESLUTNING: bestille ekstern krypto-review/pentest nå eller etter G0+G1"
description: >
Parallelt nå (raskere kalender) vs etter G0+G1-fiksene (revisor ser korrekt
kjerne — nonce-fiks + symmetrisk safety-number inne). Fable heller mot fikse først.
status: blocked
column: blocked
priority: medium
assignee: human
context: "Kobles til g1-at-rest-tamper-test; SECURITY.md-celler «Pending V4.0»"
acceptance: "Tidspunkt bestemt; g1-at-rest-tamper-test oppdatert deretter."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
- id: decision-argon2id-migration
title: "BESLUTNING: argon2id backup-migreringsstrategi"
description: >
Re-pinning av backup-vektor betyr at eksisterende 4.x-backups må migreres.
Big-bang i 4.12 vs dobbelt-lesende overgangsvindu (les HKDF-legacy, skriv argon2id).
status: blocked
column: blocked
priority: medium
assignee: human
context: "Kobles til g1-argon2id-backup"
acceptance: "Migreringsstrategi valgt; g1-argon2id-backup-kortet får todos deretter."
created: 2026-07-10
updated: 2026-07-10
completed_at: null
# ─────────────── V4.13 — @shade/vault (server-side kryptert fillager) ───────────────
- id: vault-package
title: "@shade/vault — innholdsadressert kryptert fillager på relayen"
description: >
Shade kan flytte filer mellom peers (@shade/files) og lagre én liten
profil-blob per konto (/v1/blob/<slotId>), men har ingen alltid-på lagring
av krypterte filer. Uten den kan ingen Shade-app tilby backup, og ingen
klient kan lese data når peeren er avslått. Klienten krypterer og navngir
etter hash av ciphertext; serveren ser aldri klartekst.
status: doing
column: doing
priority: high
assignee: claude
context: >
Bestilt av Scaffold-backupen 2026-08-13, men generell: docs/files.md peker
selv på Dispatch/Mail/Drive-style apps som konsumenter. Egen HKDF-gren ved
siden av shade-blob-*-v1 i storage-encrypted/src/crypto/kdf.ts, så et
vault-kompromiss ikke rører profil-slotten. Rutes i shade-server/src/
standalone.ts ved siden av createBlobRoutes.
acceptance: >
Klient kan pushe/hente en samling krypterte objekter mot relayen uten at
serveren kan lese noe; oplog gir versjonsliste og henting av tidligere
versjon; ny enhet med kontocredentials rekonstruerer hele samlingen.
SHADE_VAULT_DB_PATH dokumentert med samme advarsel som SHADE_BLOB_DB_PATH.
todos:
- text: "HKDF-gren for vault-nøkler (slot, innhold, signatur)"
done: true
- text: "Innholdsadressert put/get med CAS-semantikk"
done: true
- text: "Append-only oplog per samling — versjonsliste og rollback"
done: true
- text: "Serverruter + persistenskonfigurasjon i standalone.ts"
done: true
- text: "docs/vault.md + README-rad i statustabellen"
done: false
- text: "IKKE DEPLOYET — krever SHADE_VAULT_DB_PATH i compose + Dokploy-runde"
done: false
created: 2026-08-13
updated: 2026-08-14
completed_at: null
# ─────────────── Streaming — @shade/media ───────────────
- id: media-smf1-live
title: "@shade/media: forseglede filer (SMF1) + live-kanal (SLF1), server, CLI, nettleser, Kotlin"
description: >
E2E-kryptert streaming av filmer, video, bilder, lyd og logger. SMF1 for filer
med tilfeldig tilgang (Range), SLF1 for live-strømmer med sen innstigning og
epokerotasjon. Relay ser bare chiffertekst.
status: done
column: done
priority: high
assignee: claude
branch: streaming
context: "packages/shade-media, docs/media.md, test-vectors/media.json, android/.../no/zyon/shade/media/"
acceptance: "43 TS-tester + 9 Kotlin-vektortester grønne; film/live/bilde/lyd spilt i headless Chromium; benchmark i bench/media.chart.json."
created: 2026-10-18
updated: 2026-10-18
completed_at: 2026-10-18
- id: media-fmp4-live
title: "fMP4 (H.264/AAC) i live-splitteren"
description: "Live-splitteren forstår i dag bare WebM; fMP4 gir H.264/AAC fra kameraer og OBS, og Safari."
status: done
column: done
priority: medium
assignee: claude
branch: streaming
created: 2026-10-18
updated: 2026-10-18
completed_at: 2026-10-18
- id: media-android-exoplayer
title: "Android-demo: ExoPlayer DataSource for forseglede filmer"
description: "Avspilling (Media3 DataSource), live og opplasting fra telefonen er bygget og testet uten enhet; gjenstår kjøring på dev-telefonen (RFCN504DWJF)."
status: doing
column: doing
priority: medium
assignee: claude
branch: streaming
todos:
- text: "ShadeMediaDataSource + ShadeMedia (Media3), Robolectric: ExoPlayer spiller og spoler forseglet H.264/AAC"
done: true
- text: "Demo-app :shade-media-demo bygger (debug-APK)"
done: true
- text: "«Del til Shade»: forsegling + opplasting fra telefonen (MediaUploader, UploadJobs, forgrunnstjeneste, album) — Robolectric mot ekte relay"
done: true
- text: "Installer og spill på dev-telefonen RFCN504DWJF, og del en ekte galleri-video — ikke tilkoblet 2026-10-18/19"
done: false
created: 2026-10-18
updated: 2026-10-19
completed_at: null
- id: media-durable-store
title: "Postgres/S3-medielager for flere relay-instanser"
description: "Gjort: ObjectMediaStore (S3, egen SigV4-klient, multipart med begrenset minne) + PostgresMediaIndex/PostgresLivePinStore; SHADE_MEDIA_S3_URL/SHADE_MEDIA_PG_URL og media serve --s3 --pg. Gjenstår utenfor kortet: live-fan-out på tvers av instanser, og selve deployen (ikke bedt om)."
status: done
column: done
priority: low
assignee: any
branch: streaming
created: 2026-10-18
updated: 2026-10-18
completed_at: 2026-10-18
- id: media-resumable-upload
title: "Opplasting i stykker, gjenopptakbar (TS + Kotlin), media put på tvers av kjøringer, live record"
description: "16 MiB-stykker, 4 i flyt; relay-RSS uavhengig av filmstørrelse; media put fortsetter etter Ctrl-C/SIGKILL; shade live record [--put]; Kotlin MediaUploader med samme protokoll."
status: done
column: done
priority: high
assignee: claude
branch: streaming
created: 2026-10-18
updated: 2026-10-19
completed_at: 2026-10-19
- id: media-browser-upload
title: "Opplasting fra nettleseren (iPhone uten app)"
description: "Eiernøkkel i nettleseren og forsegling som strømmer rett inn i stykkene (MediaClient kjører allerede i nettleseren)."
status: todo
column: todo
priority: medium
assignee: any
branch: streaming
created: 2026-10-19
updated: 2026-10-19
completed_at: null
- id: media-android-camera-live
title: "Live fra telefonkameraet"
description: "LivePublisher finnes i Kotlin; mangler MediaCodec → fMP4-muxing og en publiseringsskjerm. Krever enhet for å verifiseres."
status: todo
column: todo
priority: low
assignee: any
branch: streaming
created: 2026-10-19
updated: 2026-10-19
completed_at: null

File diff suppressed because it is too large Load Diff

4
CLAUDE.md Normal file
View File

@@ -0,0 +1,4 @@
## Planlegging
Planen for dette prosjektet bor i `.scaffold/`: `plan.md` er nåbildet (hold den kort,
bump `updated` i frontmatter ved endring), `log.md` er append-only historikk (nyeste øverst),
`tasks.yaml` er kanban. Ikke opprett planfiler andre steder.

View File

@@ -100,6 +100,9 @@ matrix row in the same change.
| § 1 Network attacker — replay window | ±5 min `signedAt` enforcement | `packages/shade-server/tests/server.test.ts` (`"rejects registration with stale signedAt"`) | | § 1 Network attacker — replay window | ±5 min `signedAt` enforcement | `packages/shade-server/tests/server.test.ts` (`"rejects registration with stale signedAt"`) |
| § 1 Network attacker — header AAD | Ratchet headers bound to ciphertext | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-streams/tests/tamper.test.ts`, `packages/shade-streams/tests/aead.test.ts` | | § 1 Network attacker — header AAD | Ratchet headers bound to ciphertext | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-streams/tests/tamper.test.ts`, `packages/shade-streams/tests/aead.test.ts` |
| § 1 Network attacker — forward secrecy | DH ratchet step + chain-key zeroize | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-crypto-web/tests/hardening.test.ts` | | § 1 Network attacker — forward secrecy | DH ratchet step + chain-key zeroize | `packages/shade-core/tests/ratchet.test.ts`, `packages/shade-crypto-web/tests/hardening.test.ts` |
| § 1 Network attacker — streaming sub-session FS/replay (V4.11) | Per-frame Double-Ratchet `seal`/`open`; counter-rewind & replay rejected; in-memory-only (never persisted) | `packages/shade-core/tests/stream.test.ts` (`"R1: replayed / rewound frame is rejected"`, `"R2/R3: long one-directional burst stays correct and memory-bounded"`) |
| § 1 Network attacker — streaming handshake auth (V4.11) | Identity-bound 3-DH against parent-session-pinned identities | `packages/shade-core/tests/stream.test.ts` (`"handshake is mutually authenticated against pinned identities"`) |
| § 3 Endpoint compromise — streaming sub-session isolation (V4.11) | Stream ratchet derived without touching the stored parent session; zeroized on close | `packages/shade-core/tests/stream.test.ts` (`"R5: opening/using/closing a stream never touches the parent session"`, `"close() zeroizes and blocks further use; idempotent"`) |
| § 2 Compromised prekey server — public-only storage | Prekey store never accepts a private key | `packages/shade-server/tests/server.test.ts`, `packages/shade-storage-sqlite/tests/sqlite-prekey-store.test.ts` | | § 2 Compromised prekey server — public-only storage | Prekey store never accepts a private key | `packages/shade-server/tests/server.test.ts`, `packages/shade-storage-sqlite/tests/sqlite-prekey-store.test.ts` |
| § 2 Compromised prekey server — signed replenish/delete | Per-identity Ed25519 signature | `packages/shade-server/tests/server.test.ts` | | § 2 Compromised prekey server — signed replenish/delete | Per-identity Ed25519 signature | `packages/shade-server/tests/server.test.ts` |
| § 2 Compromised prekey server — fake-bundle detection | Out-of-band fingerprint comparison | `packages/shade-core/tests/fingerprint-session.test.ts` | | § 2 Compromised prekey server — fake-bundle detection | Out-of-band fingerprint comparison | `packages/shade-core/tests/fingerprint-session.test.ts` |

View File

@@ -1,3 +1,6 @@
plugins { plugins {
kotlin("jvm") version "2.0.20" apply false kotlin("jvm") version "2.0.20" apply false
kotlin("android") version "2.0.20" apply false
id("com.android.library") version "8.7.3" apply false
id("com.android.application") version "8.7.3" apply false
} }

View File

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

View File

@@ -4,6 +4,7 @@ pluginManagement {
repositories { repositories {
gradlePluginPortal() gradlePluginPortal()
mavenCentral() mavenCentral()
google()
} }
} }
@@ -17,3 +18,10 @@ dependencyResolutionManagement {
include(":shade-android") include(":shade-android")
project(":shade-android").projectDir = file("shade-android") project(":shade-android").projectDir = file("shade-android")
include(":shade-android-keystore")
project(":shade-android-keystore").projectDir = file("shade-android-keystore")
include(":shade-android-media")
project(":shade-android-media").projectDir = file("shade-android-media")
include(":shade-media-demo")
project(":shade-media-demo").projectDir = file("shade-media-demo")

View File

@@ -0,0 +1,68 @@
# shade-android-keystore
Android-specific bindings for `shade-android`. Lives as a sibling Gradle module so the JVM-only protocol code can keep running in CI without an Android SDK install.
Provides:
- **`KeystoreMasterKey`** — hardware-backed AES-256-GCM master key in the Android Keystore. Optionally biometric-gated (BIOMETRIC_STRONG only — Class 3 assurance), StrongBox-backed when available, invalidated on new biometric enrollment.
- **`BiometricUnlock`** — coroutine wrapper around `BiometricPrompt` for unlocking a `Cipher` instance bound to the keystore key. Throws `BiometricCancelledException` / `BiometricFailedException` so callers can handle the auth flow without writing custom callbacks.
- **`KeystoreStorage`** — `StorageProvider` implementation that persists session/identity/prekey state to `SharedPreferences`, each row encrypted under the keystore key with the row's preference key bound as AAD.
## Usage
```kotlin
import androidx.fragment.app.FragmentActivity
import no.zyon.shade.ShadeSessionManager
import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.keystore.BiometricUnlock
import no.zyon.shade.keystore.KeystoreStorage
class MyActivity : FragmentActivity() {
private val crypto = TinkProvider()
private lateinit var storage: KeystoreStorage
private lateinit var manager: ShadeSessionManager
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
storage = KeystoreStorage(this, crypto)
lifecycleScope.launch {
val unlock = BiometricUnlock(
activity = this@MyActivity,
title = "Unlock Shade",
subtitle = "Tap your fingerprint to access your messages",
)
try {
storage.unlock(unlock)
} catch (e: BiometricCancelledException) {
// user backed out — show a "tap to retry" UI
return@launch
}
manager = ShadeSessionManager(crypto, storage)
manager.initialize()
// ... use manager normally
}
}
}
```
For credential-driven bootstrap (V4.9 profile + V4.10 approval), pair this with `no.zyon.shade.blob.createProfileNamespace` and `no.zyon.shade.approval.signProxyApproval` — both pure-JVM (in `:shade-android`).
## Threat model
- **Compromised app process**: cannot read the AES key (it's in the secure environment). Can attempt to use the cipher only after the user has authenticated; biometric re-prompts are required after each biometric event.
- **Stolen device with known PIN**: cannot unlock — `setUserAuthenticationParameters(0, BIOMETRIC_STRONG)` excludes `DEVICE_CREDENTIAL`.
- **Attacker enrolls own biometric**: `setInvalidatedByBiometricEnrollment(true)` invalidates the key on enrollment, forcing a credential rebootstrap (which would need username + password + PIN).
- **Catastrophic recovery**: `forgetEverything()` deletes the master key and clears the SharedPreferences. Pair with `Profile.delete()` for full account erasure.
## Build
Requires an Android SDK. The Gradle build uses Android Gradle Plugin 8.7+, AGP minSdk 28 (Pie+ for BiometricPrompt baseline), targetSdk 35.
```bash
JAVA_HOME=/path/to/jdk-21 ./gradlew :shade-android-keystore:assembleDebug
```
Unit tests: none yet — `KeystoreStorage` requires Android runtime. Robolectric or instrumented tests against an emulator are tracked as a follow-up. The pure-JVM `SessionStateJson` round-trip serializer is tested in `:shade-android` (`SessionStateJsonTest`).

View File

@@ -0,0 +1,59 @@
plugins {
id("com.android.library")
kotlin("android")
}
// V4.10 — Android-specific KeystoreStorage adapter.
//
// Lives as a sibling module to `:shade-android` so the JVM-only
// protocol code can keep running in CI without an Android SDK.
// This module pulls in `:shade-android` for `StorageProvider`,
// `IdentityKeyPair`, etc., and binds those types to a hardware-
// backed Android Keystore master key with biometric gating.
android {
namespace = "no.zyon.shade.keystore"
compileSdk = 35
defaultConfig {
minSdk = 28 // BiometricPrompt + StrongBox baseline
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17
}
kotlinOptions {
jvmTarget = "17"
}
buildTypes {
release {
isMinifyEnabled = false
}
}
testOptions {
unitTests.isReturnDefaultValues = true
}
}
dependencies {
// Sibling: protocol types + StorageProvider interface.
api(project(":shade-android"))
// androidx.biometric — fragment-safe BiometricPrompt wrapper.
// 1.2.0-alpha05 is the latest with stable BiometricPrompt API.
implementation("androidx.biometric:biometric:1.2.0-alpha05")
// androidx.fragment — BiometricPrompt requires FragmentActivity.
implementation("androidx.fragment:fragment-ktx:1.8.5")
// Coroutines for the suspend-function StorageProvider implementation.
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.9.0")
testImplementation("junit:junit:4.13.2")
testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0")
}

View File

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

View File

@@ -0,0 +1,112 @@
package no.zyon.shade.keystore
import androidx.biometric.BiometricManager
import androidx.biometric.BiometricPrompt
import androidx.fragment.app.FragmentActivity
import javax.crypto.Cipher
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
import kotlinx.coroutines.suspendCancellableCoroutine
/**
* Biometric unlock for a `KeystoreMasterKey`-bound `Cipher`.
*
* The Android keystore enforces that any operation on a
* user-authentication-required key must happen via a
* `BiometricPrompt.CryptoObject`-wrapped `Cipher`. The user sees a
* system biometric prompt; on success the same `Cipher` instance is
* usable for one operation (or one streaming session) before
* needing to re-prompt.
*
* This is a thin coroutine wrapper around `BiometricPrompt` that
* resolves to the authenticated cipher or throws on user
* cancellation. Callers typically run it once at app start to
* unlock the master key for the lifetime of the foreground session.
*/
class BiometricUnlock(
private val activity: FragmentActivity,
private val title: String,
private val subtitle: String? = null,
private val negativeButton: String = "Cancel",
) {
/**
* True if BIOMETRIC_STRONG is currently usable on this device.
* False means the user has no enrolled fingerprint/face that
* meets the class-3 assurance level — fall back to a credential
* recovery flow rather than crashing.
*/
fun canAuthenticate(): Boolean {
val mgr = BiometricManager.from(activity)
return mgr.canAuthenticate(BiometricManager.Authenticators.BIOMETRIC_STRONG) ==
BiometricManager.BIOMETRIC_SUCCESS
}
/**
* Show the biometric prompt and return the authenticated cipher.
*
* Cancellation paths:
* - User taps the negative button → throws `BiometricCancelledException`.
* - System errors out (e.g. too many failures) → throws
* `BiometricFailedException` with the system error code.
*/
suspend fun unlock(cipher: Cipher): Cipher = suspendCancellableCoroutine { cont ->
val callback = object : BiometricPrompt.AuthenticationCallback() {
override fun onAuthenticationSucceeded(result: BiometricPrompt.AuthenticationResult) {
val authedCipher = result.cryptoObject?.cipher
if (authedCipher == null) {
cont.resumeWithException(
BiometricFailedException(-1, "BiometricPrompt returned no cipher"),
)
} else {
cont.resume(authedCipher)
}
}
override fun onAuthenticationError(errorCode: Int, errString: CharSequence) {
if (errorCode == BiometricPrompt.ERROR_USER_CANCELED ||
errorCode == BiometricPrompt.ERROR_NEGATIVE_BUTTON ||
errorCode == BiometricPrompt.ERROR_CANCELED
) {
cont.resumeWithException(BiometricCancelledException(errString.toString()))
} else {
cont.resumeWithException(
BiometricFailedException(errorCode, errString.toString()),
)
}
}
override fun onAuthenticationFailed() {
// A single failed attempt — the prompt stays open and
// gives the user another try. Don't resume the
// continuation; let the system flow continue.
}
}
val prompt = BiometricPrompt(
activity,
activity.mainExecutor,
callback,
)
val info = BiometricPrompt.PromptInfo.Builder()
.setTitle(title)
.apply { if (subtitle != null) setSubtitle(subtitle) }
.setNegativeButtonText(negativeButton)
.setAllowedAuthenticators(BiometricManager.Authenticators.BIOMETRIC_STRONG)
.build()
cont.invokeOnCancellation { prompt.cancelAuthentication() }
prompt.authenticate(info, BiometricPrompt.CryptoObject(cipher))
}
}
/** User cancelled the biometric prompt. */
class BiometricCancelledException(message: String) : RuntimeException(message)
/**
* BiometricPrompt returned a non-cancellation error (lockout, hardware
* unavailable, no enrolled biometrics, etc.). Inspect `errorCode`
* against `BiometricPrompt.ERROR_*` constants to decide UX response.
*/
class BiometricFailedException(val errorCode: Int, message: String) :
RuntimeException("[$errorCode] $message")

View File

@@ -0,0 +1,172 @@
package no.zyon.shade.keystore
import android.os.Build
import android.security.keystore.KeyGenParameterSpec
import android.security.keystore.KeyProperties
import javax.crypto.Cipher
import javax.crypto.KeyGenerator
import javax.crypto.SecretKey
import javax.crypto.spec.GCMParameterSpec
import java.security.KeyStore
/**
* Hardware-backed AES-256-GCM master key in the Android Keystore.
*
* The key never leaves the secure environment — Android's keystore
* implementation enforces that all encrypt/decrypt operations
* happen inside the TEE (or StrongBox if present), and the raw
* key bytes are never returned to userspace.
*
* The key is created on first use with these properties:
*
* - AES-256-GCM, no padding
* - User authentication required: opt-in via the `requireBiometric`
* flag. When true, every encrypt/decrypt operation must be wrapped
* in a `BiometricPrompt.authenticate(CryptoObject(cipher))` call
* that succeeds within the same `Cipher` instance.
* - StrongBox-backed if available (Pixel 3+, most Samsung flagships).
* Falls back to TEE on devices without StrongBox.
* - InvalidatedByBiometricEnrollment(true): a newly enrolled
* fingerprint/face invalidates the key, forcing the user to
* re-bootstrap from credentials. Defends against a thief who
* enrolls their own biometric.
*
* Mirrors the role `KeyManager` plays in `@shade/storage-encrypted`'s
* V4.5 KDF chain: this is the *encryption-at-rest* master key, not
* the X3DH identity key. The Shade protocol's identity keys are
* stored encrypted under THIS key.
*/
class KeystoreMasterKey(
private val alias: String,
private val requireBiometric: Boolean = true,
) {
init {
require(alias.isNotEmpty()) { "alias must be non-empty" }
}
/**
* Build a `Cipher` initialized for encryption with the master key.
*
* If the key requires user auth, the returned cipher is *not yet
* usable* — the caller MUST wrap it in a
* `BiometricPrompt.authenticate(CryptoObject(cipher))` and use
* the cipher exposed by the auth-success callback. Calling
* `cipher.doFinal(...)` before authentication throws
* `UserNotAuthenticatedException`.
*/
fun cipherForEncrypt(): Cipher {
val key = getOrCreateKey()
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.ENCRYPT_MODE, key)
return cipher
}
/**
* Build a `Cipher` initialized for decryption with the master key
* and a previously-stored 12-byte nonce. Same authentication
* requirement as `cipherForEncrypt`.
*/
fun cipherForDecrypt(nonce: ByteArray): Cipher {
require(nonce.size == 12) { "GCM nonce must be 12 bytes" }
val key = getOrCreateKey()
val cipher = Cipher.getInstance(TRANSFORMATION)
cipher.init(Cipher.DECRYPT_MODE, key, GCMParameterSpec(128, nonce))
return cipher
}
/** True if the key already exists in the Android Keystore. */
fun exists(): Boolean {
val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
return ks.containsAlias(alias)
}
/**
* Delete the master key. Catastrophic — all data encrypted under
* it becomes unrecoverable. Used by the "forget everything" flow
* (paired with `Profile.delete()` in the V4.9 namespace).
*/
fun deleteKey() {
val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
if (ks.containsAlias(alias)) ks.deleteEntry(alias)
}
private fun getOrCreateKey(): SecretKey {
val ks = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) }
ks.getEntry(alias, null)?.let { entry ->
return (entry as KeyStore.SecretKeyEntry).secretKey
}
return generateKey()
}
private fun generateKey(): SecretKey {
val builder = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
// Each encrypt operation generates a fresh IV in the secure
// env; we read it back via `cipher.iv` after init.
.setRandomizedEncryptionRequired(true)
if (requireBiometric) {
builder.setUserAuthenticationRequired(true)
// BIOMETRIC_STRONG only — class 3, the highest assurance
// level (Class 3 = false-accept rate < 1/50 000 per BiometricPrompt).
// DEVICE_CREDENTIAL is intentionally NOT included: a stolen
// device with a known PIN should not unlock Shade.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
builder.setUserAuthenticationParameters(
/* timeout = */ 0,
KeyProperties.AUTH_BIOMETRIC_STRONG,
)
} else {
@Suppress("DEPRECATION")
builder.setUserAuthenticationValidityDurationSeconds(-1)
}
builder.setInvalidatedByBiometricEnrollment(true)
}
// StrongBox if available — bumps key storage to a dedicated
// tamper-resistant chip on Pixel 3+ / most Samsung flagships.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
builder.setIsStrongBoxBacked(true)
}
val gen = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE)
return try {
gen.init(builder.build())
gen.generateKey()
} catch (_: Exception) {
// StrongBox not present or full → retry without StrongBox.
// Same for older devices that don't honor
// setUserAuthenticationParameters.
val fallback = KeyGenParameterSpec.Builder(
alias,
KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT,
)
.setBlockModes(KeyProperties.BLOCK_MODE_GCM)
.setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE)
.setKeySize(256)
.setRandomizedEncryptionRequired(true)
.apply {
if (requireBiometric) {
setUserAuthenticationRequired(true)
@Suppress("DEPRECATION")
setUserAuthenticationValidityDurationSeconds(-1)
setInvalidatedByBiometricEnrollment(true)
}
}
.build()
gen.init(fallback)
gen.generateKey()
}
}
companion object {
private const val ANDROID_KEYSTORE = "AndroidKeyStore"
private const val TRANSFORMATION = "AES/GCM/NoPadding"
}
}

View File

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

View File

@@ -0,0 +1,229 @@
package no.zyon.shade.keystore
import android.content.Context
import android.content.SharedPreferences
import android.util.Base64
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.serialization.SessionStateJson
import no.zyon.shade.storage.StorageProvider
import no.zyon.shade.types.IdentityKeyPair
import no.zyon.shade.types.OneTimePreKey
import no.zyon.shade.types.SessionState
import no.zyon.shade.types.SignedPreKey
/**
* `StorageProvider` implementation that gates all reads/writes through
* a biometric-locked `KeystoreMasterKey`. Mirrors `MemoryStorage` for
* the API surface but persists state to `SharedPreferences` with each
* row encrypted under the keystore key.
*
* Lifecycle:
*
* 1. App start → construct `KeystoreStorage(context, alias)`.
* 2. `unlock(BiometricUnlock)` runs the system biometric prompt.
* The Android keystore caches the auth state under the key's
* `setUserAuthenticationParameters(0, BIOMETRIC_STRONG)` policy
* until the next biometric event (re-enrollment, etc.).
* 3. While unlocked, `getSession`/`saveSession` etc. work normally.
* 4. `lock()` clears the in-memory unlocked flag so a future
* operation triggers another biometric prompt.
*
* Wire layout per row:
* `<base64(nonce(12))>:<base64(ct||tag)>`
*
* Stored as `String` SharedPreferences entries. AAD = the row's
* preference key (`session:<address>`, `signedPreKey:<id>`, etc.) so
* a substituted-prefs swap fails to open.
*/
class KeystoreStorage(
context: Context,
private val crypto: CryptoProvider,
keyAlias: String = DEFAULT_KEY_ALIAS,
prefsName: String = DEFAULT_PREFS_NAME,
requireBiometric: Boolean = true,
) : StorageProvider {
private val prefs: SharedPreferences =
context.applicationContext.getSharedPreferences(prefsName, Context.MODE_PRIVATE)
private val masterKey = KeystoreMasterKey(keyAlias, requireBiometric = requireBiometric)
private val writeMutex = Mutex()
@Volatile
private var unlocked: Boolean = false
/**
* Unlock the keystore via biometric prompt. Idempotent — calling
* twice without a `lock()` between is a no-op.
*/
suspend fun unlock(unlock: BiometricUnlock) {
if (unlocked) return
// The biometric flow returns an authenticated *encrypt*
// cipher; we discard it after a one-shot probe to confirm
// the master key is reachable. The actual encrypt/decrypt
// ciphers in the I/O path use the authentication state
// established here (Android Keystore caches the auth for
// the user-authentication-required key under the
// `setUserAuthenticationParameters(0, BIOMETRIC_STRONG)`
// policy until the next biometric event).
val probe = masterKey.cipherForEncrypt()
unlock.unlock(probe)
unlocked = true
}
/** Unlock without biometric — only valid for keys constructed with `requireBiometric=false`. */
fun unlockNoBiometric() {
unlocked = true
}
/** Wipe in-memory unlock state. The key itself stays in the keystore. */
fun lock() {
unlocked = false
}
/**
* Catastrophic reset: deletes the master key + all encrypted
* preferences. Used by the "forget everything" / 3-strikes-wipe
* path. The next bootstrap rebuilds from credentials.
*/
fun forgetEverything() {
masterKey.deleteKey()
prefs.edit().clear().apply()
unlocked = false
}
// ─── Identity ──────────────────────────────────────────────
override suspend fun getIdentityKeyPair(): IdentityKeyPair? {
val json = readDecrypted(KEY_IDENTITY) ?: return null
return SessionStateJson.deserializeIdentityKeyPair(json)
}
override suspend fun saveIdentityKeyPair(keyPair: IdentityKeyPair) {
writeEncrypted(KEY_IDENTITY, SessionStateJson.serializeIdentityKeyPair(keyPair))
}
override suspend fun getLocalRegistrationId(): Int {
return readDecrypted(KEY_REGISTRATION_ID)?.toIntOrNull() ?: 0
}
override suspend fun saveLocalRegistrationId(id: Int) {
writeEncrypted(KEY_REGISTRATION_ID, id.toString())
}
// ─── Signed prekeys ────────────────────────────────────────
override suspend fun getSignedPreKey(keyId: Int): SignedPreKey? {
val json = readDecrypted("$KEY_SIGNED_PREKEY:$keyId") ?: return null
return SessionStateJson.deserializeSignedPreKey(json)
}
override suspend fun saveSignedPreKey(key: SignedPreKey) {
writeEncrypted(
"$KEY_SIGNED_PREKEY:${key.keyId}",
SessionStateJson.serializeSignedPreKey(key),
)
}
override suspend fun removeSignedPreKey(keyId: Int) {
writeMutex.withLock { prefs.edit().remove("$KEY_SIGNED_PREKEY:$keyId").apply() }
}
// ─── One-time prekeys ──────────────────────────────────────
override suspend fun getOneTimePreKey(keyId: Int): OneTimePreKey? {
val json = readDecrypted("$KEY_ONETIME_PREKEY:$keyId") ?: return null
return SessionStateJson.deserializeOneTimePreKey(json)
}
override suspend fun saveOneTimePreKey(key: OneTimePreKey) {
writeEncrypted(
"$KEY_ONETIME_PREKEY:${key.keyId}",
SessionStateJson.serializeOneTimePreKey(key),
)
}
override suspend fun removeOneTimePreKey(keyId: Int) {
writeMutex.withLock { prefs.edit().remove("$KEY_ONETIME_PREKEY:$keyId").apply() }
}
override suspend fun getOneTimePreKeyCount(): Int {
return prefs.all.keys.count { it.startsWith("$KEY_ONETIME_PREKEY:") }
}
// ─── Sessions ──────────────────────────────────────────────
override suspend fun getSession(address: String): SessionState? {
val json = readDecrypted("$KEY_SESSION:$address") ?: return null
return SessionStateJson.deserialize(json)
}
override suspend fun saveSession(address: String, state: SessionState) {
writeEncrypted("$KEY_SESSION:$address", SessionStateJson.serialize(state))
}
override suspend fun removeSession(address: String) {
writeMutex.withLock { prefs.edit().remove("$KEY_SESSION:$address").apply() }
}
// ─── Trust ─────────────────────────────────────────────────
override suspend fun isTrustedIdentity(address: String, identityKey: ByteArray): Boolean {
val stored = readDecrypted("$KEY_TRUSTED:$address") ?: return true // TOFU
val storedBytes = Base64.decode(stored, Base64.NO_WRAP)
return crypto.constantTimeEqual(storedBytes, identityKey)
}
override suspend fun saveTrustedIdentity(address: String, identityKey: ByteArray) {
writeEncrypted(
"$KEY_TRUSTED:$address",
Base64.encodeToString(identityKey, Base64.NO_WRAP),
)
}
// ─── Encrypted-row plumbing ────────────────────────────────
private fun ensureUnlocked() {
check(unlocked) {
"KeystoreStorage is locked — call unlock(BiometricUnlock) first"
}
}
private suspend fun readDecrypted(prefKey: String): String? {
ensureUnlocked()
val raw = prefs.getString(prefKey, null) ?: return null
val parts = raw.split(":", limit = 2)
require(parts.size == 2) { "malformed encrypted row at $prefKey" }
val nonce = Base64.decode(parts[0], Base64.NO_WRAP)
val ct = Base64.decode(parts[1], Base64.NO_WRAP)
val cipher = masterKey.cipherForDecrypt(nonce)
cipher.updateAAD(prefKey.toByteArray(Charsets.UTF_8))
return cipher.doFinal(ct).toString(Charsets.UTF_8)
}
private suspend fun writeEncrypted(prefKey: String, plaintext: String) {
ensureUnlocked()
writeMutex.withLock {
val cipher = masterKey.cipherForEncrypt()
cipher.updateAAD(prefKey.toByteArray(Charsets.UTF_8))
val ct = cipher.doFinal(plaintext.toByteArray(Charsets.UTF_8))
val nonce = cipher.iv
val nonceB64 = Base64.encodeToString(nonce, Base64.NO_WRAP)
val ctB64 = Base64.encodeToString(ct, Base64.NO_WRAP)
prefs.edit().putString(prefKey, "$nonceB64:$ctB64").apply()
}
}
companion object {
const val DEFAULT_KEY_ALIAS = "shade-master-v1"
const val DEFAULT_PREFS_NAME = "shade-keystore-storage-v1"
private const val KEY_IDENTITY = "identity"
private const val KEY_REGISTRATION_ID = "registrationId"
private const val KEY_SIGNED_PREKEY = "signedPreKey"
private const val KEY_ONETIME_PREKEY = "oneTimePreKey"
private const val KEY_SESSION = "session"
private const val KEY_TRUSTED = "trusted"
}
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -7,7 +7,11 @@ Kotlin implementation of the Shade E2EE protocol for Android apps. Byte-for-byte
**M-Cross 1 ✅** — keys + HKDF + X3DH + fingerprint. **M-Cross 1 ✅** — keys + HKDF + X3DH + fingerprint.
**M-Cross 2 ✅** — full ratchet step (encrypt + decrypt roundtrip) + wire 0x02 (RatchetMessage and PreKeyMessage with/without OTPK). **M-Cross 2 ✅** — full ratchet step (encrypt + decrypt roundtrip) + wire 0x02 (RatchetMessage and PreKeyMessage with/without OTPK).
**M-Cross 3 ✅** — streams 0x11 (KDF labels with embedded NULs, deterministic chunk nonce/AAD, wire 0x11 encode/decode). **M-Cross 3 ✅** — streams 0x11 (KDF labels with embedded NULs, deterministic chunk nonce/AAD, wire 0x11 encode/decode).
**M-Cross 4 ✅** — backup-key HKDF + AES-GCM, group sender-key step (`kdfChainKey` + Ed25519 sign over `aad ‖ ct`), storage HKDF (storageKey/fieldKey/rowNonce). Pending: scrypt master-key, argon2id swap, Android KeystoreStorage (sibling module). **M-Cross 4 ✅** — backup-key HKDF + AES-GCM, group sender-key step (`kdfChainKey` + Ed25519 sign over `aad ‖ ct`), storage HKDF (storageKey/fieldKey/rowNonce).
**M-Cross 5 ✅** — V4.9 blob KDF + AEAD (`deriveBlobSlotId / deriveBlobKey / deriveBlobSigningSeed`, AAD-bound seal/open), `BlobClient` HTTP, `Profile` namespace. Cross-platform vectors in `blob.json`.
**M-Cross 6 ✅** — V4.10 cross-host approval routing: canonical profile-blob schema (`hosts[]` / `clients[]` / `trustedApproverFingerprints[]`), build/sign/verify proxy approvals via `canonicalApprovalSigningBytes` (length-prefixed u16 BE UTF-8). Cross-platform vectors in `approval.json`, including a TS-signed Ed25519 signature that the Kotlin port verifies.
**M-Cross 7 ✅** — scrypt + argon2id password-KDF wrappers (Bouncy Castle), NFKC-normalized inputs.
**M-Cross 8 ✅** — `:shade-android-keystore` sibling module: `KeystoreMasterKey` (StrongBox-backed AES-256-GCM, BIOMETRIC_STRONG-gated, invalidated on biometric enrollment), `BiometricUnlock`, `KeystoreStorage` (`StorageProvider` over biometric-gated AES-encrypted SharedPreferences).
Cross-platform test vectors in `/test-vectors/` are loaded by both the TS Cross-platform test vectors in `/test-vectors/` are loaded by both the TS
and Kotlin test suites; any byte-divergence fails CI within 60 s. See and Kotlin test suites; any byte-divergence fails CI within 60 s. See

View File

@@ -29,6 +29,11 @@ dependencies {
// The same `subtle.*` API as `tink-android` so the source compiles unchanged. // The same `subtle.*` API as `tink-android` so the source compiles unchanged.
implementation("com.google.crypto.tink:tink:1.15.0") implementation("com.google.crypto.tink:tink:1.15.0")
// Bouncy Castle for scrypt + argon2id. Tink doesn't ship password
// KDFs; @shade/storage-encrypted uses @noble/hashes for both. We
// pin to the JDK18-on artifact so it works on JVM 17 + Android.
implementation("org.bouncycastle:bcprov-jdk18on:1.78.1")
// JSON serialization (session state + test-vector loader on JVM). // JSON serialization (session state + test-vector loader on JVM).
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3") implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
@@ -44,6 +49,10 @@ dependencies {
tasks.withType<Test>().configureEach { tasks.withType<Test>().configureEach {
useJUnit() 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 { testLogging {
events("passed", "failed", "skipped") events("passed", "failed", "skipped")
showStandardStreams = false showStandardStreams = false

View File

@@ -0,0 +1,273 @@
package no.zyon.shade.approval
import no.zyon.shade.crypto.CryptoProvider
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* V4.10 — cross-host approval routing helpers. Mirror
* `@shade/sdk/approval.ts` byte-for-byte.
*
* The frames themselves (`approvalNeeded` / `linkApproveByProxy`) are
* app-defined payloads sent over the existing Shade bilateral E2EE
* channel. This file ships the canonical signing-payload layout, the
* Ed25519 sign step a phone runs after biometric unlock, and the
* verify step a host runs against the freshest profile blob.
*
* The signing payload is length-prefixed binary (u16 BE) so any
* platform — Kotlin, Swift, Go — can produce byte-identical input
* without needing a JSON canonicalizer. Cross-platform parity is
* gated by `test-vectors/blob-storage.json` (signing payload
* fixtures) plus a Kotlin↔TS round-trip in `CrossPlatformVectorTest`.
*/
/** Default domain separator. Apps with their own canonical name (e.g. Prism) override. */
const val DEFAULT_APPROVAL_DOMAIN = "shade-link-approve-v1"
/** Default expiry: 5 minutes after the host issues the request. */
const val DEFAULT_APPROVAL_EXPIRES_IN_MS = 5L * 60 * 1000
/** Information about the device the host received a `linkRequest` from. */
data class ApprovalRequestingDevice(
val fingerprint: String,
val deviceName: String? = null,
val userAgent: String? = null,
val ipHint: String? = null,
val receivedAt: Long,
)
data class ApprovalRequestFrame(
val kind: String = "approvalNeeded",
/** 128-bit hex (32 chars) random idempotency key. */
val requestId: String,
val hostAddress: String,
val hostFingerprint: String,
val requestingDevice: ApprovalRequestingDevice,
val expiresAt: Long,
val domain: String,
)
data class ProxyApprovalFrame(
val kind: String = "linkApproveByProxy",
val requestId: String,
val decision: String,
val approverFingerprint: String,
/** 64-byte Ed25519 signature, lowercase hex (128 chars). */
val signature: String,
val domain: String,
)
/**
* Build a fresh `approvalNeeded` frame with a 128-bit random
* `requestId`. Hosts SHOULD persist the requestId in a pending-set
* keyed by `expiresAt` so a returning `linkApproveByProxy` can be
* matched up — that's app state, the SDK doesn't track it.
*/
fun buildApprovalRequest(
crypto: CryptoProvider,
hostAddress: String,
hostFingerprint: String,
requestingDeviceFingerprint: String,
deviceName: String? = null,
userAgent: String? = null,
ipHint: String? = null,
expiresInMs: Long = DEFAULT_APPROVAL_EXPIRES_IN_MS,
domain: String = DEFAULT_APPROVAL_DOMAIN,
now: Long = System.currentTimeMillis(),
): ApprovalRequestFrame {
val requestId = crypto.randomBytes(16).joinToString("") { "%02x".format(it) }
return ApprovalRequestFrame(
requestId = requestId,
hostAddress = hostAddress,
hostFingerprint = hostFingerprint,
requestingDevice = ApprovalRequestingDevice(
fingerprint = requestingDeviceFingerprint,
deviceName = deviceName,
userAgent = userAgent,
ipHint = ipHint,
receivedAt = now,
),
expiresAt = now + expiresInMs,
domain = domain,
)
}
/**
* Sign a `linkApproveByProxy` frame with the approver's long-term
* Ed25519 identity key. The seed is the 32-byte Ed25519 private key
* (Tink's `Ed25519Sign(seed)` consumes it directly).
*/
fun signProxyApproval(
crypto: CryptoProvider,
request: ApprovalRequestFrame,
decision: String,
approverFingerprint: String,
approverSigningKey: ByteArray,
): ProxyApprovalFrame {
require(decision == "approve" || decision == "reject") {
"decision must be 'approve' or 'reject'"
}
require(approverSigningKey.size == 32) {
"approverSigningKey must be 32 bytes (Ed25519 seed)"
}
val payload = canonicalApprovalSigningBytes(
domain = request.domain,
requestId = request.requestId,
hostFingerprint = request.hostFingerprint,
requestingDeviceFingerprint = request.requestingDevice.fingerprint,
decision = decision,
)
val sig = crypto.sign(approverSigningKey, payload)
return ProxyApprovalFrame(
requestId = request.requestId,
decision = decision,
approverFingerprint = approverFingerprint,
signature = sig.joinToString("") { "%02x".format(it) },
domain = request.domain,
)
}
/** Tagged result of `verifyProxyApproval`. */
sealed class VerifyProxyApprovalResult {
data class Ok(val approver: ProfileClientEntry) : VerifyProxyApprovalResult()
data class Failed(val reason: Reason) : VerifyProxyApprovalResult()
enum class Reason {
REQUEST_ID_MISMATCH,
DOMAIN_MISMATCH,
UNKNOWN_APPROVER,
NOT_TRUSTED,
BAD_SIGNATURE,
EXPIRED,
}
}
/**
* Verify a `linkApproveByProxy` against the originating
* `approvalNeeded` and the host's freshest profile blob. Returns a
* tagged result rather than throwing — callers usually want to log
* the reason before deciding what to surface to the user.
*
* Order of checks:
*
* 1. requestId match (replay defense)
* 2. domain match (cross-app confusion defense)
* 3. approver resolves to a `clients[]` entry
* 4. approver is in `trustedApproverFingerprints[]` AND has the
* `trustedApprover` flag (cross-checked via `isTrustedApprover`)
* 5. expiresAt in the future
* 6. Ed25519 signature verifies against `clients[].identityPublicKey`
*
* Hosts MUST refetch the profile blob fresh before calling this — see
* the FR §5 "approver-revocation propagation" rationale.
*/
fun verifyProxyApproval(
crypto: CryptoProvider,
request: ApprovalRequestFrame,
approval: ProxyApprovalFrame,
profile: CanonicalProfileBlob,
now: Long = System.currentTimeMillis(),
): VerifyProxyApprovalResult {
if (approval.requestId != request.requestId) {
return VerifyProxyApprovalResult.Failed(
VerifyProxyApprovalResult.Reason.REQUEST_ID_MISMATCH,
)
}
if (approval.domain != request.domain) {
return VerifyProxyApprovalResult.Failed(
VerifyProxyApprovalResult.Reason.DOMAIN_MISMATCH,
)
}
val approver = findClientByFingerprint(profile, approval.approverFingerprint)
?: return VerifyProxyApprovalResult.Failed(
VerifyProxyApprovalResult.Reason.UNKNOWN_APPROVER,
)
if (!isTrustedApprover(profile, approval.approverFingerprint)) {
return VerifyProxyApprovalResult.Failed(
VerifyProxyApprovalResult.Reason.NOT_TRUSTED,
)
}
if (now > request.expiresAt) {
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.EXPIRED)
}
val pubkey = try {
hexToBytes(approver.identityPublicKey)
} catch (_: Exception) {
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
}
val sig = try {
hexToBytes(approval.signature)
} catch (_: Exception) {
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
}
if (pubkey.size != 32 || sig.size != 64) {
return VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
}
val payload = canonicalApprovalSigningBytes(
domain = approval.domain,
requestId = approval.requestId,
hostFingerprint = request.hostFingerprint,
requestingDeviceFingerprint = request.requestingDevice.fingerprint,
decision = approval.decision,
)
val ok = crypto.verify(pubkey, payload, sig)
return if (ok) VerifyProxyApprovalResult.Ok(approver)
else VerifyProxyApprovalResult.Failed(VerifyProxyApprovalResult.Reason.BAD_SIGNATURE)
}
/**
* Build the canonical signing payload bytes for a proxy approval.
*
* Format (length-prefixed UTF-8, big-endian u16 lengths):
*
* u16(len(domain)) || domain
* u16(len(requestId)) || requestId
* u16(len(hostFp)) || hostFingerprint
* u16(len(requestFp)) || requestingDeviceFingerprint
* u16(len(decision)) || decision
*
* This is the EXACT byte layout `@shade/sdk`'s
* `canonicalApprovalSigningBytes` produces, ensuring an Android-signed
* approval verifies on a TS host and vice versa.
*/
fun canonicalApprovalSigningBytes(
domain: String,
requestId: String,
hostFingerprint: String,
requestingDeviceFingerprint: String,
decision: String,
): ByteArray {
val fields = listOf(
domain.toByteArray(Charsets.UTF_8),
requestId.toByteArray(Charsets.UTF_8),
hostFingerprint.toByteArray(Charsets.UTF_8),
requestingDeviceFingerprint.toByteArray(Charsets.UTF_8),
decision.toByteArray(Charsets.UTF_8),
)
for (f in fields) {
require(f.size <= 0xFFFF) { "signing field too long: ${f.size} bytes (max 65535)" }
}
val total = fields.sumOf { 2 + it.size }
val buf = ByteBuffer.allocate(total).order(ByteOrder.BIG_ENDIAN)
for (f in fields) {
buf.putShort(f.size.toShort())
buf.put(f)
}
return buf.array()
}
private fun hexToBytes(hex: String): ByteArray {
require(hex.length % 2 == 0) { "hex length must be even" }
require(hex.all { it.isDigit() || it in 'a'..'f' }) { "hex must be lowercase 0-9a-f" }
val out = ByteArray(hex.length / 2)
for (i in out.indices) {
out[i] = ((Character.digit(hex[i * 2], 16) shl 4) +
Character.digit(hex[i * 2 + 1], 16)).toByte()
}
return out
}

View File

@@ -0,0 +1,307 @@
package no.zyon.shade.approval
import org.json.JSONArray
import org.json.JSONObject
/**
* V4.10 — canonical profile-blob schema. Mirror
* `@shade/sdk/approval.ts` byte-for-byte: same field names, same
* JSON shape, same denormalization invariants.
*
* The blob is the AEAD plaintext stored in the V4.9 profile slot. It
* holds the user's list of paired hosts + clients; cross-host
* approval routing reads `clients[]` to find trusted approvers when
* a headless host needs to dispatch a `linkRequest` to a phone.
*
* Mutators (`upsertHost`, `setTrustedApprover`, ...) are immutable —
* they return a new blob and never modify the input. The denormalized
* `trustedApproverFingerprints[]` is rederived on every mutation so it
* can never drift from the per-client `trustedApprover` flag.
*/
/** A host: a device that receives `linkRequest` frames and runs pairing. */
data class ProfileHostEntry(
val address: String,
val name: String,
/** Open enum: `"desktop" | "server" | "laptop" | ...`. */
val kind: String,
val addedAt: Long,
)
/**
* A client: a device that initiates link/approval flows and may
* proxy-approve when `trustedApprover == true`. Stores both the
* 32-byte Ed25519 identity public key (hex) and the safety-number
* fingerprint — the public key is what `verifyProxyApproval` checks
* signatures against; the fingerprint is what UIs display.
*/
data class ProfileClientEntry(
val address: String,
/** 32-byte Ed25519 long-term identity public key, lowercase hex (64 chars). */
val identityPublicKey: String,
/** Safety-number fingerprint of the identity key (computeFingerprint output). */
val identityFingerprint: String,
val name: String,
/** Open enum: `"mobile" | "tablet" | "browser" | ...`. */
val kind: String,
val addedAt: Long,
val trustedApprover: Boolean = false,
)
/**
* Canonical profile blob. `version=1` is the only currently-supported
* shape; bump when an incompatible field is added. Unknown top-level
* fields are dropped on parse — additive changes need a coordinated
* schema bump on both platforms.
*/
data class CanonicalProfileBlob(
val version: Int = 1,
val hosts: List<ProfileHostEntry> = emptyList(),
val clients: List<ProfileClientEntry> = emptyList(),
/** Denormalized list of trusted-approver fingerprints. Rederived on mutate. */
val trustedApproverFingerprints: List<String> = emptyList(),
val updatedAt: Long = 0,
/** Optional hex-encoded pubkey of the writer; informational only. */
val signedBy: String? = null,
)
/** Build a fresh empty profile blob with `updatedAt = now ?? System.currentTimeMillis()`. */
fun emptyCanonicalProfile(now: Long? = null): CanonicalProfileBlob =
CanonicalProfileBlob(updatedAt = now ?: System.currentTimeMillis())
/**
* Decode a profile-blob plaintext (the AEAD-opened bytes) into the
* canonical shape. Throws `IllegalArgumentException` on malformed JSON
* or wrong shape.
*/
fun parseCanonicalProfile(plaintext: ByteArray): CanonicalProfileBlob =
parseCanonicalProfile(plaintext.toString(Charsets.UTF_8))
fun parseCanonicalProfile(plaintext: String): CanonicalProfileBlob {
val obj = try {
JSONObject(plaintext)
} catch (e: Exception) {
throw IllegalArgumentException("profile blob is not valid JSON: ${e.message}")
}
val version = obj.optInt("version", -1)
require(version == 1) { "unsupported profile blob version: $version" }
val hosts = parseArray(obj.optJSONArray("hosts"), "hosts", ::parseHostEntry)
val clients = parseArray(obj.optJSONArray("clients"), "clients", ::parseClientEntry)
val trustedApproverFingerprints = parseStringArray(
obj.optJSONArray("trustedApproverFingerprints"),
"trustedApproverFingerprints",
)
val updatedAt = if (obj.has("updatedAt") && !obj.isNull("updatedAt"))
obj.getLong("updatedAt") else 0L
val signedBy = obj.optString("signedBy", "").takeIf { it.isNotEmpty() }
return CanonicalProfileBlob(
version = 1,
hosts = hosts,
clients = clients,
trustedApproverFingerprints = trustedApproverFingerprints,
updatedAt = updatedAt,
signedBy = signedBy,
)
}
/** Serialize a profile blob to UTF-8 JSON ready for `Profile.put`. */
fun serializeCanonicalProfile(blob: CanonicalProfileBlob): ByteArray {
val json = JSONObject()
json.put("version", blob.version)
json.put("hosts", JSONArray().apply {
blob.hosts.forEach { put(hostEntryToJson(it)) }
})
json.put("clients", JSONArray().apply {
blob.clients.forEach { put(clientEntryToJson(it)) }
})
json.put("trustedApproverFingerprints", JSONArray(blob.trustedApproverFingerprints))
json.put("updatedAt", blob.updatedAt)
if (blob.signedBy != null) json.put("signedBy", blob.signedBy)
return json.toString().toByteArray(Charsets.UTF_8)
}
private fun parseHostEntry(o: JSONObject): ProfileHostEntry =
ProfileHostEntry(
address = o.requireString("address", "hosts"),
name = o.requireString("name", "hosts"),
kind = o.requireString("kind", "hosts"),
addedAt = o.requireLong("addedAt", "hosts"),
)
private fun parseClientEntry(o: JSONObject): ProfileClientEntry {
val identityPublicKey = o.requireString("identityPublicKey", "clients")
require(identityPublicKey.matches(Regex("^[0-9a-f]{64}$"))) {
"clients[].identityPublicKey must be 64 lowercase hex chars"
}
return ProfileClientEntry(
address = o.requireString("address", "clients"),
identityPublicKey = identityPublicKey,
identityFingerprint = o.requireString("identityFingerprint", "clients"),
name = o.requireString("name", "clients"),
kind = o.requireString("kind", "clients"),
addedAt = o.requireLong("addedAt", "clients"),
trustedApprover = o.optBoolean("trustedApprover", false),
)
}
private fun hostEntryToJson(e: ProfileHostEntry): JSONObject = JSONObject().apply {
put("address", e.address)
put("name", e.name)
put("kind", e.kind)
put("addedAt", e.addedAt)
}
private fun clientEntryToJson(e: ProfileClientEntry): JSONObject = JSONObject().apply {
put("address", e.address)
put("identityPublicKey", e.identityPublicKey)
put("identityFingerprint", e.identityFingerprint)
put("name", e.name)
put("kind", e.kind)
put("addedAt", e.addedAt)
if (e.trustedApprover) put("trustedApprover", true)
}
private fun <T> parseArray(
arr: JSONArray?,
field: String,
parse: (JSONObject) -> T,
): List<T> {
if (arr == null) return emptyList()
return (0 until arr.length()).map { i ->
val item = arr.opt(i)
require(item is JSONObject) { "$field[$i] must be an object" }
parse(item)
}
}
private fun parseStringArray(arr: JSONArray?, field: String): List<String> {
if (arr == null) return emptyList()
return (0 until arr.length()).map { i ->
val item = arr.opt(i)
require(item is String) { "$field[$i] must be a string" }
item
}
}
private fun JSONObject.requireString(key: String, ctx: String): String {
require(has(key) && !isNull(key)) { "$ctx[].$key is required" }
val v = get(key)
require(v is String) { "$ctx[].$key must be a string" }
return v
}
private fun JSONObject.requireLong(key: String, ctx: String): Long {
require(has(key) && !isNull(key)) { "$ctx[].$key is required" }
return when (val v = get(key)) {
is Number -> v.toLong()
else -> throw IllegalArgumentException("$ctx[].$key must be a number")
}
}
// ─── Mutators (immutable; return new blob, never mutate input) ──
/** Insert or replace a host entry by address. Bumps `updatedAt`. */
fun upsertHost(
blob: CanonicalProfileBlob,
host: ProfileHostEntry,
now: Long? = null,
): CanonicalProfileBlob {
val hosts = blob.hosts.filter { it.address != host.address } + host
return blob.copy(hosts = hosts, updatedAt = now ?: System.currentTimeMillis())
}
/** Remove the host with the given address, if any. */
fun removeHost(
blob: CanonicalProfileBlob,
address: String,
now: Long? = null,
): CanonicalProfileBlob {
val hosts = blob.hosts.filter { it.address != address }
if (hosts.size == blob.hosts.size) return blob
return blob.copy(hosts = hosts, updatedAt = now ?: System.currentTimeMillis())
}
/**
* Insert or replace a client entry by `identityFingerprint`. Re-derives
* `trustedApproverFingerprints` from the resulting `clients[]` so the
* denormalized list never drifts.
*/
fun upsertClient(
blob: CanonicalProfileBlob,
client: ProfileClientEntry,
now: Long? = null,
): CanonicalProfileBlob {
val clients = blob.clients
.filter { it.identityFingerprint != client.identityFingerprint } + client
return blob.copy(
clients = clients,
trustedApproverFingerprints = deriveTrustedApprovers(clients),
updatedAt = now ?: System.currentTimeMillis(),
)
}
/** Remove the client with the given identityFingerprint, if any. */
fun removeClient(
blob: CanonicalProfileBlob,
identityFingerprint: String,
now: Long? = null,
): CanonicalProfileBlob {
val clients = blob.clients.filter { it.identityFingerprint != identityFingerprint }
if (clients.size == blob.clients.size) return blob
return blob.copy(
clients = clients,
trustedApproverFingerprints = deriveTrustedApprovers(clients),
updatedAt = now ?: System.currentTimeMillis(),
)
}
/**
* Toggle the `trustedApprover` flag on a client by fingerprint.
* Returns the input unchanged if fingerprint isn't found OR the
* desired state already matches (no spurious updatedAt bump).
*/
fun setTrustedApprover(
blob: CanonicalProfileBlob,
identityFingerprint: String,
trusted: Boolean,
now: Long? = null,
): CanonicalProfileBlob {
var touched = false
val clients = blob.clients.map { c ->
if (c.identityFingerprint != identityFingerprint) c
else if (c.trustedApprover == trusted) c
else {
touched = true
c.copy(trustedApprover = trusted)
}
}
if (!touched) return blob
return blob.copy(
clients = clients,
trustedApproverFingerprints = deriveTrustedApprovers(clients),
updatedAt = now ?: System.currentTimeMillis(),
)
}
/**
* True iff the given fingerprint resolves to a client with both
* `trustedApprover == true` AND an entry in `trustedApproverFingerprints[]`.
*/
fun isTrustedApprover(blob: CanonicalProfileBlob, identityFingerprint: String): Boolean {
if (!blob.trustedApproverFingerprints.contains(identityFingerprint)) return false
val c = findClientByFingerprint(blob, identityFingerprint) ?: return false
return c.trustedApprover
}
fun findClientByFingerprint(
blob: CanonicalProfileBlob,
identityFingerprint: String,
): ProfileClientEntry? = blob.clients.firstOrNull { it.identityFingerprint == identityFingerprint }
fun findClientByAddress(blob: CanonicalProfileBlob, address: String): ProfileClientEntry? =
blob.clients.firstOrNull { it.address == address }
private fun deriveTrustedApprovers(clients: List<ProfileClientEntry>): List<String> =
clients.filter { it.trustedApprover }.map { it.identityFingerprint }

View File

@@ -0,0 +1,94 @@
package no.zyon.shade.blob
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/**
* AEAD wrapper for the V4.9 profile blob.
*
* Wire format for one ciphertext blob:
* `nonce(12) || ciphertext(N) || tag(16)`
*
* Mirror `@shade/storage-encrypted/crypto/aead.ts` byte-for-byte. The
* relay stores this as a single opaque BLOB column; AAD is reconstructed
* at read-time as `"shade-profile-aad-v1:" + slotIdHex` and is NOT
* stored on the relay.
*/
const val BLOB_AEAD_NONCE_LEN = 12
const val BLOB_AEAD_TAG_LEN = 16
private const val MIN_CIPHERTEXT_LEN = BLOB_AEAD_NONCE_LEN + BLOB_AEAD_TAG_LEN
/**
* Seal a plaintext blob. Returns `nonce || ct||tag` ready for direct
* blob storage. The caller supplies the nonce so this function is
* deterministic — the high-level Profile namespace generates a fresh
* 12-byte random nonce per write to keep (key, nonce, plaintext)
* unique across re-uploads.
*/
fun aeadSeal(
key: ByteArray,
nonce: ByteArray,
plaintext: ByteArray,
aad: ByteArray,
): ByteArray {
require(key.size == 32) { "AES-256-GCM key must be 32 bytes" }
require(nonce.size == BLOB_AEAD_NONCE_LEN) {
"nonce must be $BLOB_AEAD_NONCE_LEN bytes"
}
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(128, nonce)
cipher.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), spec)
cipher.updateAAD(aad)
val ctTag = cipher.doFinal(plaintext)
val out = ByteArray(BLOB_AEAD_NONCE_LEN + ctTag.size)
System.arraycopy(nonce, 0, out, 0, BLOB_AEAD_NONCE_LEN)
System.arraycopy(ctTag, 0, out, BLOB_AEAD_NONCE_LEN, ctTag.size)
return out
}
/**
* Open a `nonce || ct||tag` blob and return the plaintext. Throws on
* tamper (AEAD tag mismatch) or short input. The caller may pass an
* `expectedNonce` to enforce a deterministic nonce — mismatch throws
* before the AEAD even runs (defense-in-depth against a relay returning
* the wrong slot's blob).
*/
fun aeadOpen(
key: ByteArray,
blob: ByteArray,
aad: ByteArray,
expectedNonce: ByteArray? = null,
): ByteArray {
require(key.size == 32) { "AES-256-GCM key must be 32 bytes" }
require(blob.size >= MIN_CIPHERTEXT_LEN) { "ciphertext blob too short" }
val nonce = blob.copyOfRange(0, BLOB_AEAD_NONCE_LEN)
if (expectedNonce != null && !ctEqual(nonce, expectedNonce)) {
throw IllegalArgumentException(
"nonce mismatch — ciphertext blob has been tampered or row identity changed",
)
}
val ctTag = blob.copyOfRange(BLOB_AEAD_NONCE_LEN, blob.size)
val cipher = Cipher.getInstance("AES/GCM/NoPadding")
val spec = GCMParameterSpec(128, nonce)
cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), spec)
cipher.updateAAD(aad)
return cipher.doFinal(ctTag)
}
private fun ctEqual(a: ByteArray, b: ByteArray): Boolean {
if (a.size != b.size) return false
var diff = 0
for (i in a.indices) {
diff = diff or (a[i].toInt() xor b[i].toInt())
}
return diff == 0
}
/** Build the AAD for a given slotId hex string. */
fun blobAadForSlot(slotIdHex: String): ByteArray {
require(slotIdHex.length == 64) { "slotIdHex must be 64 hex chars" }
return "shade-profile-aad-v1:$slotIdHex".toByteArray(Charsets.UTF_8)
}

View File

@@ -0,0 +1,195 @@
package no.zyon.shade.blob
import no.zyon.shade.crypto.CryptoProvider
import no.zyon.shade.serialization.canonicalJson
import org.json.JSONObject
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse
import java.time.Duration
import java.util.Base64
/**
* Low-level HTTP client for the V4.9 encrypted-blob primitive
* (`/v1/blob/<slotId>`). Mirror `@shade/inbox`'s `BlobClient` —
* stateless, reusable, and protocol-compatible with the TypeScript
* relay endpoints.
*
* The client doesn't care what the blob bytes mean — it just
* transports them. Higher-level wrappers (e.g. `Profile`) compose
* this client with AEAD-sealing of the actual payload.
*
* Auth model: every PUT/DELETE carries a detached Ed25519 signature
* (base64) over a canonical-JSON form of the request body. The
* canonicalization is deterministic — sorted keys, compact JSON, no
* trailing whitespace — so signatures generated on Kotlin verify on
* the TS server.
*/
class BlobClient(
private val baseUrl: String,
private val crypto: CryptoProvider,
private val httpClient: HttpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(15))
.build(),
) {
data class GetResult(
val blob: ByteArray,
val etag: String,
val updatedAt: Long,
)
data class PutResult(
val created: Boolean,
val etag: String,
val updatedAt: Long,
)
/**
* Read a slot. Returns null if no blob has ever been written there
* (or if it was DELETE'd). GET is unauthenticated by design — the
* slotId is itself a 256-bit secret derived from the master key.
*/
fun get(slotIdHex: String): GetResult? {
validateSlotIdHex(slotIdHex)
val req = HttpRequest.newBuilder(URI.create(joinUrl(baseUrl, "/v1/blob/$slotIdHex")))
.GET()
.build()
val res = httpClient.send(req, HttpResponse.BodyHandlers.ofString())
if (res.statusCode() == 404) return null
val json = parseJson(res, "GET")
val blob = Base64.getDecoder().decode(json.getString("blob"))
return GetResult(
blob = blob,
etag = json.getString("etag"),
updatedAt = json.getLong("updatedAt"),
)
}
/**
* Create or update a slot.
*
* `ifMatch` semantics:
* - `null`: create-only. Slot must be empty (else 409).
* - `<etag-string>`: compare-and-swap. Must match (else 412).
* - `"*"`: unconditional overwrite. Slot must already exist (else 412).
*/
fun put(
slotIdHex: String,
blob: ByteArray,
signingSeed: ByteArray,
ownerPubkey: ByteArray,
ifMatch: String? = null,
): PutResult {
validateSlotIdHex(slotIdHex)
require(blob.isNotEmpty()) { "Empty blob" }
require(ownerPubkey.size == 32) { "ownerPubkey must be 32 bytes (Ed25519)" }
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
// Canonical form for signing: sorted keys, slotId included,
// signature field absent. The wire body strips slotId (it's
// in the URL) but the signature is computed over the
// slotId-bearing form.
val signedAt = System.currentTimeMillis()
val canonical = sortedMapOf<String, Any>().apply {
put("blob", Base64.getEncoder().encodeToString(blob))
if (ifMatch != null) put("ifMatch", ifMatch)
put("ownerPubkey", Base64.getEncoder().encodeToString(ownerPubkey))
put("signedAt", signedAt)
put("slotId", slotIdHex)
}
val canonicalBytes = canonicalJson(canonical).toByteArray(Charsets.UTF_8)
val sig = crypto.sign(signingSeed, canonicalBytes)
// Wire body: same as canonical minus slotId, plus signature.
val wire = JSONObject()
wire.put("blob", Base64.getEncoder().encodeToString(blob))
if (ifMatch != null) wire.put("ifMatch", ifMatch)
wire.put("ownerPubkey", Base64.getEncoder().encodeToString(ownerPubkey))
wire.put("signedAt", signedAt)
wire.put("signature", Base64.getEncoder().encodeToString(sig))
val req = HttpRequest.newBuilder(URI.create(joinUrl(baseUrl, "/v1/blob/$slotIdHex")))
.header("content-type", "application/json")
.PUT(HttpRequest.BodyPublishers.ofString(wire.toString()))
.build()
val res = httpClient.send(req, HttpResponse.BodyHandlers.ofString())
val json = parseJson(res, "PUT")
return PutResult(
created = json.optBoolean("created"),
etag = json.getString("etag"),
updatedAt = json.getLong("updatedAt"),
)
}
/**
* Delete a slot. The next PUT TOFU-claims it again, possibly under
* a fresh signing key (e.g. after rotation). Used by "forget
* everything" flows.
*/
fun delete(slotIdHex: String, signingSeed: ByteArray): Boolean {
validateSlotIdHex(slotIdHex)
require(signingSeed.size == 32) { "signingSeed must be 32 bytes (Ed25519)" }
val signedAt = System.currentTimeMillis()
val canonical = sortedMapOf<String, Any>().apply {
put("signedAt", signedAt)
put("slotId", slotIdHex)
}
val canonicalBytes = canonicalJson(canonical).toByteArray(Charsets.UTF_8)
val sig = crypto.sign(signingSeed, canonicalBytes)
val wire = JSONObject()
wire.put("signedAt", signedAt)
wire.put("signature", Base64.getEncoder().encodeToString(sig))
val req = HttpRequest.newBuilder(URI.create(joinUrl(baseUrl, "/v1/blob/$slotIdHex")))
.header("content-type", "application/json")
.method("DELETE", HttpRequest.BodyPublishers.ofString(wire.toString()))
.build()
val res = httpClient.send(req, HttpResponse.BodyHandlers.ofString())
val json = parseJson(res, "DELETE")
return json.optBoolean("ok", false)
}
private fun parseJson(res: HttpResponse<String>, op: String): JSONObject {
val text = res.body() ?: ""
val json = if (text.isEmpty()) JSONObject() else try {
JSONObject(text)
} catch (e: Exception) {
throw BlobClientException(
code = "SHADE_NETWORK",
statusCode = res.statusCode(),
message = "Blob $op response not JSON: ${text.take(200)}",
)
}
if (res.statusCode() !in 200..299) {
throw BlobClientException(
code = json.optString("code", "SHADE_NETWORK"),
statusCode = res.statusCode(),
message = json.optString("message", text),
)
}
return json
}
private fun validateSlotIdHex(s: String) {
require(s.matches(Regex("^[0-9a-f]{64}$"))) {
"slotIdHex must be 64 lowercase hex chars (32 bytes)"
}
}
private fun joinUrl(base: String, path: String): String =
when {
base.endsWith("/") && path.startsWith("/") -> base + path.substring(1)
!base.endsWith("/") && !path.startsWith("/") -> "$base/$path"
else -> base + path
}
}
class BlobClientException(
val code: String,
val statusCode: Int,
message: String,
) : RuntimeException("[$code @ $statusCode] $message")

View File

@@ -0,0 +1,95 @@
package no.zyon.shade.blob
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters
import no.zyon.shade.crypto.CryptoProvider
/**
* V4.9 — relay-side encrypted blob primitive: deterministic
* derivations from a 32-byte master key + per-app namespace string.
*
* Mirror `@shade/storage-encrypted/crypto/kdf.ts` byte-for-byte.
* Reference vectors: `test-vectors/blob-storage.json`.
*
* Three independent 32-byte derivations:
*
* slotId = HKDF(masterKey, info=`shade-blob-slot-v1:<app>`) // relay-visible opaque ID
* blobKey = HKDF(masterKey, info=`shade-blob-key-v1:<app>`) // AEAD key for the blob
* sigSeed = HKDF(masterKey, info=`shade-blob-sig-v1:<app>`) // Ed25519 owner signing seed
*
* `app` is a caller-supplied namespace string — distinct apps under
* the same master MUST pass different values (e.g. `prism-profile-v1`)
* so they don't collide on the same slot.
*
* The signing seed is an Ed25519 *seed* in the @noble/curves convention:
* `pubkey = Ed25519.publicFromSeed(seed)` is what the relay TOFU-stores
* on the first PUT and verifies subsequent writes against.
*/
private const val SLOT_INFO_PREFIX = "shade-blob-slot-v1:"
private const val BLOB_KEY_INFO_PREFIX = "shade-blob-key-v1:"
private const val SIG_SEED_INFO_PREFIX = "shade-blob-sig-v1:"
private const val DERIVED_LEN = 32
/** Lower-hex 64-char slotId derived deterministically from the master key. */
fun deriveBlobSlotId(crypto: CryptoProvider, masterKey: ByteArray, app: String): ByteArray {
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
require(app.isNotEmpty()) { "app namespace must be non-empty" }
return crypto.hkdf(
masterKey,
ByteArray(0),
(SLOT_INFO_PREFIX + app).toByteArray(Charsets.UTF_8),
DERIVED_LEN,
)
}
/** AEAD key for sealing/opening the blob. The slotId hex is bound as AAD. */
fun deriveBlobKey(crypto: CryptoProvider, masterKey: ByteArray, app: String): ByteArray {
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
require(app.isNotEmpty()) { "app namespace must be non-empty" }
return crypto.hkdf(
masterKey,
ByteArray(0),
(BLOB_KEY_INFO_PREFIX + app).toByteArray(Charsets.UTF_8),
DERIVED_LEN,
)
}
/**
* 32-byte Ed25519 signing seed. The pubkey, derived deterministically
* from the seed, is what the relay TOFU-stores on the first PUT.
*/
fun deriveBlobSigningSeed(crypto: CryptoProvider, masterKey: ByteArray, app: String): ByteArray {
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
require(app.isNotEmpty()) { "app namespace must be non-empty" }
return crypto.hkdf(
masterKey,
ByteArray(0),
(SIG_SEED_INFO_PREFIX + app).toByteArray(Charsets.UTF_8),
DERIVED_LEN,
)
}
/**
* Recover the Ed25519 public key from a 32-byte seed. Mirrors
* `@shade/crypto-web`'s `ed25519PublicKeyFromSeed`.
*
* BouncyCastle rather than Tink, although the rest of the module signs with
* Tink: this is the one primitive the vault and blob code use OUTSIDE the
* injected [CryptoProvider], so whatever it calls is a hard dependency of
* every app that reads a vault. An Android app cannot take JVM Tink (it
* drags in full `protobuf-java`, which collides with Firebase's
* `protobuf-javalite`), while BouncyCastle is already here for scrypt and
* already in every app that embeds this module. RFC 8032 fixes the result,
* so the two produce the same bytes — the blob and vault vectors pin it.
*/
fun ed25519PublicKeyFromSeed(seed: ByteArray): ByteArray {
require(seed.size == 32) { "Ed25519 seed must be 32 bytes" }
return Ed25519PrivateKeyParameters(seed, 0).generatePublicKey().encoded
}
/** Convert a 32-byte slotId into the lowercase-hex wire form (64 chars). */
fun slotIdToHex(slotId: ByteArray): String {
require(slotId.size == 32) { "slotId must be 32 bytes" }
return slotId.joinToString("") { "%02x".format(it) }
}

View File

@@ -0,0 +1,118 @@
package no.zyon.shade.blob
import no.zyon.shade.crypto.CryptoProvider
/**
* V4.9 — high-level profile namespace. Mirror
* `@shade/sdk`'s `createProfileNamespace`. The relay never sees
* plaintext; AAD binds the slotId so a relay returning the wrong
* slot's blob fails to open.
*
* Usage:
*
* val crypto = TinkProvider()
* val masterKey = deriveMasterKey("password", salt) // V4.5 KDF chain
* val profile = createProfileNamespace(
* baseUrl = "https://shade.example/",
* crypto = crypto,
* masterKey = masterKey,
* app = "prism-profile-v1",
* )
*
* val current = profile.get() // null if no blob yet
* profile.put(serializeCanonicalProfile(...), ifMatch = current?.etag)
* profile.delete()
*
* Apps with the same master key + app namespace converge on the same
* slot — that's the whole point: a brand new device with the right
* credentials can locate, decrypt, and update the blob.
*/
class ProfileNamespace internal constructor(
/** Lower-hex 64-char slotId. Stable per (master, app). */
val slotIdHex: String,
private val blobKey: ByteArray,
private val signingSeed: ByteArray,
private val ownerPubkey: ByteArray,
private val aad: ByteArray,
private val client: BlobClient,
private val crypto: CryptoProvider,
) {
data class GetResult(
val plaintext: ByteArray,
val etag: String,
val updatedAt: Long,
)
data class PutResult(
val created: Boolean,
val etag: String,
val updatedAt: Long,
)
/** Returns null when the slot has never been written (or was deleted). */
fun get(): GetResult? {
val raw = client.get(slotIdHex) ?: return null
val plaintext = aeadOpen(blobKey, raw.blob, aad)
return GetResult(plaintext = plaintext, etag = raw.etag, updatedAt = raw.updatedAt)
}
/**
* Create or update. `ifMatch`:
* - null: create-only (fails with 409 if slot populated).
* - "<etag>": CAS (fails with 412 on stale).
* - "*": unconditional overwrite.
*/
fun put(plaintext: ByteArray, ifMatch: String? = null): PutResult {
// Fresh random nonce per write — see `BlobAead`. Re-uploading
// the same plaintext after a transient error reuses neither
// (key, nonce, plaintext) nor (key, nonce).
val nonce = crypto.randomBytes(BLOB_AEAD_NONCE_LEN)
val sealed = aeadSeal(blobKey, nonce, plaintext, aad)
val r = client.put(
slotIdHex = slotIdHex,
blob = sealed,
signingSeed = signingSeed,
ownerPubkey = ownerPubkey,
ifMatch = ifMatch,
)
return PutResult(created = r.created, etag = r.etag, updatedAt = r.updatedAt)
}
/** "Forget everything" path — the next PUT TOFU-claims it again. */
fun delete(): Boolean = client.delete(slotIdHex, signingSeed)
}
/**
* Build a Profile namespace bound to a (master key, app) pair. The
* derivations are deterministic: any device with the same master
* key + app namespace produces the same slot, so a fresh device
* after credential entry can locate the existing profile blob.
*/
fun createProfileNamespace(
baseUrl: String,
crypto: CryptoProvider,
masterKey: ByteArray,
app: String,
): ProfileNamespace {
require(masterKey.size == 32) { "masterKey must be 32 bytes" }
require(app.isNotEmpty()) { "app namespace must be non-empty" }
val slotIdBytes = deriveBlobSlotId(crypto, masterKey, app)
val slotIdHex = slotIdToHex(slotIdBytes)
val blobKey = deriveBlobKey(crypto, masterKey, app)
val signingSeed = deriveBlobSigningSeed(crypto, masterKey, app)
val ownerPubkey = ed25519PublicKeyFromSeed(signingSeed)
val aad = blobAadForSlot(slotIdHex)
val client = BlobClient(baseUrl = baseUrl, crypto = crypto)
return ProfileNamespace(
slotIdHex = slotIdHex,
blobKey = blobKey,
signingSeed = signingSeed,
ownerPubkey = ownerPubkey,
aad = aad,
client = client,
crypto = crypto,
)
}

View File

@@ -0,0 +1,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,133 @@
package no.zyon.shade.serialization
import no.zyon.shade.types.ChainState
import no.zyon.shade.types.IdentityKeyPair
import no.zyon.shade.types.KeyPair
import no.zyon.shade.types.OneTimePreKey
import no.zyon.shade.types.SessionState
import no.zyon.shade.types.SignedPreKey
import org.json.JSONObject
import java.util.Base64 as JdkBase64
/**
* Plain-JSON serialization for the persisted protocol state types
* (`IdentityKeyPair`, `SignedPreKey`, `OneTimePreKey`, `SessionState`).
*
* The on-disk shape is for at-rest storage only — it does NOT need
* to round-trip across platforms (TS uses its own JSON shape via
* `@shade/core/serialization`). What matters is that the Kotlin
* round-trip (`serialize` then `deserialize`) preserves every byte.
*
* Both Android-targeted (`shade-android-keystore`) and pure-JVM
* (`shade-android` tests) callers use this — the function works
* without any `android.*` imports so it compiles in both.
*/
object SessionStateJson {
fun serialize(state: SessionState): String {
val o = JSONObject()
o.put("remoteIdentityKey", b64(state.remoteIdentityKey))
o.put("rootKey", b64(state.rootKey))
o.put("sendChain", chainToJson(state.sendChain))
if (state.receiveChain != null) o.put("receiveChain", chainToJson(state.receiveChain!!))
o.put("dhSend", keyPairToJson(state.dhSend))
if (state.dhReceive != null) o.put("dhReceive", b64(state.dhReceive!!))
o.put("previousSendCounter", state.previousSendCounter)
val skipped = JSONObject()
for ((k, v) in state.skippedKeys) skipped.put(k, b64(v))
o.put("skippedKeys", skipped)
return o.toString()
}
fun deserialize(s: String): SessionState {
val o = JSONObject(s)
val skipped = mutableMapOf<String, ByteArray>()
val skJson = o.optJSONObject("skippedKeys")
if (skJson != null) {
val it = skJson.keys()
while (it.hasNext()) {
val k = it.next()
skipped[k] = fb64(skJson.getString(k))
}
}
return SessionState(
remoteIdentityKey = fb64(o.getString("remoteIdentityKey")),
rootKey = fb64(o.getString("rootKey")),
sendChain = chainFromJson(o.getJSONObject("sendChain")),
receiveChain = if (o.has("receiveChain"))
chainFromJson(o.getJSONObject("receiveChain")) else null,
dhSend = keyPairFromJson(o.getJSONObject("dhSend")),
dhReceive = if (o.has("dhReceive")) fb64(o.getString("dhReceive")) else null,
previousSendCounter = o.getInt("previousSendCounter"),
skippedKeys = skipped,
)
}
fun serializeIdentityKeyPair(k: IdentityKeyPair): String = JSONObject().apply {
put("signingPublicKey", b64(k.signingPublicKey))
put("signingPrivateKey", b64(k.signingPrivateKey))
put("dhPublicKey", b64(k.dhPublicKey))
put("dhPrivateKey", b64(k.dhPrivateKey))
}.toString()
fun deserializeIdentityKeyPair(s: String): IdentityKeyPair = JSONObject(s).run {
IdentityKeyPair(
signingPublicKey = fb64(getString("signingPublicKey")),
signingPrivateKey = fb64(getString("signingPrivateKey")),
dhPublicKey = fb64(getString("dhPublicKey")),
dhPrivateKey = fb64(getString("dhPrivateKey")),
)
}
fun serializeSignedPreKey(k: SignedPreKey): String = JSONObject().apply {
put("keyId", k.keyId)
put("keyPair", keyPairToJson(k.keyPair))
put("signature", b64(k.signature))
put("timestamp", k.timestamp)
}.toString()
fun deserializeSignedPreKey(s: String): SignedPreKey = JSONObject(s).run {
SignedPreKey(
keyId = getInt("keyId"),
keyPair = keyPairFromJson(getJSONObject("keyPair")),
signature = fb64(getString("signature")),
timestamp = getLong("timestamp"),
)
}
fun serializeOneTimePreKey(k: OneTimePreKey): String = JSONObject().apply {
put("keyId", k.keyId)
put("keyPair", keyPairToJson(k.keyPair))
}.toString()
fun deserializeOneTimePreKey(s: String): OneTimePreKey = JSONObject(s).run {
OneTimePreKey(
keyId = getInt("keyId"),
keyPair = keyPairFromJson(getJSONObject("keyPair")),
)
}
private fun chainToJson(c: ChainState): JSONObject = JSONObject().apply {
put("chainKey", b64(c.chainKey))
put("counter", c.counter)
}
private fun chainFromJson(o: JSONObject): ChainState =
ChainState(chainKey = fb64(o.getString("chainKey")), counter = o.getInt("counter"))
private fun keyPairToJson(k: KeyPair): JSONObject = JSONObject().apply {
put("publicKey", b64(k.publicKey))
put("privateKey", b64(k.privateKey))
}
private fun keyPairFromJson(o: JSONObject): KeyPair = KeyPair(
publicKey = fb64(o.getString("publicKey")),
privateKey = fb64(o.getString("privateKey")),
)
// android.util.Base64 isn't on the JVM classpath; java.util.Base64
// is available on both modern JVM and Android API 26+. Use JDK
// Base64 throughout — it's present on both targets.
private fun b64(b: ByteArray): String = JdkBase64.getEncoder().encodeToString(b)
private fun fb64(s: String): ByteArray = JdkBase64.getDecoder().decode(s)
}

View File

@@ -0,0 +1,107 @@
package no.zyon.shade.storage
import org.bouncycastle.crypto.generators.Argon2BytesGenerator
import org.bouncycastle.crypto.generators.SCrypt
import org.bouncycastle.crypto.params.Argon2Parameters
import java.text.Normalizer
/**
* Password / PIN key-derivation primitives. Mirror
* `@shade/storage-encrypted/crypto/kdf` (`deriveMasterKey` /
* `deriveMasterKeyArgon2id`) byte-for-byte — Tink doesn't ship password
* KDFs so we wrap Bouncy Castle.
*
* Both functions normalize string passphrases to NFKC before hashing,
* matching the TS implementation's `passphrase.normalize('NFKC')`.
* This ensures the same password typed on different OSes/keyboards
* produces the same master key regardless of which compatibility-form
* the input arrived in.
*
* The reference test-vector lives in `test-vectors/storage-encryption.json`
* and `test-vectors/blob-storage.json`. Cross-platform parity is gated
* by `CrossPlatformVectorTest`.
*/
/** scrypt parameters. Defaults match `DEFAULT_SCRYPT` in TS. */
data class ScryptParams(
/** CPU/memory cost. Must be a power of 2. */
val n: Int = 1 shl 17,
/** Block size. */
val r: Int = 8,
/** Parallelization. */
val p: Int = 1,
/** Output length in bytes. */
val dkLen: Int = 32,
)
/** Argon2id parameters. Defaults match `DEFAULT_ARGON2ID` in TS. */
data class Argon2idParams(
/** Memory cost in KiB. Default 64 MiB. */
val m: Int = 64 * 1024,
/** Time cost (iterations). Default 3. */
val t: Int = 3,
/** Parallelism. Default 1. */
val p: Int = 1,
/** Output length in bytes. Default 32. */
val dkLen: Int = 32,
)
/**
* Derive a 32-byte master key from a passphrase + salt via scrypt.
* Salt MUST be at least 16 bytes and persisted alongside the
* encrypted database. Throws on empty passphrase.
*/
fun deriveMasterKey(
passphrase: String,
salt: ByteArray,
params: ScryptParams = ScryptParams(),
): ByteArray {
require(passphrase.isNotEmpty()) { "passphrase must be non-empty" }
require(salt.size >= 16) { "salt must be at least 16 bytes" }
val nfkc = Normalizer.normalize(passphrase, Normalizer.Form.NFKC)
val pwBytes = nfkc.toByteArray(Charsets.UTF_8)
return SCrypt.generate(pwBytes, salt, params.n, params.r, params.p, params.dkLen)
}
/**
* Derive a 32-byte master key from a low-entropy secret (PIN) + salt
* via argon2id. Salt MUST be at least 16 bytes. The Bouncy Castle
* `Argon2BytesGenerator` parameters mirror RFC 9106's argon2id mode
* with version 1.3 (`Argon2Parameters.ARGON2_VERSION_13`), which is
* what `@noble/hashes/argon2` produces — keeping cross-platform parity.
*/
fun deriveMasterKeyArgon2id(
secret: String,
salt: ByteArray,
params: Argon2idParams = Argon2idParams(),
): ByteArray {
require(secret.isNotEmpty()) { "argon2id secret must be non-empty" }
require(salt.size >= 16) { "salt must be at least 16 bytes" }
val nfkc = Normalizer.normalize(secret, Normalizer.Form.NFKC)
return deriveMasterKeyArgon2id(nfkc.toByteArray(Charsets.UTF_8), salt, params)
}
/**
* Byte-array overload — useful when the secret is already binary
* (e.g. derived from a hardware token rather than typed) and
* shouldn't be NFKC-normalized as text.
*/
fun deriveMasterKeyArgon2id(
secret: ByteArray,
salt: ByteArray,
params: Argon2idParams = Argon2idParams(),
): ByteArray {
require(secret.isNotEmpty()) { "argon2id secret must be non-empty" }
require(salt.size >= 16) { "salt must be at least 16 bytes" }
val builder = Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
.withVersion(Argon2Parameters.ARGON2_VERSION_13)
.withIterations(params.t)
.withMemoryAsKB(params.m)
.withParallelism(params.p)
.withSalt(salt)
val gen = Argon2BytesGenerator()
gen.init(builder.build())
val out = ByteArray(params.dkLen)
gen.generateBytes(secret, out)
return out
}

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,593 @@
package no.zyon.shade
import no.zyon.shade.approval.ApprovalRequestFrame
import no.zyon.shade.approval.ApprovalRequestingDevice
import no.zyon.shade.approval.CanonicalProfileBlob
import no.zyon.shade.approval.DEFAULT_APPROVAL_DOMAIN
import no.zyon.shade.approval.ProfileClientEntry
import no.zyon.shade.approval.ProfileHostEntry
import no.zyon.shade.approval.ProxyApprovalFrame
import no.zyon.shade.approval.VerifyProxyApprovalResult
import no.zyon.shade.approval.buildApprovalRequest
import no.zyon.shade.approval.canonicalApprovalSigningBytes
import no.zyon.shade.approval.emptyCanonicalProfile
import no.zyon.shade.approval.findClientByAddress
import no.zyon.shade.approval.findClientByFingerprint
import no.zyon.shade.approval.isTrustedApprover
import no.zyon.shade.approval.parseCanonicalProfile
import no.zyon.shade.approval.removeClient
import no.zyon.shade.approval.serializeCanonicalProfile
import no.zyon.shade.approval.setTrustedApprover
import no.zyon.shade.approval.signProxyApproval
import no.zyon.shade.approval.upsertClient
import no.zyon.shade.approval.upsertHost
import no.zyon.shade.approval.verifyProxyApproval
import no.zyon.shade.blob.aeadOpen
import no.zyon.shade.blob.aeadSeal
import no.zyon.shade.blob.blobAadForSlot
import no.zyon.shade.blob.deriveBlobKey
import no.zyon.shade.blob.deriveBlobSigningSeed
import no.zyon.shade.blob.deriveBlobSlotId
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
import no.zyon.shade.blob.slotIdToHex
import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.storage.Argon2idParams
import no.zyon.shade.storage.ScryptParams
import no.zyon.shade.storage.deriveMasterKey
import no.zyon.shade.storage.deriveMasterKeyArgon2id
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertNotEquals
import org.junit.Assert.assertTrue
import org.junit.Test
/**
* Unit tests for the V4.9 blob primitive ports + V4.10 approval
* helpers + scrypt/argon2id wrappers. Cross-platform vector parity
* lives in `CrossPlatformVectorTest`; this file tests Kotlin-side
* round-trip behavior independent of the TS reference.
*/
class BlobAndApprovalTest {
private val crypto = TinkProvider()
private fun hex(bytes: ByteArray): String =
bytes.joinToString("") { "%02x".format(it) }
// ─── V4.9 blob KDF ─────────────────────────────────────────
@Test
fun deriveBlobSlotIdIsDeterministicPerMasterAndApp() {
val km = ByteArray(32) { it.toByte() }
val a1 = deriveBlobSlotId(crypto, km, "foo")
val a2 = deriveBlobSlotId(crypto, km, "foo")
assertArrayEquals(a1, a2)
val b = deriveBlobSlotId(crypto, km, "bar")
assertFalse(a1.contentEquals(b))
val km2 = ByteArray(32) { (it + 1).toByte() }
val c = deriveBlobSlotId(crypto, km2, "foo")
assertFalse(a1.contentEquals(c))
}
@Test
fun blobKdfHelpersAreIndependent() {
val km = ByteArray(32) { it.toByte() }
val slot = deriveBlobSlotId(crypto, km, "x")
val key = deriveBlobKey(crypto, km, "x")
val seed = deriveBlobSigningSeed(crypto, km, "x")
assertFalse(slot.contentEquals(key))
assertFalse(slot.contentEquals(seed))
assertFalse(key.contentEquals(seed))
}
@Test
fun ed25519PublicKeyFromSeedIsDeterministic() {
val seed = ByteArray(32) { it.toByte() }
val pk1 = ed25519PublicKeyFromSeed(seed)
val pk2 = ed25519PublicKeyFromSeed(seed)
assertArrayEquals(pk1, pk2)
assertEquals(32, pk1.size)
}
@Test
fun slotIdToHexProducesLowercase64Chars() {
val s = ByteArray(32) { 0xab.toByte() }
val hex = slotIdToHex(s)
assertEquals(64, hex.length)
assertEquals("a".repeat(0) + "ab".repeat(32), hex)
}
// ─── V4.9 AEAD round-trip ──────────────────────────────────
@Test
fun aeadSealOpenRoundTrip() {
val key = crypto.randomBytes(32)
val nonce = crypto.randomBytes(12)
val pt = "hello".toByteArray()
val aad = blobAadForSlot("00".repeat(32))
val sealed = aeadSeal(key, nonce, pt, aad)
val opened = aeadOpen(key, sealed, aad)
assertArrayEquals(pt, opened)
}
@Test
fun aeadOpenWithWrongAadFails() {
val key = crypto.randomBytes(32)
val nonce = crypto.randomBytes(12)
val pt = "hello".toByteArray()
val aad1 = blobAadForSlot("00".repeat(32))
val aad2 = blobAadForSlot("ff".repeat(32))
val sealed = aeadSeal(key, nonce, pt, aad1)
try {
aeadOpen(key, sealed, aad2)
org.junit.Assert.fail("expected AEAD to reject wrong AAD")
} catch (_: Exception) {
// expected
}
}
@Test
fun aeadOpenWithExpectedNonceMismatchFails() {
val key = crypto.randomBytes(32)
val nonce = crypto.randomBytes(12)
val wrongNonce = crypto.randomBytes(12)
val pt = "hello".toByteArray()
val aad = blobAadForSlot("00".repeat(32))
val sealed = aeadSeal(key, nonce, pt, aad)
try {
aeadOpen(key, sealed, aad, expectedNonce = wrongNonce)
org.junit.Assert.fail("expected expectedNonce check to reject")
} catch (_: IllegalArgumentException) {
// expected
}
}
// ─── Password KDFs ─────────────────────────────────────────
@Test
fun scryptDerivesDeterministically() {
val pw = "correct-horse-battery-staple"
val salt = ByteArray(16) { 0x42.toByte() }
val k1 = deriveMasterKey(pw, salt, ScryptParams(n = 1024))
val k2 = deriveMasterKey(pw, salt, ScryptParams(n = 1024))
assertArrayEquals(k1, k2)
assertEquals(32, k1.size)
}
@Test
fun argon2idDerivesDeterministically() {
val pw = "1234"
val salt = ByteArray(16) { 0x55.toByte() }
val k1 = deriveMasterKeyArgon2id(pw, salt, Argon2idParams(m = 256, t = 2))
val k2 = deriveMasterKeyArgon2id(pw, salt, Argon2idParams(m = 256, t = 2))
assertArrayEquals(k1, k2)
assertEquals(32, k1.size)
}
@Test
fun nfkcNormalizationMakesEquivalentInputsConverge() {
// "café" can be encoded either as 'c','a','f','é' (NFC) or
// 'c','a','f','e','́' (NFD). NFKC normalization on both
// should converge to the same bytes.
val nfc = "café"
val nfd = "café"
assertNotEquals(nfc, nfd)
val salt = ByteArray(16) { 1.toByte() }
val k1 = deriveMasterKey(nfc, salt, ScryptParams(n = 1024))
val k2 = deriveMasterKey(nfd, salt, ScryptParams(n = 1024))
assertArrayEquals(k1, k2)
}
// ─── Canonical profile schema ──────────────────────────────
private fun makeClient(name: String, trusted: Boolean = false): Pair<ProfileClientEntry, ByteArray> {
val seed = crypto.randomBytes(32)
val pubkey = ed25519PublicKeyFromSeed(seed)
val fp = "fp-$name-${hex(pubkey).take(8)}"
return ProfileClientEntry(
address = "device:$name",
identityPublicKey = hex(pubkey),
identityFingerprint = fp,
name = name,
kind = "mobile",
addedAt = 1_700_000_000_000L,
trustedApprover = trusted,
) to seed
}
private fun makeHost(): ProfileHostEntry = ProfileHostEntry(
address = "device:host-server",
name = "Server",
kind = "server",
addedAt = 1_700_000_000_000L,
)
@Test
fun emptyCanonicalProfileRoundTrips() {
val blob = emptyCanonicalProfile(now = 123L)
val bytes = serializeCanonicalProfile(blob)
val parsed = parseCanonicalProfile(bytes)
assertEquals(1, parsed.version)
assertTrue(parsed.hosts.isEmpty())
assertTrue(parsed.clients.isEmpty())
assertTrue(parsed.trustedApproverFingerprints.isEmpty())
assertEquals(123L, parsed.updatedAt)
}
@Test
fun upsertClientDenormalizesTrustedApprovers() {
var blob = emptyCanonicalProfile(0)
val (a, _) = makeClient("phone-a", trusted = true)
val (b, _) = makeClient("phone-b", trusted = false)
blob = upsertClient(blob, a)
blob = upsertClient(blob, b)
assertEquals(2, blob.clients.size)
assertEquals(listOf(a.identityFingerprint), blob.trustedApproverFingerprints)
assertTrue(isTrustedApprover(blob, a.identityFingerprint))
assertFalse(isTrustedApprover(blob, b.identityFingerprint))
}
@Test
fun setTrustedApproverIsIdempotentNoOpReturnsSameInstance() {
var blob = emptyCanonicalProfile(0)
val (c, _) = makeClient("phone", trusted = false)
blob = upsertClient(blob, c)
val before = blob
blob = setTrustedApprover(blob, c.identityFingerprint, false, now = 999L)
assertTrue(blob === before)
}
@Test
fun setTrustedApproverFlipsFlagAndDenormalizedList() {
var blob = emptyCanonicalProfile(0)
val (c, _) = makeClient("phone", trusted = false)
blob = upsertClient(blob, c)
blob = setTrustedApprover(blob, c.identityFingerprint, true, now = 100L)
assertEquals(listOf(c.identityFingerprint), blob.trustedApproverFingerprints)
assertEquals(true, blob.clients[0].trustedApprover)
blob = setTrustedApprover(blob, c.identityFingerprint, false, now = 200L)
assertTrue(blob.trustedApproverFingerprints.isEmpty())
assertEquals(false, blob.clients[0].trustedApprover)
}
@Test
fun removeClientCleansUpDenormalizedList() {
var blob = emptyCanonicalProfile(0)
val (c, _) = makeClient("phone", trusted = true)
blob = upsertClient(blob, c)
blob = removeClient(blob, c.identityFingerprint)
assertTrue(blob.clients.isEmpty())
assertTrue(blob.trustedApproverFingerprints.isEmpty())
}
@Test
fun findClientByFingerprintAndAddress() {
var blob = emptyCanonicalProfile(0)
val (c, _) = makeClient("phone")
blob = upsertClient(blob, c)
assertEquals(c.address, findClientByFingerprint(blob, c.identityFingerprint)?.address)
assertEquals(
c.identityFingerprint,
findClientByAddress(blob, c.address)?.identityFingerprint,
)
assertNull(findClientByFingerprint(blob, "unknown"))
assertNull(findClientByAddress(blob, "unknown"))
}
@Test
fun parseRejectsMalformedProfile() {
try {
parseCanonicalProfile("not json")
org.junit.Assert.fail("expected throw")
} catch (_: IllegalArgumentException) {}
try {
parseCanonicalProfile("""{"version":2}""")
org.junit.Assert.fail("expected throw")
} catch (_: IllegalArgumentException) {}
try {
parseCanonicalProfile(
"""{"version":1,"clients":[{"address":"x","name":"x","kind":"m","addedAt":0}]}""",
)
org.junit.Assert.fail("expected throw — missing identityPublicKey")
} catch (_: IllegalArgumentException) {}
try {
parseCanonicalProfile(
"""{"version":1,"clients":[{"address":"x","identityPublicKey":"NOTHEX","identityFingerprint":"x","name":"x","kind":"m","addedAt":0}]}""",
)
org.junit.Assert.fail("expected throw — bad pubkey hex")
} catch (_: IllegalArgumentException) {}
}
@Test
fun fullProfileSerializeParsePreservesAllFields() {
var blob = emptyCanonicalProfile(1L)
blob = upsertHost(blob, makeHost(), now = 2L)
val (c, _) = makeClient("phone", trusted = true)
blob = upsertClient(blob, c, now = 3L)
blob = blob.copy(signedBy = "aabbccdd")
val bytes = serializeCanonicalProfile(blob)
val parsed = parseCanonicalProfile(bytes)
assertEquals(blob, parsed)
}
// ─── Approval signing payload ──────────────────────────────
@Test
fun canonicalApprovalSigningBytesIsDeterministic() {
val a = canonicalApprovalSigningBytes(
domain = DEFAULT_APPROVAL_DOMAIN,
requestId = "aabbccddeeff00112233445566778899",
hostFingerprint = "11111 22222 33333 44444",
requestingDeviceFingerprint = "55555 66666 77777 88888",
decision = "approve",
)
val b = canonicalApprovalSigningBytes(
domain = DEFAULT_APPROVAL_DOMAIN,
requestId = "aabbccddeeff00112233445566778899",
hostFingerprint = "11111 22222 33333 44444",
requestingDeviceFingerprint = "55555 66666 77777 88888",
decision = "approve",
)
assertArrayEquals(a, b)
}
@Test
fun differentDecisionProducesDifferentSigningBytes() {
val approve = canonicalApprovalSigningBytes(
DEFAULT_APPROVAL_DOMAIN, "r", "h", "d", "approve",
)
val reject = canonicalApprovalSigningBytes(
DEFAULT_APPROVAL_DOMAIN, "r", "h", "d", "reject",
)
assertFalse(approve.contentEquals(reject))
}
@Test
fun differentDomainProducesDifferentSigningBytes() {
val a = canonicalApprovalSigningBytes("shade-link-approve-v1", "r", "h", "d", "approve")
val b = canonicalApprovalSigningBytes("prism-link-approve-v1", "r", "h", "d", "approve")
assertFalse(a.contentEquals(b))
}
// ─── Build / sign / verify ─────────────────────────────────
private data class Scenario(
val phone: ProfileClientEntry,
val phoneSeed: ByteArray,
val profile: CanonicalProfileBlob,
val request: ApprovalRequestFrame,
)
private fun buildScenario(): Scenario {
val (phone, seed) = makeClient("phone", trusted = true)
var profile = emptyCanonicalProfile(0)
profile = upsertHost(profile, makeHost())
profile = upsertClient(profile, phone)
val request = buildApprovalRequest(
crypto = crypto,
hostAddress = "device:host-server",
hostFingerprint = "host-fp-12345",
requestingDeviceFingerprint = "cafe-laptop-fp-67890",
deviceName = "cafe-laptop",
userAgent = "Mozilla/5.0",
ipHint = "203.0.113.7",
)
return Scenario(phone, seed, profile, request)
}
@Test
fun happyPathApproveVerifies() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request,
decision = "approve",
approverFingerprint = s.phone.identityFingerprint,
approverSigningKey = s.phoneSeed,
)
assertEquals("linkApproveByProxy", approval.kind)
assertEquals(s.request.requestId, approval.requestId)
assertEquals(128, approval.signature.length)
val r = verifyProxyApproval(crypto, s.request, approval, s.profile)
assertTrue(r is VerifyProxyApprovalResult.Ok)
assertEquals(s.phone.address, (r as VerifyProxyApprovalResult.Ok).approver.address)
}
@Test
fun happyPathRejectVerifies() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "reject",
s.phone.identityFingerprint, s.phoneSeed,
)
val r = verifyProxyApproval(crypto, s.request, approval, s.profile)
assertTrue(r is VerifyProxyApprovalResult.Ok)
}
@Test
fun replayAgainstDifferentRequestFails() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val other = s.request.copy(requestId = "f".repeat(32))
val r = verifyProxyApproval(crypto, other, approval, s.profile)
assertEquals(
VerifyProxyApprovalResult.Reason.REQUEST_ID_MISMATCH,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun decisionTamperingFails() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val tampered = approval.copy(decision = "reject")
val r = verifyProxyApproval(crypto, s.request, tampered, s.profile)
assertEquals(
VerifyProxyApprovalResult.Reason.BAD_SIGNATURE,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun hostFingerprintSwapFails() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val swapped = s.request.copy(hostFingerprint = "evil-host-fp")
val r = verifyProxyApproval(crypto, swapped, approval, s.profile)
assertEquals(
VerifyProxyApprovalResult.Reason.BAD_SIGNATURE,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun domainMismatchIsRejectedBeforeSignature() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val r = verifyProxyApproval(
crypto, s.request, approval.copy(domain = "prism-link-approve-v1"), s.profile,
)
assertEquals(
VerifyProxyApprovalResult.Reason.DOMAIN_MISMATCH,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun unknownApproverFails() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val lying = approval.copy(approverFingerprint = "no-such-fingerprint")
val r = verifyProxyApproval(crypto, s.request, lying, s.profile)
assertEquals(
VerifyProxyApprovalResult.Reason.UNKNOWN_APPROVER,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun revokedApproverFailsWithNotTrusted() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val revoked = setTrustedApprover(s.profile, s.phone.identityFingerprint, false)
val r = verifyProxyApproval(crypto, s.request, approval, revoked)
assertEquals(
VerifyProxyApprovalResult.Reason.NOT_TRUSTED,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun expiredRequestIsRejected() {
val s = buildScenario()
val approval = signProxyApproval(
crypto, s.request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
val r = verifyProxyApproval(crypto, s.request, approval, s.profile, now = s.request.expiresAt + 1)
assertEquals(
VerifyProxyApprovalResult.Reason.EXPIRED,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun signatureWithWrongKeyFails() {
val s = buildScenario()
val wrongSeed = crypto.randomBytes(32)
val approval = signProxyApproval(
crypto, s.request, "approve",
approverFingerprint = s.phone.identityFingerprint, // claim phone
approverSigningKey = wrongSeed, // sign with different key
)
val r = verifyProxyApproval(crypto, s.request, approval, s.profile)
assertEquals(
VerifyProxyApprovalResult.Reason.BAD_SIGNATURE,
(r as VerifyProxyApprovalResult.Failed).reason,
)
}
@Test
fun customDomainSurvivesRoundTrip() {
val s = buildScenario()
val request = s.request.copy(domain = "prism-link-approve-v1")
val approval = signProxyApproval(
crypto, request, "approve",
s.phone.identityFingerprint, s.phoneSeed,
)
assertEquals("prism-link-approve-v1", approval.domain)
val r = verifyProxyApproval(crypto, request, approval, s.profile)
assertTrue(r is VerifyProxyApprovalResult.Ok)
}
@Test
fun requestIdIs32LowercaseHexChars() {
val r = buildApprovalRequest(
crypto, "device:h", "h", "r",
)
assertTrue(r.requestId.matches(Regex("^[0-9a-f]{32}$")))
}
@Test
fun consecutiveBuildsProduceDistinctRequestIds() {
val a = buildApprovalRequest(crypto, "device:h", "h", "r")
val b = buildApprovalRequest(crypto, "device:h", "h", "r")
assertNotEquals(a.requestId, b.requestId)
}
// ─── Sanity glue: TS-side reference frame parses on Kotlin ──
@Test
fun tsStyleProxyApprovalFrameParsesAndStructurallyMatches() {
// Construct a frame the way @shade/sdk would emit it via JSON,
// and check our Kotlin types accept the same field names.
val expected = ProxyApprovalFrame(
requestId = "00112233445566778899aabbccddeeff",
decision = "approve",
approverFingerprint = "fp",
signature = "ab".repeat(64),
domain = DEFAULT_APPROVAL_DOMAIN,
)
assertEquals("linkApproveByProxy", expected.kind)
assertEquals("approve", expected.decision)
val req = ApprovalRequestFrame(
requestId = "00112233445566778899aabbccddeeff",
hostAddress = "device:h",
hostFingerprint = "host-fp",
requestingDevice = ApprovalRequestingDevice(
fingerprint = "req-fp",
receivedAt = 1L,
),
expiresAt = 2L,
domain = DEFAULT_APPROVAL_DOMAIN,
)
assertNotNull(req)
}
}

View File

@@ -1,6 +1,13 @@
package no.zyon.shade package no.zyon.shade
import no.zyon.shade.approval.canonicalApprovalSigningBytes
import no.zyon.shade.backup.deriveBackupKey import no.zyon.shade.backup.deriveBackupKey
import no.zyon.shade.blob.aeadOpen
import no.zyon.shade.blob.blobAadForSlot
import no.zyon.shade.blob.deriveBlobKey
import no.zyon.shade.blob.deriveBlobSigningSeed
import no.zyon.shade.blob.deriveBlobSlotId
import no.zyon.shade.blob.ed25519PublicKeyFromSeed
import no.zyon.shade.crypto.TinkProvider import no.zyon.shade.crypto.TinkProvider
import no.zyon.shade.fingerprint.computeFingerprint import no.zyon.shade.fingerprint.computeFingerprint
import no.zyon.shade.group.encodeSenderHeader import no.zyon.shade.group.encodeSenderHeader
@@ -447,6 +454,92 @@ class CrossPlatformVectorTest {
} }
} }
@Test
fun blobKdfAndAeadVectorsMatch() {
val vectors = loadVectors("blob.json")
var kdfMatched = 0
var aeadMatched = 0
for (i in 0 until vectors.length()) {
val v = vectors.getJSONObject(i)
val desc = v.getString("description")
if (desc.startsWith("V4.9 blob KDF")) {
kdfMatched++
val masterKey = fromHex(v.getString("masterKey"))
val app = v.getString("app")
val slotId = deriveBlobSlotId(crypto, masterKey, app)
assertEquals(v.getString("slotId"), hex(slotId))
assertEquals(v.getString("blobKey"), hex(deriveBlobKey(crypto, masterKey, app)))
val seed = deriveBlobSigningSeed(crypto, masterKey, app)
assertEquals(v.getString("signingSeed"), hex(seed))
assertEquals(v.getString("ownerPubkey"), hex(ed25519PublicKeyFromSeed(seed)))
} else if (desc.startsWith("V4.9 blob AEAD")) {
aeadMatched++
val key = fromHex(v.getString("key"))
val slotIdHex = v.getString("slotIdHex")
val expectedPlaintext = fromHex(v.getString("plaintext"))
val wire = fromHex(v.getString("wire"))
val aad = blobAadForSlot(slotIdHex)
val opened = aeadOpen(key, wire, aad)
assertEquals(hex(expectedPlaintext), hex(opened))
}
}
assertTrue("KDF vectors expected", kdfMatched >= 3)
assertTrue("AEAD vectors expected", aeadMatched >= 2)
}
@Test
fun approvalSigningPayloadVectorsMatch() {
val vectors = loadVectors("approval.json")
var payloadMatched = 0
var e2eMatched = 0
for (i in 0 until vectors.length()) {
val v = vectors.getJSONObject(i)
val desc = v.getString("description")
if (desc.startsWith("V4.10 approval signing payload")) {
payloadMatched++
val out = canonicalApprovalSigningBytes(
domain = v.getString("domain"),
requestId = v.getString("requestId"),
hostFingerprint = v.getString("hostFingerprint"),
requestingDeviceFingerprint = v.getString("requestingDeviceFingerprint"),
decision = v.getString("decision"),
)
assertEquals(v.getString("signingPayload"), hex(out))
} else if (desc.startsWith("V4.10 approval Ed25519 sign/verify")) {
e2eMatched++
val seed = fromHex(v.getString("seed"))
val pubkey = fromHex(v.getString("publicKey"))
assertEquals(hex(pubkey), hex(ed25519PublicKeyFromSeed(seed)))
val req = v.getJSONObject("request")
val payload = canonicalApprovalSigningBytes(
domain = req.getString("domain"),
requestId = req.getString("requestId"),
hostFingerprint = req.getString("hostFingerprint"),
requestingDeviceFingerprint = req.getString("requestingDeviceFingerprint"),
decision = req.getString("decision"),
)
assertEquals(v.getString("signingPayload"), hex(payload))
// Verify the TS-generated signature against our pubkey + payload.
// This is the load-bearing parity check: a Kotlin-implemented
// verifyProxyApproval running against a TS-signed approval
// succeeds.
val sig = fromHex(v.getString("signature"))
val ok = crypto.verify(pubkey, payload, sig)
assertTrue("Ed25519 verify of TS-signed approval failed", ok)
// And: Kotlin signs the same payload with the same seed and
// produces a sig the TS pubkey verifies. Ed25519 is
// deterministic, so the sig bytes also match exactly.
val mySig = crypto.sign(seed, payload)
assertEquals(v.getString("signature"), hex(mySig))
}
}
assertTrue("payload vectors expected", payloadMatched >= 3)
assertTrue("e2e sign/verify vector expected", e2eMatched >= 1)
}
@Test @Test
fun ratchetStepRoundtripMatches() { fun ratchetStepRoundtripMatches() {
val vectors = loadVectors("ratchet-step.json") val vectors = loadVectors("ratchet-step.json")

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,123 @@
package no.zyon.shade
import no.zyon.shade.serialization.SessionStateJson
import no.zyon.shade.types.ChainState
import no.zyon.shade.types.IdentityKeyPair
import no.zyon.shade.types.KeyPair
import no.zyon.shade.types.OneTimePreKey
import no.zyon.shade.types.SessionState
import no.zyon.shade.types.SignedPreKey
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Test
/**
* Round-trip tests for the at-rest JSON serialization used by
* `KeystoreStorage`. The format isn't cross-platform (TS uses its
* own shape) — what matters is `serialize → deserialize` preserves
* every byte of every key.
*/
class SessionStateJsonTest {
private fun bytes(n: Int, fill: Byte): ByteArray = ByteArray(n) { fill }
@Test
fun identityKeyPairRoundTrip() {
val k = IdentityKeyPair(
signingPublicKey = bytes(32, 0x11),
signingPrivateKey = bytes(32, 0x22),
dhPublicKey = bytes(32, 0x33),
dhPrivateKey = bytes(32, 0x44),
)
val s = SessionStateJson.serializeIdentityKeyPair(k)
val d = SessionStateJson.deserializeIdentityKeyPair(s)
assertArrayEquals(k.signingPublicKey, d.signingPublicKey)
assertArrayEquals(k.signingPrivateKey, d.signingPrivateKey)
assertArrayEquals(k.dhPublicKey, d.dhPublicKey)
assertArrayEquals(k.dhPrivateKey, d.dhPrivateKey)
}
@Test
fun signedPreKeyRoundTrip() {
val k = SignedPreKey(
keyId = 42,
keyPair = KeyPair(publicKey = bytes(32, 0x55), privateKey = bytes(32, 0x66)),
signature = bytes(64, 0x77),
timestamp = 1_700_000_000_000L,
)
val s = SessionStateJson.serializeSignedPreKey(k)
val d = SessionStateJson.deserializeSignedPreKey(s)
assertEquals(k.keyId, d.keyId)
assertArrayEquals(k.keyPair.publicKey, d.keyPair.publicKey)
assertArrayEquals(k.keyPair.privateKey, d.keyPair.privateKey)
assertArrayEquals(k.signature, d.signature)
assertEquals(k.timestamp, d.timestamp)
}
@Test
fun oneTimePreKeyRoundTrip() {
val k = OneTimePreKey(
keyId = 7,
keyPair = KeyPair(publicKey = bytes(32, 0x88.toByte()), privateKey = bytes(32, 0x99.toByte())),
)
val s = SessionStateJson.serializeOneTimePreKey(k)
val d = SessionStateJson.deserializeOneTimePreKey(s)
assertEquals(k.keyId, d.keyId)
assertArrayEquals(k.keyPair.publicKey, d.keyPair.publicKey)
assertArrayEquals(k.keyPair.privateKey, d.keyPair.privateKey)
}
@Test
fun sessionStateRoundTripFullPopulated() {
val state = SessionState(
remoteIdentityKey = bytes(32, 0x01),
rootKey = bytes(32, 0x02),
sendChain = ChainState(chainKey = bytes(32, 0x03), counter = 5),
receiveChain = ChainState(chainKey = bytes(32, 0x04), counter = 3),
dhSend = KeyPair(publicKey = bytes(32, 0x05), privateKey = bytes(32, 0x06)),
dhReceive = bytes(32, 0x07),
previousSendCounter = 9,
skippedKeys = mutableMapOf(
"remote:1" to bytes(32, 0x0A),
"remote:2" to bytes(32, 0x0B),
),
)
val s = SessionStateJson.serialize(state)
val d = SessionStateJson.deserialize(s)
assertArrayEquals(state.remoteIdentityKey, d.remoteIdentityKey)
assertArrayEquals(state.rootKey, d.rootKey)
assertArrayEquals(state.sendChain.chainKey, d.sendChain.chainKey)
assertEquals(state.sendChain.counter, d.sendChain.counter)
assertNotNull(d.receiveChain)
assertArrayEquals(state.receiveChain!!.chainKey, d.receiveChain!!.chainKey)
assertArrayEquals(state.dhSend.publicKey, d.dhSend.publicKey)
assertArrayEquals(state.dhSend.privateKey, d.dhSend.privateKey)
assertArrayEquals(state.dhReceive, d.dhReceive)
assertEquals(state.previousSendCounter, d.previousSendCounter)
assertEquals(state.skippedKeys.size, d.skippedKeys.size)
for ((k, v) in state.skippedKeys) {
assertArrayEquals(v, d.skippedKeys[k])
}
}
@Test
fun sessionStateRoundTripWithNullableFields() {
val state = SessionState(
remoteIdentityKey = bytes(32, 0x01),
rootKey = bytes(32, 0x02),
sendChain = ChainState(chainKey = bytes(32, 0x03), counter = 0),
receiveChain = null,
dhSend = KeyPair(publicKey = bytes(32, 0x05), privateKey = bytes(32, 0x06)),
dhReceive = null,
previousSendCounter = 0,
skippedKeys = mutableMapOf(),
)
val s = SessionStateJson.serialize(state)
val d = SessionStateJson.deserialize(s)
assertNull(d.receiveChain)
assertNull(d.dhReceive)
assertEquals(0, d.skippedKeys.size)
}
}

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

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