Twenty test servers picked a port with `NNNN + Math.floor(Math.random() * 500)`
and hoped it was free. Several files guessed inside the *same* range —
sdk.test.ts and gates.test.ts both on 19500, three files on 22000, and
webrtc-integration.test.ts used 22000 twice within itself — so with test files
serving in parallel the collision was not unlikely, it was scheduled.
Found from the outside, in Nova, where Shade is vendored: across eight runs of
an unchanged tree, two had failures and six were clean. The visible error was
Failed to start server. Is port 24287 in use? EADDRINUSE
and then a second, louder one: `teardownRig` ran on a rig that setup had never
finished building and died on `rig.alice`, so the TypeError from cleanup is
what you read first and the real cause scrolled past above it.
`Bun.serve({ port: 0 })` lets the OS hand out a free port and `server.port`
reads it back. There is no range to collide inside.
teardownRig now tolerates a rig that was never built. Cleanup must never be the
loudest thing in a failing test.
A suite that fails a quarter of the time is worse than a suite that fails: it
teaches everyone to re-run it, and then a real regression looks like the flake.
Verified: 1198 pass / 0 fail here, and the same fix is going into Nova's
vendored copy so the next sync does not bring the guessing back.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_014489bKUtUEY1Zgs9xN9mt7
230 lines
8.3 KiB
TypeScript
230 lines
8.3 KiB
TypeScript
import { describe, test, expect, beforeEach, afterEach, mock } from 'bun:test';
|
|
import { createShade, type Shade } from '../src/index.js';
|
|
import { FingerprintNotVerifiedError } from '@shade/core';
|
|
import { createPrekeyServer, MemoryPrekeyStore } from '@shade/server';
|
|
import { SubtleCryptoProvider } from '@shade/crypto-web';
|
|
|
|
const crypto = new SubtleCryptoProvider();
|
|
|
|
async function startPrekeyServer(): Promise<{ url: string; stop: () => void }> {
|
|
const server = createPrekeyServer({
|
|
crypto,
|
|
store: new MemoryPrekeyStore(),
|
|
disableRateLimit: true,
|
|
});
|
|
// Port 0 lets the OS hand out a free one. This guessed inside a 500-wide
|
|
// range and hoped — and several files here guessed inside the SAME range,
|
|
// so with test files serving in parallel the collision arrived about a
|
|
// quarter of the time as EADDRINUSE.
|
|
const handle = Bun.serve({ port: 0, fetch: server.fetch });
|
|
const port = handle.port;
|
|
return { url: `http://localhost:${port}`, stop: () => handle.stop() };
|
|
}
|
|
|
|
/**
|
|
* Wires Alice ↔ Bob with control + chunk transports backed by in-memory
|
|
* routing so tests don't need real HTTP. Both sides see each other's
|
|
* envelopes through the same loopback.
|
|
*/
|
|
function wireLoopback(alice: Shade, bob: Shade): void {
|
|
alice.configureTransfers({
|
|
resolveBaseUrl: async () => 'mem://bob',
|
|
envelopeTransport: { send: async (_addr, env) => bob.acceptTransferEnvelope('alice', env) },
|
|
});
|
|
bob.configureTransfers({
|
|
resolveBaseUrl: async () => 'mem://alice',
|
|
envelopeTransport: { send: async (_addr, env) => alice.acceptTransferEnvelope('bob', env) },
|
|
});
|
|
}
|
|
|
|
describe('V3.3 fingerprint gates — first-large-file', () => {
|
|
let server: Awaited<ReturnType<typeof startPrekeyServer>>;
|
|
let alice: Shade;
|
|
let bob: Shade;
|
|
|
|
beforeEach(async () => {
|
|
server = await startPrekeyServer();
|
|
alice = await createShade({ prekeyServer: server.url, address: 'alice' });
|
|
bob = await createShade({ prekeyServer: server.url, address: 'bob' });
|
|
wireLoopback(alice, bob);
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await alice.shutdown();
|
|
await bob.shutdown();
|
|
server.stop();
|
|
});
|
|
|
|
test('handler is not invoked for files under threshold', async () => {
|
|
const handler = mock(() => true);
|
|
alice.beforeFirstLargeFile(1024 * 1024, handler); // 1 MiB threshold
|
|
|
|
// Establish session so we can compare verification state
|
|
const env = await alice.send('bob', 'hi');
|
|
await bob.receive('alice', env);
|
|
|
|
expect(await alice.isPeerVerified('bob')).toBe(false);
|
|
// The gate is consulted from `upload()` which we don't actually run
|
|
// (loopback transfer plumbing is heavy). Instead we drive the gate
|
|
// directly through the public verification state and confirm size
|
|
// gating logic by asserting the threshold contract: a verified peer
|
|
// skips the handler entirely.
|
|
expect(handler).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('handler approval marks peer verified for subsequent calls', async () => {
|
|
const handler = mock((ctx: { fingerprint: string }) => {
|
|
expect(ctx.fingerprint.split(' ').length).toBe(12);
|
|
return true;
|
|
});
|
|
alice.beforeFirstLargeFile(1024, handler);
|
|
|
|
// Establish session
|
|
const env = await alice.send('bob', 'hi');
|
|
await bob.receive('alice', env);
|
|
|
|
expect(await alice.isPeerVerified('bob')).toBe(false);
|
|
await alice.markPeerVerified('bob');
|
|
expect(await alice.isPeerVerified('bob')).toBe(true);
|
|
// Handler should not fire when peer is already verified.
|
|
expect(handler).not.toHaveBeenCalled();
|
|
});
|
|
|
|
test('manual mark/unmark round trips', async () => {
|
|
const env = await alice.send('bob', 'hi');
|
|
await bob.receive('alice', env);
|
|
|
|
expect(await alice.isPeerVerified('bob')).toBe(false);
|
|
await alice.markPeerVerified('bob');
|
|
expect(await alice.isPeerVerified('bob')).toBe(true);
|
|
await alice.unmarkPeerVerified('bob');
|
|
expect(await alice.isPeerVerified('bob')).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('V3.3 fingerprint gates — backup-import', () => {
|
|
let server: Awaited<ReturnType<typeof startPrekeyServer>>;
|
|
let alice: Shade;
|
|
|
|
beforeEach(async () => {
|
|
server = await startPrekeyServer();
|
|
alice = await createShade({ prekeyServer: server.url, address: 'alice' });
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await alice.shutdown();
|
|
server.stop();
|
|
});
|
|
|
|
test('handler is invoked with the backup identity fingerprint', async () => {
|
|
const ownFp = await alice.fingerprint;
|
|
const blob = await alice.exportBackup('correct horse battery staple', []);
|
|
|
|
// Re-create alice on a fresh storage so importBackup runs against
|
|
// a different identity baseline.
|
|
await alice.shutdown();
|
|
alice = await createShade({ prekeyServer: server.url, address: 'alice' });
|
|
|
|
let observedFp: string | null = null;
|
|
alice.beforeBackupImport((ctx) => {
|
|
observedFp = ctx.fingerprint;
|
|
return true;
|
|
});
|
|
|
|
await alice.importBackup(blob, 'correct horse battery staple');
|
|
expect(observedFp).toBe(ownFp);
|
|
});
|
|
|
|
test('handler rejection throws FingerprintNotVerifiedError and skips writes', async () => {
|
|
const blob = await alice.exportBackup('correct horse battery staple', []);
|
|
const fpBefore = await alice.fingerprint;
|
|
|
|
await alice.shutdown();
|
|
alice = await createShade({ prekeyServer: server.url, address: 'alice' });
|
|
|
|
alice.beforeBackupImport(() => false);
|
|
|
|
await expect(
|
|
alice.importBackup(blob, 'correct horse battery staple'),
|
|
).rejects.toBeInstanceOf(FingerprintNotVerifiedError);
|
|
|
|
// Identity should NOT have been overwritten by the rejected import.
|
|
const fpAfter = await alice.fingerprint;
|
|
expect(fpAfter).not.toBe(fpBefore);
|
|
});
|
|
|
|
test('no handler registered → warning + TOFU allow', async () => {
|
|
const blob = await alice.exportBackup('correct horse battery staple', []);
|
|
await alice.shutdown();
|
|
alice = await createShade({ prekeyServer: server.url, address: 'alice' });
|
|
|
|
// Capture console.warn so we can assert the warning fired.
|
|
const originalWarn = console.warn;
|
|
let warnings = 0;
|
|
console.warn = (..._args: unknown[]) => {
|
|
warnings += 1;
|
|
};
|
|
try {
|
|
await alice.importBackup(blob, 'correct horse battery staple');
|
|
} finally {
|
|
console.warn = originalWarn;
|
|
}
|
|
expect(warnings).toBeGreaterThanOrEqual(1);
|
|
});
|
|
});
|
|
|
|
describe('V3.3 fingerprint gates — identity rotation invalidates verification', () => {
|
|
let server: Awaited<ReturnType<typeof startPrekeyServer>>;
|
|
let alice: Shade;
|
|
let bob: Shade;
|
|
|
|
beforeEach(async () => {
|
|
server = await startPrekeyServer();
|
|
alice = await createShade({ prekeyServer: server.url, address: 'alice' });
|
|
bob = await createShade({ prekeyServer: server.url, address: 'bob' });
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await alice.shutdown();
|
|
await bob.shutdown();
|
|
server.stop();
|
|
});
|
|
|
|
test('acceptIdentityChange bumps version and stales prior verification', async () => {
|
|
// Establish + manually mark verified
|
|
const env = await alice.send('bob', 'hi');
|
|
await bob.receive('alice', env);
|
|
await alice.markPeerVerified('bob');
|
|
expect(await alice.isPeerVerified('bob')).toBe(true);
|
|
|
|
// Bob rotates identity; Alice accepts the change.
|
|
let observedNewDeviceCtx: { peerAddress: string; fingerprint: string } | null = null;
|
|
alice.beforeNewDeviceTrust((ctx) => {
|
|
observedNewDeviceCtx = { peerAddress: ctx.peerAddress, fingerprint: ctx.fingerprint };
|
|
return false; // reject — the verification should already be stale
|
|
});
|
|
|
|
const fakeNewKey = new Uint8Array(32);
|
|
fakeNewKey.fill(7);
|
|
await expect(
|
|
alice.acceptIdentityChange('bob', fakeNewKey),
|
|
).rejects.toBeInstanceOf(FingerprintNotVerifiedError);
|
|
|
|
// Even though we rejected the gate, the identity-version was bumped
|
|
// before the gate ran, so the previous verification is now stale.
|
|
// Re-verifying via the *old* fingerprint must still report unverified.
|
|
expect(observedNewDeviceCtx).not.toBeNull();
|
|
expect(await alice.isPeerVerified('bob')).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe('V3.3 fingerprint gates — error metadata', () => {
|
|
test('FingerprintNotVerifiedError carries gate + address', () => {
|
|
const err = new FingerprintNotVerifiedError('bob', 'first-large-file');
|
|
expect(err.peerAddress).toBe('bob');
|
|
expect(err.gate).toBe('first-large-file');
|
|
expect(err.code).toBe('SHADE_FINGERPRINT_NOT_VERIFIED');
|
|
expect(err.name).toBe('FingerprintNotVerifiedError');
|
|
});
|
|
});
|