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

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');
});
});