feat(media,android): Kotlin SMF1 reader/sealer and live channel, cross-language vectors

test-vectors/media.json pins SMF1 files (empty, partial, exact boundary,
multi-segment with full metadata) and SLF1 live frames in link mode across
a rotation. Kotlin reads them and reproduces every sealed file and every
signed frame byte for byte; TS locks the same file.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:07:45 +02:00
parent f359cbd9ad
commit d117397b36
12 changed files with 1514 additions and 4 deletions

View File

@@ -18,7 +18,7 @@ decided: "2026-10-18 — Cardwell: neste steg er Shade-streaming av tekst, video
- [x] Server: diskbasert medielager med Range-GET + live-relay over WebSocket med backlog + tester
- [x] Klienter: HTTP Range-kilde, live-klient, CLI (`shade media …`, `shade live …`)
- [x] Nettleser: Service Worker som spiller forseglede filer i `<video>`/`<img>`, MSE-spiller for live WebM; headless-test + film
- [ ] Kotlin: SMF1-leser + live-mottaker, verifisert mot vektorene
- [x] Kotlin: SMF1-leser + live-mottaker, verifisert mot vektorene
- [ ] Design + docs: `docs/media.md` (SMF1, live-kanal, trusselmodell), CHANGELOG, versjon, loggpost, commit
## Neste

View File

