Commit Graph

99 Commits

Author SHA1 Message Date
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>
v4.14.1
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>
v4.14.0
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>
v4.13.1
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