Files

175 lines
8.0 KiB
TypeScript
Raw Permalink Normal View History

import { describe, test, expect } from 'bun:test';
import { LivePublisher, LiveSubscriber, MAX_SKIPPED_KEYS } from '../src/live/channel.js';
import { decodeFrame } from '../src/live/frame.js';
import { encodeGrant, parseGrant } from '../src/grant.js';
import type { LiveGrant } from '../src/grant.js';
import { LiveKeyError, MediaIntegrityError } from '../src/errors.js';
const text = (t: string) => ({ type: 'text' as const, text: t });
describe('live channel', () => {
test('a viewer granted at the start reads every frame, in order', async () => {
const pub = new LivePublisher({ meta: { name: 'logs' } });
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
for (let i = 0; i < 50; i++) {
const got = await sub.open(await pub.frame(text(`line ${i}`)));
expect(got?.content).toEqual(text(`line ${i}`));
expect(got?.seq).toBe(i);
}
});
test('grants survive the wire format', async () => {
const pub = new LivePublisher({ meta: { name: 'cam' } });
const g = pub.grant({ url: 'wss://relay.example/v1/live/x', readToken: new Uint8Array(32).fill(7) });
const back = parseGrant(encodeGrant(g)) as LiveGrant;
expect(back).toEqual(g);
const sub = new LiveSubscriber(back);
expect((await sub.open(await pub.frame(text('hi'))))?.content).toEqual(text('hi'));
});
test('late joiner starts at the oldest kept keyframe and reads sticky init', async () => {
const pub = new LivePublisher({ snapshots: 2 });
const frames: Uint8Array[] = [];
frames.push(await pub.frame({ type: 'init', mime: 'video/webm; codecs="vp8"', bytes: new Uint8Array([1, 2, 3]) }, { sticky: true }));
for (let i = 0; i < 30; i++) {
frames.push(await pub.frame({ type: 'chunk', bytes: new Uint8Array([i]) }, { keyframe: i % 10 === 0 }));
}
// Keyframes at chunk 0, 10, 20 → seqs 1, 11, 21; only the last two are kept.
const g = pub.grant();
expect(g.seq).toBe(11);
const sub = new LiveSubscriber(g);
const seen: number[] = [];
for (const f of frames) {
const r = await sub.open(f);
if (r !== null) seen.push(r.seq);
}
expect(seen[0]).toBe(0); // the sticky init, from second zero
expect(seen.slice(1)).toEqual(Array.from({ length: 20 }, (_, i) => 11 + i));
});
test('out-of-order frames decrypt once; replays are dropped', async () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
const f = [];
for (let i = 0; i < 10; i++) f.push(await pub.frame(text(String(i))));
const order = [3, 0, 9, 1, 2, 8, 4, 5, 7, 6];
for (const i of order) expect((await sub.open(f[i]!))?.seq).toBe(i);
for (const i of order) expect(await sub.open(f[i]!)).toBeNull();
});
test('forged, tampered and foreign frames are refused', async () => {
const pub = new LivePublisher();
const g = pub.grant({ from: 'now' });
const sub = new LiveSubscriber(g);
const good = await pub.frame(text('real'));
const flipped = good.slice();
flipped[60]! ^= 1;
await expect(sub.open(flipped)).rejects.toBeInstanceOf(MediaIntegrityError);
// A viewer holds the chain key — but not the signing key. A frame sealed
// correctly under the chain and signed by someone else is a forgery.
const mallory = new LivePublisher({ channelId: pub.channelId });
await expect(sub.open(await mallory.frame(text('fake')))).rejects.toBeInstanceOf(MediaIntegrityError);
const other = new LivePublisher();
await expect(sub.open(await other.frame(text('x')))).rejects.toThrow();
expect((await sub.open(good))?.content).toEqual(text('real'));
});
test('a grant cannot swap the signing key', () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant());
const g = pub.grant();
expect(() => sub.addGrant({ ...g, signingKey: new LivePublisher().signingKey })).toThrow(MediaIntegrityError);
});
test('rotation locks out a viewer who is not re-granted', async () => {
const pub = new LivePublisher();
await pub.frame({ type: 'meta', meta: { name: 'stream' } }, { sticky: true });
const alice = new LiveSubscriber(pub.grant({ from: 'now' }));
const bob = new LiveSubscriber(pub.grant({ from: 'now' }));
expect((await bob.open(await pub.frame(text('before'))))?.content).toEqual(text('before'));
await alice.open(await pub.frame(text('b2')));
const resealed = await pub.rotate();
expect(resealed.length).toBe(1);
expect(decodeFrame(resealed[0]!).header.epoch).toBe(1);
alice.addGrant(pub.grant({ from: 'now' }));
alice.forgetBefore(1);
// seq 0 of epoch 1 is the resealed sticky meta.
expect((await alice.open(resealed[0]!))?.content).toEqual({ type: 'meta', meta: { name: 'stream' } });
const after = await pub.frame(text('after'));
expect((await alice.open(after))?.content).toEqual(text('after'));
await expect(bob.open(after)).rejects.toBeInstanceOf(LiveKeyError);
});
test('a large gap is bridged and keys stay bounded', async () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
const frames = [];
for (let i = 0; i < MAX_SKIPPED_KEYS + 500; i++) frames.push(await pub.frame(text(String(i))));
expect((await sub.open(frames[frames.length - 1]!))?.seq).toBe(frames.length - 1);
// The oldest skipped keys were not kept…
expect(await sub.open(frames[0]!)).toBeNull();
// …the recent ones were.
expect((await sub.open(frames[frames.length - 2]!))?.seq).toBe(frames.length - 2);
}, 30_000);
test('every content kind round-trips', async () => {
const pub = new LivePublisher();
const sub = new LiveSubscriber(pub.grant({ from: 'now' }));
const kinds = [
text('æøå 🎬'),
{ type: 'binary' as const, bytes: new Uint8Array([0, 255]) },
{ type: 'init' as const, mime: 'audio/webm; codecs="opus"', bytes: new Uint8Array([9]) },
{ type: 'chunk' as const, bytes: new Uint8Array(1000).fill(3) },
{ type: 'image' as const, mime: 'image/jpeg', bytes: new Uint8Array([0xff, 0xd8, 0xff]) },
{ type: 'meta' as const, meta: { name: 'x', mime: 'video/webm' } },
{ type: 'end' as const },
];
for (const k of kinds) expect((await sub.open(await pub.frame(k)))?.content).toEqual(k);
});
});
describe('link mode', () => {
test('a link grant follows rotations and a publisher restart on its own', async () => {
const secret = new Uint8Array(32).fill(9);
const pub = new LivePublisher({ channelSecret: secret, rotateEvery: 5 });
const g = parseGrant(encodeGrant(pub.grant({ link: true }))) as LiveGrant;
expect(g.channelSecret).toEqual(secret);
const sub = new LiveSubscriber(g);
const seen: string[] = [];
for (let i = 0; i < 12; i++) {
if (pub.rotationDue) await pub.rotate();
const r = await sub.open(await pub.frame(text(`a${i}`)));
if (r?.content.type === 'text') seen.push(r.content.text);
}
expect(seen.length).toBe(12);
expect(pub.epoch).toBe(2);
// The publisher process restarts with the same identity, one epoch on.
const restarted = new LivePublisher({
channelId: pub.channelId,
signingSecret: (pub as unknown as { signingSecret: Uint8Array }).signingSecret,
channelSecret: secret,
epoch: pub.epoch + 1,
});
// A late viewer joins mid-epoch: it derives forward from seq 0.
for (let i = 0; i < 40; i++) await restarted.frame(text(`skip${i}`));
const r = await sub.open(await restarted.frame(text('after restart')));
expect(r?.content).toEqual(text('after restart'));
expect(r?.epoch).toBe(3);
});
test('a session grant does not carry the secret, and cannot read later epochs', async () => {
const pub = new LivePublisher({ channelSecret: new Uint8Array(32).fill(1) });
const g = pub.grant({ from: 'now' });
expect(g.channelSecret).toBeUndefined();
const sub = new LiveSubscriber(g);
await pub.rotate();
await expect(sub.open(await pub.frame(text('x')))).rejects.toBeInstanceOf(LiveKeyError);
expect(() => new LivePublisher().grant({ link: true })).toThrow();
});
});