Publish self-hostable Meets relay
This commit is contained in:
commit
a18442dcf5
11 files changed
+1076
No files matched your search
+189
@@ -0,0 +1,189 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const serverPath = fileURLToPath(new URL('./server.mjs', import.meta.url));
|
||||
|
||||
test('relay persists opaque chunks, acknowledges and revokes pairings', async t => {
|
||||
const dataDir = await mkdtemp(path.join(os.tmpdir(), 'audiorecorder-relay-'));
|
||||
const probe = net.createServer();
|
||||
await new Promise(resolve => probe.listen(0, '127.0.0.1', resolve));
|
||||
const port = probe.address().port;
|
||||
await new Promise(resolve => probe.close(resolve));
|
||||
const env = { ...process.env, PORT: String(port), HOST: '127.0.0.1', RELAY_DATA_DIR: dataDir, TURN_HOST: '127.0.0.1', TURN_PORT: '3478', TURN_SHARED_SECRET: 'test-only' };
|
||||
let child;
|
||||
const start = async () => {
|
||||
child = spawn(process.execPath, [serverPath], { env, stdio: 'ignore' });
|
||||
for (let attempt = 0; attempt < 80; attempt++) {
|
||||
try {
|
||||
if ((await fetch(`http://127.0.0.1:${port}/health`)).ok) return;
|
||||
} catch {}
|
||||
await new Promise(resolve => setTimeout(resolve, 50));
|
||||
}
|
||||
throw new Error('relay server did not start');
|
||||
};
|
||||
const stop = async () => {
|
||||
if (!child || child.exitCode !== null) return;
|
||||
await new Promise(resolve => { child.once('exit', resolve); child.kill('SIGTERM'); });
|
||||
};
|
||||
const postJSON = (url, body, token) => fetch(url, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json', ...(token ? { authorization: `Bearer ${token}` } : {}) },
|
||||
body: JSON.stringify(body)
|
||||
});
|
||||
|
||||
t.after(async () => { await stop(); await rm(dataDir, { recursive: true, force: true }); });
|
||||
await start();
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
const secretHash = crypto.createHash('sha256').update('test-pairing-secret').digest('hex');
|
||||
const legacyOffer = await postJSON(`${base}/api/v1/pairing/offers`, { secretHash, publicKey: 'mac-key', identityKey: 'mac-identity' });
|
||||
assert.equal(legacyOffer.status, 426);
|
||||
const offerResponse = await postJSON(`${base}/api/v1/pairing/offers`, { protocolVersion: 2, secretHash, publicKey: 'mac-key', identityKey: 'mac-identity', directEndpoints: ['http://192.168.1.2:8787'] });
|
||||
assert.equal(offerResponse.status, 201);
|
||||
const offer = await offerResponse.json();
|
||||
assert.deepEqual(offer.public.directEndpoints, []);
|
||||
const leakedQueryProof = await fetch(`${base}/api/v1/pairing/offers/${offer.id}?secretHash=${secretHash}`);
|
||||
assert.equal((await leakedQueryProof.json()).sessionToken, null);
|
||||
const legacyClaim = await postJSON(`${base}/api/v1/pairing/offers/${offer.id}/claim`, { secretHash, publicKey: 'phone-key', identityKey: 'phone-identity' });
|
||||
assert.equal(legacyClaim.status, 426);
|
||||
const claimResponse = await postJSON(`${base}/api/v1/pairing/offers/${offer.id}/claim`, { protocolVersion: 2, secretHash, publicKey: 'phone-key', identityKey: 'phone-identity' });
|
||||
assert.equal(claimResponse.status, 200);
|
||||
const claim = await claimResponse.json();
|
||||
assert.ok(claim.relayToken);
|
||||
const persistedPairing = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8')).pairingSessions[0];
|
||||
assert.equal(persistedPairing.sessionToken, undefined);
|
||||
assert.equal(persistedPairing.relayToken, undefined);
|
||||
const claimedOffer = await fetch(`${base}/api/v1/pairing/offers/${offer.id}`, { headers: { authorization: `Bearer ${secretHash}` } });
|
||||
assert.equal((await claimedOffer.json()).sessionToken, claim.sessionToken);
|
||||
|
||||
const sessionPath = `${base}/api/v1/pairing/sessions/${offer.id}`;
|
||||
const forbiddenPush = await fetch(`${base}/api/v1/relay/sessions/${offer.id}/push-devices`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.equal(forbiddenPush.status, 404);
|
||||
const forbiddenNotification = await postJSON(`${base}/api/v1/relay/sessions/${offer.id}/notifications`, { eventID: crypto.randomUUID(), eventType: 'completed', recordingID: crypto.randomUUID() }, claim.relayToken);
|
||||
assert.equal(forbiddenNotification.status, 404);
|
||||
const legacyHeartbeat = await postJSON(`${sessionPath}/heartbeat`, { side: 'client' }, claim.sessionToken);
|
||||
assert.equal(legacyHeartbeat.status, 426);
|
||||
const heartbeat = await postJSON(`${sessionPath}/heartbeat`, { protocolVersion: 2, side: 'client', directEndpoints: ['http://192.168.1.2:8787'] }, claim.sessionToken);
|
||||
assert.equal(heartbeat.status, 200);
|
||||
assert.deepEqual((await heartbeat.json()).directEndpoints, []);
|
||||
const generationResponse = await postJSON(`${sessionPath}/generation`, {}, claim.sessionToken);
|
||||
assert.equal(generationResponse.status, 200);
|
||||
const { generationID } = await generationResponse.json();
|
||||
const signalBody = { protocolVersion: 2, generationID, side: 'client', messageID: crypto.randomUUID(), authenticator: Buffer.alloc(32, 7).toString('base64url'), description: { type: 'offer', sdp: 'v=0\r\n' }, candidates: [] };
|
||||
const unsignedSignal = await postJSON(`${sessionPath}/signal`, { ...signalBody, authenticator: undefined }, claim.sessionToken);
|
||||
assert.equal(unsignedSignal.status, 426);
|
||||
const signalResponse = await postJSON(`${sessionPath}/signal`, signalBody, claim.sessionToken);
|
||||
assert.equal(signalResponse.status, 202);
|
||||
const replayedSignal = await postJSON(`${sessionPath}/signal`, signalBody, claim.sessionToken);
|
||||
assert.equal(replayedSignal.status, 409);
|
||||
const statusResponse = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||
const status = await statusResponse.json();
|
||||
assert.equal(status.signals[0].protocolVersion, 2);
|
||||
assert.equal(status.signals[0].generationID, generationID);
|
||||
assert.equal(status.signals[0].messageID, signalBody.messageID);
|
||||
assert.equal(status.signals[0].authenticator, signalBody.authenticator);
|
||||
|
||||
const id = crypto.randomUUID();
|
||||
const relayPath = `${base}/api/v1/relay/sessions/${offer.id}`;
|
||||
const manifest = await postJSON(`${relayPath}/uploads`, { id, size: 3, chunkCount: 1 }, claim.relayToken);
|
||||
assert.equal(manifest.status, 201);
|
||||
const ciphertext = Buffer.from([0x81, 0x22, 0xfe]);
|
||||
const put = await fetch(`${relayPath}/uploads/${id}/chunks/0`, {
|
||||
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: ciphertext
|
||||
});
|
||||
assert.equal(put.status, 200);
|
||||
await stop();
|
||||
await start();
|
||||
|
||||
// Pairing metadata and bearer credentials must survive a handshake service
|
||||
// restart; only the WebRTC generation is transient and renegotiated.
|
||||
const restoredStatusResponse = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||
assert.equal(restoredStatusResponse.status, 200);
|
||||
const restoredStatus = await restoredStatusResponse.json();
|
||||
assert.equal(restoredStatus.sessionID, offer.id);
|
||||
assert.equal(restoredStatus.generationID, null);
|
||||
const restoredHeartbeat = await postJSON(`${sessionPath}/heartbeat`, { protocolVersion: 2, side: 'mac' }, claim.sessionToken);
|
||||
assert.equal(restoredHeartbeat.status, 200);
|
||||
const restoredIce = await fetch(`${sessionPath}/ice-servers`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||
assert.equal(restoredIce.status, 200);
|
||||
|
||||
// RPC jobs use the same encrypted durable store, but separate directional
|
||||
// queues so the relay cannot route a response back as a new request.
|
||||
const messageID = crypto.randomUUID();
|
||||
const messagePath = `${relayPath}/messages`;
|
||||
const messageManifest = await postJSON(messagePath, { id: messageID, direction: 'request', size: 3, chunkCount: 1 }, claim.relayToken);
|
||||
assert.equal(messageManifest.status, 201);
|
||||
const macWait = fetch(`${relayPath}?queue=mac&wait=10`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
await new Promise(resolve => setTimeout(resolve, 75));
|
||||
const messageCiphertext = Buffer.from([0x35, 0x86, 0xf1]);
|
||||
const messagePut = await fetch(`${messagePath}/${messageID}/chunks/0`, {
|
||||
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: messageCiphertext
|
||||
});
|
||||
assert.equal(messagePut.status, 200);
|
||||
const wokenMacWait = await macWait;
|
||||
assert.equal(wokenMacWait.status, 200);
|
||||
await stop();
|
||||
await start();
|
||||
const requestQueueResponse = await fetch(`${messagePath}?direction=request`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual((await requestQueueResponse.json()).messages.map(message => message.id), [messageID]);
|
||||
const messageChunk = await fetch(`${messagePath}/${messageID}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual(Buffer.from(await messageChunk.arrayBuffer()), messageCiphertext);
|
||||
const messageAck = await postJSON(`${messagePath}/${messageID}/ack`, {}, claim.relayToken);
|
||||
assert.equal(messageAck.status, 200);
|
||||
const responseWait = fetch(`${messagePath}?direction=response&wait=10`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
await new Promise(resolve => setTimeout(resolve, 75));
|
||||
const responseID = crypto.randomUUID();
|
||||
const responseManifest = await postJSON(messagePath, { id: responseID, direction: 'response', size: 2, chunkCount: 1 }, claim.relayToken);
|
||||
assert.equal(responseManifest.status, 201);
|
||||
const responsePut = await fetch(`${messagePath}/${responseID}/chunks/0`, {
|
||||
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: Buffer.from([0x01, 0x02])
|
||||
});
|
||||
assert.equal(responsePut.status, 200);
|
||||
const responseQueueResponse = await responseWait;
|
||||
assert.equal(responseQueueResponse.status, 200);
|
||||
assert.deepEqual((await responseQueueResponse.json()).messages.map(message => message.id), [responseID]);
|
||||
|
||||
// Large audio replies are advertised in the small RPC envelope and fetched
|
||||
// as independently authenticated attachment chunks, not base64 RPC bodies.
|
||||
const attachmentID = crypto.randomUUID();
|
||||
const attachmentPath = `${messagePath}`;
|
||||
const attachmentManifest = await postJSON(attachmentPath, { id: attachmentID, direction: 'attachment', size: 21, chunkCount: 1 }, claim.relayToken);
|
||||
assert.equal(attachmentManifest.status, 201);
|
||||
const attachmentCiphertext = Buffer.from('encrypted-audio-chunk');
|
||||
const attachmentPut = await fetch(`${attachmentPath}/${attachmentID}/chunks/0`, {
|
||||
method: 'PUT', headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' }, body: attachmentCiphertext
|
||||
});
|
||||
assert.equal(attachmentPut.status, 200);
|
||||
const attachmentQueue = await fetch(`${messagePath}?direction=response`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual((await attachmentQueue.json()).messages.map(message => message.id), [responseID]);
|
||||
const attachmentChunk = await fetch(`${attachmentPath}/${attachmentID}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual(Buffer.from(await attachmentChunk.arrayBuffer()), attachmentCiphertext);
|
||||
const attachmentAck = await postJSON(`${attachmentPath}/${attachmentID}/ack`, {}, claim.relayToken);
|
||||
assert.equal(attachmentAck.status, 200);
|
||||
|
||||
let listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual((await listing.json()).uploads.map(upload => upload.id), [id]);
|
||||
const chunk = await fetch(`${relayPath}/uploads/${id}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual(Buffer.from(await chunk.arrayBuffer()), ciphertext);
|
||||
const ack = await postJSON(`${relayPath}/uploads/${id}/ack`, {}, claim.relayToken);
|
||||
assert.equal(ack.status, 200);
|
||||
listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.deepEqual((await listing.json()).uploads, []);
|
||||
const revoke = await fetch(relayPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.equal(revoke.status, 200);
|
||||
const unauthorized = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.equal(unauthorized.status, 401);
|
||||
const revokePairing = await fetch(sessionPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||
assert.equal(revokePairing.status, 200);
|
||||
const afterUnpair = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
|
||||
assert.equal(afterUnpair.pushDevices, undefined);
|
||||
assert.equal(afterUnpair.pushEvents, undefined);
|
||||
const revokedStatus = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||
assert.equal(revokedStatus.status, 404);
|
||||
});
|
||||
Reference in new issue
Block a user