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