From f5125b8f66db9e16561fb067d292d7831022c5d0 Mon Sep 17 00:00:00 2001 From: Sterister Date: Mon, 19 Oct 2026 00:18:31 +0200 Subject: [PATCH] =?UTF-8?q?feat(android):=20MediaUploader=20=E2=80=94=20a?= =?UTF-8?q?=20phone=20puts=20films=20on=20a=20relay,=20in=20resumable=20pi?= =?UTF-8?q?eces?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MediaOwner signs owner requests and MediaUploader speaks the piece protocol of media put (window, retries, resync after a lost answer). MediaSealer .sealStream seals a film to a file; MediaGrant.encode/capabilityUrl make the link to share. Owner signatures and encoded grants are pinned by new vectors; scripts/media-live-kotlin.ts runs the uploader against a real TS relay with a lost answer and a refused piece injected. Co-Authored-By: Claude Opus 5.5 (1M context) --- CHANGELOG.md | 9 + android/shade-android/build.gradle.kts | 3 +- .../kotlin/no/zyon/shade/media/MediaFormat.kt | 30 +- .../kotlin/no/zyon/shade/media/MediaGrant.kt | 24 ++ .../kotlin/no/zyon/shade/media/MediaOwner.kt | 63 ++++ .../kotlin/no/zyon/shade/media/MediaReader.kt | 19 ++ .../no/zyon/shade/media/MediaUploader.kt | 319 ++++++++++++++++++ .../kotlin/no/zyon/shade/MediaLiveTest.kt | 87 +++++ .../kotlin/no/zyon/shade/MediaVectorTest.kt | 46 +++ docs/media.md | 23 +- scripts/generate-vectors.ts | 53 ++- scripts/media-live-kotlin.ts | 117 +++++++ test-vectors/media.json | 109 ++++++ 13 files changed, 897 insertions(+), 5 deletions(-) create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaOwner.kt create mode 100644 android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt create mode 100644 android/shade-android/src/test/kotlin/no/zyon/shade/MediaLiveTest.kt create mode 100644 scripts/media-live-kotlin.ts diff --git a/CHANGELOG.md b/CHANGELOG.md index a10590c..8d4088b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -113,6 +113,15 @@ New package **`@shade/media`** — see `docs/media.md`. `ShadeMedia.liveMediaSource(grant)` play live WebM/fMP4 in ExoPlayer, with late joining from a keyframe, gap recovery and the timeline rebased to 0:00. +- **Uploads from Kotlin.** `MediaUploader` puts sealed files on a relay from + a phone: one PUT up to 16 MiB, larger ones in pieces with the relay's + window, retries and a resync after a lost answer — the same protocol as + `media put`. `MediaOwner` signs owner requests (byte for byte against the + new owner vector), `MediaSealer.sealStream` seals a film to a file, and + `MediaGrant.encode()` / `capabilityUrl(page)` make the link to share + (against a new grant-encode vector). `scripts/media-live-kotlin.ts` runs it + against a real TS relay with a lost answer and a refused piece injected; + TS reads the film back byte for byte. ### Fixed diff --git a/android/shade-android/build.gradle.kts b/android/shade-android/build.gradle.kts index 1834761..467f0b6 100644 --- a/android/shade-android/build.gradle.kts +++ b/android/shade-android/build.gradle.kts @@ -49,9 +49,10 @@ dependencies { tasks.withType().configureEach { useJUnit() - // VaultLiveTest is gated on this; as an input, a new spec (a new live + // VaultLiveTest and MediaLiveTest are gated on these; as an input, a new spec (a new live // relay) reruns the tests instead of reporting a stale UP-TO-DATE. inputs.property("shadeVaultLiveSpec", System.getenv("SHADE_VAULT_LIVE_SPEC") ?: "") + inputs.property("shadeMediaLiveSpec", System.getenv("SHADE_MEDIA_LIVE_SPEC") ?: "") testLogging { events("passed", "failed", "skipped") showStandardStreams = false diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaFormat.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaFormat.kt index f2eb6ee..86318f2 100644 --- a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaFormat.kt +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaFormat.kt @@ -61,7 +61,10 @@ data class MediaMeta( val extra: Map? = null, ) { /** `JSON.stringify` of the TS-validated object — same key order, same bytes. */ - fun toJson(): String { + fun toJson(): String = stringifyJson(toJsonMap()) + + /** The fields in `toJson`'s order, for embedding in a larger JSON (a grant). */ + internal fun toJsonMap(): Map { val m = LinkedHashMap() mime?.let { m["mime"] = it } name?.let { m["name"] = it } @@ -70,7 +73,7 @@ data class MediaMeta( height?.let { m["height"] = it } createdAt?.let { m["createdAt"] = it } extra?.let { m["extra"] = LinkedHashMap(it) } - return stringifyJson(m) + return m } companion object { @@ -289,6 +292,29 @@ class MediaSealer private constructor( internal fun withPinnedKeys(mediaId: ByteArray, mediaKey: ByteArray, meta: MediaMeta, segmentSize: Int) = MediaSealer(mediaId, mediaKey, segmentSize, meta) + /** + * Seal a stream (a film from the gallery, a recording) to `out`, one + * segment in memory at a time. Neither stream is closed. + */ + fun sealStream( + input: java.io.InputStream, + out: java.io.OutputStream, + meta: MediaMeta = MediaMeta(), + segmentSize: Int = DEFAULT_SEGMENT_SIZE, + ): SealResult { + val sealer = MediaSealer(meta, segmentSize) + val buf = ByteArray(segmentSize) + while (true) { + val n = input.read(buf) + if (n < 0) break + if (n > 0) sealer.push(buf.copyOf(n)).forEach { out.write(it) } + } + val (rest, result) = sealer.finish() + rest.forEach { out.write(it) } + out.flush() + return result + } + /** Seal bytes already in memory. */ fun sealBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE): Pair = MediaSealer(meta, segmentSize).sealAll(plaintext) diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaGrant.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaGrant.kt index 226d536..5c392c3 100644 --- a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaGrant.kt +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaGrant.kt @@ -1,5 +1,6 @@ package no.zyon.shade.media +import no.zyon.shade.serialization.stringifyJson import org.json.JSONException import org.json.JSONObject import java.net.URI @@ -34,6 +35,29 @@ class MediaGrant( } fun open(): MediaReader = MediaReader.open(source(), keys()) + + /** Wire JSON, byte for byte what TS `encodeGrant` writes (field order fixed, meta canonical). */ + fun encode(): String { + val o = LinkedHashMap() + o["kind"] = MEDIA_GRANT_KIND + o["mediaId"] = b64u(mediaId) + o["key"] = b64u(mediaKey) + o["root"] = rootDigest.joinToString("") { "%02x".format(it) } + url?.let { o["url"] = it } + readToken?.let { o["token"] = b64u(it) } + meta?.let { o["meta"] = MediaMeta.validate(it).toJsonMap() } + return stringifyJson(o) + } + + /** `pageUrl#shade=`: the link that opens this file, the key in the fragment (never sent to a server). */ + fun capabilityUrl(pageUrl: String): String = + "${pageUrl.substringBefore('#')}#shade=${b64u(encode().toByteArray(Charsets.UTF_8))}" + + companion object { + /** The grant for a file just sealed (and uploaded to `url`). */ + fun of(r: SealResult, url: String? = null, readToken: ByteArray? = null, meta: MediaMeta? = null) = + MediaGrant(r.mediaId, r.mediaKey, r.rootDigest, url, readToken, meta) + } } class LiveGrant( diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaOwner.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaOwner.kt new file mode 100644 index 0000000..be484c5 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaOwner.kt @@ -0,0 +1,63 @@ +package no.zyon.shade.media + +import com.google.crypto.tink.subtle.Ed25519Sign +import java.security.SecureRandom + +/** + * Who may upload to a relay and delete from it: an Ed25519 key and nothing + * else (mirror of `@shade/media` owner.ts). Requests are signed over a fixed + * string naming the operation, so a signature for one request cannot be + * replayed as another, and over a timestamp the relay accepts within ten + * minutes of its own clock. + */ +class MediaOwner(seed: ByteArray) { + private val seed = seed.copyOf() + private val signer = Ed25519Sign(seed) + val publicKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(seed).publicKey + + init { + require(seed.size == 32) { "owner seed must be 32 bytes" } + } + + /** The key as a relay's owner lists name it (`--owners`, `SHADE_MEDIA_OWNERS`). */ + val id: String get() = b64u(publicKey) + + /** The seed, for keeping — in the Keystore-backed storage, never in plain prefs. */ + fun exportSeed(): ByteArray = seed.copyOf() + + fun headers(op: OwnerOp, at: Long = System.currentTimeMillis()): Map = mapOf( + OWNER_HEADER to id, + AT_HEADER to at.toString(), + SIGNATURE_HEADER to b64u(signer.sign(message(op, at))), + ) + + companion object { + const val OWNER_HEADER = "x-shade-owner" + const val AT_HEADER = "x-shade-at" + const val SIGNATURE_HEADER = "x-shade-signature" + const val READ_HASH_HEADER = "x-shade-read-hash" + const val READ_TOKEN_HEADER = "x-shade-read" + + fun generate(): MediaOwner = MediaOwner(ByteArray(32).also { SecureRandom().nextBytes(it) }) + + /** The exact bytes signed for `op` at `at` — shared with TS through `test-vectors/media.json`. */ + fun message(op: OwnerOp, at: Long): ByteArray = when (op) { + is OwnerOp.Put -> "shade.media-put/v1|${op.id}|${op.size}|${op.readTokenHash}|$at" + is OwnerOp.Upload -> "shade.media-upload/v1|${op.id}|${op.size}|${op.readTokenHash}|$at" + is OwnerOp.Piece -> "shade.media-piece/v1|${op.id}|${op.offset}|${op.length}|$at" + is OwnerOp.Abort -> "shade.media-abort/v1|${op.id}|$at" + is OwnerOp.Delete -> "shade.media-delete/v1|${op.id}|$at" + OwnerOp.List -> "shade.media-list/v1|$at" + }.toByteArray(Charsets.UTF_8) + } +} + +/** What an owner signs. `readTokenHash` is the hex SHA-256 of the read token, or "" for public ciphertext. */ +sealed class OwnerOp { + data class Put(val id: String, val size: Long, val readTokenHash: String) : OwnerOp() + data class Upload(val id: String, val size: Long, val readTokenHash: String) : OwnerOp() + data class Piece(val id: String, val offset: Long, val length: Long) : OwnerOp() + data class Abort(val id: String) : OwnerOp() + data class Delete(val id: String) : OwnerOp() + object List : OwnerOp() +} diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaReader.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaReader.kt index 7298a47..55299a1 100644 --- a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaReader.kt +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaReader.kt @@ -1,9 +1,14 @@ package no.zyon.shade.media +import java.io.Closeable +import java.io.File import java.io.IOException import java.io.InputStream import java.net.HttpURLConnection import java.net.URL +import java.nio.ByteBuffer +import java.nio.channels.FileChannel +import java.nio.file.StandardOpenOption /** Where sealed bytes come from: a size and byte ranges, nothing else. */ interface RangeSource { @@ -21,6 +26,20 @@ class ByteArraySource(private val bytes: ByteArray) : RangeSource { } } +/** A sealed file on disk — a film too large to hold, uploaded a piece at a time. Safe to read from several threads. */ +class FileRangeSource(file: File) : RangeSource, Closeable { + private val ch = FileChannel.open(file.toPath(), StandardOpenOption.READ) + override fun size(): Long = ch.size() + override fun read(offset: Long, length: Int): ByteArray { + val buf = ByteBuffer.allocate(length.coerceAtMost((size() - offset).coerceAtLeast(0).toInt())) + while (buf.hasRemaining()) { + if (ch.read(buf, offset + buf.position()) < 0) break + } + return if (buf.hasRemaining()) buf.array().copyOf(buf.position()) else buf.array() + } + override fun close() = ch.close() +} + /** * HTTP Range reads against the Shade media routes (or any Range-capable * server). The read token, when the grant carries one, rides in diff --git a/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt new file mode 100644 index 0000000..3fafa16 --- /dev/null +++ b/android/shade-android/src/main/kotlin/no/zyon/shade/media/MediaUploader.kt @@ -0,0 +1,319 @@ +package no.zyon.shade.media + +import org.json.JSONException +import org.json.JSONObject +import java.io.File +import java.io.IOException +import java.net.HttpURLConnection +import java.net.URL +import java.security.MessageDigest +import java.security.SecureRandom +import java.util.ArrayDeque +import java.util.TreeSet +import java.util.concurrent.ExecutorCompletionService +import java.util.concurrent.Executors + +/** Files up to this size go up in one PUT; larger ones in pieces (mirror of `@shade/media` upload.ts). */ +const val DEFAULT_CHUNK_BYTES = 16L * 1024 * 1024 +const val OFFSET_HEADER = "x-shade-offset" + +/** Failed tries in a row before a resumable upload gives up. */ +private const val MAX_TRIES = 8 + +/** The relay is restarting, overloaded or the network dropped: try again. */ +private class Transient(message: String) : IOException(message) + +class MediaUploadException(message: String) : IOException(message) + +/** + * Upload sealed files to a Shade relay — mirror of the TS `MediaClient`, so a + * phone can share a film or a video it recorded. Blocking: call it off the + * main thread. + * + * A file above [DEFAULT_CHUNK_BYTES] goes in pieces, up to the relay's + * window of them in flight. A dropped connection or a relay restart costs + * the pieces in flight, not the upload: a failed piece is sent again after + * asking the relay whether it landed after all. Calling [putSealed] again + * with the same seal result and the same sealed file (after the app was + * killed, say) resumes where the relay got to, since the media id is the same. + */ +class MediaUploader( + server: String, + private val owner: MediaOwner, + private val timeoutMs: Int = 60_000, +) { + private val server = server.trimEnd('/') + + fun mediaUrl(mediaId: ByteArray): String = "$server/v1/media/${hex(mediaId)}" + + /** + * Upload an already sealed file; `body` must be exactly `result.sealedSize` + * bytes. `readToken`: what viewers must present — a fresh random one by + * default, `null` for public ciphertext. `onProgress(acked, total)` after + * each piece the relay has. + */ + fun putSealed( + result: SealResult, + body: RangeSource, + readToken: ByteArray? = newReadToken(), + meta: MediaMeta? = null, + onProgress: ((Long, Long) -> Unit)? = null, + ): MediaGrant { + val size = body.size() + if (size != result.sealedSize) throw MediaFormatException("body is $size bytes, the seal produced ${result.sealedSize}") + val readTokenHash = readToken?.let { hex(MessageDigest.getInstance("SHA-256").digest(it)) } ?: "" + val id = hex(result.mediaId) + val url = mediaUrl(result.mediaId) + if (size <= DEFAULT_CHUNK_BYTES) { + val bytes = body.read(0, size.toInt()) + val headers = owner.headers(OwnerOp.Put(id, size, readTokenHash)) + + mapOf("content-type" to "application/vnd.shade.smf1") + + (if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap()) + val res = try { + request("PUT", url, headers, bytes) + } catch (e: IOException) { + throw MediaUploadException("upload failed: ${e.message}") + } + if (res.status != 201) throw MediaUploadException("upload failed: HTTP ${res.status} ${res.text()}") + onProgress?.invoke(size, size) + } else { + Pieces("$url/upload", id, size, readTokenHash, body, onProgress).run() + } + return MediaGrant.of(result, url, readToken, meta) + } + + /** Seal in memory and upload — a photo, a short clip, a document. */ + fun uploadBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), readToken: ByteArray? = newReadToken()): MediaGrant { + val (sealed, result) = MediaSealer.sealBytes(plaintext, meta) + return putSealed(result, ByteArraySource(sealed), readToken, meta) + } + + /** + * Seal `input` into `sealedFile` and upload it — a film without holding it + * in memory. The sealed copy is the caller's: keep it (with the returned + * seal result) until this returns, to resume with [putSealed] if it fails. + */ + fun uploadStream( + input: java.io.InputStream, + sealedFile: File, + meta: MediaMeta = MediaMeta(), + readToken: ByteArray? = newReadToken(), + onProgress: ((Long, Long) -> Unit)? = null, + ): MediaGrant { + val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(input, it, meta) } + return FileRangeSource(sealedFile).use { putSealed(result, it, readToken, meta, onProgress) } + } + + /** Remove one of your files from the relay; false if it was not there. */ + fun delete(mediaId: ByteArray): Boolean { + val res = request("DELETE", mediaUrl(mediaId), owner.headers(OwnerOp.Delete(hex(mediaId))), null) + if (res.status == 404) return false + if (res.status !in 200..299) throw MediaUploadException("delete failed: HTTP ${res.status} ${res.text()}") + return true + } + + private inner class Pieces( + private val at: String, + private val id: String, + private val size: Long, + private val readTokenHash: String, + private val body: RangeSource, + private val onProgress: ((Long, Long) -> Unit)?, + ) { + private inner class Status(json: JSONObject) { + val chunk = json.getLong("chunk") + val window = json.optInt("window", 1).coerceAtLeast(1) + val received = json.getLong("received") + val landed: Set = json.optJSONArray("landed")?.let { a -> (0 until a.length()).map { a.getLong(it) }.toSet() } ?: emptySet() + val complete = json.optBoolean("complete", false) + fun has(offset: Long) = offset < received || (offset / chunk) in landed + } + + /** A request that got no answer (refused, reset, timed out) is worth repeating. */ + private fun send(method: String, headers: Map, body: ByteArray?): Answer = + try { + request(method, at, headers, body) + } catch (e: IOException) { + throw Transient(e.message ?: e.javaClass.simpleName) + } + + private fun fail(res: Answer, what: String): Nothing { + if (res.status >= 500 || res.status == 429) throw Transient("$what: HTTP ${res.status} ${res.text()}") + throw MediaUploadException("upload failed: $what: HTTP ${res.status} ${res.text()}") + } + + /** Retry `fn` while it fails transiently, with backoff; `fn` learns which try it is. */ + private fun retrying(fn: (attempt: Int) -> T): T { + var attempt = 0 + while (true) { + try { + return fn(attempt) + } catch (e: Transient) { + if (attempt + 1 >= MAX_TRIES) throw MediaUploadException("upload failed after $MAX_TRIES tries: ${e.message}") + attempt++ + Thread.sleep(minOf(30_000L, 500L shl attempt)) + } + } + } + + /** Start the upload, or learn how far it got. */ + private fun status(): Status { + val headers = owner.headers(OwnerOp.Upload(id, size, readTokenHash)) + + mapOf("x-shade-size" to size.toString()) + + (if (readTokenHash != "") mapOf(MediaOwner.READ_HASH_HEADER to readTokenHash) else emptyMap()) + val res = send("POST", headers, ByteArray(0)) + if (res.status != 200 && res.status != 201) fail(res, "start") + return try { + Status(JSONObject(res.body)) + } catch (e: JSONException) { + throw Transient("start: the relay's answer is not JSON") + } + } + + private var chunk = 0L + + /** One piece until the relay has it; true once the relay stored the whole file. */ + private fun sendPiece(offset: Long): Boolean = retrying { attempt -> + if (attempt > 0) { + // It may have landed before the connection dropped: ask before sending it again. + val st = status() + if (st.complete) return@retrying true + if (st.has(offset)) return@retrying false + } + val length = minOf(chunk, size - offset) + val piece = body.read(offset, length.toInt()) + if (piece.size.toLong() != length) throw MediaFormatException("the file shrank: read ${piece.size} of $length bytes at $offset") + val res = send( + "PUT", + owner.headers(OwnerOp.Piece(id, offset, length)) + + mapOf("content-type" to "application/octet-stream", OFFSET_HEADER to offset.toString()), + piece, + ) + when (res.status) { + 201 -> true + 200 -> false + // Ahead of the window (pieces before it are still on the way): later. + 409 -> { + val error = try { JSONObject(res.body).optString("error") } catch (e: JSONException) { "" } + if (error == "OFFSET") throw Transient("piece ahead of the upload") + throw MediaUploadException("upload failed: HTTP 409 ${res.text()}") + } + else -> fail(res, "piece at $offset") + } + } + + private inner class Outcome(val offset: Long, val done: Boolean, val error: Throwable?) + + fun run() { + val opened = retrying { status() } + if (opened.complete) { + onProgress?.invoke(size, size) + return + } + chunk = opened.chunk + val window = opened.window + var acked = 0L + var complete = false + val todo = ArrayDeque() + var off = 0L + while (off < size) { + if (opened.has(off)) acked += minOf(chunk, size - off) else todo.add(off) + off += chunk + } + onProgress?.invoke(acked, size) + + val pool = Executors.newFixedThreadPool(window) { r -> Thread(r, "shade-upload").apply { isDaemon = true } } + val done = ExecutorCompletionService(pool) + val flying = TreeSet() + var failure: Throwable? = null + /** + * The relay takes `window` pieces past what it has from the start, so a + * piece is only sent within `window` of the first one not yet answered: + * one slow piece holds the window, rather than pieces past it bouncing. + */ + fun mayLaunch(): Boolean { + if (todo.isEmpty() || flying.size >= window) return false + val lowest = if (flying.isEmpty()) todo.first() else minOf(todo.first(), flying.first()) + return todo.first() < lowest + window * chunk + } + try { + while (!complete && failure == null && (todo.isNotEmpty() || flying.isNotEmpty())) { + while (mayLaunch()) { + val o = todo.removeFirst() + flying.add(o) + done.submit { + try { + Outcome(o, sendPiece(o), null) + } catch (e: Throwable) { + Outcome(o, false, e) + } + } + } + val r = done.take().get() + flying.remove(r.offset) + if (r.error != null) { + failure = failure ?: r.error + continue + } + if (r.done) complete = true + acked += minOf(chunk, size - r.offset) + if (!complete) onProgress?.invoke(acked, size) + } + while (flying.isNotEmpty()) flying.remove(done.take().get().offset) + } finally { + pool.shutdownNow() + } + failure?.let { throw it } + if (!complete) { + // Every piece is in but no answer said so (they crossed a completion + // that failed and was retried): an empty piece at the end finishes it. + retrying { + val res = send("PUT", owner.headers(OwnerOp.Piece(id, size, 0)) + mapOf(OFFSET_HEADER to size.toString()), ByteArray(0)) + if (res.status != 201) fail(res, "finish") + } + } + onProgress?.invoke(size, size) + } + } + + private class Answer(val status: Int, val body: String, private val contentType: String) { + /** + * What a refusal says, for an error message: the relay's JSON as it is, + * but not an HTML error page (a proxy's) poured into a log. + */ + fun text(): String { + if (contentType.contains("text/html") || body.trimStart().startsWith("<")) return "" + return if (body.length > 300) "${body.take(300)}…" else body + } + } + + private fun request(method: String, url: String, headers: Map, body: ByteArray?): Answer { + val c = URL(url).openConnection() as HttpURLConnection + try { + c.requestMethod = method + c.connectTimeout = timeoutMs + c.readTimeout = timeoutMs + c.useCaches = false + for ((k, v) in headers) c.setRequestProperty(k, v) + if (body != null) { + c.doOutput = true + c.setFixedLengthStreamingMode(body.size) + c.outputStream.use { it.write(body) } + } + val status = c.responseCode + val stream = if (status >= 400) c.errorStream else c.inputStream + val text = stream?.use { String(it.readBytes(), Charsets.UTF_8) } ?: "" + return Answer(status, text, c.contentType ?: "") + } finally { + c.disconnect() + } + } + + companion object { + private val rng = SecureRandom() + + fun newReadToken(): ByteArray = ByteArray(32).also { rng.nextBytes(it) } + + private fun hex(b: ByteArray) = b.joinToString("") { "%02x".format(it) } + } +} diff --git a/android/shade-android/src/test/kotlin/no/zyon/shade/MediaLiveTest.kt b/android/shade-android/src/test/kotlin/no/zyon/shade/MediaLiveTest.kt new file mode 100644 index 0000000..7931026 --- /dev/null +++ b/android/shade-android/src/test/kotlin/no/zyon/shade/MediaLiveTest.kt @@ -0,0 +1,87 @@ +package no.zyon.shade + +import no.zyon.shade.media.FileRangeSource +import no.zyon.shade.media.Grants +import no.zyon.shade.media.MediaGrant +import no.zyon.shade.media.MediaMeta +import no.zyon.shade.media.MediaOwner +import no.zyon.shade.media.MediaSealer +import no.zyon.shade.media.MediaUploader +import org.json.JSONObject +import org.junit.Assert.assertEquals +import org.junit.Assert.assertFalse +import org.junit.Assert.assertTrue +import org.junit.Assume.assumeTrue +import org.junit.Test +import java.io.File +import java.security.MessageDigest +import java.security.SecureRandom + +/** + * Live cross-check of [MediaUploader] against the real TS relay — skipped + * unless `SHADE_MEDIA_LIVE_SPEC` points at the spec file a TS driver wrote. + * + * Run it via `bun run scripts/media-live-kotlin.ts`: the driver serves + * `createMediaService` with two faults injected on the pieces, uploads a file + * with the TS client and writes `{ url, seed, tsLink, tsSha256, scratch, + * kotlinOut }`. This test opens the TS file, uploads a film in pieces and a + * photo in one PUT, and records the links in `kotlinOut`; the driver then + * reads the film back with the TS reader. + */ +class MediaLiveTest { + + private fun sha256(b: ByteArray) = MessageDigest.getInstance("SHA-256").digest(b).joinToString("") { "%02x".format(it) } + + private fun fromHex(s: String) = + ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() } + + @Test + fun uploadsInPiecesThroughFaultsForTsToRead() { + val specPath = System.getenv("SHADE_MEDIA_LIVE_SPEC") + assumeTrue("SHADE_MEDIA_LIVE_SPEC not set — live cross-check skipped", !specPath.isNullOrEmpty()) + val spec = JSONObject(File(specPath!!).readText()) + val uploader = MediaUploader(spec.getString("url"), MediaOwner(fromHex(spec.getString("seed")))) + + // Read what TS uploaded, from its link. + val tsGrant = Grants.fromCapabilityUrl(spec.getString("tsLink")) as MediaGrant + tsGrant.open().use { r -> assertEquals(spec.getString("tsSha256"), sha256(r.read(0, r.size.toInt()))) } + + // A film from the phone: sealed to a file, up in three pieces (16 MiB each), + // through a lost answer on the second and a refusal of the third. + val plain = ByteArray(40 * 1024 * 1024).also { SecureRandom().nextBytes(it) } + val sealedFile = File(spec.getString("scratch"), "film.smf") + val meta = MediaMeta(name = "Fra telefonen — «Kveld».mp4", mime = "video/mp4", durationMs = 61_500, width = 1080, height = 1920) + val progress = mutableListOf() + val token = MediaUploader.newReadToken() + val result = sealedFile.outputStream().buffered().use { MediaSealer.sealStream(plain.inputStream(), it, meta) } + val film = FileRangeSource(sealedFile).use { body -> + uploader.putSealed(result, body, token, meta) { acked, total -> + synchronized(progress) { progress += acked } + assertEquals(result.sealedSize, total) + } + } + assertEquals(result.sealedSize, progress.last()) + assertTrue("progress only grows: $progress", progress.zipWithNext().all { (a, b) -> a <= b }) + film.open().use { r -> assertEquals(sha256(plain), sha256(r.read(0, r.size.toInt()))) } + + // The same film again (the app was killed after the upload): the relay + // already has it, nothing is sent, the link is the same. + val again = FileRangeSource(sealedFile).use { uploader.putSealed(result, it, token, meta) } + assertEquals(film.capabilityUrl("https://watch.example/"), again.capabilityUrl("https://watch.example/")) + + // A photo: one PUT; then deleted. + val photo = uploader.uploadBytes(ByteArray(300_000).also { SecureRandom().nextBytes(it) }, MediaMeta(name = "IMG_0001.jpg", mime = "image/jpeg")) + photo.open().use { assertEquals("IMG_0001.jpg", it.meta.name) } + assertTrue(uploader.delete(photo.mediaId)) + assertFalse(uploader.delete(photo.mediaId)) + + File(spec.getString("kotlinOut")).writeText( + JSONObject() + .put("film", JSONObject().put("link", film.capabilityUrl("https://watch.example/")).put("sha256", sha256(plain)).put("size", plain.size)) + .put("again", again.capabilityUrl("https://watch.example/")) + .put("photo", JSONObject().put("url", photo.url)) + .toString(), + ) + sealedFile.delete() + } +} 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 2999da5..97e44bf 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 @@ -17,8 +17,10 @@ import no.zyon.shade.media.MediaGrant import no.zyon.shade.media.MediaIntegrityException import no.zyon.shade.media.MediaKeys import no.zyon.shade.media.MediaMeta +import no.zyon.shade.media.MediaOwner import no.zyon.shade.media.MediaReader import no.zyon.shade.media.MediaSealer +import no.zyon.shade.media.OwnerOp import no.zyon.shade.media.Subtitles import no.zyon.shade.media.chainStep import no.zyon.shade.media.decodeFrame @@ -228,4 +230,48 @@ class MediaVectorTest { Subtitles.of(MediaMeta(extra = mapOf("shade.subtitles" to """[{"lang":"no; x","grant":{}}]"""))) } } + + @Test + fun ownerSignaturesMatchTheRelaysByteForByte() { + val v = byPrefix("owner:").single() + val owner = MediaOwner(hex(v.getString("seed"))) + assertEquals(v.getString("owner"), owner.id) + val at = v.getLong("at") + val requests = v.getJSONArray("requests") + for (i in 0 until requests.length()) { + val r = requests.getJSONObject(i) + val op = when (r.getString("op")) { + "put" -> OwnerOp.Put(r.getString("id"), r.getLong("size"), r.getString("readTokenHash")) + "upload" -> OwnerOp.Upload(r.getString("id"), r.getLong("size"), r.getString("readTokenHash")) + "piece" -> OwnerOp.Piece(r.getString("id"), r.getLong("offset"), r.getLong("length")) + "abort" -> OwnerOp.Abort(r.getString("id")) + "delete" -> OwnerOp.Delete(r.getString("id")) + "list" -> OwnerOp.List + else -> error("unknown op ${r.getString("op")}") + } + assertEquals(r.getString("message"), String(MediaOwner.message(op, at))) + val want = r.getJSONObject("headers") + val got = owner.headers(op, at) + assertEquals(want.keySet(), got.keys) + for (k in got.keys) assertEquals("${r.getString("op")} $k", want.getString(k), got[k]) + } + } + + @Test + fun grantsEncodeToTheSameJsonAndLinkAsTs() { + val v = byPrefix("grant encode:").single() + val g = MediaGrant( + hex(v.getString("mediaId")), + hex(v.getString("mediaKey")), + hex(v.getString("rootDigest")), + v.getString("url"), + hex(v.getString("readToken")), + MediaMeta.fromJson(v.getString("meta")), + ) + assertEquals(v.getString("json"), g.encode()) + assertEquals(v.getString("link"), g.capabilityUrl(v.getString("pageUrl"))) + // And back. + val back = Grants.fromCapabilityUrl(v.getString("link")) as MediaGrant + assertEquals(v.getString("json"), back.encode()) + } } diff --git a/docs/media.md b/docs/media.md index 00f0f5b..becc1b2 100644 --- a/docs/media.md +++ b/docs/media.md @@ -258,6 +258,24 @@ On Android/JVM, `no.zyon.shade.media`: `Grants.fromCapabilityUrl(link)`, `inputStream()`. `LiveSubscriber(grant).open(frame)` handles live frames, and `MediaSealer` and `LivePublisher` write both formats byte for byte the way TS does. +Uploading from a phone is `MediaUploader` (blocking; off the main thread): + +```kotlin +val owner = MediaOwner(seed) // 32 bytes, kept in the Keystore-backed storage +val up = MediaUploader("https://relay.example", owner) +val grant = contentResolver.openInputStream(uri)!!.use { input -> + up.uploadStream(input, File(cacheDir, "film.smf"), MediaMeta(name = "Kveld.mp4", mime = "video/mp4")) { acked, total -> … } +} +share(grant.capabilityUrl("https://relay.example/watch/")) +``` + +It speaks the same piece protocol as `media put` (one PUT up to 16 MiB, then pieces +with the relay's window, retries and a resync after a lost answer). To survive the +app being killed, keep the sealed file and the `SealResult` and call `putSealed` +again: the media id is the same, so the relay picks up where it stopped, and a file it +already has gives the same link without sending anything. The relay must list +`owner.id` among its owners. + For playback, `:shade-android-media` hands a reader to Media3/ExoPlayer, so any container ExoPlayer understands plays and seeks from a sealed file: @@ -508,7 +526,10 @@ done in v1. A deployment that needs it can pad above this layer. racing uploads and pins, sweeping, bounded memory. - `test-vectors/media.json` (`bun run scripts/generate-vectors.ts media.json`): the Kotlin port reads every vector and reproduces every sealed file and signed frame - byte for byte (`MediaVectorTest`). + byte for byte (`MediaVectorTest`), owner signatures and encoded grants included. +- `bun run scripts/media-live-kotlin.ts`: the Kotlin uploader against a real TS relay, + with a lost answer and a refused piece injected; TS reads the 40 MiB film back + byte for byte (`MediaLiveTest`, skipped without the driver). - `bench/media.ts`: throughput, seek latency and live fan-out, written as `bench/media.chart.json`. - `bench/media-store.ts`: disk store against S3 (+ Postgres) through the real routes, diff --git a/scripts/generate-vectors.ts b/scripts/generate-vectors.ts index 881635c..2919d4a 100644 --- a/scripts/generate-vectors.ts +++ b/scripts/generate-vectors.ts @@ -57,7 +57,9 @@ import { sealWithPinnedKeys } from '../packages/shade-media/src/testing.js'; import { LivePublisher, epochKeys, chainStep, linkEpochSeed } from '../packages/shade-media/src/live/channel.js'; import { encodeContent, decodeFrame } 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, toCapabilityUrl } from '../packages/shade-media/src/grant.js'; +import { OwnerKey, ownerMessage } from '../packages/shade-media/src/owner.js'; +import type { OwnerOp } from '../packages/shade-media/src/owner.js'; import type { MediaGrant } from '../packages/shade-media/src/grant.js'; import { albumMeta, encodeAlbum } from '../packages/shade-media/src/album.js'; import { withSubtitles } from '../packages/shade-media/src/subtitles.js'; @@ -1122,6 +1124,55 @@ async function generateMediaVectors(): Promise { labels: ['Norsk', null], mediaIds: [hex(new Uint8Array(16).fill(0x55)), hex(new Uint8Array(16).fill(0x66))], }); + + // Owner-signed requests: what a relay checks before it takes an upload, a + // piece of one, a delete. Ed25519 is deterministic, so the signatures are too. + const owner = new OwnerKey(new Uint8Array(32).fill(0x07)); + const at = 1792360000000; + const id = '0123456789abcdef0123456789abcdef'; + const readTokenHash = 'ab'.repeat(32); + const ops: OwnerOp[] = [ + { op: 'put', id, size: 4096, readTokenHash }, + { op: 'upload', id, size: 50 * 1024 ** 3, readTokenHash }, + { op: 'upload', id, size: 4096, readTokenHash: '' }, + { op: 'piece', id, offset: 3 * 16 * 1024 * 1024, length: 16 * 1024 * 1024 }, + { op: 'piece', id, offset: 50 * 1024 ** 3, length: 0 }, + { op: 'abort', id }, + { op: 'delete', id }, + { op: 'list' }, + ]; + vectors.push({ + description: 'owner: signed media requests (x-shade-owner / x-shade-at / x-shade-signature)', + seed: hex(new Uint8Array(32).fill(0x07)), + owner: owner.id, + at, + requests: ops.map((o) => ({ + ...o, + message: new TextDecoder().decode(ownerMessage(o, at)), + headers: owner.headers(o, at), + })), + }); + + // A grant as an uploader hands it on: the wire JSON (field order fixed, the + // meta canonical) and the capability link it makes. + const shared: MediaGrant = { + ...film, + mediaId: new Uint8Array(16).fill(0x77), + readToken: new Uint8Array(32).fill(0x88), + meta: { extra: { 'shade.note': 'æøå' }, name: 'Fra telefonen — «Kveld».mp4', mime: 'video/mp4', durationMs: 61500, width: 1080, height: 1920 }, + }; + vectors.push({ + description: 'grant encode: a media grant with url, token and meta, as JSON and as a capability link', + mediaId: hex(shared.mediaId), + mediaKey: hex(shared.mediaKey), + rootDigest: hex(shared.rootDigest), + url: shared.url, + readToken: hex(shared.readToken!), + meta: JSON.stringify(shared.meta), + json: encodeGrant(shared), + pageUrl: 'https://watch.example/', + link: toCapabilityUrl('https://watch.example/', shared), + }); return vectors; } diff --git a/scripts/media-live-kotlin.ts b/scripts/media-live-kotlin.ts new file mode 100644 index 0000000..e6a9c85 --- /dev/null +++ b/scripts/media-live-kotlin.ts @@ -0,0 +1,117 @@ +/** + * Live cross-check of the Kotlin media uploader against the real TS relay. + * + * bun run scripts/media-live-kotlin.ts + * + * Serves `createMediaService` (disk store in a temp dir) on a free local + * port, with two faults on the way in: the piece at 16 MiB is stored but its + * answer is lost (a 503 after the store took it), and the piece at 32 MiB is + * refused once before the relay sees it. Uploads a small file with the TS + * client, then runs the gated `MediaLiveTest` in android/ with + * `SHADE_MEDIA_LIVE_SPEC` set. That test opens the TS file from its link, + * seals and uploads a 40 MiB film in pieces and a photo in one PUT, puts the + * film again (the relay already has it) and deletes the photo. This script + * then opens the Kotlin film from its link with the TS reader and checks every + * byte, and that both faults were hit and recovered from. + * + * Vectors pin the signatures byte for byte; this pins the conversation — + * real HTTP, real owner checks, the piece window and the resync after a lost + * answer — which no vector can. + */ +import { createHash, randomBytes } from 'node:crypto'; +import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { MediaClient, OwnerKey, fromCapabilityUrl, openGrant, toCapabilityUrl } from '../packages/shade-media/src/index.js'; +import type { MediaGrant } from '../packages/shade-media/src/index.js'; +import { createMediaService, mediaMaxRequestBody } from '../packages/shade-media/src/server.js'; +import { OFFSET_HEADER } from '../packages/shade-media/src/upload.js'; + +const sha256 = (b: Uint8Array) => createHash('sha256').update(b).digest('hex'); +function check(cond: unknown, what: string): asserts cond { + if (!cond) throw new Error(`live cross-check failed: ${what}`); +} + +const MiB = 1024 * 1024; +const dir = await mkdtemp(join(tmpdir(), 'shade-media-live-')); +const kotlinSeed = new Uint8Array(randomBytes(32)); +const kotlinOwner = new OwnerKey(kotlinSeed); +const tsOwner = new OwnerKey(new Uint8Array(randomBytes(32))); +const service = createMediaService({ dir, owners: [kotlinOwner.id, tsOwner.id] }); + +const faults = { lostAnswer: 0, refused: 0, pieces: 0, starts: 0 }; +const server = Bun.serve({ + port: 0, + hostname: '127.0.0.1', + maxRequestBodySize: mediaMaxRequestBody(), + async fetch(req) { + const path = new URL(req.url).pathname; + if (path.endsWith('/upload') && req.method === 'POST') faults.starts++; + if (path.endsWith('/upload') && req.method === 'PUT') { + faults.pieces++; + const offset = Number(req.headers.get(OFFSET_HEADER)); + if (offset === 32 * MiB && faults.refused === 0) { + faults.refused++; + await req.arrayBuffer(); + return new Response('502 Bad Gateway', { status: 503, headers: { 'content-type': 'text/html' } }); + } + if (offset === 16 * MiB && faults.lostAnswer === 0) { + faults.lostAnswer++; + const res = await service.app.fetch(req); + check(res.status === 200 || res.status === 201, `the stored-but-lost piece was refused: ${res.status}`); + return new Response('upstream went away', { status: 503 }); + } + } + return service.app.fetch(req); + }, +}); +const url = `http://127.0.0.1:${server.port}`; + +try { + const tsBytes = new TextEncoder().encode('hei fra TS — æøå\n'.repeat(5000)); + const tsGrant = await new MediaClient(url, tsOwner).uploadBytes(tsBytes, { meta: { name: 'fra-ts.txt', mime: 'text/plain' } }); + const specPath = join(dir, 'spec.json'); + const kotlinOut = join(dir, 'kotlin-out.json'); + await writeFile( + specPath, + JSON.stringify({ + url, + seed: Buffer.from(kotlinSeed).toString('hex'), + tsLink: toCapabilityUrl('https://watch.example/', tsGrant), + tsSha256: sha256(tsBytes), + scratch: dir, + kotlinOut, + }), + ); + + const androidDir = resolve(import.meta.dir, '../android'); + const gradle = Bun.spawn( + ['./gradlew', ':shade-android:test', '--tests', 'no.zyon.shade.MediaLiveTest', '--console=plain'], + { cwd: androidDir, env: { ...process.env, SHADE_MEDIA_LIVE_SPEC: specPath }, stdout: 'inherit', stderr: 'inherit' }, + ); + check((await gradle.exited) === 0, 'Kotlin MediaLiveTest failed'); + + const out = JSON.parse(await readFile(kotlinOut, 'utf8')) as { + film: { link: string; sha256: string; size: number }; + again: string; + photo: { url: string }; + }; + const film = fromCapabilityUrl(out.film.link) as MediaGrant; + const reader = await openGrant(film); + check(reader.size === out.film.size, `film is ${reader.size} bytes, Kotlin sealed ${out.film.size}`); + check(sha256(await reader.read(0, reader.size)) === out.film.sha256, 'film bytes differ'); + check(reader.meta.name === 'Fra telefonen — «Kveld».mp4', `film name is ${reader.meta.name}`); + check(out.again === out.film.link, 'putting the film again gave another link'); + check((await fetch(out.photo.url, { method: 'HEAD' })).status === 404, 'the deleted photo is still served'); + check(faults.lostAnswer === 1 && faults.refused === 1, `faults not hit: ${JSON.stringify(faults)}`); + const left = await new MediaClient(url, kotlinOwner).list(); + check(left.items.length === 1, `Kotlin owner should have 1 file left, has ${left.items.length}`); + console.log( + `LIVE OK — Kotlin read the TS file; Kotlin film ${(out.film.size / MiB).toFixed(1)} MiB in ${faults.pieces} piece requests ` + + `(${faults.starts} starts/resyncs, 1 lost answer, 1 refusal) read back by TS byte for byte; photo deleted`, + ); +} finally { + server.stop(true); + await service.stop(); + await rm(dir, { recursive: true, force: true }); +} diff --git a/test-vectors/media.json b/test-vectors/media.json index 1dc5c8d..634724f 100644 --- a/test-vectors/media.json +++ b/test-vectors/media.json @@ -171,6 +171,115 @@ "55555555555555555555555555555555", "66666666666666666666666666666666" ] + }, + { + "description": "owner: signed media requests (x-shade-owner / x-shade-at / x-shade-signature)", + "seed": "0707070707070707070707070707070707070707070707070707070707070707", + "owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "at": 1792360000000, + "requests": [ + { + "op": "put", + "id": "0123456789abcdef0123456789abcdef", + "size": 4096, + "readTokenHash": "abababababababababababababababababababababababababababababababab", + "message": "shade.media-put/v1|0123456789abcdef0123456789abcdef|4096|abababababababababababababababababababababababababababababababab|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "W_y7J_OXdJfR074zPgCMadZMZprs23V-loVMpd_UMXA0vnyRiOZna7O5ZLhepXT7ZnHaqZdOHJ3l4lDjZQU1Dw" + } + }, + { + "op": "upload", + "id": "0123456789abcdef0123456789abcdef", + "size": 53687091200, + "readTokenHash": "abababababababababababababababababababababababababababababababab", + "message": "shade.media-upload/v1|0123456789abcdef0123456789abcdef|53687091200|abababababababababababababababababababababababababababababababab|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "WSEDyRSHbDji6ryrCTRXhEwEa1eMflF2ji6DaFO7xc49wgIjwsk3cZ_sE0M-2xXMRlVJNcUSG5KmRgJ1E-49BQ" + } + }, + { + "op": "upload", + "id": "0123456789abcdef0123456789abcdef", + "size": 4096, + "readTokenHash": "", + "message": "shade.media-upload/v1|0123456789abcdef0123456789abcdef|4096||1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "T9F38O9Na5Es8WrN4SnY0-LVC3LGlM0xpfi0jtf8agluLdLTg9b_HR8yXS7VXWbwbTAEfaRdaeX8jXGSKBmMAw" + } + }, + { + "op": "piece", + "id": "0123456789abcdef0123456789abcdef", + "offset": 50331648, + "length": 16777216, + "message": "shade.media-piece/v1|0123456789abcdef0123456789abcdef|50331648|16777216|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "lePaHRTZq1FYGP1TY9oDm5T3bYxl6iWtDJjB_oxgEdOHvnjTMOCch8MmrayN2KoK7tm9VWPvPy0IzTdp0xkMBw" + } + }, + { + "op": "piece", + "id": "0123456789abcdef0123456789abcdef", + "offset": 53687091200, + "length": 0, + "message": "shade.media-piece/v1|0123456789abcdef0123456789abcdef|53687091200|0|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "ZgHZnycTzsQTc1O6g0UUgRBwfNeSybZ-WbhIeyqFXBX-cXP4XbgR_2QYNwnlbLq6MtjLxI2ovh0Bn7dfxpS4Ag" + } + }, + { + "op": "abort", + "id": "0123456789abcdef0123456789abcdef", + "message": "shade.media-abort/v1|0123456789abcdef0123456789abcdef|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "udeUwLhWJTUtBE8JzdqIGfIK5-Vtxkqr5gW7o6KxLYOeqzbAVyvKwnD7D9TELAC31NyLcrfdg9KZl9UehI8fCQ" + } + }, + { + "op": "delete", + "id": "0123456789abcdef0123456789abcdef", + "message": "shade.media-delete/v1|0123456789abcdef0123456789abcdef|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "Kn3mgiEhFxWraSVxx-IKI1L8j2mhOIlOKmM9dKM4QCs_S6SX-SacHPvlKAkjVj6g11LLN1pMrQ6wscGnT42rBQ" + } + }, + { + "op": "list", + "message": "shade.media-list/v1|1792360000000", + "headers": { + "x-shade-owner": "6kpsY-KcUgq-9VB7Ey7F-ZVHdq6-vnuSQh7qaRRG0iw", + "x-shade-at": "1792360000000", + "x-shade-signature": "4jopYZxeczF49BVHx9NrFjQxvOEBddYiq_nSYzjJD_-Z4JpH2lh6rGH5yLeTp3pqMNfsjZD1MtABeTNPsWPGDg" + } + } + ] + }, + { + "description": "grant encode: a media grant with url, token and meta, as JSON and as a capability link", + "mediaId": "77777777777777777777777777777777", + "mediaKey": "2222222222222222222222222222222222222222222222222222222222222222", + "rootDigest": "3333333333333333333333333333333333333333333333333333333333333333", + "url": "https://relay.example/v1/media/11111111111111111111111111111111", + "readToken": "8888888888888888888888888888888888888888888888888888888888888888", + "meta": "{\"extra\":{\"shade.note\":\"æøå\"},\"name\":\"Fra telefonen — «Kveld».mp4\",\"mime\":\"video/mp4\",\"durationMs\":61500,\"width\":1080,\"height\":1920}", + "json": "{\"kind\":\"shade.media-grant/v1\",\"mediaId\":\"d3d3d3d3d3d3d3d3d3d3dw\",\"key\":\"IiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiI\",\"root\":\"3333333333333333333333333333333333333333333333333333333333333333\",\"url\":\"https://relay.example/v1/media/11111111111111111111111111111111\",\"token\":\"iIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIiIg\",\"meta\":{\"mime\":\"video/mp4\",\"name\":\"Fra telefonen — «Kveld».mp4\",\"durationMs\":61500,\"width\":1080,\"height\":1920,\"extra\":{\"shade.note\":\"æøå\"}}}", + "pageUrl": "https://watch.example/", + "link": "https://watch.example/#shade=eyJraW5kIjoic2hhZGUubWVkaWEtZ3JhbnQvdjEiLCJtZWRpYUlkIjoiZDNkM2QzZDNkM2QzZDNkM2QzZDNkdyIsImtleSI6IklpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUkiLCJyb290IjoiMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMzMyIsInVybCI6Imh0dHBzOi8vcmVsYXkuZXhhbXBsZS92MS9tZWRpYS8xMTExMTExMTExMTExMTExMTExMTExMTExMTExMTExMSIsInRva2VuIjoiaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJaUlpSWlJZyIsIm1ldGEiOnsibWltZSI6InZpZGVvL21wNCIsIm5hbWUiOiJGcmEgdGVsZWZvbmVuIOKAlCDCq0t2ZWxkwrsubXA0IiwiZHVyYXRpb25NcyI6NjE1MDAsIndpZHRoIjoxMDgwLCJoZWlnaHQiOjE5MjAsImV4dHJhIjp7InNoYWRlLm5vdGUiOiLDpsO4w6UifX19" } ] }