feat(media): @shade/media — seekable sealed media (SMF1), live channels, media routes and live relay
SMF1 seals a film, video, image or song once into a file any Range-capable store can serve; the reader fetches only segments under the playhead and checks each against a digest table pinned by the grant's root digest. Live channels use a sender-key chain with per-frame Ed25519 signatures, sticky init frames and keyframe snapshots for late joiners, and epoch rotation to remove a viewer. Server side: a disk-backed media store with signed owner uploads and a WebSocket relay with bounded backlog. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
133
packages/shade-media/tests/live.test.ts
Normal file
133
packages/shade-media/tests/live.test.ts
Normal file
@@ -0,0 +1,133 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
197
packages/shade-media/tests/sealed.test.ts
Normal file
197
packages/shade-media/tests/sealed.test.ts
Normal file
@@ -0,0 +1,197 @@
|
||||
import { describe, test, expect } from 'bun:test';
|
||||
import {
|
||||
MediaReader,
|
||||
MediaSealer,
|
||||
sealMediaBytes,
|
||||
sealMediaStream,
|
||||
MIN_SEGMENT_SIZE,
|
||||
FOOTER_BYTES,
|
||||
decodeFooter,
|
||||
} from '../src/sealed.js';
|
||||
import { MemorySource } from '../src/source.js';
|
||||
import { MediaFormatError, MediaIntegrityError } from '../src/errors.js';
|
||||
|
||||
const S = MIN_SEGMENT_SIZE;
|
||||
|
||||
function pattern(n: number, seed = 1): Uint8Array {
|
||||
const out = new Uint8Array(n);
|
||||
let x = seed >>> 0 || 1;
|
||||
for (let i = 0; i < n; i++) {
|
||||
x ^= x << 13;
|
||||
x ^= x >>> 17;
|
||||
x ^= x << 5;
|
||||
out[i] = x & 0xff;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
async function sealed(plain: Uint8Array, segmentSize = S) {
|
||||
const { bytes, result } = await sealMediaBytes(plain, {
|
||||
segmentSize,
|
||||
meta: { mime: 'video/webm', name: 'test.webm' },
|
||||
});
|
||||
return { bytes, result, keys: { mediaId: result.mediaId, mediaKey: result.mediaKey, rootDigest: result.rootDigest } };
|
||||
}
|
||||
|
||||
describe('SMF1 round trip', () => {
|
||||
for (const n of [0, 1, S - 1, S, S + 1, 3 * S, 3 * S + 17]) {
|
||||
test(`${n} bytes`, async () => {
|
||||
const plain = pattern(n, n + 1);
|
||||
const { bytes, result, keys } = await sealed(plain);
|
||||
expect(result.plaintextSize).toBe(n);
|
||||
expect(result.sealedSize).toBe(bytes.length);
|
||||
expect(result.segmentCount).toBe(Math.max(1, Math.ceil(n / S)));
|
||||
const r = await MediaReader.open(new MemorySource(bytes), keys);
|
||||
expect(r.size).toBe(n);
|
||||
expect(r.meta).toEqual({ mime: 'video/webm', name: 'test.webm' });
|
||||
expect(await r.read(0, n)).toEqual(plain);
|
||||
});
|
||||
}
|
||||
|
||||
test('random access matches the plaintext at every boundary', async () => {
|
||||
const plain = pattern(5 * S + 123, 7);
|
||||
const { bytes, keys } = await sealed(plain);
|
||||
const r = await MediaReader.open(new MemorySource(bytes), keys, { cacheSegments: 0 });
|
||||
const points = [0, 1, S - 1, S, S + 1, 2 * S - 3, 4 * S, 5 * S, 5 * S + 122];
|
||||
for (const a of points) {
|
||||
for (const len of [1, 2, S, 2 * S + 5, 10 * S]) {
|
||||
expect(await r.read(a, len)).toEqual(plain.subarray(a, Math.min(plain.length, a + len)));
|
||||
}
|
||||
}
|
||||
expect((await r.read(plain.length, 10)).length).toBe(0);
|
||||
});
|
||||
|
||||
test('stream() yields the requested range', async () => {
|
||||
const plain = pattern(9 * S + 5, 3);
|
||||
const { bytes, keys } = await sealed(plain);
|
||||
const r = await MediaReader.open(new MemorySource(bytes), keys, { maxSegmentsPerFetch: 2 });
|
||||
const got: Uint8Array[] = [];
|
||||
for await (const c of r.stream(S + 7, 7 * S + 1)) got.push(c);
|
||||
expect(Buffer.concat(got)).toEqual(Buffer.from(plain.subarray(S + 7, 7 * S + 1)));
|
||||
});
|
||||
|
||||
test('streaming seal in odd chunks produces a readable file of the same size', async () => {
|
||||
const plain = pattern(4 * S + 999, 11);
|
||||
async function* chunks() {
|
||||
let off = 0;
|
||||
let k = 1;
|
||||
while (off < plain.length) {
|
||||
const n = Math.min(plain.length - off, (k++ * 977) % (2 * S) + 1);
|
||||
yield plain.subarray(off, off + n);
|
||||
off += n;
|
||||
}
|
||||
}
|
||||
const { stream, result } = sealMediaStream(chunks(), { segmentSize: S });
|
||||
const parts: Uint8Array[] = [];
|
||||
for await (const p of stream) parts.push(p);
|
||||
const bytes = new Uint8Array(Buffer.concat(parts));
|
||||
const res = await result;
|
||||
expect(res.sealedSize).toBe(bytes.length);
|
||||
const r = await MediaReader.open(new MemorySource(bytes), {
|
||||
mediaId: res.mediaId,
|
||||
mediaKey: res.mediaKey,
|
||||
rootDigest: res.rootDigest,
|
||||
});
|
||||
expect(await r.read(0, plain.length)).toEqual(plain);
|
||||
});
|
||||
|
||||
test('every seal draws a fresh key and id', async () => {
|
||||
const a = new MediaSealer({ segmentSize: S });
|
||||
const b = new MediaSealer({ segmentSize: S });
|
||||
expect(a.mediaKey).not.toEqual(b.mediaKey);
|
||||
expect(a.mediaId).not.toEqual(b.mediaId);
|
||||
});
|
||||
});
|
||||
|
||||
describe('SMF1 tamper resistance', () => {
|
||||
test('a flipped ciphertext byte fails that segment', async () => {
|
||||
const plain = pattern(3 * S, 5);
|
||||
const { bytes, keys } = await sealed(plain);
|
||||
const bad = bytes.slice();
|
||||
bad[S + 100]! ^= 1; // inside segment 1
|
||||
const r = await MediaReader.open(new MemorySource(bad), keys);
|
||||
expect(await r.read(0, 10)).toEqual(plain.subarray(0, 10));
|
||||
await expect(r.read(S + 50, 10)).rejects.toBeInstanceOf(MediaIntegrityError);
|
||||
});
|
||||
|
||||
test('swapping two segments is caught', async () => {
|
||||
const plain = pattern(3 * S, 9);
|
||||
const { bytes, keys } = await sealed(plain);
|
||||
const seg = S + 16;
|
||||
const bad = bytes.slice();
|
||||
bad.set(bytes.subarray(0, seg), seg);
|
||||
bad.set(bytes.subarray(seg, 2 * seg), 0);
|
||||
const r = await MediaReader.open(new MemorySource(bad), keys);
|
||||
await expect(r.read(0, 1)).rejects.toBeInstanceOf(MediaIntegrityError);
|
||||
});
|
||||
|
||||
test('a key holder who rewrites the table is caught by the root digest', async () => {
|
||||
// Without the root digest a forged table could vouch for forged segments;
|
||||
// the grant pins the trailer, so even a holder of the key cannot.
|
||||
const plain = pattern(2 * S, 2);
|
||||
const { bytes, keys } = await sealed(plain);
|
||||
const bad = bytes.slice();
|
||||
bad[bad.length - FOOTER_BYTES - 1]! ^= 1; // last byte of the table
|
||||
await expect(MediaReader.open(new MemorySource(bad), keys)).rejects.toBeInstanceOf(
|
||||
MediaIntegrityError,
|
||||
);
|
||||
// …and without a root it still fails, at the segment.
|
||||
const r = await MediaReader.open(new MemorySource(bad), { mediaId: keys.mediaId, mediaKey: keys.mediaKey });
|
||||
await expect(r.read(S, 1)).rejects.toBeInstanceOf(MediaIntegrityError);
|
||||
});
|
||||
|
||||
test('truncation and a shrunk footer both fail closed', async () => {
|
||||
const plain = pattern(3 * S, 4);
|
||||
const { bytes, keys } = await sealed(plain);
|
||||
await expect(
|
||||
MediaReader.open(new MemorySource(bytes.subarray(0, bytes.length - 1)), keys),
|
||||
).rejects.toThrow();
|
||||
// Rewrite the footer to claim two segments: the second becomes "last",
|
||||
// which its AAD says it is not.
|
||||
const f = decodeFooter(bytes.subarray(bytes.length - FOOTER_BYTES));
|
||||
expect(f.plaintextSize).toBe(3 * S);
|
||||
const footer = bytes.slice(bytes.length - FOOTER_BYTES);
|
||||
new DataView(footer.buffer).setBigUint64(12, BigInt(2 * S), false);
|
||||
const r = await MediaReader.open(
|
||||
new MemorySource(
|
||||
new Uint8Array(
|
||||
Buffer.concat([
|
||||
bytes.subarray(0, 2 * (S + 16)),
|
||||
bytes.subarray(3 * (S + 16), 3 * (S + 16) + 16 + 32 * 2), // meta + 2 digests
|
||||
footer,
|
||||
]),
|
||||
),
|
||||
),
|
||||
{ mediaId: keys.mediaId, mediaKey: keys.mediaKey },
|
||||
).catch((e) => e);
|
||||
if (r instanceof Error) {
|
||||
expect(r).toBeInstanceOf(Error);
|
||||
} else {
|
||||
await expect(r.read(S, 1)).rejects.toBeInstanceOf(MediaIntegrityError);
|
||||
}
|
||||
});
|
||||
|
||||
test('wrong key, wrong id, bad magic', async () => {
|
||||
const { bytes, keys } = await sealed(pattern(100));
|
||||
await expect(
|
||||
MediaReader.open(new MemorySource(bytes), { ...keys, mediaKey: new Uint8Array(32) }),
|
||||
).rejects.toBeInstanceOf(MediaIntegrityError);
|
||||
await expect(
|
||||
MediaReader.open(new MemorySource(bytes), { ...keys, mediaId: new Uint8Array(16) }),
|
||||
).rejects.toBeInstanceOf(MediaIntegrityError);
|
||||
const bad = bytes.slice();
|
||||
bad[bad.length - 1] = 0;
|
||||
await expect(MediaReader.open(new MemorySource(bad), keys)).rejects.toBeInstanceOf(
|
||||
MediaFormatError,
|
||||
);
|
||||
});
|
||||
|
||||
test('invalid metadata is refused at seal time', async () => {
|
||||
await expect(sealMediaBytes(new Uint8Array(1), { meta: { mime: 'not a mime' } })).rejects.toBeInstanceOf(
|
||||
MediaFormatError,
|
||||
);
|
||||
await expect(sealMediaBytes(new Uint8Array(1), { meta: { name: 'a\nb' } })).rejects.toBeInstanceOf(
|
||||
MediaFormatError,
|
||||
);
|
||||
});
|
||||
});
|
||||
252
packages/shade-media/tests/server.test.ts
Normal file
252
packages/shade-media/tests/server.test.ts
Normal file
@@ -0,0 +1,252 @@
|
||||
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<string> {
|
||||
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 = 3000) => {
|
||||
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('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 });
|
||||
}
|
||||
await client.flush();
|
||||
|
||||
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 until(() => terr.length > 0);
|
||||
expect(terr[0]).toMatch(/pinned/);
|
||||
tc.close();
|
||||
|
||||
await client.end();
|
||||
await until(() => early.at(-1)?.content.type === 'end');
|
||||
viewer.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);
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user