diff --git a/.scaffold/branches/streaming.md b/.scaffold/branches/streaming.md index 98a7e9a..8e4f763 100644 --- a/.scaffold/branches/streaming.md +++ b/.scaffold/branches/streaming.md @@ -24,6 +24,8 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video - [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 ## Neste - Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18) diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/06-album.png b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/06-album.png new file mode 100644 index 0000000..1ebfdd2 Binary files /dev/null and b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/06-album.png differ diff --git a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt index c601f6a..dea43b8 100644 --- a/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt +++ b/.scaffold/logs/streaming/media/2026-10-18-shade-streaming/captions.txt @@ -3,3 +3,4 @@ 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 diff --git a/CHANGELOG.md b/CHANGELOG.md index 396d0e2..d7e12e0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -38,6 +38,13 @@ New package **`@shade/media`** — see `docs/media.md`. frag_keyframe+empty_moov` for H.264/AAC; the container is detected). `MediaSplitter`, `WebmSplitter` and `Fmp4Splitter` are exported for apps that publish from their own source. +- **Albums.** One link for a season, a photo album or a camera wall: an + album is a sealed file listing grants (`shade.album/v1`), so the relay + cannot tell it from a film. `shade media put dir/` uploads every file + and prints the album's link (subdirectories become nested albums, in + natural order); `shade media get` downloads an album back into a + directory; `/watch/` shows it as a grid with decrypted previews. + `uploadAlbum`, `openAlbum`, `Albums.read` (Kotlin), and a shared vector. - **Kotlin.** `no.zyon.shade.media`: SMF1 reader and sealer, grants, live subscriber and publisher — byte-for-byte against `test-vectors/media.json`. `:shade-android-media` plays sealed files in Media3/ExoPlayer @@ -46,6 +53,13 @@ New package **`@shade/media`** — see `docs/media.md`. ### Fixed +- `shade media get` used the sealed file's `meta.name` as the output path, + so whoever sealed a file chose where it was written (`../../.bashrc`). + Names are now reduced to one safe path component. +- A relay test raced: `flush()` means sent, not received, so a viewer could + join mid-burst and (correctly) get an older backlog. The relay now counts + `framesIn` in `stats()`, and the test waits on it. + - The container refused every request body over 128 MiB (Bun's default), which would have made every film a 413. The cap is raised only when media is mounted, and every other route now has an explicit 128 MiB body limit. diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/Album.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/Album.kt new file mode 100644 index 0000000..05b5140 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/Album.kt @@ -0,0 +1,67 @@ +package no.zyon.shade.media + +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) + +object Albums { + /** 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 + } +} diff --git a/android/shade-android/src/test/kotlin/no/zyon/shade/MediaVectorTest.kt b/android/shade-android/src/test/kotlin/no/zyon/shade/MediaVectorTest.kt index bac4412..c38d3db 100644 --- a/android/shade-android/src/test/kotlin/no/zyon/shade/MediaVectorTest.kt +++ b/android/shade-android/src/test/kotlin/no/zyon/shade/MediaVectorTest.kt @@ -1,13 +1,18 @@ 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 @@ -23,6 +28,7 @@ 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 @@ -176,4 +182,30 @@ class MediaVectorTest { 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) + 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())) } + } } diff --git a/docs/media.md b/docs/media.md index ea10e83..56f7ea1 100644 --- a/docs/media.md +++ b/docs/media.md @@ -31,6 +31,10 @@ shade media put Film.mkv --server https://relay.example # Back on disk, decrypted and verified. shade media get '' -o Film.mkv +# A season, a photo album: every file, plus one link that opens them all. +shade media put "Sesong 1/" --server https://relay.example +shade media get '' -o "Sesong 1" # the whole directory back + # Live logs. tail -f /var/log/app.log | shade live text --server https://relay.example --name "api logs" --channel ~/.config/shade/api-logs.json shade live watch '' # in a terminal — or open the link in a browser @@ -253,6 +257,35 @@ cannot tell which ids exist. A link is `…/watch/#shade=`. Th fragment is never sent to a server, and the page removes it from the address bar once it has read it. +## Albums + +An album is a sealed file like any other, with meta `mime` +`application/vnd.shade.album+json` and this plaintext: + +```jsonc +{ "kind": "shade.album/v1", "title": "Sesong 1", + "items": [ { "kind": "shade.media-grant/v1", … }, { "kind": "shade.live-grant/v1", … }, … ] } +``` + +Items are grants in their wire form, so an album can hold films, pictures, live +channels and other albums (`shade media put dir/` turns subdirectories into nested +albums, in natural order). Parsing is strict on both sides: every item must be a +valid grant, at most 10 000 items, a title of at most 512 characters. + +The relay stores an album as one more opaque object. It cannot tell an album from a +film, see its title, count its items or link it to them. Holding the album link means +holding every item's keys: deleting the album does not take them back from someone who +has already opened it. To revoke, delete the items. + +Names in an album (and in any sealed file's meta) come from whoever sealed it, so +`shade media get` never uses them as paths: only the last path segment is kept, +without control characters or leading dots, and duplicates get a ` (2)` suffix. + +`MediaClient.uploadAlbum`, `openAlbum` / `readAlbum` and `encodeAlbum` / `parseAlbum` +in TS, `Albums.parse` / `Albums.read` in Kotlin. The `/watch/` page shows an album as a +grid with decrypted previews, and Back returns from an item to its album. History +entries hold only a depth, never a grant. + ## What the relay learns - **Sealed:** that an opaque id exists, its size (to within a segment), when it was diff --git a/packages/shade-media/src/album.ts b/packages/shade-media/src/album.ts new file mode 100644 index 0000000..5bb2b36 --- /dev/null +++ b/packages/shade-media/src/album.ts @@ -0,0 +1,91 @@ +/** + * Albums: one link for many files. + * + * A season of a series, a photo album, a playlist, a wall of cameras. An + * album is itself a sealed file (SMF1) whose plaintext is a list of grants, + * with the MIME type `application/vnd.shade.album+json`. So: + * + * - one capability link opens every item, and nothing else; + * - the relay stores it like any other object: it cannot tell an album + * from a film, let alone count or name what is in it; + * - an album may hold live grants (a camera wall) and other albums. + * + * Holding an album means holding every item's keys. Deleting the album + * object does not revoke them from anyone who already opened it — delete + * the items to do that. + */ + +import { MediaFormatError } from './errors.js'; +import { encodeGrant, parseGrant } from './grant.js'; +import type { Grant, MediaGrant } from './grant.js'; +import type { MediaMeta } from './sealed.js'; + +export const ALBUM_KIND = 'shade.album/v1'; +export const ALBUM_MIME = 'application/vnd.shade.album+json'; + +/** Enough for any season or camera roll, small enough to parse without thought. */ +export const MAX_ALBUM_ITEMS = 10_000; +const MAX_TITLE = 512; + +export interface Album { + title: string; + items: Grant[]; +} + +const enc = new TextEncoder(); +const dec = new TextDecoder('utf-8', { fatal: true }); + +export function encodeAlbum(album: Album): Uint8Array { + checkTitle(album.title); + if (album.items.length > MAX_ALBUM_ITEMS) throw new MediaFormatError(`album holds more than ${MAX_ALBUM_ITEMS} items`); + // Grants are embedded as objects, each in its own wire form. + const items = album.items.map((g) => JSON.parse(encodeGrant(g)) as unknown); + return enc.encode(JSON.stringify({ kind: ALBUM_KIND, title: album.title, items })); +} + +/** Parse an album's plaintext, strictly: every item must be a valid grant. */ +export function parseAlbum(bytes: Uint8Array): Album { + let o: unknown; + try { + o = JSON.parse(dec.decode(bytes)); + } catch { + throw new MediaFormatError('album is not UTF-8 JSON'); + } + if (typeof o !== 'object' || o === null || Array.isArray(o)) throw new MediaFormatError('album must be an object'); + const r = o as Record; + if (r.kind !== ALBUM_KIND) throw new MediaFormatError(`not an album (kind ${String(r.kind)})`); + if (typeof r.title !== 'string') throw new MediaFormatError('album.title must be a string'); + checkTitle(r.title); + if (!Array.isArray(r.items)) throw new MediaFormatError('album.items must be an array'); + if (r.items.length > MAX_ALBUM_ITEMS) throw new MediaFormatError(`album holds more than ${MAX_ALBUM_ITEMS} items`); + const items = r.items.map((it, i) => { + if (typeof it !== 'object' || it === null || Array.isArray(it)) throw new MediaFormatError(`album item ${i} is not a grant`); + try { + return parseGrant(JSON.stringify(it)); + } catch (e) { + throw new MediaFormatError(`album item ${i}: ${(e as Error).message}`); + } + }); + return { title: r.title, items }; +} + +/** Does this grant (by its meta preview) or this sealed meta name an album? */ +export function isAlbum(x: Grant | MediaMeta | undefined): boolean { + if (x === undefined) return false; + const meta = 'kind' in x ? x.meta : x; + return meta?.mime === ALBUM_MIME; +} + +/** The meta an album's sealed file carries. */ +export function albumMeta(title: string): MediaMeta { + return { mime: ALBUM_MIME, name: title }; +} + +/** Narrow for callers that only take sealed files. */ +export function isMediaGrant(g: Grant): g is MediaGrant { + return g.kind === 'shade.media-grant/v1'; +} + +function checkTitle(t: string): void { + if (t.length > MAX_TITLE) throw new MediaFormatError(`album title longer than ${MAX_TITLE} characters`); +} diff --git a/packages/shade-media/src/browser/watch-app.ts b/packages/shade-media/src/browser/watch-app.ts index 3e36e85..65a8150 100644 --- a/packages/shade-media/src/browser/watch-app.ts +++ b/packages/shade-media/src/browser/watch-app.ts @@ -6,21 +6,26 @@ * A sealed file plays through the Service Worker in a native element — * `