release(v4.0.0): Shade GA — V3.x consolidation + audit prep
Some checks failed
Test / test (push) Has been cancelled
Cross-platform vectors / TypeScript vectors (bun) (push) Has been cancelled
Cross-platform vectors / Kotlin vectors (gradle) (push) Has been cancelled
Docker build and publish / docker (push) Has been cancelled
Publish / publish (push) Has been cancelled

V3.1 → V3.12 consolidated and tagged for the first GA release. Wire
format unchanged from 0.4.x — 4.0 peers interoperate with 0.4.x peers
byte-for-byte. The version bump is semantic: audit-cycle complete,
opt-in surface fully exposed, threat model refreshed for every new
surface.

Highlights:
- All 24 @shade/* packages bumped to 4.0.0 in lockstep.
- CHANGELOG 4.0.0 section is the canonical manifest of what landed.
- THREAT-MODEL extended (§10 fingerprint gates, §11 WebRTC P2P, §12
  Web-Worker boundary) + residual-risks table refreshed.
- OpenAPI now covers all 27 routes: prekey, transfer, KT, inbox,
  bridge, observer, /metrics, /healthz, /ready.
- MIGRATION 0.3.x → 4.0 documented + smoke-tested against
  shade migrate-storage on a real SQLite DB.
- docs/audit/REVIEW-BUNDLE.md + SCOPE.md ready for external reviewer.
- scripts/soak.ts harness for the GA-stable 2-week soak window.
- All V*.md plans archived under docs/archive/ with Status: Done.
- Voice/Video carved out into V5.0; 4.0 audit focuses on the frozen
  non-realtime stack.

Tests: TS 1000/1000 + Kotlin 11/11 cross-platform vectors green.
Docker: gt.zyon.no/stian/shade-prekey:4.0.0 builds and reports
  version 4.0.0 on /health.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-03 18:35:35 +02:00
parent 8b055912b7
commit e6fdf31b49
298 changed files with 37909 additions and 256 deletions

View File

@@ -0,0 +1,223 @@
import { afterEach, describe, expect, it } from 'bun:test';
import {
encodeChunkFrame,
encodeResumeQueryFrame,
randomRequestId,
STREAM_ID_LEN,
WIRE_CHUNK,
WIRE_CHUNK_ACK,
WIRE_RESUME_QUERY,
WIRE_RESUME_STATE,
WIRE_ERROR,
bytesEqual,
} from '../src/wire.js';
import { MemoryRtcFactory } from '../src/memory-rtc.js';
import { MemoryShadeBridge, WebRtcSignalingChannel } from '../src/signaling.js';
import { WebRtcConnectionManager } from '../src/manager.js';
afterEach(() => {
MemoryRtcFactory.reset();
});
async function setupPair(opts?: {
bobReceiver?: import('../src/connection.js').WebRtcReceiverHooks;
aliceReceiver?: import('../src/connection.js').WebRtcReceiverHooks;
}): Promise<{
alice: WebRtcConnectionManager;
bob: WebRtcConnectionManager;
aliceSig: WebRtcSignalingChannel;
bobSig: WebRtcSignalingChannel;
}> {
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const aliceSig = new WebRtcSignalingChannel(a);
const bobSig = new WebRtcSignalingChannel(b);
const factory = new MemoryRtcFactory();
const alice = new WebRtcConnectionManager({
factory,
signaling: aliceSig,
...(opts?.aliceReceiver !== undefined ? { receiver: opts.aliceReceiver } : {}),
});
const bob = new WebRtcConnectionManager({
factory,
signaling: bobSig,
...(opts?.bobReceiver !== undefined ? { receiver: opts.bobReceiver } : {}),
});
return { alice, bob, aliceSig, bobSig };
}
describe('WebRtcConnection — caller/callee handshake', () => {
it('opens a data channel after offer/answer/ICE flow', async () => {
const { alice, bob } = await setupPair();
const conn = await alice.getOrCreate('bob');
expect(conn.state).toBe('connected');
expect(bob.isConnected('alice')).toBe(true);
// The peer connection on the bob side should also be open and reachable.
const bobConn = await bob.getOrCreate('alice');
expect(bobConn.state).toBe('connected');
alice.destroy();
bob.destroy();
});
it('routes a chunk request to the receiver hook and replies with chunk-ack', async () => {
const calls: Array<{
from: string;
streamId: string;
laneId: number;
seq: bigint;
bytes: number;
}> = [];
const { alice, bob } = await setupPair({
bobReceiver: {
async onChunk(from, streamId, laneId, seq, envelope) {
calls.push({ from, streamId, laneId, seq, bytes: envelope.length });
return { lastSeq: Number(seq), bytesReceived: envelope.length };
},
async onResumeQuery() {
return null;
},
},
});
const conn = await alice.getOrCreate('bob');
const requestId = randomRequestId();
const streamId = new Uint8Array(STREAM_ID_LEN).fill(0xaa);
const envelope = new Uint8Array(64);
for (let i = 0; i < envelope.length; i++) envelope[i] = i;
const frame = encodeChunkFrame({
type: WIRE_CHUNK,
requestId,
streamId,
laneId: 3,
seq: 7n,
envelope,
});
const response = await conn.request(frame, requestId);
expect(response.type).toBe(WIRE_CHUNK_ACK);
if (response.type === WIRE_CHUNK_ACK) {
expect(bytesEqual(response.requestId, requestId)).toBe(true);
expect(response.lastSeq).toBe(7);
expect(response.bytesReceived).toBe(64);
}
expect(calls).toHaveLength(1);
expect(calls[0]!.laneId).toBe(3);
expect(calls[0]!.seq).toBe(7n);
expect(calls[0]!.bytes).toBe(64);
alice.destroy();
bob.destroy();
});
it('returns error frame when receiver throws', async () => {
const { alice, bob } = await setupPair({
bobReceiver: {
async onChunk() {
throw new Error('nope');
},
async onResumeQuery() {
return null;
},
},
});
const conn = await alice.getOrCreate('bob');
const requestId = randomRequestId();
const streamId = new Uint8Array(STREAM_ID_LEN).fill(0x01);
const frame = encodeChunkFrame({
type: WIRE_CHUNK,
requestId,
streamId,
laneId: 0,
seq: 0n,
envelope: new Uint8Array(4),
});
const response = await conn.request(frame, requestId);
expect(response.type).toBe(WIRE_ERROR);
if (response.type === WIRE_ERROR) {
expect(response.json).toContain('nope');
}
alice.destroy();
bob.destroy();
});
it('handles resume-query with not-found → error frame', async () => {
const { alice, bob } = await setupPair({
bobReceiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
const conn = await alice.getOrCreate('bob');
const requestId = randomRequestId();
const streamId = new Uint8Array(STREAM_ID_LEN).fill(0x55);
const frame = encodeResumeQueryFrame({
type: WIRE_RESUME_QUERY,
requestId,
streamId,
});
const res = await conn.request(frame, requestId);
expect(res.type).toBe(WIRE_ERROR);
if (res.type === WIRE_ERROR) {
expect(res.json).toContain('not found');
}
alice.destroy();
bob.destroy();
});
it('handles resume-query that returns state → resume-state frame', async () => {
const { alice, bob } = await setupPair({
bobReceiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery(_from, streamId) {
return { streamId, lanes: [{ laneId: 0, lastSeqAcked: 11 }] };
},
},
});
const conn = await alice.getOrCreate('bob');
const requestId = randomRequestId();
const streamId = new Uint8Array(STREAM_ID_LEN).fill(0x77);
const frame = encodeResumeQueryFrame({
type: WIRE_RESUME_QUERY,
requestId,
streamId,
});
const res = await conn.request(frame, requestId);
expect(res.type).toBe(WIRE_RESUME_STATE);
if (res.type === WIRE_RESUME_STATE) {
const parsed = JSON.parse(res.json) as { lanes: { laneId: number; lastSeqAcked: number }[] };
expect(parsed.lanes[0]!.lastSeqAcked).toBe(11);
}
alice.destroy();
bob.destroy();
});
});
describe('WebRtcConnectionManager pool', () => {
it('reuses one connection per peer', async () => {
const { alice, bob } = await setupPair();
const c1 = await alice.getOrCreate('bob');
const c2 = await alice.getOrCreate('bob');
expect(c1).toBe(c2);
alice.destroy();
bob.destroy();
});
it('removes the connection from the pool when it closes', async () => {
const { alice, bob } = await setupPair();
const conn = await alice.getOrCreate('bob');
expect(alice.isConnected('bob')).toBe(true);
await conn.close('test');
expect(alice.isConnected('bob')).toBe(false);
alice.destroy();
bob.destroy();
});
});

View File

@@ -0,0 +1,49 @@
/**
* Glare = both peers initiate at the same instant. The manager resolves
* deterministically: the address with the lexically-larger value yields
* to the smaller one's offer.
*/
import { afterEach, describe, expect, it } from 'bun:test';
import { MemoryRtcFactory } from '../src/memory-rtc.js';
import { MemoryShadeBridge, WebRtcSignalingChannel } from '../src/signaling.js';
import { WebRtcConnectionManager } from '../src/manager.js';
afterEach(() => {
MemoryRtcFactory.reset();
});
describe('Glare resolution', () => {
it('two simultaneous getOrCreate() calls converge on a single connection', async () => {
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const aliceSig = new WebRtcSignalingChannel(a);
const bobSig = new WebRtcSignalingChannel(b);
const factory = new MemoryRtcFactory();
const alice = new WebRtcConnectionManager({ factory, signaling: aliceSig });
const bob = new WebRtcConnectionManager({
factory,
signaling: bobSig,
receiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
// Both kick off at once.
const [aConn, bConn] = await Promise.all([
alice.getOrCreate('bob'),
bob.getOrCreate('alice'),
]);
expect(aConn.state).toBe('connected');
expect(bConn.state).toBe('connected');
expect(alice.isConnected('bob')).toBe(true);
expect(bob.isConnected('alice')).toBe(true);
alice.destroy();
bob.destroy();
});
});

View File

@@ -0,0 +1,28 @@
/**
* Smoke test against the native RTCPeerConnection adapter when the
* runtime exposes one (browsers / Deno / Bun ≥ X). Skipped otherwise so
* Bun's own test runner stays green without third-party native modules.
*/
import { describe, test, expect } from 'bun:test';
import { isNativeRtcAvailable, nativeRtcFactory } from '../src/native-rtc.js';
describe('native RTC adapter', () => {
test('isNativeRtcAvailable() returns false in plain Bun', () => {
// This may flip to true in future Bun releases; the test is mostly a
// belt-and-suspenders against accidental globalThis pollution by
// earlier tests.
expect(typeof isNativeRtcAvailable()).toBe('boolean');
});
test('nativeRtcFactory()-built PC throws a clear error if RTCPeerConnection is missing', () => {
if (isNativeRtcAvailable()) {
const f = nativeRtcFactory();
const pc = f.createPeerConnection({});
expect(typeof pc.createDataChannel).toBe('function');
pc.close();
} else {
const f = nativeRtcFactory();
expect(() => f.createPeerConnection({})).toThrow(/RTCPeerConnection/);
}
});
});

View File

@@ -0,0 +1,76 @@
import { describe, expect, it } from 'bun:test';
import {
MemoryShadeBridge,
WebRtcSignalingChannel,
} from '../src/signaling.js';
describe('WebRtcSignalingChannel', () => {
it('routes typed signaling messages through the bridge', async () => {
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const aliceSig = new WebRtcSignalingChannel(a);
const bobSig = new WebRtcSignalingChannel(b);
const received: Array<{ from: string; kind: string }> = [];
bobSig.onSignal((from, msg) => {
received.push({ from, kind: msg.kind });
});
await aliceSig.sendOffer('bob', 'sess-1', 'v=0\nfake-sdp');
await aliceSig.sendIce('bob', 'sess-1', {
candidate: 'candidate:1 1 udp 0 1.2.3.4 1234 typ host',
sdpMid: '0',
sdpMLineIndex: 0,
});
await aliceSig.sendBye('bob', 'sess-1', 'no longer needed');
expect(received).toEqual([
{ from: 'alice', kind: 'shade.webrtc-offer/v1' },
{ from: 'alice', kind: 'shade.webrtc-ice/v1' },
{ from: 'alice', kind: 'shade.webrtc-bye/v1' },
]);
aliceSig.destroy();
bobSig.destroy();
});
it('passes non-signaling messages through to the passthrough hook', async () => {
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const passthrough: string[] = [];
const bobSig = new WebRtcSignalingChannel(b, {
passthrough: (_from, plaintext) => passthrough.push(plaintext),
});
const seen: string[] = [];
bobSig.onSignal((_from, msg) => seen.push(msg.kind));
await a.send('bob', 'hello world (not signaling)');
await a.send('bob', JSON.stringify({ kind: 'shade.fs.cancel/v1' }));
expect(passthrough).toContain('hello world (not signaling)');
expect(seen).toEqual([]);
bobSig.destroy();
});
it('preserves causal order — offer awaited before ICE handler runs', async () => {
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const aliceSig = new WebRtcSignalingChannel(a);
const bobSig = new WebRtcSignalingChannel(b);
const order: string[] = [];
bobSig.onSignal(async (_from, msg) => {
if (msg.kind === 'shade.webrtc-offer/v1') {
// Slow handler — must complete before ICE arrives.
await new Promise<void>((resolve) => setTimeout(resolve, 25));
order.push('offer-done');
} else if (msg.kind === 'shade.webrtc-ice/v1') {
order.push('ice');
}
});
await aliceSig.sendOffer('bob', 's', 'sdp');
await aliceSig.sendIce('bob', 's', null);
expect(order).toEqual(['offer-done', 'ice']);
aliceSig.destroy();
bobSig.destroy();
});
});

View File

@@ -0,0 +1,193 @@
/**
* End-to-end test of `WebRtcTransferTransport` against the manager + memory
* factory. Exercises the same `ITransferTransport` API the engine calls
* (`probe`, `sendChunk`, `fetchResumeState`).
*/
import { afterEach, describe, expect, it } from 'bun:test';
import { MemoryRtcFactory } from '../src/memory-rtc.js';
import { MemoryShadeBridge, WebRtcSignalingChannel } from '../src/signaling.js';
import { WebRtcConnectionManager } from '../src/manager.js';
import {
DEFAULT_MAX_DATACHANNEL_MESSAGE,
WebRtcTransferTransport,
} from '../src/transport.js';
import { streamIdBytesToString } from '../src/wire.js';
afterEach(() => {
MemoryRtcFactory.reset();
});
function paired(opts: {
bobReceiver: import('../src/connection.js').WebRtcReceiverHooks;
}): {
alice: WebRtcConnectionManager;
bob: WebRtcConnectionManager;
aliceTransport: WebRtcTransferTransport;
} {
const factory = new MemoryRtcFactory();
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const aliceSig = new WebRtcSignalingChannel(a);
const bobSig = new WebRtcSignalingChannel(b);
const alice = new WebRtcConnectionManager({ factory, signaling: aliceSig });
const bob = new WebRtcConnectionManager({
factory,
signaling: bobSig,
receiver: opts.bobReceiver,
});
const aliceTransport = new WebRtcTransferTransport({ manager: alice });
return { alice, bob, aliceTransport };
}
function makeStreamId(): string {
const b = new Uint8Array(16);
globalThis.crypto.getRandomValues(b);
return streamIdBytesToString(b);
}
describe('WebRtcTransferTransport', () => {
it('probe opens the peer connection', async () => {
const { alice, bob, aliceTransport } = paired({
bobReceiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
await aliceTransport.probe('bob');
expect(alice.isConnected('bob')).toBe(true);
alice.destroy();
bob.destroy();
});
it('sendChunk routes envelope to receiver and returns the ack', async () => {
let received: { laneId: number; seq: bigint; bytes: number } | null = null;
const { alice, bob, aliceTransport } = paired({
bobReceiver: {
async onChunk(_from, _streamId, laneId, seq, envelope) {
received = { laneId, seq, bytes: envelope.length };
return { lastSeq: Number(seq), bytesReceived: envelope.length };
},
async onResumeQuery() {
return null;
},
},
});
const streamId = makeStreamId();
const envelope = new Uint8Array(2048);
envelope.fill(0x42);
const ack = await aliceTransport.sendChunk('bob', streamId, 1, 5n, envelope);
expect(ack.lastSeq).toBe(5);
expect(ack.bytesReceived).toBe(2048);
expect(received).not.toBeNull();
expect(received!.laneId).toBe(1);
expect(received!.seq).toBe(5n);
expect(received!.bytes).toBe(2048);
alice.destroy();
bob.destroy();
});
it('rejects oversized envelopes that would exceed the data channel cap', async () => {
const { alice, bob, aliceTransport } = paired({
bobReceiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
const streamId = makeStreamId();
const huge = new Uint8Array(DEFAULT_MAX_DATACHANNEL_MESSAGE + 1);
await expect(aliceTransport.sendChunk('bob', streamId, 0, 0n, huge)).rejects.toThrow(
/frame too large/,
);
alice.destroy();
bob.destroy();
});
it('fetchResumeState returns parsed state when the receiver knows the stream', async () => {
const { alice, bob, aliceTransport } = paired({
bobReceiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery(_from, streamId) {
return {
streamId,
lanes: [
{ laneId: 0, lastSeqAcked: 11 },
{ laneId: 1, lastSeqAcked: 4 },
],
};
},
},
});
const sid = makeStreamId();
const state = await aliceTransport.fetchResumeState('bob', sid);
expect(state).not.toBeNull();
expect(state!.streamId).toBe(sid);
expect(state!.lanes[0]!.lastSeqAcked).toBe(11);
expect(state!.lanes[1]!.lastSeqAcked).toBe(4);
alice.destroy();
bob.destroy();
});
it('fetchResumeState returns null when the peer reports not found', async () => {
const { alice, bob, aliceTransport } = paired({
bobReceiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
const state = await aliceTransport.fetchResumeState('bob', makeStreamId());
expect(state).toBeNull();
alice.destroy();
bob.destroy();
});
it('multiple in-flight requests interleave correctly via requestId correlation', async () => {
let inflight = 0;
let maxInflight = 0;
const { alice, bob, aliceTransport } = paired({
bobReceiver: {
async onChunk(_from, _streamId, _laneId, seq) {
inflight++;
if (inflight > maxInflight) maxInflight = inflight;
// Stagger response so request ordering doesn't trivially match
// response ordering.
await new Promise<void>((resolve) =>
setTimeout(resolve, Number(seq % 5n) * 5),
);
inflight--;
return { lastSeq: Number(seq), bytesReceived: 0 };
},
async onResumeQuery() {
return null;
},
},
});
const streamId = makeStreamId();
const acks = await Promise.all(
Array.from({ length: 12 }, (_, i) =>
aliceTransport.sendChunk('bob', streamId, i % 4, BigInt(i), new Uint8Array(8)),
),
);
// Each ack matches its request seq (round-trip via requestId).
for (let i = 0; i < acks.length; i++) {
expect(acks[i]!.lastSeq).toBe(i);
}
expect(maxInflight).toBeGreaterThan(1);
alice.destroy();
bob.destroy();
});
});

View File

@@ -0,0 +1,116 @@
/**
* V3.11 acceptance criterion: TURN-relay påtvinger relay-modus.
*
* We can't do real ICE in the memory factory, but we CAN verify that the
* RTCConfiguration we pass to the underlying factory carries the
* `iceTransportPolicy: 'relay'` flag through unchanged when the
* application configures a TURN-only setup. This guarantees a real
* RTCPeerConnection adapter (browser / wrtc / node-datachannel) will
* reject all non-relay candidate pairs as the spec requires.
*/
import { afterEach, describe, expect, it } from 'bun:test';
import { MemoryShadeBridge, WebRtcSignalingChannel } from '../src/signaling.js';
import { WebRtcConnectionManager } from '../src/manager.js';
import {
DEFAULT_STUN_SERVERS,
type IDataChannel,
type IPeerConnection,
type IRtcFactory,
type ShadeIceCandidate,
type ShadeRtcConfig,
type ShadeRtcConnectionState,
type ShadeSessionDescription,
} from '../src/types.js';
import { MemoryRtcFactory } from '../src/memory-rtc.js';
afterEach(() => {
MemoryRtcFactory.reset();
});
class CapturingFactory implements IRtcFactory {
configs: ShadeRtcConfig[] = [];
constructor(private readonly inner: IRtcFactory) {}
createPeerConnection(config: ShadeRtcConfig): IPeerConnection {
this.configs.push(config);
return this.inner.createPeerConnection(config);
}
}
describe('TURN-relay configuration plumbing', () => {
it('passes iceServers + iceTransportPolicy through to the underlying RTCConfiguration', async () => {
const turnServers = [
{
urls: 'turn:turn.example.com:3478',
username: 'shade',
credential: 'secret',
},
];
const inner = new MemoryRtcFactory();
const factory = new CapturingFactory(inner);
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const aliceSig = new WebRtcSignalingChannel(a);
const bobSig = new WebRtcSignalingChannel(b);
const alice = new WebRtcConnectionManager({
factory,
signaling: aliceSig,
config: { iceServers: turnServers, iceTransportPolicy: 'relay' },
});
const bob = new WebRtcConnectionManager({
factory,
signaling: bobSig,
config: { iceServers: turnServers, iceTransportPolicy: 'relay' },
receiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
await alice.getOrCreate('bob');
// Both sides created at least one PC; each call's config should carry
// the TURN-only policy verbatim.
expect(factory.configs.length).toBeGreaterThanOrEqual(2);
for (const c of factory.configs) {
expect(c.iceTransportPolicy).toBe('relay');
expect(c.iceServers).toEqual(turnServers);
}
alice.destroy();
bob.destroy();
});
it('falls back to default public STUN when no iceServers are supplied', async () => {
const inner = new MemoryRtcFactory();
const factory = new CapturingFactory(inner);
const { a, b } = MemoryShadeBridge.linked('alice', 'bob');
const alice = new WebRtcConnectionManager({
factory,
signaling: new WebRtcSignalingChannel(a),
defaultStunServers: DEFAULT_STUN_SERVERS,
});
const bob = new WebRtcConnectionManager({
factory,
signaling: new WebRtcSignalingChannel(b),
defaultStunServers: DEFAULT_STUN_SERVERS,
receiver: {
async onChunk() {
return { lastSeq: 0 };
},
async onResumeQuery() {
return null;
},
},
});
await alice.getOrCreate('bob');
for (const c of factory.configs) {
expect(c.iceServers).toEqual(DEFAULT_STUN_SERVERS);
}
alice.destroy();
bob.destroy();
});
});

View File

@@ -0,0 +1,140 @@
import { describe, expect, it } from 'bun:test';
import {
CHUNK_HEADER_LEN,
bytesEqual,
decodeFrame,
encodeChunkAckFrame,
encodeChunkFrame,
encodeErrorFrame,
encodePingFrame,
encodePongFrame,
encodeResumeQueryFrame,
encodeResumeStateFrame,
randomRequestId,
REQUEST_ID_LEN,
STREAM_ID_LEN,
streamIdBytesToString,
streamIdStringToBytes,
WIRE_CHUNK,
WIRE_CHUNK_ACK,
WIRE_ERROR,
WIRE_PING,
WIRE_PONG,
WIRE_RESUME_QUERY,
WIRE_RESUME_STATE,
} from '../src/wire.js';
describe('wire format', () => {
it('roundtrips a chunk frame', () => {
const requestId = randomRequestId();
const streamId = new Uint8Array(STREAM_ID_LEN).fill(0xab);
const envelope = new Uint8Array(1024);
for (let i = 0; i < envelope.length; i++) envelope[i] = i & 0xff;
const buf = encodeChunkFrame({
type: WIRE_CHUNK,
requestId,
streamId,
laneId: 7,
seq: 12345n,
envelope,
});
expect(buf.length).toBe(CHUNK_HEADER_LEN + envelope.length);
const decoded = decodeFrame(buf);
expect(decoded.type).toBe(WIRE_CHUNK);
if (decoded.type !== WIRE_CHUNK) throw new Error('type narrow failed');
expect(bytesEqual(decoded.requestId, requestId)).toBe(true);
expect(bytesEqual(decoded.streamId, streamId)).toBe(true);
expect(decoded.laneId).toBe(7);
expect(decoded.seq).toBe(12345n);
expect(bytesEqual(decoded.envelope, envelope)).toBe(true);
});
it('roundtrips a resume-query frame', () => {
const requestId = randomRequestId();
const streamId = new Uint8Array(STREAM_ID_LEN).fill(0x33);
const buf = encodeResumeQueryFrame({
type: WIRE_RESUME_QUERY,
requestId,
streamId,
});
const decoded = decodeFrame(buf);
if (decoded.type !== WIRE_RESUME_QUERY) throw new Error('type narrow failed');
expect(bytesEqual(decoded.requestId, requestId)).toBe(true);
expect(bytesEqual(decoded.streamId, streamId)).toBe(true);
});
it('roundtrips chunk-ack', () => {
const requestId = randomRequestId();
const buf = encodeChunkAckFrame({
type: WIRE_CHUNK_ACK,
requestId,
lastSeq: 42,
bytesReceived: 1024,
});
const decoded = decodeFrame(buf);
if (decoded.type !== WIRE_CHUNK_ACK) throw new Error('type narrow failed');
expect(decoded.lastSeq).toBe(42);
expect(decoded.bytesReceived).toBe(1024);
});
it('roundtrips resume-state frame', () => {
const json = JSON.stringify({
streamId: 'abc',
lanes: [{ laneId: 0, lastSeqAcked: 5 }],
});
const buf = encodeResumeStateFrame({
type: WIRE_RESUME_STATE,
requestId: randomRequestId(),
json,
});
const decoded = decodeFrame(buf);
if (decoded.type !== WIRE_RESUME_STATE) throw new Error('type narrow failed');
expect(decoded.json).toBe(json);
});
it('roundtrips ping/pong frames', () => {
const requestId = randomRequestId();
const ping = encodePingFrame({ type: WIRE_PING, requestId, nonce: 99n });
const decodedPing = decodeFrame(ping);
if (decodedPing.type !== WIRE_PING) throw new Error('type narrow failed');
expect(decodedPing.nonce).toBe(99n);
const pong = encodePongFrame({ type: WIRE_PONG, requestId, nonce: 99n });
const decodedPong = decodeFrame(pong);
if (decodedPong.type !== WIRE_PONG) throw new Error('type narrow failed');
expect(decodedPong.nonce).toBe(99n);
});
it('roundtrips error frame', () => {
const buf = encodeErrorFrame({
type: WIRE_ERROR,
requestId: randomRequestId(),
json: '{"error":"oh no"}',
});
const decoded = decodeFrame(buf);
if (decoded.type !== WIRE_ERROR) throw new Error('type narrow failed');
expect(JSON.parse(decoded.json)).toEqual({ error: 'oh no' });
});
it('rejects truncated frames', () => {
const tiny = new Uint8Array(8);
expect(() => decodeFrame(tiny)).toThrow();
});
it('rejects unknown type', () => {
const bad = new Uint8Array(REQUEST_ID_LEN + 1);
bad[0] = 0x77;
expect(() => decodeFrame(bad)).toThrow();
});
});
describe('streamId base64url codec', () => {
it('roundtrips arbitrary 16-byte ids', () => {
const original = new Uint8Array(STREAM_ID_LEN);
globalThis.crypto.getRandomValues(original);
const s = streamIdBytesToString(original);
const back = streamIdStringToBytes(s);
expect(bytesEqual(back, original)).toBe(true);
});
});