@@ -0,0 +1,331 @@
package no.zyon.shade.media
import com.google.crypto.tink.subtle.Ed25519Sign
import com.google.crypto.tink.subtle.Ed25519Verify
import com.google.crypto.tink.subtle.Hkdf
import java.nio.ByteBuffer
import java.security.GeneralSecurityException
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec
/**
* Live channels — mirror of `@shade/media/src/live/{frame,channel}.ts`.
*
* SLF1 frame: 48-byte header ("SLF1", ver, flags, 0 0, channelId(16),
* epoch u32, seq u64, timestamp u64, ctLen u32) ‖ AES-256-GCM(ct‖tag, aad =
* header) ‖ Ed25519 signature over everything before it.
*
* Keys: Sender Keys. ck[0]/stickyKey from the epoch seed; mk[i] = HMAC(ck[i],
* 01) used once; ck[i+1] = HMAC(ck[i], 02). Every frame is signed by the
* channel key, so a viewer (who holds the chain) cannot forge to another.
*/
class LiveKeyException(message: String) : Exception(message)
const val SLF_HEADER_BYTES = 48
const val SLF_SIGNATURE_BYTES = 64
const val FLAG_STICKY = 0x01
const val FLAG_KEYFRAME = 0x02
const val FLAG_END = 0x04
const val LIVE_MAX_SKIP = 100_000L
const val LIVE_MAX_SKIPPED_KEYS = 2_000
const val LIVE_MAX_FRAME_PAYLOAD = 16 * 1024 * 1024
private val SLF_MAGIC = byteArrayOf(0x53, 0x4c, 0x46, 0x31)
private val INFO_CHAIN = "shade-live/v1\u0000chain".toByteArray(Charsets.UTF_8)
private val INFO_STICKY = "shade-live/v1\u0000sticky".toByteArray(Charsets.UTF_8)
private val INFO_EPOCH = "shade-live/v1\u0000epoch".toByteArray(Charsets.UTF_8)
class EpochKeys(val chainKey: ByteArray, val stickyKey: ByteArray)
fun epochKeys(epochSeed: ByteArray, channelId: ByteArray, epoch: Long): EpochKeys {
val salt = channelId + u32(epoch)
return EpochKeys(
Hkdf.computeHkdf("HMACSHA256", epochSeed, salt, INFO_CHAIN, 32),
Hkdf.computeHkdf("HMACSHA256", epochSeed, salt, INFO_STICKY, 32),
)
}
fun linkEpochSeed(channelSecret: ByteArray, channelId: ByteArray, epoch: Long): ByteArray =
Hkdf.computeHkdf("HMACSHA256", channelSecret, channelId, INFO_EPOCH + u32(epoch), 32)
private fun hmac(key: ByteArray, data: ByteArray): ByteArray =
Mac.getInstance("HmacSHA256").apply { init(SecretKeySpec(key, "HmacSHA256")) }.doFinal(data)
/** One chain step: (message key for this seq, chain key for the next). */
fun chainStep(ck: ByteArray): Pair<ByteArray, ByteArray> = hmac(ck, byteArrayOf(1)) to hmac(ck, byteArrayOf(2))
fun frameNonce(epoch: Long, seq: Long): ByteArray = u32(epoch) + u64(seq)
/** What a frame carries — mirror of the TS `LiveContent` union. */
sealed class LiveContent {
data class Text(val text: String) : LiveContent()
class Binary(val bytes: ByteArray) : LiveContent()
class Init(val mime: String, val bytes: ByteArray) : LiveContent()
class Chunk(val bytes: ByteArray) : LiveContent()
class Image(val mime: String, val bytes: ByteArray) : LiveContent()
data class Meta(val meta: MediaMeta) : LiveContent()
object End : LiveContent()
fun encode(): ByteArray = when (this) {
is Text -> byteArrayOf(1) + text.toByteArray(Charsets.UTF_8)
is Binary -> byteArrayOf(2) + bytes
is Init -> withMime(3, mime, bytes)
is Chunk -> byteArrayOf(4) + bytes
is Image -> withMime(5, mime, bytes)
is Meta -> byteArrayOf(6) + MediaMeta.validate(meta).toJson().toByteArray(Charsets.UTF_8)
End -> byteArrayOf(7)
}
companion object {
private fun withMime(kind: Int, mime: String, bytes: ByteArray): ByteArray {
val m = mime.toByteArray(Charsets.UTF_8)
if (m.isEmpty() || m.size > 255) throw MediaFormatException("mime must be 1–255 bytes")
return byteArrayOf(kind.toByte(), m.size.toByte()) + m + bytes
}
fun decode(p: ByteArray): LiveContent {
if (p.isEmpty()) throw MediaFormatException("empty live payload")
val body = p.copyOfRange(1, p.size)
fun mimeBody(): Pair<String, ByteArray> {
val n = body.firstOrNull()?.toInt()?.and(0xff) ?: throw MediaFormatException("bad mime prefix")
if (n == 0 || body.size < 1 + n) throw MediaFormatException("bad mime prefix")
return String(body, 1, n, Charsets.UTF_8) to body.copyOfRange(1 + n, body.size)
}
return when (p[0].toInt()) {
1 -> Text(String(body, Charsets.UTF_8))
2 -> Binary(body)
3 -> mimeBody().let { Init(it.first, it.second) }
4 -> Chunk(body)
5 -> mimeBody().let { Image(it.first, it.second) }
6 -> Meta(MediaMeta.fromJson(String(body, Charsets.UTF_8)))
7 -> End
else -> throw MediaFormatException("unknown live content kind ${p[0]}")
}
}
}
}
class FrameHeader(val flags: Int, val channelId: ByteArray, val epoch: Long, val seq: Long, val timestamp: Long, val ctLen: Int) {
fun encode(): ByteArray = ByteBuffer.allocate(SLF_HEADER_BYTES)
.put(SLF_MAGIC).put(1).put(flags.toByte()).put(0).put(0)
.put(channelId).putInt(epoch.toInt()).putLong(seq).putLong(timestamp).putInt(ctLen)
.array()
}
class DecodedFrame(val header: FrameHeader, val headerBytes: ByteArray, val ciphertext: ByteArray, val signed: ByteArray, val signature: ByteArray)
fun decodeFrame(frame: ByteArray): DecodedFrame {
if (frame.size < SLF_HEADER_BYTES + TAG_BYTES + SLF_SIGNATURE_BYTES) throw MediaFormatException("live frame too short")
if (!frame.copyOfRange(0, 4).contentEquals(SLF_MAGIC)) throw MediaFormatException("not an SLF1 frame")
if (frame[4].toInt() != 1) throw MediaFormatException("unsupported SLF version ${frame[4]}")
val flags = frame[5].toInt() and 0xff
if (flags and (FLAG_STICKY or FLAG_KEYFRAME or FLAG_END).inv() != 0 || frame[6].toInt() != 0 || frame[7].toInt() != 0) {
throw MediaFormatException("unknown SLF flags or reserved bytes")
}
val bb = ByteBuffer.wrap(frame)
val ctLen = bb.getInt(44)
if (ctLen < TAG_BYTES || ctLen > LIVE_MAX_FRAME_PAYLOAD + 17) throw MediaFormatException("bad ctLen")
if (frame.size != SLF_HEADER_BYTES + ctLen + SLF_SIGNATURE_BYTES) throw MediaFormatException("live frame length does not match its header")
val seq = bb.getLong(28)
val ts = bb.getLong(36)
if (seq < 0 || seq > (1L shl 53) || ts < 0) throw MediaFormatException("u64 field exceeds 2^53")
return DecodedFrame(
FrameHeader(flags, frame.copyOfRange(8, 24), bb.getInt(24).toLong() and 0xffff_ffffL, seq, ts, ctLen),
frame.copyOfRange(0, SLF_HEADER_BYTES),
frame.copyOfRange(SLF_HEADER_BYTES, SLF_HEADER_BYTES + ctLen),
frame.copyOfRange(0, SLF_HEADER_BYTES + ctLen),
frame.copyOfRange(SLF_HEADER_BYTES + ctLen, frame.size),
)
}
class ReceivedFrame(val epoch: Long, val seq: Long, val timestamp: Long, val sticky: Boolean, val keyframe: Boolean, val content: LiveContent)
/**
* Viewing side. Feed frames in any order; each is returned once, or `null`
* for a harmless drop (a duplicate, or backlog before the grant's start).
* Throws on a forgery. Not thread-safe: call from one thread (the socket's).
*/
class LiveSubscriber(grant: LiveGrant) {
val channelId: ByteArray = grant.channelId
val signingKey: ByteArray = grant.signingKey
private val verifier = Ed25519Verify(grant.signingKey)
private class EpochState(val stickyKey: ByteArray, var nextSeq: Long, var chainKey: ByteArray) {
val skipped = LinkedHashMap<Long, ByteArray>()
val stickySeen = HashSet<Long>()
}
private val epochs = HashMap<Long, EpochState>()
private var link: Pair<ByteArray, Long>? = null
init {
addGrant(grant)
}
fun addGrant(g: LiveGrant) {
if (!g.channelId.contentEquals(channelId)) throw MediaFormatException("grant is for another channel")
if (!g.signingKey.contentEquals(signingKey)) throw MediaIntegrityException("grant changes the channel signing key")
g.channelSecret?.let { s -> if (link == null || g.epoch < link!!.second) link = s.copyOf() to g.epoch }
val existing = epochs[g.epoch]
if (existing != null && existing.nextSeq <= g.seq) return
epochs[g.epoch] = EpochState(g.stickyKey.copyOf(), g.seq, g.chainKey.copyOf())
}
fun forgetBefore(epoch: Long) {
val it = epochs.entries.iterator()
while (it.hasNext()) {
val (e, st) = it.next()
if (e < epoch) {
st.chainKey.fill(0)
st.stickyKey.fill(0)
st.skipped.values.forEach { k -> k.fill(0) }
it.remove()
}
}
}
private fun epochState(epoch: Long): EpochState? {
epochs[epoch]?.let { return it }
val (secret, from) = link ?: return null
if (epoch < from) return null
val k = epochKeys(linkEpochSeed(secret, channelId, epoch), channelId, epoch)
val st = EpochState(k.stickyKey, 0, k.chainKey)
epochs[epoch] = st
forgetBefore(epoch)
return st
}
fun open(frame: ByteArray): ReceivedFrame? {
val f = decodeFrame(frame)
val h = f.header
if (!h.channelId.contentEquals(channelId)) throw MediaFormatException("frame is for another channel")
try {
verifier.verify(f.signature, f.signed)
} catch (e: GeneralSecurityException) {
throw MediaIntegrityException("live frame signature does not verify")
}
val st = epochState(h.epoch) ?: throw LiveKeyException("no grant for epoch ${h.epoch}")
val sticky = h.flags and FLAG_STICKY != 0
val nonce = frameNonce(h.epoch, h.seq)
val plain = if (sticky) {
if (!st.stickySeen.add(h.seq)) return null
gcmOpen(st.stickyKey, nonce, f.ciphertext, f.headerBytes)
} else {
val mk = messageKey(st, h.seq) ?: return null
try {
gcmOpen(mk, nonce, f.ciphertext, f.headerBytes)
} finally {
mk.fill(0)
}
}
return ReceivedFrame(h.epoch, h.seq, h.timestamp, sticky, h.flags and FLAG_KEYFRAME != 0, LiveContent.decode(plain))
}
private fun messageKey(st: EpochState, seq: Long): ByteArray? {
if (seq < st.nextSeq) return st.skipped.remove(seq)
if (seq - st.nextSeq > LIVE_MAX_SKIP) throw LiveKeyException("frame $seq is ${seq - st.nextSeq} ahead — beyond MAX_SKIP")
var ck = st.chainKey
for (s in st.nextSeq until seq) {
val (mk, next) = chainStep(ck)
ck.fill(0)
ck = next
if (seq - s <= LIVE_MAX_SKIPPED_KEYS) {
st.skipped[s] = mk
if (st.skipped.size > LIVE_MAX_SKIPPED_KEYS) {
val oldest = st.skipped.keys.first()
st.skipped.remove(oldest)?.fill(0)
}
} else {
mk.fill(0)
}
}
val (mk, next) = chainStep(ck)
ck.fill(0)
st.chainKey = next
st.nextSeq = seq + 1
return mk
}
}
/**
* Sending side — a phone streaming its camera or its own logs. Mirror of the
* TS `LivePublisher` (link mode supported). Not thread-safe; frames are
* numbered in call order.
*/
class LivePublisher(
val channelId: ByteArray,
private val signingSeed: ByteArray,
private val channelSecret: ByteArray?,
startEpoch: Long = 0,
private val snapshotLimit: Int = 64,
) {
private val signer = Ed25519Sign(signingSeed)
val signingKey: ByteArray = Ed25519Sign.KeyPair.newKeyPairFromSeed(signingSeed).publicKey
var epoch: Long = startEpoch
private set
private var seq = 0L
private var chainKey: ByteArray
private var stickyKey: ByteArray
private val snapshots = ArrayDeque<Pair<Long, ByteArray>>()
private val stickyContent = ArrayList<Pair<LiveContent, Boolean>>()
init {
require(channelId.size == 16) { "channelId must be 16 bytes" }
val k = epochKeys(seedFor(epoch), channelId, epoch)
chainKey = k.chainKey
stickyKey = k.stickyKey
}
private fun seedFor(e: Long): ByteArray =
channelSecret?.let { linkEpochSeed(it, channelId, e) } ?: ByteArray(32).also { java.security.SecureRandom().nextBytes(it) }
fun frame(content: LiveContent, keyframe: Boolean = false, sticky: Boolean = false, timestamp: Long = System.currentTimeMillis()): ByteArray {
val plain = content.encode()
if (plain.size > LIVE_MAX_FRAME_PAYLOAD) throw MediaFormatException("live frame payload too large")
val s = seq++
var flags = 0
if (sticky) flags = flags or FLAG_STICKY
if (keyframe) flags = flags or FLAG_KEYFRAME
if (content is LiveContent.End) flags = flags or FLAG_END
if (keyframe && !sticky) {
snapshots.addLast(s to chainKey.copyOf())
while (snapshots.size > snapshotLimit) snapshots.removeFirst().second.fill(0)
}
val (mk, next) = chainStep(chainKey)
chainKey.fill(0)
chainKey = next
val header = FrameHeader(flags, channelId, epoch, s, timestamp, plain.size + TAG_BYTES).encode()
val ct = gcmSeal(if (sticky) stickyKey else mk, frameNonce(epoch, s), plain, header)
mk.fill(0)
val signed = header + ct
if (sticky) stickyContent += content to keyframe
return signed + signer.sign(signed)
}
fun grant(from: String = "oldest", link: Boolean = false, url: String? = null, readToken: ByteArray? = null): LiveGrant {
val (s, ck) = when {
from == "now" || snapshots.isEmpty() -> seq to chainKey
from == "latest" -> snapshots.last()
else -> snapshots.first()
}
if (link && channelSecret == null) throw IllegalStateException("link grants need a channelSecret")
return LiveGrant(channelId, signingKey, epoch, s, ck.copyOf(), stickyKey.copyOf(), url, readToken, null, if (link) channelSecret!!.copyOf() else null)
}
/** New epoch; returns the sticky frames resealed for it — send them first. */
fun rotate(timestamp: Long = System.currentTimeMillis()): List<ByteArray> {
epoch++
seq = 0
snapshots.forEach { it.second.fill(0) }
snapshots.clear()
chainKey.fill(0)
stickyKey.fill(0)
val k = epochKeys(seedFor(epoch), channelId, epoch)
chainKey = k.chainKey
stickyKey = k.stickyKey
val content = stickyContent.toList()
stickyContent.clear()
return content.map { (c, kf) -> frame(c, keyframe = kf, sticky = true, timestamp = timestamp) }
}
}

