Files
Shade/packages/shade-media/tests/vectors.test.ts

60 lines
2.3 KiB
TypeScript
Raw Normal View History

/**
* `test-vectors/media.json` — the contract the Kotlin port is held to.
* Regenerate with `bun run scripts/generate-vectors.ts media.json`.
*/
import { describe, test, expect } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { MediaReader, deriveMediaSubkeys } from '../src/sealed.js';
import { sealWithPinnedKeys } from '../src/testing.js';
import { MemorySource } from '../src/source.js';
import { LiveSubscriber } from '../src/live/channel.js';
import { encodeContent } from '../src/live/frame.js';
import { parseGrant } from '../src/grant.js';
import type { LiveGrant } from '../src/grant.js';
const file = JSON.parse(readFileSync(join(import.meta.dir, '../../../test-vectors/media.json'), 'utf8'));
const vs: any[] = file.vectors;
const hex = (s: string) => Uint8Array.from(Buffer.from(s, 'hex'));
const toHex = (b: Uint8Array) => Buffer.from(b).toString('hex');
const by = (p: string) => vs.filter((v) => v.description.startsWith(p));
describe('media vectors', () => {
const keys = by('smf1 keys')[0];
test('subkeys', () => {
const k = deriveMediaSubkeys(hex(keys.mediaKey), hex(keys.mediaId));
expect(toHex(k.segmentKey)).toBe(keys.segmentKey);
expect(toHex(k.metaKey)).toBe(keys.metaKey);
});
for (const v of by('smf1 file')) {
test(v.description, async () => {
const { bytes, result } = await sealWithPinnedKeys(hex(v.plaintext), hex(keys.mediaId), hex(keys.mediaKey), {
segmentSize: v.segmentSize,
meta: v.meta,
});
expect(toHex(bytes)).toBe(v.sealed);
expect(toHex(result.rootDigest)).toBe(v.rootDigest);
const r = await MediaReader.open(new MemorySource(hex(v.sealed)), {
mediaId: hex(keys.mediaId),
mediaKey: hex(keys.mediaKey),
rootDigest: hex(v.rootDigest),
});
expect(toHex(await r.read(0, r.size))).toBe(v.plaintext);
expect(r.meta).toEqual(v.meta);
});
}
test('live frames open from the link grant, across a rotation', async () => {
const g = parseGrant(by('live grant')[0].json) as LiveGrant;
const sub = new LiveSubscriber(g);
for (const v of by('live frame')) {
const f = await sub.open(hex(v.wire));
expect(f).not.toBeNull();
expect(f!.seq).toBe(v.seq);
expect(toHex(encodeContent(f!.content))).toBe(v.payload);
}
});
});