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>
This commit is contained in:
@@ -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] 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] 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
|
## Neste
|
||||||
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18)
|
- Kjør `:shade-media-demo` på dev-telefonen (RFCN504DWJF var ikke tilkoblet 2026-10-18)
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 53 KiB |
@@ -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)
|
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
|
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
|
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
|
||||||
|
|||||||
14
CHANGELOG.md
14
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).
|
frag_keyframe+empty_moov` for H.264/AAC; the container is detected).
|
||||||
`MediaSplitter`, `WebmSplitter` and `Fmp4Splitter` are exported for apps
|
`MediaSplitter`, `WebmSplitter` and `Fmp4Splitter` are exported for apps
|
||||||
that publish from their own source.
|
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
|
- **Kotlin.** `no.zyon.shade.media`: SMF1 reader and sealer, grants, live
|
||||||
subscriber and publisher — byte-for-byte against `test-vectors/media.json`.
|
subscriber and publisher — byte-for-byte against `test-vectors/media.json`.
|
||||||
`:shade-android-media` plays sealed files in Media3/ExoPlayer
|
`:shade-android-media` plays sealed files in Media3/ExoPlayer
|
||||||
@@ -46,6 +53,13 @@ New package **`@shade/media`** — see `docs/media.md`.
|
|||||||
|
|
||||||
### Fixed
|
### 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),
|
- 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
|
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.
|
is mounted, and every other route now has an explicit 128 MiB body limit.
|
||||||
|
|||||||
@@ -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<Grant>)
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,13 +1,18 @@
|
|||||||
package no.zyon.shade
|
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.ByteArraySource
|
||||||
import no.zyon.shade.media.FOOTER_BYTES
|
import no.zyon.shade.media.FOOTER_BYTES
|
||||||
import no.zyon.shade.media.Grants
|
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.LiveContent
|
||||||
import no.zyon.shade.media.LiveGrant
|
import no.zyon.shade.media.LiveGrant
|
||||||
import no.zyon.shade.media.LiveKeyException
|
import no.zyon.shade.media.LiveKeyException
|
||||||
import no.zyon.shade.media.LivePublisher
|
import no.zyon.shade.media.LivePublisher
|
||||||
import no.zyon.shade.media.LiveSubscriber
|
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.MediaGrant
|
||||||
import no.zyon.shade.media.MediaIntegrityException
|
import no.zyon.shade.media.MediaIntegrityException
|
||||||
import no.zyon.shade.media.MediaKeys
|
import no.zyon.shade.media.MediaKeys
|
||||||
@@ -23,6 +28,7 @@ import org.json.JSONArray
|
|||||||
import org.json.JSONObject
|
import org.json.JSONObject
|
||||||
import org.junit.Assert.assertArrayEquals
|
import org.junit.Assert.assertArrayEquals
|
||||||
import org.junit.Assert.assertEquals
|
import org.junit.Assert.assertEquals
|
||||||
|
import org.junit.Assert.assertFalse
|
||||||
import org.junit.Assert.assertNotNull
|
import org.junit.Assert.assertNotNull
|
||||||
import org.junit.Assert.assertNull
|
import org.junit.Assert.assertNull
|
||||||
import org.junit.Assert.assertThrows
|
import org.junit.Assert.assertThrows
|
||||||
@@ -176,4 +182,30 @@ class MediaVectorTest {
|
|||||||
assertArrayEquals(mediaId, g.mediaId)
|
assertArrayEquals(mediaId, g.mediaId)
|
||||||
assertThrows(Exception::class.java) { Grants.parse("""{"kind":"shade.media-grant/v1","mediaId":"AA","key":"AA","root":"ab"}""") }
|
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())) }
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -31,6 +31,10 @@ shade media put Film.mkv --server https://relay.example
|
|||||||
# Back on disk, decrypted and verified.
|
# Back on disk, decrypted and verified.
|
||||||
shade media get '<link>' -o Film.mkv
|
shade media get '<link>' -o Film.mkv
|
||||||
|
|
||||||
|
# A season, a photo album: every file, plus one link that opens them all.
|
||||||
|
shade media put "Sesong 1/" --server https://relay.example
|
||||||
|
shade media get '<album link>' -o "Sesong 1" # the whole directory back
|
||||||
|
|
||||||
# Live logs.
|
# Live logs.
|
||||||
tail -f /var/log/app.log | shade live text --server https://relay.example --name "api logs" --channel ~/.config/shade/api-logs.json
|
tail -f /var/log/app.log | shade live text --server https://relay.example --name "api logs" --channel ~/.config/shade/api-logs.json
|
||||||
shade live watch '<link>' # in a terminal — or open the link in a browser
|
shade live watch '<link>' # in a terminal — or open the link in a browser
|
||||||
@@ -253,6 +257,35 @@ cannot tell which ids exist. A link is `…/watch/#shade=<b64u(grant JSON)>`. Th
|
|||||||
fragment is never sent to a server, and the page removes it from the address bar
|
fragment is never sent to a server, and the page removes it from the address bar
|
||||||
once it has read it.
|
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
|
## What the relay learns
|
||||||
|
|
||||||
- **Sealed:** that an opaque id exists, its size (to within a segment), when it was
|
- **Sealed:** that an opaque id exists, its size (to within a segment), when it was
|
||||||
|
|||||||
91
packages/shade-media/src/album.ts
Normal file
91
packages/shade-media/src/album.ts
Normal file
@@ -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<string, unknown>;
|
||||||
|
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`);
|
||||||
|
}
|
||||||
@@ -6,21 +6,26 @@
|
|||||||
* A sealed file plays through the Service Worker in a native element —
|
* A sealed file plays through the Service Worker in a native element —
|
||||||
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
|
* `<video>`, `<audio>`, `<img>` or a text view — with seeking. A live
|
||||||
* channel plays through MSE (video/audio) or as a scrolling log (text),
|
* channel plays through MSE (video/audio) or as a scrolling log (text),
|
||||||
* with images replacing each other in place.
|
* with images replacing each other in place. An album shows its items as a
|
||||||
|
* grid; opening one pushes a view, and Back returns to the album.
|
||||||
*
|
*
|
||||||
* The grant never leaves the browser: it is in the fragment, which is not
|
* The grant never leaves the browser: it is in the fragment, which is not
|
||||||
* sent to the server, and the page drops it from the address bar once read.
|
* sent to the server, and the page drops it from the address bar once read.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { ALBUM_MIME, parseAlbum } from '../album.js';
|
||||||
|
import type { Album } from '../album.js';
|
||||||
import { fromCapabilityUrl } from '../grant.js';
|
import { fromCapabilityUrl } from '../grant.js';
|
||||||
import type { LiveGrant, MediaGrant } from '../grant.js';
|
import type { Grant, LiveGrant, MediaGrant } from '../grant.js';
|
||||||
import { LiveWatchClient } from '../live/client.js';
|
import { LiveWatchClient } from '../live/client.js';
|
||||||
import type { ReceivedFrame } from '../live/channel.js';
|
import type { ReceivedFrame } from '../live/channel.js';
|
||||||
import { installMediaWorker } from './index.js';
|
import { installMediaWorker } from './index.js';
|
||||||
|
import type { MediaKeyring } from './index.js';
|
||||||
import { LivePlayer } from './player.js';
|
import { LivePlayer } from './player.js';
|
||||||
|
|
||||||
interface Stats {
|
interface Stats {
|
||||||
kind: 'media' | 'live' | 'none';
|
kind: 'media' | 'live' | 'album' | 'none';
|
||||||
|
items?: number;
|
||||||
state: string;
|
state: string;
|
||||||
mime?: string;
|
mime?: string;
|
||||||
frames: number;
|
frames: number;
|
||||||
@@ -57,16 +62,83 @@ function human(n: number): string {
|
|||||||
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
|
return `${n.toFixed(i === 0 ? 0 : 1)} ${u[i]}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ─── Views ──────────────────────────────────────────────────────
|
||||||
|
//
|
||||||
|
// A stack of views mirrored in the history, so Back leaves an item for its
|
||||||
|
// album. History entries hold only the depth: the grants stay in memory.
|
||||||
|
|
||||||
|
type View = () => Promise<void> | void;
|
||||||
|
const views: View[] = [];
|
||||||
|
let cleanups: (() => void)[] = [];
|
||||||
|
|
||||||
|
function reset(): void {
|
||||||
|
for (const c of cleanups) c();
|
||||||
|
cleanups = [];
|
||||||
|
const stage = $('#stage');
|
||||||
|
for (const m of stage.querySelectorAll('video, audio')) (m as HTMLMediaElement).pause();
|
||||||
|
stage.replaceChildren();
|
||||||
|
stage.className = '';
|
||||||
|
$('#actions').replaceChildren();
|
||||||
|
$('#sub').textContent = '';
|
||||||
|
Object.assign(stats, { kind: 'none', state: 'starting', frames: 0, lines: 0, images: 0 });
|
||||||
|
delete stats.error;
|
||||||
|
delete stats.player;
|
||||||
|
delete stats.items;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function render(view: View): Promise<void> {
|
||||||
|
reset();
|
||||||
|
if (views.length > 1) {
|
||||||
|
const back = document.createElement('a');
|
||||||
|
back.href = '#';
|
||||||
|
back.id = 'back';
|
||||||
|
back.textContent = '← Back';
|
||||||
|
back.addEventListener('click', (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
history.back();
|
||||||
|
});
|
||||||
|
$('#actions').append(back);
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await view();
|
||||||
|
} catch (e) {
|
||||||
|
fail(String((e as Error)?.message ?? e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function push(view: View): Promise<void> {
|
||||||
|
views.push(view);
|
||||||
|
history.pushState({ depth: views.length - 1 }, '');
|
||||||
|
return render(view);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('popstate', (e: PopStateEvent) => {
|
||||||
|
const depth = Math.min((e.state as { depth?: number } | null)?.depth ?? 0, views.length - 1);
|
||||||
|
views.length = depth + 1;
|
||||||
|
void render(views[depth]!);
|
||||||
|
});
|
||||||
|
|
||||||
|
let keyring: Promise<MediaKeyring> | null = null;
|
||||||
|
function ring(): Promise<MediaKeyring> {
|
||||||
|
keyring ??= installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
|
||||||
|
return keyring;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function open(g: Grant): Promise<void> {
|
||||||
|
if (g.kind === 'shade.media-grant/v1') await playMedia(g);
|
||||||
|
else playLive(g);
|
||||||
|
}
|
||||||
|
|
||||||
async function playMedia(g: MediaGrant): Promise<void> {
|
async function playMedia(g: MediaGrant): Promise<void> {
|
||||||
stats.kind = 'media';
|
stats.kind = 'media';
|
||||||
setStatus('starting the decryption worker…');
|
setStatus('starting the decryption worker…');
|
||||||
const keyring = await installMediaWorker(new URL('sw.js', location.href).pathname, new URL('./', location.href).pathname);
|
const src = await (await ring()).add(g);
|
||||||
const src = await keyring.add(g);
|
|
||||||
const head = await fetch(src, { method: 'HEAD' });
|
const head = await fetch(src, { method: 'HEAD' });
|
||||||
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
|
if (!head.ok) return fail(`could not open: ${head.status} ${await head.text()}`);
|
||||||
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
|
const mime = head.headers.get('content-type') ?? 'application/octet-stream';
|
||||||
const size = Number(head.headers.get('content-length'));
|
const size = Number(head.headers.get('content-length'));
|
||||||
stats.mime = mime;
|
stats.mime = mime;
|
||||||
|
if (mime === ALBUM_MIME) return showAlbum(parseAlbum(new Uint8Array(await (await fetch(src)).arrayBuffer())));
|
||||||
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
|
const name = decodeURIComponent(/filename\*=UTF-8''([^;]+)/.exec(head.headers.get('content-disposition') ?? '')?.[1] ?? '');
|
||||||
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
|
$('#title').textContent = g.meta?.name ?? (name || 'Sealed media');
|
||||||
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
|
$('#sub').textContent = `${mime} · ${human(size)} · end-to-end encrypted`;
|
||||||
@@ -105,6 +177,73 @@ async function playMedia(g: MediaGrant): Promise<void> {
|
|||||||
$('#actions').append(a);
|
$('#actions').append(a);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** What an item is, from its grant's meta preview (before opening it). */
|
||||||
|
function itemKind(g: Grant): string {
|
||||||
|
if (g.kind === 'shade.live-grant/v1') return 'live';
|
||||||
|
const mime = g.meta?.mime ?? '';
|
||||||
|
if (mime === ALBUM_MIME) return 'album';
|
||||||
|
return mime.split('/')[0] || 'file';
|
||||||
|
}
|
||||||
|
|
||||||
|
const ICONS: Record<string, string> = { album: '▦', audio: '♪', text: '≡', live: '●', file: '⬚', video: '▶', image: '◩' };
|
||||||
|
|
||||||
|
async function showAlbum(album: Album): Promise<void> {
|
||||||
|
stats.kind = 'album';
|
||||||
|
stats.items = album.items.length;
|
||||||
|
$('#title').textContent = album.title || 'Album';
|
||||||
|
const counts = new Map<string, number>();
|
||||||
|
for (const it of album.items) counts.set(itemKind(it), (counts.get(itemKind(it)) ?? 0) + 1);
|
||||||
|
$('#sub').textContent = `album · ${[...counts].map(([k, n]) => `${n} ${k}`).join(', ') || 'empty'} · end-to-end encrypted`;
|
||||||
|
const stage = $('#stage');
|
||||||
|
stage.className = 'album';
|
||||||
|
const grid = document.createElement('div');
|
||||||
|
grid.className = 'grid';
|
||||||
|
stage.append(grid);
|
||||||
|
const kr = await ring();
|
||||||
|
for (const [i, item] of album.items.entries()) {
|
||||||
|
const kind = itemKind(item);
|
||||||
|
const card = document.createElement('button');
|
||||||
|
card.className = 'card';
|
||||||
|
card.dataset.kind = kind;
|
||||||
|
const thumb = document.createElement('div');
|
||||||
|
thumb.className = 'thumb';
|
||||||
|
thumb.textContent = ICONS[kind] ?? ICONS.file!;
|
||||||
|
const label = document.createElement('div');
|
||||||
|
label.className = 'name';
|
||||||
|
label.textContent = item.meta?.name ?? `Item ${i + 1}`;
|
||||||
|
const sub = document.createElement('div');
|
||||||
|
sub.className = 'kind';
|
||||||
|
sub.textContent = kind === 'live' ? 'live channel' : kind === 'album' ? 'album' : (item.meta?.mime ?? kind);
|
||||||
|
card.append(thumb, label, sub);
|
||||||
|
card.addEventListener('click', () => void push(() => open(item)));
|
||||||
|
grid.append(card);
|
||||||
|
// Previews decrypt through the worker like the item itself: an image
|
||||||
|
// shows itself, a video its first frame. Fetched only as cards scroll in.
|
||||||
|
if (item.kind === 'shade.media-grant/v1' && (kind === 'image' || kind === 'video')) {
|
||||||
|
const io = new IntersectionObserver(async (entries) => {
|
||||||
|
if (!entries.some((e) => e.isIntersecting)) return;
|
||||||
|
io.disconnect();
|
||||||
|
const src = await kr.add(item);
|
||||||
|
if (kind === 'image') {
|
||||||
|
const img = document.createElement('img');
|
||||||
|
img.alt = '';
|
||||||
|
img.addEventListener('load', () => thumb.replaceChildren(img));
|
||||||
|
img.src = src;
|
||||||
|
} else {
|
||||||
|
const v = document.createElement('video');
|
||||||
|
v.muted = true;
|
||||||
|
v.preload = 'metadata';
|
||||||
|
v.addEventListener('loadeddata', () => thumb.replaceChildren(v));
|
||||||
|
v.src = `${src}#t=1`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
io.observe(card);
|
||||||
|
cleanups.push(() => io.disconnect());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
setStatus(`${album.items.length} item(s)`);
|
||||||
|
}
|
||||||
|
|
||||||
function playLive(g: LiveGrant): void {
|
function playLive(g: LiveGrant): void {
|
||||||
stats.kind = 'live';
|
stats.kind = 'live';
|
||||||
$('#title').textContent = g.meta?.name ?? 'Live channel';
|
$('#title').textContent = g.meta?.name ?? 'Live channel';
|
||||||
@@ -157,9 +296,11 @@ function playLive(g: LiveGrant): void {
|
|||||||
el.id = 'player';
|
el.id = 'player';
|
||||||
stage.append(el);
|
stage.append(el);
|
||||||
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
|
const player = new LivePlayer(el, g, { onState: states, onError: onErr, onOther: other });
|
||||||
|
cleanups.push(() => player.close());
|
||||||
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
|
stats.player = () => ({ ...player.stats(), currentTime: el.currentTime, paused: el.paused, readyState: el.readyState });
|
||||||
} else {
|
} else {
|
||||||
new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
|
const client = new LiveWatchClient(g, { onFrame: other, onState: states, onError: onErr });
|
||||||
|
cleanups.push(() => client.close());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,9 +313,9 @@ async function main(): Promise<void> {
|
|||||||
return fail(`no grant in this link — ${(e as Error).message}`);
|
return fail(`no grant in this link — ${(e as Error).message}`);
|
||||||
}
|
}
|
||||||
// Keep the key out of the history and out of anything that reads the URL later.
|
// Keep the key out of the history and out of anything that reads the URL later.
|
||||||
history.replaceState(null, '', location.pathname + location.search);
|
history.replaceState({ depth: 0 }, '', location.pathname + location.search);
|
||||||
if (grant.kind === 'shade.media-grant/v1') await playMedia(grant);
|
views.push(() => open(grant));
|
||||||
else playLive(grant);
|
await render(views[0]!);
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((e) => fail(String((e as Error)?.message ?? e)));
|
main().catch((e) => fail(String((e as Error)?.message ?? e)));
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
*
|
*
|
||||||
* shade media serve relay + media store + watch page
|
* shade media serve relay + media store + watch page
|
||||||
* shade media put film.mkv --server URL seal, upload, print a watch link
|
* shade media put film.mkv --server URL seal, upload, print a watch link
|
||||||
|
* shade media put Season1/ --server URL every file, plus an album: one link for all
|
||||||
* shade media get <link> -o out.mkv download and decrypt
|
* shade media get <link> -o out.mkv download and decrypt
|
||||||
* shade media ls|rm --server URL
|
* shade media ls|rm --server URL
|
||||||
* tail -f app.log | shade live text --server URL --name "app logs"
|
* tail -f app.log | shade live text --server URL --name "app logs"
|
||||||
@@ -13,12 +14,14 @@
|
|||||||
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
|
* `$XDG_CONFIG_HOME/shade/` and reused; nothing to configure.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { chmod, mkdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
import { chmod, mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
|
||||||
import { createWriteStream } from 'node:fs';
|
import { createWriteStream } from 'node:fs';
|
||||||
import { homedir, tmpdir } from 'node:os';
|
import { homedir, tmpdir } from 'node:os';
|
||||||
import { basename, extname, join } from 'node:path';
|
import { basename, extname, join } from 'node:path';
|
||||||
import { fromB64u, randomBytes, toB64u, toHex } from './bytes.js';
|
import { fromB64u, randomBytes, toB64u, toHex } from './bytes.js';
|
||||||
import { MediaClient, openGrant } from './client.js';
|
import { ALBUM_MIME } from './album.js';
|
||||||
|
import type { Album } from './album.js';
|
||||||
|
import { MediaClient, openGrant, readAlbum } from './client.js';
|
||||||
import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js';
|
import { encodeGrant, fromCapabilityUrl, toCapabilityUrl } from './grant.js';
|
||||||
import type { Grant, MediaGrant } from './grant.js';
|
import type { Grant, MediaGrant } from './grant.js';
|
||||||
import { LivePublisher } from './live/channel.js';
|
import { LivePublisher } from './live/channel.js';
|
||||||
@@ -130,47 +133,147 @@ async function mediaServe(flags: Flags): Promise<number> {
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `media put a.mkv b.jpg Season1/ …`: one path that is a file uploads that
|
||||||
|
* file; several paths, a directory or `--album T` upload every file and then
|
||||||
|
* an album that holds them all, and print the album's link. Directories
|
||||||
|
* become nested albums, in natural order (episode 2 before episode 10).
|
||||||
|
*/
|
||||||
async function mediaPut(pos: string[], flags: Flags): Promise<number> {
|
async function mediaPut(pos: string[], flags: Flags): Promise<number> {
|
||||||
const file = pos[0];
|
if (pos.length === 0) throw new UsageError('usage: shade media put <file|dir>… --server URL [--album T]');
|
||||||
if (file === undefined) throw new UsageError('usage: shade media put <file> --server URL');
|
|
||||||
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
|
const server = need(flags, 'server', 'SHADE_MEDIA_SERVER');
|
||||||
const meta: MediaMeta = { name: str(flags, 'name') ?? basename(file) };
|
const client = new MediaClient(server, await loadOwnerKey());
|
||||||
const mime = str(flags, 'mime') ?? guessMime(file);
|
|
||||||
if (mime !== undefined) meta.mime = mime;
|
|
||||||
const size = (await stat(file)).size;
|
|
||||||
const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);
|
|
||||||
const started = Date.now();
|
const started = Date.now();
|
||||||
try {
|
const albumTitle = str(flags, 'album');
|
||||||
err(`sealing ${basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`);
|
const oneDir = pos.length === 1 && (await stat(pos[0]!)).isDirectory();
|
||||||
const result = await sealFile(file, tmp, { meta });
|
let grant: MediaGrant;
|
||||||
err(`uploading ${(result.sealedSize / 1048576).toFixed(1)} MiB…`);
|
if (pos.length === 1 && !oneDir && albumTitle === undefined) {
|
||||||
const client = new MediaClient(server, await loadOwnerKey());
|
grant = await putFile(client, pos[0]!, flags, str(flags, 'name'));
|
||||||
const grant = await client.putSealed(result, Bun.file(tmp), {
|
} else if (oneDir) {
|
||||||
meta,
|
// The directory is the album (`--album` renames it), not an album inside one.
|
||||||
...(flags.public === true ? { readToken: null } : {}),
|
grant = await putPath(client, pos[0]!, flags, albumTitle);
|
||||||
});
|
} else {
|
||||||
err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
|
const items: Grant[] = [];
|
||||||
out(flags.json === true ? encodeGrant(grant) : watchLink(server, grant));
|
for (const p of pos) items.push(await putPath(client, p, flags));
|
||||||
} finally {
|
const title = albumTitle ?? 'Album';
|
||||||
await rm(tmp, { force: true });
|
grant = await client.uploadAlbum({ title, items }, putOpts(flags));
|
||||||
|
err(`album "${title}": ${items.length} item(s)`);
|
||||||
}
|
}
|
||||||
|
err(`done in ${((Date.now() - started) / 1000).toFixed(1)} s`);
|
||||||
|
out(flags.json === true ? encodeGrant(grant) : watchLink(server, grant));
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const naturally = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' });
|
||||||
|
|
||||||
|
/** A file, or a directory as an album of its (non-hidden) entries. */
|
||||||
|
async function putPath(client: MediaClient, path: string, flags: Flags, titled?: string): Promise<MediaGrant> {
|
||||||
|
if (!(await stat(path)).isDirectory()) return putFile(client, path, flags);
|
||||||
|
const names = (await readdir(path)).filter((n) => !n.startsWith('.')).sort(naturally.compare);
|
||||||
|
const items: Grant[] = [];
|
||||||
|
for (const n of names) items.push(await putPath(client, join(path, n), flags));
|
||||||
|
const title = titled ?? basename(path.replace(/\/+$/, ''));
|
||||||
|
err(`album "${title}": ${items.length} item(s)`);
|
||||||
|
return client.uploadAlbum({ title, items }, putOpts(flags));
|
||||||
|
}
|
||||||
|
|
||||||
|
function putOpts(flags: Flags): { readToken?: null } {
|
||||||
|
return flags.public === true ? { readToken: null } : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function putFile(client: MediaClient, file: string, flags: Flags, name?: string): Promise<MediaGrant> {
|
||||||
|
const meta: MediaMeta = { name: name ?? basename(file) };
|
||||||
|
// --mime names one file's type; in an album every file is guessed.
|
||||||
|
const mime = (name !== undefined || flags.album === undefined ? str(flags, 'mime') : undefined) ?? guessMime(file);
|
||||||
|
if (mime !== undefined) meta.mime = mime;
|
||||||
|
const size = (await stat(file)).size;
|
||||||
|
const tmp = join(tmpdir(), `shade-seal-${toHex(randomBytes(8))}.smf`);
|
||||||
|
try {
|
||||||
|
err(`sealing ${basename(file)} (${(size / 1048576).toFixed(1)} MiB)…`);
|
||||||
|
const result = await sealFile(file, tmp, { meta });
|
||||||
|
return await client.putSealed(result, Bun.file(tmp), { meta, ...putOpts(flags) });
|
||||||
|
} finally {
|
||||||
|
await rm(tmp, { force: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* `media get <link> [-o path|-]`: a file is written to `path` (default: its
|
||||||
|
* own name); an album becomes a directory of its items, nested albums as
|
||||||
|
* subdirectories. Live items cannot be downloaded; their links are listed.
|
||||||
|
*/
|
||||||
async function mediaGet(pos: string[], flags: Flags): Promise<number> {
|
async function mediaGet(pos: string[], flags: Flags): Promise<number> {
|
||||||
const link = pos[0];
|
const link = pos[0];
|
||||||
if (link === undefined) throw new UsageError('usage: shade media get <link> [-o file]');
|
if (link === undefined) throw new UsageError('usage: shade media get <link> [-o file|dir|-]');
|
||||||
const g = fromCapabilityUrl(link);
|
const g = fromCapabilityUrl(link);
|
||||||
if (g.kind !== 'shade.media-grant/v1') throw new UsageError('that link is a live channel — use `shade live watch`');
|
if (g.kind !== 'shade.media-grant/v1') throw new UsageError('that link is a live channel — use `shade live watch`');
|
||||||
|
const target = str(flags, 'out');
|
||||||
const reader = await openGrant(g);
|
const reader = await openGrant(g);
|
||||||
const target = str(flags, 'out') ?? reader.meta.name ?? 'shade-media.bin';
|
if (reader.meta.mime === ALBUM_MIME && target !== '-') {
|
||||||
const ws = target === '-' ? process.stdout : createWriteStream(target);
|
const album = await readAlbum(reader);
|
||||||
|
const dir = target ?? safeName(album.title, 'album');
|
||||||
|
const n = await getAlbum(album, dir, server(g));
|
||||||
|
err(`wrote ${dir}/ (${n} file(s), verified)`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
const path = target ?? safeName(reader.meta.name, 'shade-media.bin');
|
||||||
|
await writeReader(reader, path);
|
||||||
|
if (path !== '-') err(`wrote ${path} (${reader.size} bytes, verified)`);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Origin of the relay a grant points at, for watch links of live items. */
|
||||||
|
function server(g: MediaGrant): string {
|
||||||
|
return g.url !== undefined ? new URL(g.url).origin : 'http://localhost';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function writeReader(reader: Awaited<ReturnType<typeof openGrant>>, path: string): Promise<void> {
|
||||||
|
const ws = path === '-' ? process.stdout : createWriteStream(path);
|
||||||
for await (const chunk of reader.stream()) {
|
for await (const chunk of reader.stream()) {
|
||||||
if (!ws.write(chunk)) await new Promise<void>((r) => ws.once('drain', () => r()));
|
if (!ws.write(chunk)) await new Promise<void>((r) => ws.once('drain', () => r()));
|
||||||
}
|
}
|
||||||
if (ws !== process.stdout) await new Promise<void>((r) => (ws as ReturnType<typeof createWriteStream>).end(() => r()));
|
if (ws !== process.stdout) await new Promise<void>((r) => (ws as ReturnType<typeof createWriteStream>).end(() => r()));
|
||||||
if (target !== '-') err(`wrote ${target} (${reader.size} bytes, verified)`);
|
}
|
||||||
return 0;
|
|
||||||
|
async function getAlbum(album: Album, dir: string, relay: string): Promise<number> {
|
||||||
|
await mkdir(dir, { recursive: true });
|
||||||
|
const taken = new Set<string>();
|
||||||
|
// Names come from whoever sealed the files: never a path, never twice.
|
||||||
|
const unique = (name: string) => {
|
||||||
|
let n = name;
|
||||||
|
const ext = extname(name);
|
||||||
|
for (let i = 2; taken.has(n.toLowerCase()); i++) n = `${name.slice(0, name.length - ext.length)} (${i})${ext}`;
|
||||||
|
taken.add(n.toLowerCase());
|
||||||
|
return n;
|
||||||
|
};
|
||||||
|
let files = 0;
|
||||||
|
for (const [i, item] of album.items.entries()) {
|
||||||
|
const fallback = `item-${i + 1}`;
|
||||||
|
if (item.kind !== 'shade.media-grant/v1') {
|
||||||
|
err(` live: ${item.meta?.name ?? fallback} ${watchLink(relay, item)}`);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const reader = await openGrant(item);
|
||||||
|
if (reader.meta.mime === ALBUM_MIME) {
|
||||||
|
files += await getAlbum(await readAlbum(reader), join(dir, unique(safeName(reader.meta.name, fallback))), relay);
|
||||||
|
} else {
|
||||||
|
const path = join(dir, unique(safeName(reader.meta.name, fallback)));
|
||||||
|
await writeReader(reader, path);
|
||||||
|
err(` ${path}`);
|
||||||
|
files++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return files;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A display name made safe as one path component: the last segment only,
|
||||||
|
* no control characters, no leading dots (no `..`, no hidden files).
|
||||||
|
*/
|
||||||
|
export function safeName(name: string | undefined, fallback: string): string {
|
||||||
|
const last = (name ?? '').split(/[\\/]/).pop() ?? '';
|
||||||
|
const clean = last.replace(/[\u0000-\u001f\u007f]/g, '').replace(/^[.\s]+/, '').trim().slice(0, 200);
|
||||||
|
return clean.length > 0 ? clean : fallback;
|
||||||
}
|
}
|
||||||
|
|
||||||
async function mediaLs(flags: Flags): Promise<number> {
|
async function mediaLs(flags: Flags): Promise<number> {
|
||||||
@@ -371,10 +474,11 @@ export const MEDIA_HELP = `
|
|||||||
Run a media relay: sealed store, live relay, watch page.
|
Run a media relay: sealed store, live relay, watch page.
|
||||||
Only this machine's key (and --owners) may upload/publish.
|
Only this machine's key (and --owners) may upload/publish.
|
||||||
media whoami Print this machine's owner key (to add to a relay's --owners)
|
media whoami Print this machine's owner key (to add to a relay's --owners)
|
||||||
media put <file> --server URL [--name N] [--mime M] [--public] [--json]
|
media put <file|dir>… --server URL [--album T] [--name N] [--mime M] [--public] [--json]
|
||||||
Seal a film/video/image/song, upload it, print a watch link
|
Seal a film/video/image/song, upload it, print a watch link.
|
||||||
media get <link> [-o file|-]
|
Several files or a directory become an album: one link for all.
|
||||||
Download and decrypt a sealed file
|
media get <link> [-o file|dir|-]
|
||||||
|
Download and decrypt a sealed file (an album: a directory)
|
||||||
media ls --server URL Your uploads on that server
|
media ls --server URL Your uploads on that server
|
||||||
media rm <link|id> --server URL
|
media rm <link|id> --server URL
|
||||||
live text --server URL [--name N] [--channel file.json]
|
live text --server URL [--name N] [--channel file.json]
|
||||||
|
|||||||
@@ -3,6 +3,8 @@
|
|||||||
* own, and open anything you hold a grant for.
|
* own, and open anything you hold a grant for.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
|
import { ALBUM_MIME, albumMeta, encodeAlbum, parseAlbum } from './album.js';
|
||||||
|
import type { Album } from './album.js';
|
||||||
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
|
import { randomBytes, sha256, toB64u, toHex } from './bytes.js';
|
||||||
import { MediaFormatError } from './errors.js';
|
import { MediaFormatError } from './errors.js';
|
||||||
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
|
import { mediaGrantFrom, mediaKeysOf } from './grant.js';
|
||||||
@@ -79,6 +81,12 @@ export class MediaClient {
|
|||||||
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
|
return this.putSealed(result, bytes, opts.meta !== undefined ? { ...opts, meta: opts.meta } : opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Seal and upload an album; the grant opens every item in it. */
|
||||||
|
async uploadAlbum(album: Album, opts: Omit<PutOptions, 'meta'> = {}): Promise<MediaGrant> {
|
||||||
|
const meta = albumMeta(album.title);
|
||||||
|
return this.uploadBytes(encodeAlbum(album), { ...opts, meta });
|
||||||
|
}
|
||||||
|
|
||||||
async delete(mediaId: Uint8Array): Promise<boolean> {
|
async delete(mediaId: Uint8Array): Promise<boolean> {
|
||||||
const id = toHex(mediaId);
|
const id = toHex(mediaId);
|
||||||
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
|
const res = await this.fetchFn(mediaUrl(this.server, mediaId), {
|
||||||
@@ -112,3 +120,21 @@ export function openGrant(
|
|||||||
});
|
});
|
||||||
return MediaReader.open(source, mediaKeysOf(grant), opts);
|
return MediaReader.open(source, mediaKeysOf(grant), opts);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** An album holds at most 10 000 grants of well under 1 KiB each. */
|
||||||
|
const MAX_ALBUM_BYTES = 16 * 1024 * 1024;
|
||||||
|
|
||||||
|
/** Open a granted album and read its items. */
|
||||||
|
export async function openAlbum(
|
||||||
|
grant: MediaGrant,
|
||||||
|
opts: ReaderOptions & { fetch?: typeof fetch; url?: string } = {},
|
||||||
|
): Promise<Album> {
|
||||||
|
return readAlbum(await openGrant(grant, opts));
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The items of an album already opened as a reader. */
|
||||||
|
export async function readAlbum(reader: MediaReader): Promise<Album> {
|
||||||
|
if (reader.meta.mime !== ALBUM_MIME) throw new MediaFormatError(`not an album (${reader.meta.mime ?? 'no type'})`);
|
||||||
|
if (reader.size > MAX_ALBUM_BYTES) throw new MediaFormatError('album larger than 16 MiB');
|
||||||
|
return parseAlbum(await reader.read(0, reader.size));
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,7 +20,9 @@ export type { RangeSource, HttpRangeSourceOptions } from './source.js';
|
|||||||
export * from './grant.js';
|
export * from './grant.js';
|
||||||
export { OwnerKey, verifyOwner, READ_TOKEN_HEADER, READ_HASH_HEADER } from './owner.js';
|
export { OwnerKey, verifyOwner, READ_TOKEN_HEADER, READ_HASH_HEADER } from './owner.js';
|
||||||
export type { OwnerOp } from './owner.js';
|
export type { OwnerOp } from './owner.js';
|
||||||
export { MediaClient, openGrant, mediaUrl } from './client.js';
|
export { MediaClient, openGrant, openAlbum, readAlbum, mediaUrl } from './client.js';
|
||||||
|
export { ALBUM_KIND, ALBUM_MIME, MAX_ALBUM_ITEMS, encodeAlbum, parseAlbum, isAlbum, albumMeta, isMediaGrant } from './album.js';
|
||||||
|
export type { Album } from './album.js';
|
||||||
export type { PutOptions } from './client.js';
|
export type { PutOptions } from './client.js';
|
||||||
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
|
export { LivePublisher, LiveSubscriber, epochKeys, chainStep, MAX_SKIP, MAX_SKIPPED_KEYS } from './live/channel.js';
|
||||||
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
|
export type { FrameOptions, PublisherOptions, GrantOptions, ReceivedFrame } from './live/channel.js';
|
||||||
|
|||||||
@@ -165,7 +165,8 @@ function toBytes(data: unknown): Uint8Array | null {
|
|||||||
export interface LiveRelay {
|
export interface LiveRelay {
|
||||||
app: Hono;
|
app: Hono;
|
||||||
/** Channels currently held, for metrics and tests. */
|
/** Channels currently held, for metrics and tests. */
|
||||||
stats(): { channels: number; viewers: number; backlogBytes: number };
|
/** `framesIn`: frames accepted from publishers since the relay started. */
|
||||||
|
stats(): { channels: number; viewers: number; backlogBytes: number; framesIn: number };
|
||||||
/** Drop idle channels now (also runs on a timer). */
|
/** Drop idle channels now (also runs on a timer). */
|
||||||
sweep(): void;
|
sweep(): void;
|
||||||
stop(): void;
|
stop(): void;
|
||||||
@@ -178,6 +179,7 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
|||||||
const maxFrames = opts.maxBacklogFrames ?? 5000;
|
const maxFrames = opts.maxBacklogFrames ?? 5000;
|
||||||
const highWater = opts.viewerHighWater ?? 8 * 1024 * 1024;
|
const highWater = opts.viewerHighWater ?? 8 * 1024 * 1024;
|
||||||
const idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
|
const idleMs = opts.idleRetentionMs ?? 10 * 60 * 1000;
|
||||||
|
let framesIn = 0;
|
||||||
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
|
const maxFrameBytes = opts.maxFrameBytes ?? 16 * 1024 * 1024 + 256;
|
||||||
const channels = new Map<string, Channel>();
|
const channels = new Map<string, Channel>();
|
||||||
const allowedOwners = opts.allowedOwners !== undefined ? new Set(opts.allowedOwners) : null;
|
const allowedOwners = opts.allowedOwners !== undefined ? new Set(opts.allowedOwners) : null;
|
||||||
@@ -284,6 +286,7 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
|||||||
trim(ch);
|
trim(ch);
|
||||||
}
|
}
|
||||||
if ((flags & FLAG_END) !== 0) ch.ended = true;
|
if ((flags & FLAG_END) !== 0) ch.ended = true;
|
||||||
|
framesIn++;
|
||||||
for (const v of ch.viewers) deliver(v, copy, sticky, keyframe, ch.sawKeyframe);
|
for (const v of ch.viewers) deliver(v, copy, sticky, keyframe, ch.sawKeyframe);
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -441,7 +444,7 @@ export function createLiveRelay(opts: LiveRelayOptions): LiveRelay {
|
|||||||
viewers += ch.viewers.size;
|
viewers += ch.viewers.size;
|
||||||
backlogBytes += ch.backlogBytes;
|
backlogBytes += ch.backlogBytes;
|
||||||
}
|
}
|
||||||
return { channels: channels.size, viewers, backlogBytes };
|
return { channels: channels.size, viewers, backlogBytes, framesIn };
|
||||||
},
|
},
|
||||||
sweep,
|
sweep,
|
||||||
stop() {
|
stop() {
|
||||||
|
|||||||
@@ -39,6 +39,16 @@ const HTML = `<!doctype html>
|
|||||||
#status[data-tone="warn"]::before { background: var(--warn); }
|
#status[data-tone="warn"]::before { background: var(--warn); }
|
||||||
#status[data-tone="bad"]::before { background: var(--bad); }
|
#status[data-tone="bad"]::before { background: var(--bad); }
|
||||||
#status[data-tone="bad"] { color: var(--bad); }
|
#status[data-tone="bad"] { color: var(--bad); }
|
||||||
|
#stage.album { background: transparent; border: 0; border-radius: 0; }
|
||||||
|
.grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); gap: 14px; }
|
||||||
|
.card { background: var(--panel); border: 1px solid var(--line); border-radius: 10px; overflow: hidden; cursor: pointer; text-align: left; color: inherit; font: inherit; padding: 0; display: block; }
|
||||||
|
.card:hover, .card:focus-visible { border-color: var(--dim); outline: none; }
|
||||||
|
#stage .thumb { aspect-ratio: 16 / 9; background: #000; display: grid; place-items: center; color: var(--dim); font-size: 30px; overflow: hidden; }
|
||||||
|
#stage .thumb img, #stage .thumb video { width: 100%; height: 100%; max-height: none; object-fit: cover; }
|
||||||
|
.card .name { padding: 9px 11px 2px; font-size: 13.5px; overflow-wrap: anywhere; }
|
||||||
|
.card .kind { padding: 0 11px 10px; font-size: 12px; color: var(--dim); }
|
||||||
|
.card[data-kind="live"] .thumb { color: var(--bad); }
|
||||||
|
#actions { display: inline-flex; gap: 8px; }
|
||||||
#actions a { color: var(--text); font-size: 13px; text-decoration: none; border: 1px solid var(--line); padding: 6px 12px; border-radius: 6px; }
|
#actions a { color: var(--text); font-size: 13px; text-decoration: none; border: 1px solid var(--line); padding: 6px 12px; border-radius: 6px; }
|
||||||
#actions a:hover { border-color: var(--dim); }
|
#actions a:hover { border-color: var(--dim); }
|
||||||
</style>
|
</style>
|
||||||
|
|||||||
112
packages/shade-media/tests/album.test.ts
Normal file
112
packages/shade-media/tests/album.test.ts
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
import { describe, test, expect } from 'bun:test';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
import { createMediaRoutes, MemoryMediaStore } from '../src/server.js';
|
||||||
|
import {
|
||||||
|
ALBUM_MIME,
|
||||||
|
MAX_ALBUM_ITEMS,
|
||||||
|
MediaClient,
|
||||||
|
MediaFormatError,
|
||||||
|
OwnerKey,
|
||||||
|
LivePublisher,
|
||||||
|
encodeAlbum,
|
||||||
|
isAlbum,
|
||||||
|
openAlbum,
|
||||||
|
openGrant,
|
||||||
|
parseAlbum,
|
||||||
|
} from '../src/index.js';
|
||||||
|
import type { Grant, MediaGrant } from '../src/index.js';
|
||||||
|
import { safeName } from '../src/cli.js';
|
||||||
|
|
||||||
|
const enc = new TextEncoder();
|
||||||
|
|
||||||
|
function serve() {
|
||||||
|
const app = new Hono();
|
||||||
|
app.route('/', createMediaRoutes(new MemoryMediaStore()));
|
||||||
|
const server = Bun.serve({ port: 0, fetch: (req) => app.fetch(req) });
|
||||||
|
return { server, base: `http://localhost:${server.port}` };
|
||||||
|
}
|
||||||
|
|
||||||
|
describe('album format', () => {
|
||||||
|
const live = new LivePublisher({ meta: { name: 'Kamera 1', mime: 'video/webm' } }).grant({ from: 'now' });
|
||||||
|
|
||||||
|
test('round trip keeps every grant, media and live, byte for byte', async () => {
|
||||||
|
const { server, base } = serve();
|
||||||
|
try {
|
||||||
|
const client = new MediaClient(base, OwnerKey.generate());
|
||||||
|
const a = await client.uploadBytes(enc.encode('one'), { meta: { name: 'E01.mkv', mime: 'video/x-matroska' } });
|
||||||
|
const b = await client.uploadBytes(enc.encode('two'), { meta: { name: 'cover.jpg', mime: 'image/jpeg' } });
|
||||||
|
const items: Grant[] = [a, b, live];
|
||||||
|
const back = parseAlbum(encodeAlbum({ title: 'Sesong 1 — «Vinter»', items }));
|
||||||
|
expect(back.title).toBe('Sesong 1 — «Vinter»');
|
||||||
|
expect(back.items).toEqual(items);
|
||||||
|
} finally {
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test('strict: wrong kind, bad items, too many items, junk', () => {
|
||||||
|
const wrap = (o: unknown) => enc.encode(JSON.stringify(o));
|
||||||
|
expect(() => parseAlbum(wrap({ kind: 'shade.album/v2', title: '', items: [] }))).toThrow(MediaFormatError);
|
||||||
|
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: 1, items: [] }))).toThrow(/title/);
|
||||||
|
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: '', items: [{ kind: 'shade.media-grant/v1' }] }))).toThrow(/item 0/);
|
||||||
|
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: '', items: ['x'] }))).toThrow(/item 0/);
|
||||||
|
expect(() => parseAlbum(wrap({ kind: 'shade.album/v1', title: '', items: new Array(MAX_ALBUM_ITEMS + 1).fill({}) }))).toThrow(/more than/);
|
||||||
|
expect(() => parseAlbum(enc.encode('{"kind":'))).toThrow(MediaFormatError);
|
||||||
|
expect(() => parseAlbum(new Uint8Array([0xff, 0xfe]))).toThrow(MediaFormatError);
|
||||||
|
expect(() => encodeAlbum({ title: 'x'.repeat(513), items: [] })).toThrow(/title/);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('albums over the media routes', () => {
|
||||||
|
test('upload items + album; one grant opens all; the relay sees one more opaque object', async () => {
|
||||||
|
const { server, base } = serve();
|
||||||
|
try {
|
||||||
|
const client = new MediaClient(base, OwnerKey.generate());
|
||||||
|
const files = ['E01', 'E02', 'E10'].map((n, i) => ({ name: `${n}.webm`, bytes: enc.encode(`episode ${i}`.repeat(1000)) }));
|
||||||
|
const grants: MediaGrant[] = [];
|
||||||
|
for (const f of files) grants.push(await client.uploadBytes(f.bytes, { meta: { name: f.name, mime: 'video/webm' } }));
|
||||||
|
const inner = await client.uploadAlbum({ title: 'Extras', items: [grants[0]!] });
|
||||||
|
const album = await client.uploadAlbum({ title: 'Sesong 1', items: [...grants, inner] });
|
||||||
|
|
||||||
|
expect(isAlbum(album)).toBe(true);
|
||||||
|
expect(isAlbum(grants[0])).toBe(false);
|
||||||
|
// The grant alone is enough: open the album, then every item in it.
|
||||||
|
const opened = await openAlbum(album);
|
||||||
|
expect(opened.title).toBe('Sesong 1');
|
||||||
|
expect(opened.items.map((g) => g.meta?.name)).toEqual(['E01.webm', 'E02.webm', 'E10.webm', 'Extras']);
|
||||||
|
for (const [i, f] of files.entries()) {
|
||||||
|
const r = await openGrant(opened.items[i] as MediaGrant);
|
||||||
|
expect(Buffer.from(await r.read(0, r.size)).equals(Buffer.from(f.bytes))).toBe(true);
|
||||||
|
}
|
||||||
|
expect((await openAlbum(opened.items[3] as MediaGrant)).items[0]).toEqual(grants[0]!);
|
||||||
|
// A film is not an album.
|
||||||
|
await expect(openAlbum(grants[0]!)).rejects.toThrow(/not an album/);
|
||||||
|
|
||||||
|
// What the relay holds: five sealed objects of plain sizes, no names, no
|
||||||
|
// types, nothing linking the album to its items.
|
||||||
|
const list = await client.list();
|
||||||
|
expect(list.items.length).toBe(5);
|
||||||
|
const raw = await (await fetch(album.url!, { headers: { 'x-shade-read': Buffer.from(album.readToken!).toString('base64url') } })).arrayBuffer();
|
||||||
|
const text = Buffer.from(raw).toString('latin1');
|
||||||
|
for (const leak of ['Sesong', 'E01', ALBUM_MIME, 'shade.album', 'shade.media-grant']) expect(text.includes(leak)).toBe(false);
|
||||||
|
} finally {
|
||||||
|
server.stop(true);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('safeName: names from a sealed file never become paths', () => {
|
||||||
|
test.each([
|
||||||
|
['film.mkv', 'film.mkv'],
|
||||||
|
['../../.bashrc', 'bashrc'],
|
||||||
|
['/etc/passwd', 'passwd'],
|
||||||
|
['C:\\Windows\\evil.dll', 'evil.dll'],
|
||||||
|
['..', 'fallback'],
|
||||||
|
['.hidden', 'hidden'],
|
||||||
|
['a\u0000b\u001fc\u007f.txt', 'abc.txt'],
|
||||||
|
[' ', 'fallback'],
|
||||||
|
[undefined, 'fallback'],
|
||||||
|
] as const)('%p → %p', (input, want) => {
|
||||||
|
expect(safeName(input, 'fallback')).toBe(want);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -191,7 +191,9 @@ describe('live relay over real WebSockets', () => {
|
|||||||
for (let i = 0; i < 30; i++) {
|
for (let i = 0; i < 30; i++) {
|
||||||
await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 });
|
await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 });
|
||||||
}
|
}
|
||||||
await client.flush();
|
// flush() means sent, not received: wait until the relay holds all 31,
|
||||||
|
// or a fast viewer joins mid-burst and (correctly) gets an older backlog.
|
||||||
|
await until(() => relay.stats().framesIn === 31);
|
||||||
|
|
||||||
const early: ReceivedFrame[] = [];
|
const early: ReceivedFrame[] = [];
|
||||||
const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant;
|
const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant;
|
||||||
|
|||||||
@@ -58,6 +58,8 @@ import { LivePublisher, epochKeys, chainStep, linkEpochSeed } from '../packages/
|
|||||||
import { encodeContent, decodeFrame } from '../packages/shade-media/src/live/frame.js';
|
import { encodeContent, decodeFrame } from '../packages/shade-media/src/live/frame.js';
|
||||||
import type { LiveContent } from '../packages/shade-media/src/live/frame.js';
|
import type { LiveContent } from '../packages/shade-media/src/live/frame.js';
|
||||||
import { encodeGrant } from '../packages/shade-media/src/grant.js';
|
import { encodeGrant } from '../packages/shade-media/src/grant.js';
|
||||||
|
import type { MediaGrant } from '../packages/shade-media/src/grant.js';
|
||||||
|
import { albumMeta, encodeAlbum } from '../packages/shade-media/src/album.js';
|
||||||
import { ed25519PublicKeyFromSeed as edPub } from '../packages/shade-crypto-web/src/index.js';
|
import { ed25519PublicKeyFromSeed as edPub } from '../packages/shade-crypto-web/src/index.js';
|
||||||
|
|
||||||
const VECTOR_FILE_VERSION = 2;
|
const VECTOR_FILE_VERSION = 2;
|
||||||
@@ -1083,6 +1085,29 @@ async function generateMediaVectors(): Promise<Vector[]> {
|
|||||||
description: 'live grant: wire JSON of a link grant (base64url fields, from: now at seq 0)',
|
description: 'live grant: wire JSON of a link grant (base64url fields, from: now at seq 0)',
|
||||||
json: encodeGrant(grant),
|
json: encodeGrant(grant),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Album: a sealed file whose plaintext lists grants — a film, a nested
|
||||||
|
// album and the live link grant above.
|
||||||
|
const film: MediaGrant = {
|
||||||
|
kind: 'shade.media-grant/v1',
|
||||||
|
mediaId: new Uint8Array(16).fill(0x11),
|
||||||
|
mediaKey: new Uint8Array(32).fill(0x22),
|
||||||
|
rootDigest: new Uint8Array(32).fill(0x33),
|
||||||
|
url: 'https://relay.example/v1/media/11111111111111111111111111111111',
|
||||||
|
meta: { name: 'Episode 1.mkv', mime: 'video/x-matroska' },
|
||||||
|
};
|
||||||
|
const nested: MediaGrant = { ...film, mediaId: new Uint8Array(16).fill(0x44), meta: albumMeta('Ekstra') };
|
||||||
|
const albumPlain = encodeAlbum({ title: 'Sesong 1 — «Vinter»', items: [film, nested, grant] });
|
||||||
|
const sealedAlbum = await sealWithPinnedKeys(albumPlain, mediaId, mediaKey, { segmentSize: 4096, meta: albumMeta('Sesong 1 — «Vinter»') });
|
||||||
|
vectors.push({
|
||||||
|
description: 'album: sealed shade.album/v1 holding a media grant, a nested album and a live link grant',
|
||||||
|
sealed: hex(sealedAlbum.bytes),
|
||||||
|
rootDigest: hex(sealedAlbum.result.rootDigest),
|
||||||
|
plaintext: new TextDecoder().decode(albumPlain),
|
||||||
|
title: 'Sesong 1 — «Vinter»',
|
||||||
|
itemKinds: ['shade.media-grant/v1', 'shade.media-grant/v1', 'shade.live-grant/v1'],
|
||||||
|
itemNames: ['Episode 1.mkv', 'Ekstra', grant.meta?.name ?? ''],
|
||||||
|
});
|
||||||
return vectors;
|
return vectors;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -138,6 +138,23 @@
|
|||||||
{
|
{
|
||||||
"description": "live grant: wire JSON of a link grant (base64url fields, from: now at seq 0)",
|
"description": "live grant: wire JSON of a link grant (base64url fields, from: now at seq 0)",
|
||||||
"json": "{\"kind\":\"shade.live-grant/v1\",\"channelId\":\"EBESExQVFhcYGRobHB0eHw\",\"signingKey\":\"JUO5L_EJVRFHatyDadtt3JM2ZaEZeN2hQE7hBmypVZ0\",\"epoch\":0,\"seq\":0,\"chainKey\":\"E6_jBkmqrEm5L2k4DEJCZf4Sw-pHpHVbBu8X2ROtkVs\",\"stickyKey\":\"5Ej5ayGHESce-3SHm4PaGvZrzkWDAEiGSyZ25yiwk_s\",\"channelSecret\":\"gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp8\",\"url\":\"wss://relay.example/v1/live/EBESExQVFhcYGRobHB0eHw\",\"token\":\"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU\",\"meta\":{\"name\":\"kanal\",\"mime\":\"text/plain\"}}"
|
"json": "{\"kind\":\"shade.live-grant/v1\",\"channelId\":\"EBESExQVFhcYGRobHB0eHw\",\"signingKey\":\"JUO5L_EJVRFHatyDadtt3JM2ZaEZeN2hQE7hBmypVZ0\",\"epoch\":0,\"seq\":0,\"chainKey\":\"E6_jBkmqrEm5L2k4DEJCZf4Sw-pHpHVbBu8X2ROtkVs\",\"stickyKey\":\"5Ej5ayGHESce-3SHm4PaGvZrzkWDAEiGSyZ25yiwk_s\",\"channelSecret\":\"gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp8\",\"url\":\"wss://relay.example/v1/live/EBESExQVFhcYGRobHB0eHw\",\"token\":\"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU\",\"meta\":{\"name\":\"kanal\",\"mime\":\"text/plain\"}}"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"description": "album: sealed shade.album/v1 holding a media grant, a nested album and a live link grant",
|
||||||
|
"sealed": "cd6f802752a18e84202f631e652a5652c8657b42715d8acc387a5ed39df3ea319df8a9f1d0180e15f6b4cb6e3f055cad44702a97a04b591f702ab3112a1ac78a8869aff0c92f49989f7a03c878043f0b770420264708e212c41ef4fbd9ab7dc9f215783c2db8d8964eb6b9b9047c436ee7091d5a0d86b4fc13ded73abfee300a34a2afa5bf6fd68682b1053abeccb4eb48b446cd9fdefc5f7a6f3aa4bac533085cf47d5b6ba89376ded9d64dddcd8e67fec6d661978a6961b4d708489a5329d02ca49362f0fc27d28789652c2626eae7bd90a96ec9b7074101a6727f7c09eed3af0a909df555251a8ceb6a240cc8accd2c73cb7510a87731e537b55c42c9210cdb175bd826890a138f4297a70e57cb7672bec0cc1fb926418eca82060f3457b3fcd7128e553d6bc3fdf08c9e2b644d5db0643b9760d53e5046b3e9fcd5b38cdb24a946b15ba73403156b0f53b9472b8688f5dd76e0c31667b5f1a7b82180c522ff60f38f09d6d7e15618e2ea15f84409254d83d8f0bf499020f68de5b2d0bb51893a641b5b3bf05a06f5effda1e04f3c8d5fa0c6f94a5ee672bc94856717443bd31ec860037eb4f8fd530079abafe2380903fd2e9b190d10f58770d0c50d87bfaa36aa4df7399f98f82e6dac1cd29da23e16d6097e86abf6c682c507d4adc15462b28c9d51d90b4ca173da7ce63f9f083cbdd5f06488f849dc0f6e76a4ed17ae3609a65ed4b46ce55f04aee3e1349db0a88d90bcfd0916a9a1e946ba5c0e242cf3599967a5b4411d7824e862df19802b3af43b9d635d5e61577d605fbfc5205f857c438be313513da59a006507509853db012ca58d670ebaf2b563284c5e07b1b4b4393edf8c84419db3696183777a623feabd05934bd9e549d8b9edaba68a0ad5bcd18f9e2d8c2ec5626c34854d8c738584cbcc55574c929583eb4a47d8790f0420703c0dcf205047cc5e278c91ba7c35c4b90764b8e782e8bb04436415b663fd19d161747e58b08c2abca8e1a66a019ebd0e613fad4ab93557b0360bcac26d3453fd216c7c7431f7e185e2ebfee4c38959c912e7fb1d16968a2edce04c8495e6ef2d187a3fe6162cbda091dc30370058136c1d55c037621af1b50ebb8a140c9c14e82e94e9db2a9fc7e5020ab61757888611a573b3bb9cca044787c9a919a7f27a05bbd20bad9ad595ef2a708efcb00c3f4e32acd36dbac35f816627e9571be709a2a1cd32418934682d0dac1db1c3ae906b9d1f5f6322e3171ffe088ec556d13327448ccfafbf1de1fdfaaa3315647707e10494b78a3c5dcde7b05c6bcb41e17cc8b5969af54773a0ac576540b8701edd8c80e3c96669f4bc1929e0ec075a7de30edad9d2db01391a318dd84ddd0777a5faa1dd1f78a8028313810ca87122d6c0674cdef4fc343a917c73e2a527c5d0db58e6b8dfeb7afa3e8a642b9fa856f4c4333f19de6cef9e30be95f8d38d15150c1420ec4cd1b3c275e50b857e82614f19a7926760175f6f831c03997eef3ccb6ac4fc37ebb2d2f24666f8802b62b97e80188ab942cb23b2d55060084e0f798d5544b21e9356234e8137a1a9cbdda77904f6f8837cc4a1042bb06ea7eb2a29cb8451048bc73206bc3d683d37f05d68b7d3932b467f532f06d7c6c7b291b9aa0678c8e8d0c757a7683ce7f464026f9b02b5c30cce6e9d5594c556f55ad635427bca8568d935712a474e4166e811f57e6bab914f428bbbd7a8c0e0f98c2ac41fdbc1d3212ef004949fecdf176392cc83c6e5b1d2ef14de7765bf296da9cb45f3f3b78f964c37915ff92ead13c0019551451ab0114628c73ebe62cd81e401920068dace7bb2ffa0f319a8b1ea583cb8fb94734519759f85d30957d70ed51be32b74a343983e99b9902c1ecd53cc708e534d4631010000000000100000000000000004b30000005ca0a1a2a3a4a5a6a7a8a9aaabacadaeaf0000000000000000000000000000000000000000534d4631",
|
||||||
|
"rootDigest": "3f2aed0d1c8919eaeffef9e1d68425d1037ecddac2ba7862b3f492202d99aa02",
|
||||||
|
"plaintext": "{\"kind\":\"shade.album/v1\",\"title\":\"Sesong 1 — «Vinter»\",\"items\":[{\"kind\":\"shade.media-grant/v1\",\"mediaId\":\"EREREREREREREREREREREQ\",\"key\":\"IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI\",\"root\":\"3333333333333333333333333333333333333333333333333333333333333333\",\"url\":\"https://relay.example/v1/media/11111111111111111111111111111111\",\"meta\":{\"name\":\"Episode 1.mkv\",\"mime\":\"video/x-matroska\"}},{\"kind\":\"shade.media-grant/v1\",\"mediaId\":\"RERERERERERERERERERERA\",\"key\":\"IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI\",\"root\":\"3333333333333333333333333333333333333333333333333333333333333333\",\"url\":\"https://relay.example/v1/media/11111111111111111111111111111111\",\"meta\":{\"mime\":\"application/vnd.shade.album+json\",\"name\":\"Ekstra\"}},{\"kind\":\"shade.live-grant/v1\",\"channelId\":\"EBESExQVFhcYGRobHB0eHw\",\"signingKey\":\"JUO5L_EJVRFHatyDadtt3JM2ZaEZeN2hQE7hBmypVZ0\",\"epoch\":0,\"seq\":0,\"chainKey\":\"E6_jBkmqrEm5L2k4DEJCZf4Sw-pHpHVbBu8X2ROtkVs\",\"stickyKey\":\"5Ej5ayGHESce-3SHm4PaGvZrzkWDAEiGSyZ25yiwk_s\",\"channelSecret\":\"gIGCg4SFhoeIiYqLjI2Oj5CRkpOUlZaXmJmam5ydnp8\",\"url\":\"wss://relay.example/v1/live/EBESExQVFhcYGRobHB0eHw\",\"token\":\"VVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVU\",\"meta\":{\"name\":\"kanal\",\"mime\":\"text/plain\"}}]}",
|
||||||
|
"title": "Sesong 1 — «Vinter»",
|
||||||
|
"itemKinds": [
|
||||||
|
"shade.media-grant/v1",
|
||||||
|
"shade.media-grant/v1",
|
||||||
|
"shade.live-grant/v1"
|
||||||
|
],
|
||||||
|
"itemNames": [
|
||||||
|
"Episode 1.mkv",
|
||||||
|
"Ekstra",
|
||||||
|
"kanal"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user