View File

@@ -0,0 +1,304 @@
package no.zyon.shade.media
import com.google.crypto.tink.subtle.Hkdf
import no.zyon.shade.serialization.stringifyJson
import org.json.JSONException
import org.json.JSONObject
import java.nio.ByteBuffer
import java.security.MessageDigest
import java.security.SecureRandom
import javax.crypto.AEADBadTagException
import javax.crypto.Cipher
import javax.crypto.spec.GCMParameterSpec
import javax.crypto.spec.SecretKeySpec
/**
* SMF1 — Shade Media Format v1, mirror of `@shade/media/src/sealed.ts`.
* The cross-language contract is `docs/media.md`; vectors in
* `test-vectors/media.json`.
*
* segment[0] … segment[n-1] AES-256-GCM, `segmentSize` plaintext each
* meta AES-256-GCM over UTF-8 JSON
* table n × SHA-256(segment bytes)
* footer (64) "SMF1" · ver · flags · 0 0 · segSize u32 ·
* plainSize u64 · metaLen u32 · mediaId(16) ·
* 20 × 0 · "SMF1"
*/
class MediaFormatException(message: String) : Exception(message)
/** Bytes failed authentication — a store or another key holder changed them. */
class MediaIntegrityException(message: String) : Exception(message)
val SMF_MAGIC = byteArrayOf(0x53, 0x4d, 0x46, 0x31)
const val SMF_VERSION = 1
const val FOOTER_BYTES = 64
const val DIGEST_BYTES = 32
const val TAG_BYTES = 16
const val MEDIA_ID_BYTES = 16
const val MEDIA_KEY_BYTES = 32
const val DEFAULT_SEGMENT_SIZE = 1024 * 1024
const val MIN_SEGMENT_SIZE = 4 * 1024
const val MAX_SEGMENT_SIZE = 16 * 1024 * 1024
const val MAX_META_BYTES = 64 * 1024
private val INFO_SEGMENT = "shade-media/v1\u0000segment".toByteArray(Charsets.UTF_8)
private val INFO_META = "shade-media/v1\u0000meta".toByteArray(Charsets.UTF_8)
private val AAD_META_PREFIX = "SMF1-meta".toByteArray(Charsets.UTF_8)
/**
* Sealed metadata. Numbers are whole (milliseconds, pixels): the TS writer
* would accept a fraction, but JSON number formatting is not something two
* languages agree on byte for byte, and nothing here needs one.
*/
data class MediaMeta(
val mime: String? = null,
val name: String? = null,
val durationMs: Long? = null,
val width: Long? = null,
val height: Long? = null,
val createdAt: Long? = null,
val extra: Map<String, String>? = null,
) {
/** `JSON.stringify` of the TS-validated object — same key order, same bytes. */
fun toJson(): String {
val m = LinkedHashMap<String, Any>()
mime?.let { m["mime"] = it }
name?.let { m["name"] = it }
durationMs?.let { m["durationMs"] = it }
width?.let { m["width"] = it }
height?.let { m["height"] = it }
createdAt?.let { m["createdAt"] = it }
extra?.let { m["extra"] = LinkedHashMap(it) }
return stringifyJson(m)
}
companion object {
private val MIME_RE = Regex("""^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}(?:;[ -~]{0,200})?$""", RegexOption.IGNORE_CASE)
fun validate(m: MediaMeta): MediaMeta {
m.mime?.let { if (!MIME_RE.matches(it)) throw MediaFormatException("bad mime") }
m.name?.let { n ->
if (n.length > 1024 || n.any { it.code < 0x20 || it.code == 0x7f }) throw MediaFormatException("bad name")
}
listOf(m.durationMs, m.width, m.height, m.createdAt).forEach {
if (it != null && it < 0) throw MediaFormatException("negative number in meta")
}
return m
}
/** Parse strictly, like the TS reader: unknown shapes are refused, unknown keys ignored. */
fun fromJson(json: String): MediaMeta {
val o = try { JSONObject(json) } catch (e: JSONException) { throw MediaFormatException("meta is not a JSON object") }
fun str(k: String): String? = if (!o.has(k)) null else (o.get(k) as? String ?: throw MediaFormatException("bad $k"))
fun num(k: String): Long? {
if (!o.has(k)) return null
val v = o.get(k) as? Number ?: throw MediaFormatException("bad $k")
val d = v.toDouble()
if (d < 0 || d.isNaN() || d.isInfinite()) throw MediaFormatException("bad $k")
return v.toLong()
}
val extra = if (!o.has("extra")) null else {
val e = o.get("extra") as? JSONObject ?: throw MediaFormatException("extra must be an object of strings")
val out = LinkedHashMap<String, String>()
for (k in e.keys()) out[k] = e.get(k) as? String ?: throw MediaFormatException("extra values must be strings")
out
}
return validate(MediaMeta(str("mime"), str("name"), num("durationMs"), num("width"), num("height"), num("createdAt"), extra))
}
}
}
/** Raw subkeys of a media item: segment key and meta key. */
class MediaSubkeys(val segmentKey: ByteArray, val metaKey: ByteArray)
fun deriveMediaSubkeys(mediaKey: ByteArray, mediaId: ByteArray): MediaSubkeys {
if (mediaKey.size != MEDIA_KEY_BYTES) throw MediaFormatException("mediaKey must be 32 bytes")
if (mediaId.size != MEDIA_ID_BYTES) throw MediaFormatException("mediaId must be 16 bytes")
return MediaSubkeys(
Hkdf.computeHkdf("HMACSHA256", mediaKey, mediaId, INFO_SEGMENT, 32),
Hkdf.computeHkdf("HMACSHA256", mediaKey, mediaId, INFO_META, 32),
)
}
internal fun u32(n: Long): ByteArray = ByteBuffer.allocate(4).putInt(n.toInt()).array()
internal fun u64(n: Long): ByteArray = ByteBuffer.allocate(8).putLong(n).array()
fun segmentNonce(index: Long): ByteArray = u32(0) + u64(index)
internal val META_NONCE: ByteArray = u32(1) + u64(0)
fun segmentAad(mediaId: ByteArray, index: Long, last: Boolean): ByteArray =
SMF_MAGIC + mediaId + u64(index) + byteArrayOf(if (last) 1 else 0)
internal fun metaAad(mediaId: ByteArray): ByteArray = AAD_META_PREFIX + mediaId
internal fun sha256(b: ByteArray): ByteArray = MessageDigest.getInstance("SHA-256").digest(b)
/** AES-256-GCM with a caller-supplied nonce; returns ct‖tag (no nonce prefix). */
internal fun gcmSeal(key: ByteArray, nonce: ByteArray, plaintext: ByteArray, aad: ByteArray): ByteArray {
val c = Cipher.getInstance("AES/GCM/NoPadding")
c.init(Cipher.ENCRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
c.updateAAD(aad)
return c.doFinal(plaintext)
}
internal fun gcmOpen(key: ByteArray, nonce: ByteArray, ciphertext: ByteArray, aad: ByteArray): ByteArray {
val c = Cipher.getInstance("AES/GCM/NoPadding")
c.init(Cipher.DECRYPT_MODE, SecretKeySpec(key, "AES"), GCMParameterSpec(128, nonce))
c.updateAAD(aad)
return try {
c.doFinal(ciphertext)
} catch (e: AEADBadTagException) {
throw MediaIntegrityException("AEAD authentication failed")
}
}
internal fun ctEquals(a: ByteArray, b: ByteArray): Boolean = MessageDigest.isEqual(a, b)
class Footer(val segmentSize: Int, val plaintextSize: Long, val metaLen: Int, val mediaId: ByteArray) {
val segmentCount: Long get() = segmentCountFor(plaintextSize, segmentSize)
/** Offset and sealed length of segment `i`. */
fun span(i: Long): Pair<Long, Int> {
val n = segmentCount
val plain = if (i < n - 1) segmentSize.toLong() else plaintextSize - (n - 1) * segmentSize
return i * (segmentSize + TAG_BYTES) to (plain + TAG_BYTES).toInt()
}
val sealedSize: Long
get() = plaintextSize + segmentCount * TAG_BYTES + metaLen + segmentCount * DIGEST_BYTES + FOOTER_BYTES
fun encode(): ByteArray {
val b = ByteBuffer.allocate(FOOTER_BYTES)
b.put(SMF_MAGIC).put(SMF_VERSION.toByte()).put(0).put(0).put(0)
b.putInt(segmentSize).putLong(plaintextSize).putInt(metaLen).put(mediaId)
b.put(ByteArray(20)).put(SMF_MAGIC)
return b.array()
}
companion object {
fun decode(b: ByteArray): Footer {
if (b.size != FOOTER_BYTES) throw MediaFormatException("footer must be 64 bytes")
if (!b.copyOfRange(0, 4).contentEquals(SMF_MAGIC) || !b.copyOfRange(60, 64).contentEquals(SMF_MAGIC)) {
throw MediaFormatException("not an SMF1 file (bad magic)")
}
if (b[4].toInt() != SMF_VERSION) throw MediaFormatException("unsupported SMF version ${b[4]}")
if (b[5].toInt() != 0 || b[6].toInt() != 0 || b[7].toInt() != 0 || (40 until 60).any { b[it].toInt() != 0 }) {
throw MediaFormatException("unknown SMF flags or non-zero reserved bytes")
}
val bb = ByteBuffer.wrap(b)
val seg = bb.getInt(8)
if (seg < MIN_SEGMENT_SIZE || seg > MAX_SEGMENT_SIZE) throw MediaFormatException("segmentSize out of range: $seg")
val plain = bb.getLong(12)
if (plain < 0 || plain > (1L shl 53)) throw MediaFormatException("plaintext size out of range")
val metaLen = bb.getInt(20)
if (metaLen < TAG_BYTES || metaLen > MAX_META_BYTES + TAG_BYTES) throw MediaFormatException("metaLen out of range: $metaLen")
return Footer(seg, plain, metaLen, b.copyOfRange(24, 40))
}
}
}
fun segmentCountFor(plaintextSize: Long, segmentSize: Int): Long =
maxOf(1L, (plaintextSize + segmentSize - 1) / segmentSize)
class SealResult(
val mediaId: ByteArray,
val mediaKey: ByteArray,
val rootDigest: ByteArray,
val plaintextSize: Long,
val sealedSize: Long,
val segmentSize: Int,
val segmentCount: Long,
)
/**
* Incremental sealer — feed plaintext in any chunking, write out what it
* returns, in order. Constant memory (one segment). Mirror of the TS
* `MediaSealer`: a segment is held back until more input proves it is not
* the last one, because "last" is in its AAD.
*/
class MediaSealer private constructor(
val mediaId: ByteArray,
val mediaKey: ByteArray,
val segmentSize: Int,
meta: MediaMeta,
) {
constructor(meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE) :
this(random(MEDIA_ID_BYTES), random(MEDIA_KEY_BYTES), segmentSize, meta)
private val keys = deriveMediaSubkeys(mediaKey, mediaId)
private val metaJson = MediaMeta.validate(meta).toJson().toByteArray(Charsets.UTF_8)
private val pending = java.io.ByteArrayOutputStream()
private val digests = java.io.ByteArrayOutputStream()
private var index = 0L
private var plaintextSize = 0L
private var sealedSize = 0L
private var finished = false
init {
if (segmentSize < MIN_SEGMENT_SIZE || segmentSize > MAX_SEGMENT_SIZE) {
throw MediaFormatException("segmentSize out of range: $segmentSize")
}
if (metaJson.size > MAX_META_BYTES) throw MediaFormatException("meta too large")
}
fun push(chunk: ByteArray): List<ByteArray> {
check(!finished) { "push after finish" }
pending.write(chunk)
plaintextSize += chunk.size
val out = ArrayList<ByteArray>()
if (pending.size() > segmentSize) {
val all = pending.toByteArray()
var off = 0
while (all.size - off > segmentSize) {
out += sealSegment(all.copyOfRange(off, off + segmentSize), false)
off += segmentSize
}
pending.reset()
pending.write(all, off, all.size - off)
}
return out
}
fun finish(): Pair<List<ByteArray>, SealResult> {
check(!finished) { "finish called twice" }
finished = true
val last = sealSegment(pending.toByteArray(), true)
val metaBlock = gcmSeal(keys.metaKey, META_NONCE, metaJson, metaAad(mediaId))
val footer = Footer(segmentSize, plaintextSize, metaBlock.size, mediaId).encode()
val trailer = metaBlock + digests.toByteArray() + footer
sealedSize += trailer.size
keys.segmentKey.fill(0)
keys.metaKey.fill(0)
return listOf(last, trailer) to SealResult(mediaId, mediaKey, sha256(trailer), plaintextSize, sealedSize, segmentSize, index)
}
private fun sealSegment(plain: ByteArray, last: Boolean): ByteArray {
val i = index++
val sealed = gcmSeal(keys.segmentKey, segmentNonce(i), plain, segmentAad(mediaId, i, last))
digests.write(sha256(sealed))
sealedSize += sealed.size
return sealed
}
companion object {
private val rng = SecureRandom()
private fun random(n: Int) = ByteArray(n).also { rng.nextBytes(it) }
/** Pinned key and id — for cross-language vectors ONLY (nonces are per key). */
internal fun withPinnedKeys(mediaId: ByteArray, mediaKey: ByteArray, meta: MediaMeta, segmentSize: Int) =
MediaSealer(mediaId, mediaKey, segmentSize, meta)
/** Seal bytes already in memory. */
fun sealBytes(plaintext: ByteArray, meta: MediaMeta = MediaMeta(), segmentSize: Int = DEFAULT_SEGMENT_SIZE): Pair<ByteArray, SealResult> =
MediaSealer(meta, segmentSize).sealAll(plaintext)
}
internal fun sealAll(plaintext: ByteArray): Pair<ByteArray, SealResult> {
val out = java.io.ByteArrayOutputStream()
push(plaintext).forEach { out.write(it) }
val (rest, result) = finish()
rest.forEach { out.write(it) }
return out.toByteArray() to result
}
}

View File

@@ -0,0 +1,113 @@
package no.zyon.shade.media
import org.json.JSONException
import org.json.JSONObject
import java.net.URI
import java.util.Base64
/**
* Grants — mirror of `@shade/media/src/grant.ts`. A grant travels as a
* message over an existing Shade session, or in the `#shade=` fragment of a
* capability link. Parsing is strict: a field of the wrong size or shape is
* refused, never guessed at.
*/
const val MEDIA_GRANT_KIND = "shade.media-grant/v1"
const val LIVE_GRANT_KIND = "shade.live-grant/v1"
sealed class Grant
class MediaGrant(
val mediaId: ByteArray,
val mediaKey: ByteArray,
val rootDigest: ByteArray,
val url: String? = null,
val readToken: ByteArray? = null,
val meta: MediaMeta? = null,
) : Grant() {
fun keys() = MediaKeys(mediaId, mediaKey, rootDigest)
/** Range source for the granted file, with the read token attached. */
fun source(): HttpRangeSource {
val u = url ?: throw MediaFormatException("grant has no URL")
return HttpRangeSource(u, readToken?.let { mapOf("x-shade-read" to b64u(it)) } ?: emptyMap())
}
fun open(): MediaReader = MediaReader.open(source(), keys())
}
class LiveGrant(
val channelId: ByteArray,
val signingKey: ByteArray,
val epoch: Long,
val seq: Long,
val chainKey: ByteArray,
val stickyKey: ByteArray,
val url: String? = null,
val readToken: ByteArray? = null,
val meta: MediaMeta? = null,
/** Link mode: reads this epoch and every later one, unaided. */
val channelSecret: ByteArray? = null,
) : Grant()
internal fun b64u(b: ByteArray): String = Base64.getUrlEncoder().withoutPadding().encodeToString(b)
internal fun fromB64u(s: String, expected: Int? = null): ByteArray {
if (!Regex("^[A-Za-z0-9_-]*$").matches(s)) throw MediaFormatException("not base64url")
val b = try { Base64.getUrlDecoder().decode(s) } catch (e: IllegalArgumentException) { throw MediaFormatException("not base64url") }
if (expected != null && b.size != expected) throw MediaFormatException("expected $expected bytes, got ${b.size}")
return b
}
internal fun fromHexStrict(s: String, expected: Int): ByteArray {
if (!Regex("^(?:[0-9a-f]{2})*$").matches(s) || s.length != expected * 2) throw MediaFormatException("bad hex")
return ByteArray(expected) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
}
object Grants {
fun parse(json: String): Grant {
val o = try { JSONObject(json) } catch (e: JSONException) { throw MediaFormatException("grant is not JSON") }
fun str(k: String): String = o.opt(k) as? String ?: throw MediaFormatException("grant.$k must be a string")
fun optStr(k: String): String? = if (!o.has(k)) null else str(k)
fun int(k: String, max: Long): Long {
val v = o.opt(k) as? Number ?: throw MediaFormatException("grant.$k must be an integer")
val l = v.toLong()
if (l.toDouble() != v.toDouble() || l < 0 || l > max) throw MediaFormatException("grant.$k out of range")
return l
}
val url = optStr("url")?.also {
val scheme = try { URI(it).scheme } catch (e: Exception) { null }
if (scheme !in setOf("http", "https", "ws", "wss")) throw MediaFormatException("grant.url must be http(s) or ws(s)")
}
val token = optStr("token")?.let { fromB64u(it) }?.also {
if (it.size < 16 || it.size > 64) throw MediaFormatException("grant.token must be 16–64 bytes")
}
val meta = (o.opt("meta") as? JSONObject)?.let { MediaMeta.fromJson(it.toString()) }
return when (o.opt("kind")) {
MEDIA_GRANT_KIND -> MediaGrant(
fromB64u(str("mediaId"), MEDIA_ID_BYTES),
fromB64u(str("key"), MEDIA_KEY_BYTES),
fromHexStrict(str("root"), DIGEST_BYTES),
url, token, meta,
)
LIVE_GRANT_KIND -> LiveGrant(
fromB64u(str("channelId"), 16),
fromB64u(str("signingKey"), 32),
int("epoch", 0xffff_ffffL),
int("seq", (1L shl 53) - 1),
fromB64u(str("chainKey"), 32),
fromB64u(str("stickyKey"), 32),
url, token, meta,
optStr("channelSecret")?.let { fromB64u(it, 32) },
)
else -> throw MediaFormatException("unknown grant kind ${o.opt("kind")}")
}
}
/** Grant from a capability link `…#shade=<base64url(json)>`. */
fun fromCapabilityUrl(link: String): Grant {
val frag = link.substringAfter('#', link)
val m = Regex("(?:^|&)shade=([A-Za-z0-9_-]+)").find(frag) ?: throw MediaFormatException("link carries no #shade= grant")
return parse(String(fromB64u(m.groupValues[1]), Charsets.UTF_8))
}
}

View File

@@ -0,0 +1,236 @@
package no.zyon.shade.media
import java.io.IOException
import java.io.InputStream
import java.net.HttpURLConnection
import java.net.URL
/** Where sealed bytes come from: a size and byte ranges, nothing else. */
interface RangeSource {
fun size(): Long
/** Exactly `length` bytes from `offset` (fewer only past the end). */
fun read(offset: Long, length: Int): ByteArray
}
class ByteArraySource(private val bytes: ByteArray) : RangeSource {
override fun size(): Long = bytes.size.toLong()
override fun read(offset: Long, length: Int): ByteArray {
val start = offset.toInt().coerceAtMost(bytes.size)
return bytes.copyOfRange(start, (start + length).coerceAtMost(bytes.size))
}
}
/**
* HTTP Range reads against the Shade media routes (or any Range-capable
* server). The read token, when the grant carries one, rides in
* `x-shade-read`. Retries network errors and 5xx; a 4xx is final.
*/
class HttpRangeSource(
private val url: String,
private val headers: Map<String, String> = emptyMap(),
private val retries: Int = 3,
private val timeoutMs: Int = 15_000,
) : RangeSource {
@Volatile private var knownSize: Long = -1
override fun size(): Long {
if (knownSize >= 0) return knownSize
val len = attempt {
val c = open("HEAD", null)
try {
check4xx(c)
c.getHeaderField("content-length")?.toLongOrNull() ?: throw MediaFormatException("HEAD $url gave no Content-Length")
} finally {
c.disconnect()
}
}
knownSize = len
return len
}
override fun read(offset: Long, length: Int): ByteArray {
if (length == 0) return ByteArray(0)
return attempt {
val c = open("GET", "bytes=$offset-${offset + length - 1}")
try {
check4xx(c)
val body = c.inputStream.use { it.readBytes() }
when (c.responseCode) {
206 -> body
// A server that ignores Range sends everything; correct, if wasteful.
200 -> if (body.size >= offset + length) body.copyOfRange(offset.toInt(), (offset + length).toInt()) else throw MediaFormatException("short 200 body")
else -> throw MediaFormatException("GET $url answered ${c.responseCode} to a Range request")
}
} finally {
c.disconnect()
}
}
}
private fun open(method: String, range: String?): HttpURLConnection {
val c = URL(url).openConnection() as HttpURLConnection
c.requestMethod = method
c.connectTimeout = timeoutMs
c.readTimeout = timeoutMs
for ((k, v) in headers) c.setRequestProperty(k, v)
if (range != null) c.setRequestProperty("Range", range)
return c
}
private fun check4xx(c: HttpURLConnection) {
val code = c.responseCode
if (code in 400..499) throw MediaFormatException("HTTP $code from $url")
if (code >= 500) throw IOException("HTTP $code from $url")
}
private fun <T> attempt(run: () -> T): T {
var last: Exception? = null
repeat(retries.coerceAtLeast(1)) { i ->
try {
return run()
} catch (e: MediaFormatException) {
throw e
} catch (e: IOException) {
last = e
Thread.sleep(150L shl i)
}
}
throw last ?: IOException("unreachable")
}
}
/** What a reader needs: the secret half of a grant. */
class MediaKeys(val mediaId: ByteArray, val mediaKey: ByteArray, val rootDigest: ByteArray? = null)
/**
* Random-access reader over a sealed file — mirror of the TS `MediaReader`.
* `open` checks the trailer against the root digest; every `read` then
* fetches only the segments under the range (neighbours in one request) and
* checks each against the digest table before decrypting it.
*
* Thread-safe: ExoPlayer reads from its loader thread while the UI may seek.
*/
class MediaReader private constructor(
private val source: RangeSource,
private val footer: Footer,
private val table: ByteArray,
private val segmentKey: ByteArray,
val meta: MediaMeta,
private val cacheSegments: Int,
private val maxSegmentsPerFetch: Int,
) : AutoCloseable {
val size: Long get() = footer.plaintextSize
val segmentSize: Int get() = footer.segmentSize
val segmentCount: Long get() = footer.segmentCount
private val cache = object : LinkedHashMap<Long, ByteArray>(16, 0.75f, true) {
override fun removeEldestEntry(eldest: MutableMap.MutableEntry<Long, ByteArray>?) = size > cacheSegments
}
companion object {
fun open(source: RangeSource, keys: MediaKeys, cacheSegments: Int = 8, maxSegmentsPerFetch: Int = 8): MediaReader {
val total = source.size()
if (total < FOOTER_BYTES) throw MediaFormatException("file too short to be SMF1")
val footer = Footer.decode(source.read(total - FOOTER_BYTES, FOOTER_BYTES))
if (!ctEquals(footer.mediaId, keys.mediaId)) throw MediaIntegrityException("file is a different media item than the grant names")
if (footer.sealedSize != total) throw MediaIntegrityException("size mismatch: footer implies ${footer.sealedSize}, file has $total")
val n = footer.segmentCount
val trailerLen = footer.metaLen + n * DIGEST_BYTES + FOOTER_BYTES
if (trailerLen > Int.MAX_VALUE) throw MediaFormatException("trailer too large")
val trailer = source.read(total - trailerLen, trailerLen.toInt())
if (keys.rootDigest != null && !ctEquals(sha256(trailer), keys.rootDigest)) {
throw MediaIntegrityException("trailer does not match the root digest in the grant")
}
val sub = deriveMediaSubkeys(keys.mediaKey, keys.mediaId)
val metaPlain = gcmOpen(sub.metaKey, META_NONCE, trailer.copyOfRange(0, footer.metaLen), metaAad(keys.mediaId))
sub.metaKey.fill(0)
val meta = MediaMeta.fromJson(String(metaPlain, Charsets.UTF_8))
val table = trailer.copyOfRange(footer.metaLen, footer.metaLen + (n * DIGEST_BYTES).toInt())
return MediaReader(source, footer, table, sub.segmentKey, meta, cacheSegments, maxSegmentsPerFetch.coerceAtLeast(1))
}
}
/** Plaintext `[offset, offset+length)`, clamped to the end. */
fun read(offset: Long, length: Int): ByteArray {
require(offset >= 0 && length >= 0) { "offset and length must be non-negative" }
val end = minOf(size, offset + length)
if (offset >= end) return ByteArray(0)
val first = offset / segmentSize
val last = (end - 1) / segmentSize
val out = ByteArray((end - offset).toInt())
var w = 0
for ((i, seg) in segments(first, last).withIndex()) {
val segStart = (first + i) * segmentSize
val from = maxOf(offset, segStart) - segStart
val to = minOf(end, segStart + seg.size) - segStart
System.arraycopy(seg, from.toInt(), out, w, (to - from).toInt())
w += (to - from).toInt()
}
return out
}
/** A plain InputStream over `[start, end)` — for players and file copies. */
fun inputStream(start: Long = 0, end: Long = size): InputStream = object : InputStream() {
private var pos = start
override fun read(): Int {
val b = ByteArray(1)
return if (read(b, 0, 1) <= 0) -1 else b[0].toInt() and 0xff
}
override fun read(b: ByteArray, off: Int, len: Int): Int {
if (pos >= end) return -1
val n = minOf(len.toLong(), end - pos, segmentSize.toLong() * maxSegmentsPerFetch).toInt()
val bytes = this@MediaReader.read(pos, n)
System.arraycopy(bytes, 0, b, off, bytes.size)
pos += bytes.size
return bytes.size
}
override fun skip(n: Long): Long {
val s = minOf(n, end - pos).coerceAtLeast(0)
pos += s
return s
}
}
private fun segments(first: Long, last: Long): List<ByteArray> {
if (first < 0 || last >= segmentCount || first > last) throw IndexOutOfBoundsException("segments $first..$last")
val out = ArrayList<ByteArray>()
var i = first
while (i <= last) {
val cached = synchronized(cache) { cache[i] }
if (cached != null) {
out += cached
i++
continue
}
var j = i
while (j + 1 <= last && j + 1 - i < maxSegmentsPerFetch && synchronized(cache) { !cache.containsKey(j + 1) }) j++
val run = fetchRun(i, j)
synchronized(cache) { run.forEachIndexed { k, s -> cache[i + k] = s } }
out += run
i = j + 1
}
return out
}
private fun fetchRun(first: Long, last: Long): List<ByteArray> {
val (aOff, _) = footer.span(first)
val (bOff, bLen) = footer.span(last)
val len = bOff + bLen - aOff
if (len > Int.MAX_VALUE) throw MediaFormatException("range too large")
val bytes = source.read(aOff, len.toInt())
if (bytes.size.toLong() != len) throw MediaIntegrityException("short read from media source")
return (first..last).map { i ->
val (off, l) = footer.span(i)
val sealed = bytes.copyOfRange((off - aOff).toInt(), (off - aOff).toInt() + l)
val want = table.copyOfRange((i * DIGEST_BYTES).toInt(), ((i + 1) * DIGEST_BYTES).toInt())
if (!ctEquals(sha256(sealed), want)) throw MediaIntegrityException("segment $i does not match its digest")
gcmOpen(segmentKey, segmentNonce(i), sealed, segmentAad(footer.mediaId, i, i == segmentCount - 1))
}
}
override fun close() {
synchronized(cache) { cache.clear() }
segmentKey.fill(0)
}
}

View File

@@ -0,0 +1,179 @@
package no.zyon.shade
import no.zyon.shade.media.ByteArraySource
import no.zyon.shade.media.FOOTER_BYTES
import no.zyon.shade.media.Grants
import no.zyon.shade.media.LiveContent
import no.zyon.shade.media.LiveGrant
import no.zyon.shade.media.LiveKeyException
import no.zyon.shade.media.LivePublisher
import no.zyon.shade.media.LiveSubscriber
import no.zyon.shade.media.MediaGrant
import no.zyon.shade.media.MediaIntegrityException
import no.zyon.shade.media.MediaKeys
import no.zyon.shade.media.MediaMeta
import no.zyon.shade.media.MediaReader
import no.zyon.shade.media.MediaSealer
import no.zyon.shade.media.chainStep
import no.zyon.shade.media.decodeFrame
import no.zyon.shade.media.deriveMediaSubkeys
import no.zyon.shade.media.epochKeys
import no.zyon.shade.media.linkEpochSeed
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertNull
import org.junit.Assert.assertThrows
import org.junit.Assert.assertTrue
import org.junit.Test
import java.io.File
/**
* `@shade/media` against `test-vectors/media.json` — SMF1 sealed files and
* SLF1 live frames, byte for byte. Generated by
* `bun run scripts/generate-vectors.ts media.json`.
*/
class MediaVectorTest {
private val vectors: JSONArray = run {
val obj = JSONObject(File("../../test-vectors/media.json").readText())
assertEquals("media.json schema version", 2, obj.getInt("version"))
obj.getJSONArray("vectors")
}
private fun byPrefix(prefix: String): List<JSONObject> =
(0 until vectors.length()).map { vectors.getJSONObject(it) }
.filter { it.getString("description").startsWith(prefix) }
.also { assertTrue("no vectors for '$prefix'", it.isNotEmpty()) }
private fun hex(s: String): ByteArray =
ByteArray(s.length / 2) { ((Character.digit(s[it * 2], 16) shl 4) + Character.digit(s[it * 2 + 1], 16)).toByte() }
private fun toHex(b: ByteArray) = b.joinToString("") { "%02x".format(it) }
private val keys = byPrefix("smf1 keys").single()
private val mediaId = hex(keys.getString("mediaId"))
private val mediaKey = hex(keys.getString("mediaKey"))
@Test
fun subkeys() {
val k = deriveMediaSubkeys(mediaKey, mediaId)
assertEquals(keys.getString("segmentKey"), toHex(k.segmentKey))
assertEquals(keys.getString("metaKey"), toHex(k.metaKey))
}
@Test
fun sealedFilesReadAndResealByteForByte() {
for (v in byPrefix("smf1 file")) {
val sealed = hex(v.getString("sealed"))
val plain = hex(v.getString("plaintext"))
val reader = MediaReader.open(ByteArraySource(sealed), MediaKeys(mediaId, mediaKey, hex(v.getString("rootDigest"))))
assertArrayEquals(v.getString("description"), plain, reader.read(0, plain.size))
val meta = MediaMeta.fromJson(v.getString("metaJson"))
assertEquals(meta, reader.meta)
// Writer parity: the same key, id and input give the same bytes.
val (resealed, result) = MediaSealer.withPinnedKeys(mediaId, mediaKey, meta, v.getInt("segmentSize")).sealAll(plain)
assertEquals(v.getString("description"), v.getString("sealed"), toHex(resealed))
assertEquals(v.getString("rootDigest"), toHex(result.rootDigest))
assertEquals(v.getLong("segmentCount"), result.segmentCount)
}
}
@Test
fun randomAccessAndStreaming() {
val v = byPrefix("smf1 file: three segments").single()
val plain = hex(v.getString("plaintext"))
val reader = MediaReader.open(ByteArraySource(hex(v.getString("sealed"))), MediaKeys(mediaId, mediaKey), cacheSegments = 0)
for (off in listOf(0, 1, 4095, 4096, 4097, 8191, 8192, plain.size - 1)) {
for (len in listOf(1, 100, 4096, 9000)) {
assertArrayEquals("at $off+$len", plain.copyOfRange(off, minOf(plain.size, off + len)), reader.read(off.toLong(), len))
}
}
assertArrayEquals(plain, reader.inputStream().readBytes())
assertArrayEquals(plain.copyOfRange(5000, 9000), reader.inputStream(5000, 9000).readBytes())
}
@Test
fun tamperedSegmentAndTrailerAreRefused() {
val v = byPrefix("smf1 file: three segments").single()
val sealed = hex(v.getString("sealed"))
val root = hex(v.getString("rootDigest"))
val bad = sealed.copyOf().also { it[5000] = (it[5000].toInt() xor 1).toByte() }
val r = MediaReader.open(ByteArraySource(bad), MediaKeys(mediaId, mediaKey, root))
assertThrows(MediaIntegrityException::class.java) { r.read(4096, 10) }
val badTable = sealed.copyOf().also { it[it.size - FOOTER_BYTES - 1] = (it[it.size - FOOTER_BYTES - 1].toInt() xor 1).toByte() }
assertThrows(MediaIntegrityException::class.java) { MediaReader.open(ByteArraySource(badTable), MediaKeys(mediaId, mediaKey, root)) }
}
@Test
fun liveKeySchedule() {
val k = byPrefix("live keys").single()
val channelId = hex(k.getString("channelId"))
val seed = linkEpochSeed(hex(k.getString("channelSecret")), channelId, 0)
assertEquals(k.getString("epochSeed"), toHex(seed))
assertEquals(k.getString("epochSeed1"), toHex(linkEpochSeed(hex(k.getString("channelSecret")), channelId, 1)))
val ek = epochKeys(seed, channelId, 0)
assertEquals(k.getString("chainKey0"), toHex(ek.chainKey))
assertEquals(k.getString("stickyKey"), toHex(ek.stickyKey))
val (mk0, ck1) = chainStep(ek.chainKey)
assertEquals(k.getString("messageKey0"), toHex(mk0))
assertEquals(k.getString("chainKey1"), toHex(ck1))
assertEquals(k.getString("messageKey1"), toHex(chainStep(ck1).first))
}
@Test
fun liveFramesOpenFromTheLinkGrantAcrossARotation() {
val g = Grants.parse(byPrefix("live grant").single().getString("json")) as LiveGrant
assertNotNull(g.channelSecret)
val sub = LiveSubscriber(g)
for (v in byPrefix("live frame")) {
val f = sub.open(hex(v.getString("wire")))
assertNotNull(v.getString("description"), f)
assertEquals(v.getLong("seq"), f!!.seq)
assertEquals(v.getString("payload"), toHex(f.content.encode()))
// Replays are dropped quietly.
assertNull(sub.open(hex(v.getString("wire"))))
}
}
@Test
fun livePublisherReproducesTheWireBytes() {
val k = byPrefix("live keys").single()
val pub = LivePublisher(hex(k.getString("channelId")), hex(k.getString("signingSecret")), hex(k.getString("channelSecret")))
assertEquals(k.getString("signingKey"), toHex(pub.signingKey))
val frames = byPrefix("live frame: seq")
for ((i, v) in frames.withIndex()) {
val content = LiveContent.decode(hex(v.getString("payload")))
val sticky = v.getString("description").contains("sticky")
val keyframe = decodeFrame(hex(v.getString("wire"))).header.flags and 0x02 != 0
val wire = pub.frame(content, keyframe = keyframe, sticky = sticky, timestamp = 1_786_600_000_000L + i * 100)
assertEquals(v.getString("description"), v.getString("wire"), toHex(wire))
}
}
@Test
fun forgedFramesAndForeignEpochsAreRefused() {
val k = byPrefix("live keys").single()
val channelId = hex(k.getString("channelId"))
val pub = LivePublisher(channelId, ByteArray(32) { 7 }, null)
val sub = LiveSubscriber(pub.grant(from = "now"))
val good = pub.frame(LiveContent.Text("hei"))
val mallory = LivePublisher(channelId, ByteArray(32) { 9 }, null)
assertThrows(MediaIntegrityException::class.java) { sub.open(mallory.frame(LiveContent.Text("falsk"))) }
assertEquals(LiveContent.Text("hei"), sub.open(good)!!.content)
pub.rotate()
assertThrows(LiveKeyException::class.java) { sub.open(pub.frame(LiveContent.Text("etter"))) }
}
@Test
fun mediaGrantParses() {
val g = Grants.parse(
"""{"kind":"shade.media-grant/v1","mediaId":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaId)}","key":"${java.util.Base64.getUrlEncoder().withoutPadding().encodeToString(mediaKey)}","root":"${"ab".repeat(32)}","url":"https://relay.example/v1/media/x","token":"${"A".repeat(43)}"}""",
) as MediaGrant
assertArrayEquals(mediaId, g.mediaId)
assertThrows(Exception::class.java) { Grants.parse("""{"kind":"shade.media-grant/v1","mediaId":"AA","key":"AA","root":"ab"}""") }
}
}

View File

@@ -10,7 +10,8 @@
"./node": "./src/node.ts",
"./server": "./src/server.ts",
"./browser": "./src/browser/index.ts",
"./cli": "./src/cli.ts"
"./cli": "./src/cli.ts",
"./testing": "./src/testing.ts"
},
"dependencies": {
"@noble/curves": "^2.0.1",

View File

@@ -108,9 +108,17 @@ export interface SealResult {
segmentCount: number;
}
/**
* Pins the key and id instead of drawing them — for cross-language vectors
* ONLY, via `@shade/media/testing`. Not exported from the package root: SMF1
* nonces are deterministic, so a key used for two files breaks AES-GCM.
*/
export const VECTOR_KEYS: unique symbol = Symbol('shade-media/vector-keys');
export interface SealOptions {
meta?: MediaMeta;
segmentSize?: number;
[VECTOR_KEYS]?: { mediaId: Uint8Array; mediaKey: Uint8Array };
}
interface DerivedKeys {
@@ -118,6 +126,14 @@ interface DerivedKeys {
meta: AeadKey;
}
/** Raw segment and meta keys — exposed for vectors and ports, not for sealing. */
export function deriveMediaSubkeys(mediaKey: Uint8Array, mediaId: Uint8Array): { segmentKey: Uint8Array; metaKey: Uint8Array } {
return {
segmentKey: hkdf(nobleSha256, mediaKey, mediaId, INFO_SEGMENT, 32),
metaKey: hkdf(nobleSha256, mediaKey, mediaId, INFO_META, 32),
};
}
function deriveKeys(mediaKey: Uint8Array, mediaId: Uint8Array): DerivedKeys {
if (mediaKey.length !== MEDIA_KEY_BYTES) throw new MediaFormatError('mediaKey must be 32 bytes');
if (mediaId.length !== MEDIA_ID_BYTES) throw new MediaFormatError('mediaId must be 16 bytes');
@@ -288,8 +304,9 @@ export class MediaSealer {
this.segmentSize = opts.segmentSize ?? DEFAULT_SEGMENT_SIZE;
checkSegmentSize(this.segmentSize);
this.meta = validateMeta(opts.meta ?? {});
this.mediaId = randomBytes(MEDIA_ID_BYTES);
this.mediaKey = randomBytes(MEDIA_KEY_BYTES);
const pinned = opts[VECTOR_KEYS];
this.mediaId = pinned?.mediaId ?? randomBytes(MEDIA_ID_BYTES);
this.mediaKey = pinned?.mediaKey ?? randomBytes(MEDIA_KEY_BYTES);
this.keys = deriveKeys(this.mediaKey, this.mediaId);
}

View File

@@ -0,0 +1,15 @@
/**
* Vector helpers. NOT for production: these pin keys that the real API
* always draws fresh, and SMF1's nonces are deterministic per key.
*/
import { sealMediaBytes, VECTOR_KEYS } from './sealed.js';
import type { SealOptions } from './sealed.js';
export function sealWithPinnedKeys(
plaintext: Uint8Array,
mediaId: Uint8Array,
mediaKey: Uint8Array,
opts: Omit<SealOptions, typeof VECTOR_KEYS> = {},
): ReturnType<typeof sealMediaBytes> {
return sealMediaBytes(plaintext, { ...opts, [VECTOR_KEYS]: { mediaId, mediaKey } });
}

View File

@@ -0,0 +1,59 @@
/**
* `test-vectors/media.json` — the contract the Kotlin port is held to.
* Regenerate with `bun run scripts/generate-vectors.ts media.json`.
*/
import { describe, test, expect } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { MediaReader, deriveMediaSubkeys } from '../src/sealed.js';
import { sealWithPinnedKeys } from '../src/testing.js';
import { MemorySource } from '../src/source.js';
import { LiveSubscriber } from '../src/live/channel.js';
import { encodeContent } from '../src/live/frame.js';
import { parseGrant } from '../src/grant.js';
import type { LiveGrant } from '../src/grant.js';
const file = JSON.parse(readFileSync(join(import.meta.dir, '../../../test-vectors/media.json'), 'utf8'));
const vs: any[] = file.vectors;
const hex = (s: string) => Uint8Array.from(Buffer.from(s, 'hex'));
const toHex = (b: Uint8Array) => Buffer.from(b).toString('hex');
const by = (p: string) => vs.filter((v) => v.description.startsWith(p));
describe('media vectors', () => {
const keys = by('smf1 keys')[0];
test('subkeys', () => {
const k = deriveMediaSubkeys(hex(keys.mediaKey), hex(keys.mediaId));
expect(toHex(k.segmentKey)).toBe(keys.segmentKey);
expect(toHex(k.metaKey)).toBe(keys.metaKey);
});
for (const v of by('smf1 file')) {
test(v.description, async () => {
const { bytes, result } = await sealWithPinnedKeys(hex(v.plaintext), hex(keys.mediaId), hex(keys.mediaKey), {
segmentSize: v.segmentSize,
meta: v.meta,
});
expect(toHex(bytes)).toBe(v.sealed);
expect(toHex(result.rootDigest)).toBe(v.rootDigest);
const r = await MediaReader.open(new MemorySource(hex(v.sealed)), {
mediaId: hex(keys.mediaId),
mediaKey: hex(keys.mediaKey),
rootDigest: hex(v.rootDigest),
});
expect(toHex(await r.read(0, r.size))).toBe(v.plaintext);
expect(r.meta).toEqual(v.meta);
});
}
test('live frames open from the link grant, across a rotation', async () => {
const g = parseGrant(by('live grant')[0].json) as LiveGrant;
const sub = new LiveSubscriber(g);
for (const v of by('live frame')) {
const f = await sub.open(hex(v.wire));
expect(f).not.toBeNull();
expect(f!.seq).toBe(v.seq);
expect(toHex(encodeContent(f!.content))).toBe(v.payload);
}
});
});

View File

@@ -52,6 +52,13 @@ import {
} from '../packages/shade-vault/src/testing.js';
import type { VaultEntry, VaultManifest } from '../packages/shade-vault/src/types.js';
import { canonicalizePayload } from '../packages/shade-server/src/auth.js';
import { deriveMediaSubkeys } from '../packages/shade-media/src/sealed.js';
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 { ed25519PublicKeyFromSeed as edPub } from '../packages/shade-crypto-web/src/index.js';
const VECTOR_FILE_VERSION = 2;
@@ -975,6 +982,110 @@ async function generateVaultV2Vectors(): Promise<Vector[]> {
return vectors;
}
async function generateMediaVectors(): Promise<Vector[]> {
// SMF1: everything is deterministic once the key and id are pinned —
// segment nonces are the segment index. Small segments keep it readable.
const mediaId = new Uint8Array(16).map((_, i) => 0xa0 + i);
const mediaKey = new Uint8Array(32).map((_, i) => (i * 7 + 3) & 0xff);
const sub = deriveMediaSubkeys(mediaKey, mediaId);
const vectors: Vector[] = [
{
description: 'smf1 keys: segmentKey/metaKey = HKDF(mediaKey, salt = mediaId, "shade-media/v1\\0segment" | "…\\0meta")',
mediaId: hex(mediaId),
mediaKey: hex(mediaKey),
segmentKey: hex(sub.segmentKey),
metaKey: hex(sub.metaKey),
},
];
const seg = 4096;
const fill = (n: number, seed: number) => new Uint8Array(n).map((_, i) => (i * 131 + seed * 17 + (i >> 7)) & 0xff);
const cases: Array<{ name: string; plaintext: Uint8Array; meta: Record<string, unknown> }> = [
{ name: 'empty file — one empty last segment', plaintext: new Uint8Array(0), meta: {} },
{ name: 'one partial segment', plaintext: new TextEncoder().encode('Shade media — æøå 🎬\n'), meta: { mime: 'text/plain', name: 'hei.txt' } },
{ name: 'exact boundary — two full segments, the second is last', plaintext: fill(2 * seg, 1), meta: { mime: 'application/octet-stream' } },
{
name: 'three segments, last partial, full metadata',
plaintext: fill(2 * seg + 1000, 2),
meta: { mime: 'video/webm', name: 'Film.webm', durationMs: 5400000, width: 1920, height: 1080, createdAt: 1786600000000, extra: { series: 'S01E01' } },
},
];
for (const c of cases) {
const { bytes, result } = await sealWithPinnedKeys(c.plaintext, mediaId, mediaKey, { segmentSize: seg, meta: c.meta });
vectors.push({
description: `smf1 file: ${c.name}`,
segmentSize: seg,
meta: c.meta,
metaJson: JSON.stringify(c.meta),
plaintext: hex(c.plaintext),
sealed: hex(bytes),
rootDigest: hex(result.rootDigest),
segmentCount: result.segmentCount,
});
}
// Live: link mode with pinned secrets and timestamps makes every frame
// byte-for-byte reproducible (Ed25519 signatures are deterministic).
const channelId = new Uint8Array(16).map((_, i) => 0x10 + i);
const signingSecret = new Uint8Array(32).map((_, i) => 0x40 + i);
const channelSecret = new Uint8Array(32).map((_, i) => 0x80 + i);
const pub = new LivePublisher({ channelId, signingSecret, channelSecret, epoch: 0, meta: { name: 'kanal', mime: 'text/plain' } });
const seed0 = linkEpochSeed(channelSecret, channelId, 0);
const k0 = epochKeys(seed0, channelId, 0);
const s0 = chainStep(k0.chainKey);
const s1 = chainStep(s0.next);
vectors.push({
description: 'live keys: epochSeed = HKDF(channelSecret, salt = channelId, "shade-live/v1\\0epoch" || u32 epoch); chain/sticky = HKDF(epochSeed, channelId || u32 epoch, …); mk = HMAC(ck, 01), ck\' = HMAC(ck, 02)',
channelId: hex(channelId),
signingSecret: hex(signingSecret),
signingKey: hex(await edPub(signingSecret)),
channelSecret: hex(channelSecret),
epoch: 0,
epochSeed: hex(seed0),
chainKey0: hex(k0.chainKey),
stickyKey: hex(k0.stickyKey),
messageKey0: hex(s0.messageKey),
chainKey1: hex(s0.next),
messageKey1: hex(s1.messageKey),
epochSeed1: hex(linkEpochSeed(channelSecret, channelId, 1)),
});
const frames: Array<{ content: LiveContent; opts: { sticky?: boolean; keyframe?: boolean } }> = [
{ content: { type: 'meta', meta: { name: 'kanal', mime: 'text/plain' } }, opts: { sticky: true } },
{ content: { type: 'text', text: 'første linje\n' }, opts: { keyframe: true } },
{ content: { type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([0x1a, 0x45, 0xdf, 0xa3]) }, opts: { sticky: true } },
{ content: { type: 'chunk', bytes: fill(64, 3) }, opts: { keyframe: true } },
{ content: { type: 'image', mime: 'image/jpeg', bytes: new Uint8Array([0xff, 0xd8, 0xff, 0xe0]) }, opts: {} },
{ content: { type: 'binary', bytes: new Uint8Array([0, 1, 2, 255]) }, opts: {} },
{ content: { type: 'end' }, opts: {} },
];
const grant = pub.grant({ from: 'now', link: true, url: 'wss://relay.example/v1/live/EBESExQVFhcYGRobHB0eHw', readToken: new Uint8Array(32).fill(0x55) });
for (const [i, f] of frames.entries()) {
const wire = await pub.frame(f.content, { ...f.opts, timestamp: 1_786_600_000_000 + i * 100 });
vectors.push({
description: `live frame: seq ${i} ${f.content.type}${f.opts.sticky ? ' (sticky — sealed under stickyKey)' : ''}`,
seq: i,
content: f.content.type,
payload: hex(encodeContent(f.content)),
wire: hex(wire),
});
}
// One more epoch, so a port checks that link mode derives it unaided.
const resealed = await pub.rotate();
const after = await pub.frame({ type: 'text', text: 'etter rotasjon\n' }, { timestamp: 1_786_600_010_000 });
vectors.push({
description: `live frame: epoch 1 after rotate() — the ${resealed.length} sticky frames are resealed first (seq 0…${resealed.length - 1}); readable from the link grant alone`,
epoch: 1,
seq: decodeFrame(after).header.seq,
content: 'text',
payload: hex(encodeContent({ type: 'text', text: 'etter rotasjon\n' })),
wire: hex(after),
});
vectors.push({
description: 'live grant: wire JSON of a link grant (base64url fields, from: now at seq 0)',
json: encodeGrant(grant),
});
return vectors;
}
async function main() {
console.log('Generating cross-platform test vectors…');
@@ -992,6 +1103,7 @@ async function main() {
['blob.json', { vectors: await generateBlobVectors() }],
['approval.json', { vectors: await generateApprovalVectors() }],
['vault-v2.json', { vectors: await generateVaultV2Vectors() }],
['media.json', { vectors: await generateMediaVectors() }],
];
const only = new Set(process.argv.slice(2));

143
test-vectors/media.json Normal file

File diff suppressed because one or more lines are too long