feat(sdk): shareMedia / onMediaGrant — media grants over a Shade session

A grant for a sealed file or a live channel rides the Double Ratchet like
any message. With an onMediaGrant handler registered, grants are routed
there instead of onMessage; with none, they arrive as text as before.
Bench results for @shade/media (1 GiB, up to 200 live viewers, 100 %
delivered) committed with their chart spec.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-10-18 21:17:59 +02:00
parent e9ae5bd28e
commit 8fd1b19902
7 changed files with 347 additions and 0 deletions

67
bench/media-results.json Normal file
View File

@@ -0,0 +1,67 @@
{
"at": "2026-10-18T19:15:13.188Z",
"bun": "1.3.5",
"bigMiB": 1024,
"seal": {
"mibPerSec": 259.1,
"ms": 3951.4,
"overheadPct": 0.0046
},
"readDisk": {
"mibPerSec": 480.2,
"ms": 2132.4
},
"upload": {
"mibPerSec": 50.9
},
"readHttp": {
"mibPerSec": 209.5,
"ms": 4889
},
"open": {
"p50": 3.28,
"p95": 6.58
},
"seek": {
"p50": 3.98,
"p95": 8.21,
"max": 16.08
},
"live": [
{
"viewers": 1,
"delivered": 100,
"p50": 3,
"p95": 12,
"max": 14
},
{
"viewers": 10,
"delivered": 100,
"p50": 6,
"p95": 20,
"max": 49
},
{
"viewers": 50,
"delivered": 100,
"p50": 22,
"p95": 58,
"max": 213
},
{
"viewers": 100,
"delivered": 100,
"p50": 15,
"p95": 72,
"max": 255
},
{
"viewers": 200,
"delivered": 100,
"p50": 28,
"p95": 151,
"max": 443
}
]
}

147
bench/media.chart.json Normal file
View File

@@ -0,0 +1,147 @@
[
{
"type": "bar",
"title": "Sealed media throughput (MiB/s)",
"subtitle": "1024 MiB of incompressible data, 1 MiB segments, one core",
"y": {
"label": "MiB/s",
"min": 0
},
"note": "Bun 1.3.5; HTTP is localhost through the real media routes; size overhead 0.0046 %",
"source": {
"path": "media-results.json"
},
"series": [
{
"name": "MiB/s",
"data": [
[
"seal (disk → disk)",
259.1
],
[
"read + verify (disk)",
480.2
],
[
"upload (HTTP PUT)",
50.9
],
[
"read + verify (HTTP Range)",
209.5
]
]
}
]
},
{
"type": "bar",
"title": "Seeking in a sealed film over HTTP (ms)",
"subtitle": "open = footer + trailer + root check; seek = first 64 KiB at a random offset, no cache",
"y": {
"label": "ms",
"min": 0
},
"note": "n = 10 opens, 100 seeks; localhost",
"source": {
"path": "media-results.json"
},
"series": [
{
"name": "p50",
"data": [
[
"open",
3.28
],
[
"seek",
3.98
]
]
},
{
"name": "p95",
"data": [
[
"open",
6.58
],
[
"seek",
8.21
]
]
}
]
},
{
"type": "line",
"title": "Live fan-out: latency publish → decrypted, by viewers",
"subtitle": "10 fps × 32 KiB frames (≈ 2.6 Mbit/s) for 6 s; relay in its own process, all viewers in one",
"x": {
"label": "viewers"
},
"y": {
"label": "ms",
"min": 0
},
"note": "delivered: 1 → 100 %, 10 → 100 %, 50 → 100 %, 100 → 100 %, 200 → 100 %. Every viewer verifies every signature and decrypts every frame, in one process, so the curve is mostly the viewers' CPU, not the relay's.",
"source": {
"path": "media-results.json"
},
"series": [
{
"name": "p50",
"data": [
[
1,
3
],
[
10,
6
],
[
50,
22
],
[
100,
15
],
[
200,
28
]
]
},
{
"name": "p95",
"data": [
[
1,
12
],
[
10,
20
],
[
50,
58
],
[
100,
72
],
[
200,
151
]
]
}
]
}
]

