import { describe, test, expect, afterAll } from 'bun:test'; import { mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { websocket } from 'hono/bun'; import { Hono } from 'hono'; import { createMediaRoutes, createLiveRelay, FileMediaStore, MemoryLivePinStore, FileLivePinStore, parseRange, } from '../src/server.js'; import { MediaClient, OwnerKey, openGrant, sealMediaBytes, LivePublisher, LivePublishClient, LiveWatchClient, encodeGrant, parseGrant, MIN_SEGMENT_SIZE, } from '../src/index.js'; import type { LiveGrant, ReceivedFrame } from '../src/index.js'; const dirs: string[] = []; async function tempDir(): Promise { const d = await mkdtemp(join(tmpdir(), 'shade-media-')); dirs.push(d); return d; } afterAll(async () => { for (const d of dirs) await rm(d, { recursive: true, force: true }); }); function serve(app: Hono) { const server = Bun.serve({ port: 0, fetch: (req, srv) => app.fetch(req, { server: srv }), websocket }); return { server, base: `http://localhost:${server.port}` }; } function pattern(n: number): Uint8Array { const out = new Uint8Array(n); for (let i = 0; i < n; i++) out[i] = (i * 31 + (i >> 8)) & 0xff; return out; } const until = async (cond: () => boolean, ms = 10_000) => { const t = Date.now(); while (!cond()) { if (Date.now() - t > ms) throw new Error('timed out'); await new Promise((r) => setTimeout(r, 10)); } }; describe('parseRange', () => { test('forms', () => { expect(parseRange('bytes=0-9', 100)).toEqual({ start: 0, end: 10 }); expect(parseRange('bytes=90-', 100)).toEqual({ start: 90, end: 100 }); expect(parseRange('bytes=-5', 100)).toEqual({ start: 95, end: 100 }); expect(parseRange('bytes=50-500', 100)).toEqual({ start: 50, end: 100 }); expect(parseRange('bytes=100-', 100)).toBe('invalid'); expect(parseRange('bytes=0-1,5-6', 100)).toBe('invalid'); expect(parseRange(null, 100)).toBeNull(); }); }); describe('media routes over real HTTP', () => { test('upload, ranged playback, token, list, delete — and it survives a restart', async () => { const dir = await tempDir(); const app = new Hono(); app.route('/', createMediaRoutes(new FileMediaStore(dir))); const { server, base } = serve(app); try { const owner = OwnerKey.generate(); const client = new MediaClient(base, owner); const plain = pattern(10 * MIN_SEGMENT_SIZE + 77); const grant = await client.uploadBytes(plain, { segmentSize: MIN_SEGMENT_SIZE, meta: { mime: 'video/webm', name: 'Film.webm' }, }); // The grant crosses a Shade session as JSON. const g2 = parseGrant(encodeGrant(grant)); if (g2.kind !== 'shade.media-grant/v1') throw new Error('kind'); const reader = await openGrant(g2); expect(reader.meta.name).toBe('Film.webm'); expect(await reader.read(5 * MIN_SEGMENT_SIZE - 3, 2 * MIN_SEGMENT_SIZE)).toEqual( plain.subarray(5 * MIN_SEGMENT_SIZE - 3, 7 * MIN_SEGMENT_SIZE - 3), ); // Without the token: the same 404 as for an id that does not exist. const bare = await fetch(grant.url!); expect(bare.status).toBe(404); // Immutable. const { bytes, result } = await sealMediaBytes(new Uint8Array(10)); await client.putSealed(result, bytes); await expect(client.putSealed(result, bytes)).rejects.toThrow(/409/); expect((await client.list()).items.length).toBe(2); // Restart: a fresh store over the same directory serves the same film. const app2 = new Hono(); app2.route('/', createMediaRoutes(new FileMediaStore(dir))); const s2 = serve(app2); try { const r2 = await openGrant(g2, { url: grant.url!.replace(base, s2.base) }); expect(await r2.read(0, plain.length)).toEqual(plain); } finally { s2.server.stop(true); } // Someone else cannot delete it. const mallory = new MediaClient(base, OwnerKey.generate()); expect(await mallory.delete(grant.mediaId)).toBe(false); expect(await client.delete(grant.mediaId)).toBe(true); expect((await fetch(grant.url!, { headers: { 'x-shade-read': 'x' } })).status).toBe(404); } finally { server.stop(true); } }); test('a Range request on a multi-MiB file returns exactly that range', async () => { // Regression: Bun.file().slice() in a Response sent the whole file. const dir = await tempDir(); const app = new Hono(); app.route('/', createMediaRoutes(new FileMediaStore(dir))); const { server, base } = serve(app); try { const client = new MediaClient(base, OwnerKey.generate()); const plain = pattern(3 * 1024 * 1024 + 5); const grant = await client.uploadBytes(plain, { readToken: null }); const res = await fetch(grant.url!, { headers: { Range: 'bytes=100-1048675' } }); expect(res.status).toBe(206); expect((await res.arrayBuffer()).byteLength).toBe(1048576); const r = await openGrant(grant); expect(await r.read(0, plain.length)).toEqual(plain); } finally { server.stop(true); } }); test('refuses what is not a sealed file, bad signatures, and owners not on the list', async () => { const dir = await tempDir(); const allowed = OwnerKey.generate(); const app = new Hono(); app.route('/', createMediaRoutes(new FileMediaStore(dir), { allowedOwners: [allowed.id], maxObjectBytes: 1 << 20 })); const { server, base } = serve(app); try { const { bytes, result } = await sealMediaBytes(new Uint8Array(100)); await expect(new MediaClient(base, OwnerKey.generate()).putSealed(result, bytes)).rejects.toThrow(/403/); // Right owner, garbage body of the right length. const junk = new Uint8Array(bytes.length); const id = Buffer.from(result.mediaId).toString('hex'); const res = await fetch(`${base}/v1/media/${id}`, { method: 'PUT', headers: { 'content-length': String(junk.length), ...allowed.headers({ op: 'put', id, size: junk.length, readTokenHash: '' }) }, body: junk, }); expect(res.status).toBe(422); // Signature for a different size. const res2 = await fetch(`${base}/v1/media/${id}`, { method: 'PUT', headers: { 'content-length': String(bytes.length), ...allowed.headers({ op: 'put', id, size: 1, readTokenHash: '' }) }, body: bytes, }); expect(res2.status).toBe(401); const big = await sealMediaBytes(new Uint8Array(2 << 20)); await expect(new MediaClient(base, allowed).putSealed(big.result, big.bytes)).rejects.toThrow(/413/); await new MediaClient(base, allowed).putSealed(result, bytes); } finally { server.stop(true); } }); }); describe('live relay over real WebSockets', () => { test('publish → relay → viewers, with late join from backlog and sticky init', async () => { const relay = createLiveRelay({ pins: new MemoryLivePinStore(), backlogKeyframes: 2 }); const { server, base } = serve(relay.app); try { const pub = new LivePublisher({ meta: { name: 'cam' } }); const client = new LivePublishClient({ relay: base, publisher: pub, readToken: new Uint8Array(32).fill(1) }); await client.whenReady(); await client.send({ type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([0xaa]) }, { sticky: true }); for (let i = 0; i < 30; i++) { await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 }); } // flush() means sent, not received: wait until the relay holds all 31, // or a fast viewer joins mid-burst and (correctly) gets an older backlog. await until(() => relay.stats().framesIn === 31); const early: ReceivedFrame[] = []; const grant = parseGrant(encodeGrant(client.grant('oldest'))) as LiveGrant; const viewer = new LiveWatchClient(grant, { onFrame: (f) => void early.push(f) }); // Backlog: init (sticky) + frames from the 2nd-latest keyframe (chunk 10, seq 11). await until(() => early.length === 21); expect(early[0]!.content.type).toBe('init'); expect(early[1]!.seq).toBe(11); // Live frames arrive in order after the backlog. for (let i = 30; i < 40; i++) await client.send({ type: 'chunk', bytes: new Uint8Array([i]) }); await until(() => early.length === 31); expect(early.map((f) => f.seq).slice(1)).toEqual(Array.from({ length: 30 }, (_, i) => 11 + i)); expect(relay.stats().viewers).toBe(1); // A viewer with a wrong token is turned away. const errors: string[] = []; const bad = new LiveWatchClient({ ...grant, readToken: new Uint8Array(32) }, { onFrame: () => { throw new Error('should not get frames'); }, onError: (e) => errors.push(e.message), }); await until(() => errors.length > 0); bad.close(); // Someone else cannot take over the channel id. const thief = new LivePublisher({ channelId: pub.channelId }); const terr: string[] = []; const tc = new LivePublishClient({ relay: base, publisher: thief, readToken: new Uint8Array(32), onError: (m) => terr.push(m) }); await expect(tc.whenReady()).rejects.toThrow(/pinned/); expect(terr[0]).toMatch(/pinned/); await client.end(); await until(() => early.at(-1)?.content.type === 'end'); viewer.close(); } finally { relay.stop(); server.stop(true); } }); test('a relay with owners only takes channels co-signed by one of them', async () => { const owner = OwnerKey.generate(); const relay = createLiveRelay({ pins: new MemoryLivePinStore(), allowedOwners: [owner.id] }); const { server, base } = serve(relay.app); try { const errs: string[] = []; const stranger = new LivePublishClient({ relay: base, publisher: new LivePublisher(), readToken: new Uint8Array(32), onError: (m) => errs.push(m) }); await expect(stranger.whenReady()).rejects.toThrow(/owners/); expect(errs[0]).toMatch(/owners/); // Another owner's co-signature on this hello does not count either. const errs2: string[] = []; const wrong = new LivePublishClient({ relay: base, publisher: new LivePublisher(), readToken: new Uint8Array(32), owner: OwnerKey.generate(), onError: (m) => errs2.push(m) }); await until(() => errs2.length > 0); wrong.close(); const ok = new LivePublishClient({ relay: base, publisher: new LivePublisher(), readToken: new Uint8Array(32), owner }); await ok.whenReady(); ok.close(); } finally { relay.stop(); server.stop(true); } }); test('rotation: a re-granted viewer continues, the other is locked out; pins persist', async () => { const dir = await tempDir(); const pins = new FileLivePinStore(join(dir, 'pins.json')); const relay = createLiveRelay({ pins }); const { server, base } = serve(relay.app); try { const pub = new LivePublisher(); const client = new LivePublishClient({ relay: base, publisher: pub, readToken: new Uint8Array(32).fill(2) }); await client.whenReady(); await client.send({ type: 'meta', meta: { name: 'logs' } }, { sticky: true }); const a: ReceivedFrame[] = []; const b: ReceivedFrame[] = []; const bErr: Error[] = []; const va = new LiveWatchClient(client.grant('now'), { onFrame: (f) => void a.push(f) }); const vb = new LiveWatchClient(client.grant('now'), { onFrame: (f) => void b.push(f), onError: (e) => bErr.push(e) }); await until(() => a.length === 1 && b.length === 1); await client.send({ type: 'text', text: 'one' }); await until(() => a.length === 2 && b.length === 2); await client.rotate(); va.addGrant(client.grant('now')); await client.send({ type: 'text', text: 'two' }); await until(() => a.some((f) => f.content.type === 'text' && f.content.text === 'two')); await until(() => bErr.length >= 1); expect(b.some((f) => f.content.type === 'text' && f.content.text === 'two')).toBe(false); va.close(); vb.close(); client.close(); expect((await new FileLivePinStore(join(dir, 'pins.json')).get(Buffer.from(pub.channelId).toString('base64url')))?.signingKey).toBeDefined(); } finally { relay.stop(); server.stop(true); } }); });