View File

@@ -216,6 +216,7 @@
"@shade/files": "workspace:*",
"@shade/inbox": "workspace:*",
"@shade/key-transparency": "workspace:*",
"@shade/media": "workspace:*",
"@shade/observability": "workspace:*",
"@shade/observer": "workspace:*",
"@shade/proto": "workspace:*",

View File

@@ -10,6 +10,7 @@
"@shade/files": "workspace:*",
"@shade/inbox": "workspace:*",
"@shade/key-transparency": "workspace:*",
"@shade/media": "workspace:*",
"@shade/observability": "workspace:*",
"@shade/observer": "workspace:*",
"@shade/proto": "workspace:*",

View File

@@ -166,3 +166,4 @@ export type {
CreateEncryptStreamOptions,
CreateDecryptStreamOptions,
} from '@shade/crypto-web';
export type { Grant, MediaGrant, LiveGrant } from '@shade/media';

View File

@@ -1,4 +1,6 @@
import type { ShadeEnvelope, StorageProvider, RatchetMessage } from '@shade/core';
import { encodeGrant, isGrantMessage, parseGrant } from '@shade/media';
import type { Grant } from '@shade/media';
import {
ShadeSessionManager,
ShadeEventEmitter,
@@ -181,6 +183,8 @@ export class Shade {
// Message handlers — may be sync or async; receive() awaits each. The
// optional third arg distinguishes direct vs broadcast plaintexts;
// handlers registered without it work unchanged (V4.6 back-compat).
/** V4.15 — handlers for media grants; while any is registered, grants skip `onMessage`. */
private mediaGrantHandlers: Array<(from: string, grant: Grant) => void | Promise<void>> = [];
private messageHandlers: Array<
(from: string, plaintext: string, meta?: MessageMeta) => void | Promise<void>
> = [];
@@ -490,6 +494,7 @@ export class Shade {
plaintext,
);
if (consumed) return '';
if (await this.maybeDispatchMediaGrant(from, plaintext)) return '';
const meta: MessageMeta = { kind: 'direct' };
for (const handler of this.messageHandlers) {
try {
@@ -518,6 +523,53 @@ export class Shade {
};
}
// ─── V4.15 Media grants ────────────────────────────────────
/**
* Give a peer the keys to a sealed file or a live channel
* (`@shade/media`). The grant rides this Double-Ratchet session, so it is
* authenticated to us and forward-secret; the relay holding the media
* never sees it.
*/
async shareMedia(address: string, grant: Grant): Promise<ShadeEnvelope> {
return this.send(address, encodeGrant(grant));
}
/**
* Receive media grants. While at least one handler is registered, grant
* messages go here and not to `onMessage`; with none, they arrive as
* ordinary text, as before. A grant that does not parse is dropped with a
* warning rather than handed on — it claimed to be a grant.
*
* `from` is the authenticated sender: check it (or its verified
* fingerprint) before playing what it sent.
*/
onMediaGrant(handler: (from: string, grant: Grant) => void | Promise<void>): () => void {
this.mediaGrantHandlers.push(handler);
return () => {
this.mediaGrantHandlers = this.mediaGrantHandlers.filter((h) => h !== handler);
};
}
private async maybeDispatchMediaGrant(from: string, plaintext: string): Promise<boolean> {
if (this.mediaGrantHandlers.length === 0 || !isGrantMessage(plaintext)) return false;
let grant: Grant;
try {
grant = parseGrant(plaintext);
} catch (err) {
console.warn(`[Shade] Dropped a malformed media grant from ${from}:`, (err as Error).message);
return true;
}
for (const handler of this.mediaGrantHandlers) {
try {
await handler(from, grant);
} catch (err) {
console.error('[Shade] Media grant handler threw:', err);
}
}
return true;
}
// ─── V4.6 Broadcast channels ───────────────────────────────
/**

View File

@@ -0,0 +1,78 @@
import { describe, test, expect, afterEach } from 'bun:test';
import { Hono } from 'hono';
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { createShade, type Shade } from '../src/index.js';
import { createPrekeyServer, MemoryPrekeyStore } from '@shade/server';
import { SubtleCryptoProvider } from '@shade/crypto-web';
import { MediaClient, OwnerKey, openGrant } from '@shade/media';
import type { Grant } from '@shade/media';
import { createMediaRoutes, FileMediaStore } from '@shade/media/server';
const crypto = new SubtleCryptoProvider();
/**
* A film shared over a Shade session: Alice seals and uploads it, sends the
* grant through the Double Ratchet, Bob plays it from the relay — which
* never saw a key.
*/
describe('media grants over a Shade session', () => {
const stops: Array<() => void | Promise<void>> = [];
afterEach(async () => {
for (const s of stops.splice(0).reverse()) await s();
});
async function setup(): Promise<{ alice: Shade; bob: Shade; media: string }> {
const prekeys = Bun.serve({ port: 0, fetch: createPrekeyServer({ crypto, store: new MemoryPrekeyStore(), disableRateLimit: true }).fetch });
stops.push(() => prekeys.stop(true));
const dir = await mkdtemp(join(tmpdir(), 'sdk-media-'));
stops.push(() => rm(dir, { recursive: true, force: true }));
const app = new Hono();
app.route('/', createMediaRoutes(new FileMediaStore(dir)));
const media = Bun.serve({ port: 0, fetch: app.fetch });
stops.push(() => media.stop(true));
const alice = await createShade({ prekeyServer: `http://localhost:${prekeys.port}`, address: 'alice' });
const bob = await createShade({ prekeyServer: `http://localhost:${prekeys.port}`, address: 'bob' });
stops.push(() => alice.shutdown(), () => bob.shutdown());
return { alice, bob, media: `http://localhost:${media.port}` };
}
test('shareMedia → onMediaGrant → play', async () => {
const { alice, bob, media } = await setup();
const film = new Uint8Array(3 * 1024 * 1024 + 11).map((_, i) => (i * 7) & 0xff);
const grant = await new MediaClient(media, OwnerKey.generate()).uploadBytes(film, {
meta: { mime: 'video/mp4', name: 'Ferie.mp4' },
});
const got: Array<{ from: string; grant: Grant }> = [];
const texts: string[] = [];
bob.onMediaGrant((from, g) => void got.push({ from, grant: g }));
bob.onMessage((_from, text) => void texts.push(text));
const env = await alice.shareMedia('bob', grant);
expect(await bob.receive('alice', env)).toBe('');
expect(texts).toEqual([]);
expect(got.length).toBe(1);
expect(got[0]!.from).toBe('alice');
const g = got[0]!.grant;
if (g.kind !== 'shade.media-grant/v1') throw new Error('expected a media grant');
const reader = await openGrant(g);
expect(reader.meta.name).toBe('Ferie.mp4');
expect(await reader.read(2 * 1024 * 1024, 1024)).toEqual(film.subarray(2 * 1024 * 1024, 2 * 1024 * 1024 + 1024));
// Ordinary messages still reach onMessage.
await bob.receive('alice', await alice.send('bob', 'hei'));
expect(texts).toEqual(['hei']);
});
test('with no grant handler, a grant arrives as plain text (unchanged behaviour)', async () => {
const { alice, bob, media } = await setup();
const grant = await new MediaClient(media, OwnerKey.generate()).uploadBytes(new Uint8Array(10));
const texts: string[] = [];
bob.onMessage((_f, t) => void texts.push(t));
await bob.receive('alice', await alice.shareMedia('bob', grant));
expect(texts.length).toBe(1);
expect(texts[0]).toContain('shade.media-grant/v1');
});
});