commit a18442dcf5ce6f875bbe3818639a66c192d3372e Author: Meets contributors Date: Fri Oct 23 22:38:29 2026 +0200 Publish self-hostable Meets relay diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b9ba60b --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +.env* +*.log +node_modules +README.md +test-*.mjs diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..8524dc1 --- /dev/null +++ b/.env.example @@ -0,0 +1,6 @@ +# Hostname configured by your own reverse proxy and DNS. +TURN_HOST=turn.example.net +TURN_PORT=3478 + +# Use a long random secret shared with your TURN server. +TURN_SHARED_SECRET=replace-with-a-random-secret diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..216157b --- /dev/null +++ b/.gitignore @@ -0,0 +1,7 @@ +.env +.env.* +!.env.example +!.env.example +node_modules/ +data/ +*.log diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..56fd1e5 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,9 @@ +FROM node:24-alpine +WORKDIR /app +ENV NODE_ENV=production PORT=8080 HOST=0.0.0.0 RELAY_DATA_DIR=/data/relay +COPY --chown=node:node package.json server.mjs ./ +RUN mkdir -p /data/relay && chown node:node /data/relay +USER node +EXPOSE 8080 +HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 CMD node -e "fetch('http://127.0.0.1:8080/health').then(r=>{if(!r.ok)process.exit(1)}).catch(()=>process.exit(1))" +CMD ["node", "server.mjs"] diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..ab7c511 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Meets contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..cc849c6 --- /dev/null +++ b/README.md @@ -0,0 +1,63 @@ +# Meets Relay + +Self-hostable encrypted relay service for Meets pairing and synchronization. The service stores pairing metadata and encrypted transfer chunks; application data is encrypted by the clients before it reaches this server. + +## Docker Compose + +Requirements: Docker Compose, a public HTTPS URL configured by the operator's reverse proxy, and a separately operated TURN server for networks where direct WebRTC connectivity is unavailable. The reverse proxy, DNS, TLS certificate, firewall and TURN service are intentionally outside this project. + +Copy `.env.example` to `.env`, set your TURN hostname and port, and create a unique shared secret that matches your TURN service (for example, `openssl rand -hex 32`). Keep `.env` private; it is ignored by Git. + +```yaml +services: + meets-relay: + image: git.maddin.app/maddin/meets-relay:latest + restart: unless-stopped + env_file: [.env] + read_only: true + security_opt: + - no-new-privileges:true + cap_drop: [ALL] + pids_limit: 64 + mem_limit: 512m + ports: + - "127.0.0.1:8080:8080" + environment: + PORT: "8080" + RELAY_DATA_DIR: /data/relay + RELAY_MAX_BYTES: "10737418240" + RELAY_PAIRING_MAX_BYTES: "1073741824" + RELAY_TTL_SECONDS: "604800" + RELAY_INCOMPLETE_TTL_SECONDS: "86400" + volumes: + - relay_data:/data/relay + tmpfs: + - /tmp:rw,noexec,nosuid,size=16m + +volumes: + relay_data: +``` + +Set a reverse-proxy route from your own HTTPS hostname to `127.0.0.1:8080`. Configure that HTTPS base URL in the Meets Mac app before generating a new pairing QR code. Existing pairings retain their relay address. + +The default quotas above cap stored data at 10 GiB total and 1 GiB per pairing. Choose values appropriate for your host. Completed transfers expire after seven days; incomplete transfers expire after one day. Pairings expire after 30 days without a heartbeat. Keep the named volume in backups if you need to retain pairings across host replacement. + +## Security and privacy + +- HTTPS must be terminated by the operator's reverse proxy. Keep the container port bound to loopback unless the host firewall and TLS termination are configured deliberately. +- Transfer chunks are end-to-end encrypted by the clients. The relay cannot decrypt recording content. +- The relay does not provide push notifications and does not accept or store APNs device tokens. +- The relay does not run a TURN server. WebRTC signaling remains available for connection setup; configure `TURN_HOST`, `TURN_PORT` and `TURN_SHARED_SECRET` for a separately operated TURN service. The relay itself does not route or decrypt WebRTC media. Direct or STUN-only connections may work without TURN depending on the network. +- The image runs as an unprivileged user, with a read-only root filesystem, no Linux capabilities and only `/data/relay` writable. +- Do not expose the health or API endpoints through a proxy that adds caching. Configure `Cache-Control: no-store` for API traffic. +- This service has no administrator account or remote shell. Restrict Docker access on the host; Docker administration is equivalent to host root. + +## Operations + +Health check: `GET /health`. Logs contain operational errors only. The relay does not log request bodies, authorization headers, pairing secrets or recording contents. + +Build locally with `docker compose build`; run with `docker compose up -d`. To update, pull the selected image tag and recreate the service. Pin a version tag or image digest for reproducible deployments. + +## License + +MIT. See [LICENSE](LICENSE). diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 0000000..da00041 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,32 @@ +services: + meets-relay: + build: . + image: git.maddin.app/maddin/meets-relay:latest + restart: unless-stopped + env_file: + - .env + read_only: true + security_opt: + - no-new-privileges:true + cap_drop: [ALL] + pids_limit: 64 + mem_limit: 512m + ports: + - "127.0.0.1:8080:8080" + environment: + PORT: "8080" + RELAY_DATA_DIR: /data/relay + RELAY_MAX_BYTES: "10737418240" + RELAY_PAIRING_MAX_BYTES: "1073741824" + RELAY_TTL_SECONDS: "604800" + RELAY_INCOMPLETE_TTL_SECONDS: "86400" + TURN_HOST: "${TURN_HOST:?Set TURN_HOST to the hostname of your separately operated TURN service}" + TURN_PORT: "${TURN_PORT:-3478}" + TURN_SHARED_SECRET: "${TURN_SHARED_SECRET:?Set TURN_SHARED_SECRET for your TURN service}" + volumes: + - relay_data:/data/relay + tmpfs: + - /tmp:rw,noexec,nosuid,size=16m + +volumes: + relay_data: diff --git a/package.json b/package.json new file mode 100644 index 0000000..985dad4 --- /dev/null +++ b/package.json @@ -0,0 +1,11 @@ +{ + "name": "meets-relay", + "version": "1.0.0", + "private": false, + "license": "MIT", + "type": "module", + "scripts": { + "start": "node server.mjs", + "test": "node --test test-relay.mjs" + } +} diff --git a/scripts/publish-image.sh b/scripts/publish-image.sh new file mode 100755 index 0000000..bc854e8 --- /dev/null +++ b/scripts/publish-image.sh @@ -0,0 +1,10 @@ +#!/bin/sh +set -eu + +tag="${1:?Usage: scripts/publish-image.sh }" +case "$tag" in + *[!a-zA-Z0-9_.-]*|'') echo "Invalid image tag." >&2; exit 2 ;; +esac + +image="git.maddin.app/maddin/meets-relay:${tag}" +docker buildx build --platform linux/amd64,linux/arm64 --tag "$image" --push . diff --git a/server.mjs b/server.mjs new file mode 100644 index 0000000..67dda55 --- /dev/null +++ b/server.mjs @@ -0,0 +1,722 @@ +import http from 'node:http'; +import crypto from 'node:crypto'; +import fs from 'node:fs/promises'; +import path from 'node:path'; + +const port = Number(process.env.PORT || 8080); +const host = process.env.HOST || '0.0.0.0'; +const offerTTL = Number(process.env.OFFER_TTL_SECONDS || 600) * 1000; +// Pairing is a durable device relationship, not a short-lived login. Heartbeats +// still refresh this lease, but an app being suspended for a few hours must not +// silently destroy the pairing. +const sessionTTL = Number(process.env.SESSION_TTL_SECONDS || 30 * 24 * 60 * 60) * 1000; +const turnHost = cleanText(process.env.TURN_HOST || '', 253); +const turnPort = Number(process.env.TURN_PORT || 3478); +const turnSharedSecret = process.env.TURN_SHARED_SECRET || ''; +const maxBodyBytes = 128 * 1024; +const relayRoot = process.env.RELAY_DATA_DIR || '/data/relay'; +const relayMaxBytes = Number(process.env.RELAY_MAX_BYTES || 10 * 1024 * 1024 * 1024); +const relayPairingMaxBytes = Number(process.env.RELAY_PAIRING_MAX_BYTES || 1024 * 1024 * 1024); +const relayUploadMaxBytes = 350 * 1024 * 1024; +const relayChunkMaxBytes = 4 * 1024 * 1024 + 64; +const relayTTL = Number(process.env.RELAY_TTL_SECONDS || 604800) * 1000; +const relayIncompleteTTL = Number(process.env.RELAY_INCOMPLETE_TTL_SECONDS || 86400) * 1000; +const offers = new Map(); +const sessions = new Map(); +const rateBuckets = new Map(); +const relayWaiters = new Map(); +let relayState = { credentials: {}, uploads: {}, messages: {} }; +let relayWrite = Promise.resolve(); + +function scopedPairingToken(secretHash, sessionID, scope) { + return crypto.createHmac('sha256', Buffer.from(secretHash, 'hex')) + .update(`AudioRecorder pairing v2:${scope}:${sessionID}`) + .digest('base64url'); +} + +function persistentSession(session) { + // Derive bearer tokens from the already high-entropy QR-secret hash rather + // than writing either token in plaintext to the relay volume. SDP/ICE state + // is deliberately transient and gets renegotiated after a server restart. + return { + id: session.id, + secretHash: session.secretHash, + offer: session.offer, + lastMacHeartbeat: session.lastMacHeartbeat, + lastClientHeartbeat: session.lastClientHeartbeat, + expiresAt: session.expiresAt + }; +} + +function restoreSession(saved) { + if (!saved || typeof saved.id !== 'string' || !/^[a-f0-9]{64}$/i.test(saved.secretHash || '') || + !saved.offer || saved.offer.id !== saved.id || !Number.isFinite(saved.expiresAt) || saved.expiresAt <= now()) return null; + const sessionToken = scopedPairingToken(saved.secretHash, saved.id, 'session'); + const relayToken = scopedPairingToken(saved.secretHash, saved.id, 'relay'); + const offer = { ...saved.offer, consumed: true }; + return { + ...saved, + offer, + sessionToken, + relayToken, + signals: [], + lastSignalID: 0, + signalMessageIDs: new Set(), + generationID: null + }; +} + +async function persistRelayState() { + relayWrite = relayWrite.then(async () => { + await fs.mkdir(relayRoot, { recursive: true, mode: 0o700 }); + const temporary = path.join(relayRoot, `state-${process.pid}.tmp`); + const state = { + ...relayState, + pairingSessions: [...sessions.values()].map(persistentSession) + }; + await fs.writeFile(temporary, JSON.stringify(state), { mode: 0o600 }); + await fs.rename(temporary, path.join(relayRoot, 'state.json')); + }); + return relayWrite; +} + +async function loadRelayState() { + await fs.mkdir(relayRoot, { recursive: true, mode: 0o700 }); + try { + const saved = JSON.parse(await fs.readFile(path.join(relayRoot, 'state.json'), 'utf8')); + relayState = { credentials: saved.credentials || {}, uploads: saved.uploads || {}, messages: saved.messages || {} }; + for (const savedSession of saved.pairingSessions || []) { + const session = restoreSession(savedSession); + if (!session) continue; + sessions.set(session.id, session); + offers.set(session.id, session.offer); + relayState.credentials[hash(session.relayToken)] = session.id; + } + } catch (error) { + if (error.code !== 'ENOENT') console.error('Relay state could not be loaded; check volume permissions and backup integrity.'); + } +} + +function relaySession(req, sessionID) { + const supplied = String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim(); + if (!supplied) return false; + return relayState.credentials[hash(supplied)] === sessionID; +} + +function readBinary(req, limit = relayChunkMaxBytes) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on('data', chunk => { + size += chunk.length; + if (size > limit) { reject(new Error('relay_chunk_too_large')); req.destroy(); return; } + chunks.push(chunk); + }); + req.on('end', () => resolve(Buffer.concat(chunks))); + req.on('error', reject); + }); +} + +function relayUploadPath(upload) { return path.join(relayRoot, 'uploads', upload.sessionID, upload.id); } +function relayMessagePath(message) { return path.join(relayRoot, 'messages', message.sessionID, message.id); } + +async function removeRelayUpload(upload, keepTombstone = false) { + await fs.rm(relayUploadPath(upload), { recursive: true, force: true }); + if (keepTombstone) { + upload.acknowledged = true; + upload.acknowledgedAt = now(); + upload.chunks = {}; + } else { + delete relayState.uploads[uploadKey(upload.sessionID, upload.id)]; + } +} + +function uploadKey(sessionID, uploadID) { return `${sessionID}:${uploadID}`; } +function messageKey(sessionID, messageID) { return `${sessionID}:${messageID}`; } + +function relayQueueHasItems(sessionID, queue) { + if (queue === 'mac') { + return relayQueueHasItems(sessionID, 'uploads') || relayQueueHasItems(sessionID, 'request'); + } + if (queue === 'uploads') { + return Object.values(relayState.uploads).some(item => item.sessionID === sessionID && item.complete && !item.acknowledged); + } + return Object.values(relayState.messages || {}).some(item => item.sessionID === sessionID && item.direction === queue && item.complete && !item.acknowledged); +} + +function wakeRelayWaiters(sessionID, queue) { + const keys = queue === 'uploads' || queue === 'request' + ? [`${sessionID}:${queue}`, `${sessionID}:mac`] + : [`${sessionID}:${queue}`]; + for (const key of keys) { + for (const wake of relayWaiters.get(key) || []) wake(); + } +} + +async function waitForRelayQueue(req, res, sessionID, queue, waitMilliseconds) { + if (relayQueueHasItems(sessionID, queue) || waitMilliseconds <= 0) return; + const key = `${sessionID}:${queue}`; + await new Promise(resolve => { + let done = false; + let timer; + const finish = () => { + if (done) return; + done = true; + clearTimeout(timer); + res.off('close', onClose); + const waiters = relayWaiters.get(key); + waiters?.delete(finish); + if (!waiters?.size) relayWaiters.delete(key); + resolve(); + }; + const onClose = () => finish(); + const waiters = relayWaiters.get(key) || new Set(); + waiters.add(finish); + relayWaiters.set(key, waiters); + res.once('close', onClose); + timer = setTimeout(finish, waitMilliseconds); + // Recheck after registering so a message completed between the first + // queue check and waiter registration cannot be missed. + if (relayQueueHasItems(sessionID, queue)) finish(); + }); +} + +function relayWaitMilliseconds(url) { + const requested = Number(url.searchParams.get('wait') || 0); + return Number.isFinite(requested) ? Math.max(0, Math.min(25, Math.floor(requested))) * 1000 : 0; +} + +async function removeRelayMessage(message, keepTombstone = false) { + await fs.rm(relayMessagePath(message), { recursive: true, force: true }); + if (keepTombstone) { + message.acknowledged = true; + message.acknowledgedAt = now(); + message.chunks = {}; + } else { + delete relayState.messages[messageKey(message.sessionID, message.id)]; + } +} + +function relayUsage(sessionID = null) { + let bytes = 0; + for (const upload of [...Object.values(relayState.uploads), ...Object.values(relayState.messages || {})]) { + if (upload.acknowledged || (sessionID && upload.sessionID !== sessionID)) continue; + bytes += upload.reservedBytes || upload.encryptedBytes || 0; + } + return bytes; +} + +function json(res, status, body) { + const data = JSON.stringify(body); + res.writeHead(status, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store', + 'content-length': Buffer.byteLength(data) + }); + res.end(data); +} + +function readBody(req) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on('data', chunk => { + size += chunk.length; + if (size > maxBodyBytes) { + reject(new Error('request_too_large')); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on('end', () => { + try { resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {}); } + catch { reject(new Error('invalid_json')); } + }); + req.on('error', reject); + }); +} + +function randomID() { return crypto.randomUUID(); } +function hash(value) { return crypto.createHash('sha256').update(value).digest('hex'); } +function now() { return Date.now(); } + +function turnCredentials(sessionID) { + const expiresAt = Math.floor(Date.now() / 1000) + 60 * 60; + const username = `${expiresAt}:${sessionID}`; + const credential = crypto.createHmac('sha1', turnSharedSecret).update(username).digest('base64'); + return { + expiresAt, + iceServers: [ + { urls: [`stun:${turnHost}:${turnPort}`] }, + { + urls: [ + `turn:${turnHost}:${turnPort}?transport=udp`, + `turn:${turnHost}:${turnPort}?transport=tcp`, + `turns:${turnHost}:5349?transport=tcp` + ], + username, + credential + } + ] + }; +} + +function cleanText(value, max = 160) { + return String(value ?? '').trim().slice(0, max); +} + +function cleanCandidates(value) { + if (!Array.isArray(value)) return []; + return value.slice(0, 128).map(candidate => ({ + sdpMid: cleanText(candidate?.sdpMid, 80), + sdpMLineIndex: Number.isInteger(candidate?.sdpMLineIndex) ? candidate.sdpMLineIndex : 0, + sdp: cleanText(candidate?.sdp, 4096) + })).filter(candidate => candidate.sdp); +} + +function cleanDescription(value) { + if (!value || typeof value !== 'object') return null; + const type = value.type === 'offer' || value.type === 'answer' || value.type === 'prAnswer' ? value.type : null; + // SDP is a line-oriented protocol: trimming the final CRLF can make + // libwebrtc reject an otherwise valid session description on some peers. + // Preserve the bytes (including line endings), while still bounding size + // and rejecting whitespace-only payloads. + const sdp = typeof value.sdp === 'string' ? value.sdp.slice(0, 96 * 1024) : ''; + return type && sdp.trim() ? { type, sdp } : null; +} + +function clientIP(req) { + const forwarded = String(req.headers['x-forwarded-for'] || '').split(',')[0].trim(); + return forwarded || req.socket.remoteAddress || 'unknown'; +} + +function rateLimit(req, res) { + const key = clientIP(req); + const timestamp = now(); + const recent = (rateBuckets.get(key) || []).filter(value => timestamp - value < 60_000); + // The Mac polls an active, short-lived offer while the iPhone camera is + // open. Thirty requests per minute was too low for that legitimate flow + // and caused a second pairing attempt to receive 429 after about one + // minute. Keep abuse protection, but allow several simultaneous pairings. + if (recent.length >= 600) { + json(res, 429, { error: 'rate_limited' }); + return false; + } + recent.push(timestamp); + rateBuckets.set(key, recent); + return true; +} + +function publicOffer(offer) { + return { + id: offer.id, + expiresAt: new Date(offer.expiresAt).toISOString(), + mac: { + name: offer.macName, + publicKey: offer.macPublicKey, + identityKey: offer.macIdentityKey, + description: offer.description, + candidates: offer.candidates + }, + client: offer.client ? { + name: offer.client.name, + publicKey: offer.client.publicKey, + identityKey: offer.client.identityKey, + description: offer.client.description, + candidates: offer.client.candidates + } : null, + bootstrap: offer.bootstrap || null, + directEndpoints: [] + }; +} + +function authSession(req, session) { + const supplied = String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim(); + return supplied && crypto.timingSafeEqual(Buffer.from(hash(supplied)), Buffer.from(hash(session.sessionToken))); +} + +async function purge() { + const timestamp = now(); + let sessionsChanged = false; + for (const [id, offer] of offers) { + // Keep a claimed offer available until its normal TTL expires. The Mac + // polls this endpoint after the iPhone claims the offer; deleting it at + // the next 30-second purge could make a valid QR pairing appear to fail + // before the Mac received the session token. + if (offer.expiresAt <= timestamp) offers.delete(id); + } + for (const [id, session] of sessions) { + if (session.expiresAt <= timestamp) { + sessions.delete(id); + offers.delete(id); + delete relayState.credentials[hash(session.relayToken)]; + sessionsChanged = true; + } + } + for (const [ip, values] of rateBuckets) { + const active = values.filter(value => timestamp - value < 60_000); + if (active.length) rateBuckets.set(ip, active); else rateBuckets.delete(ip); + } + let changed = sessionsChanged; + for (const upload of Object.values(relayState.uploads)) { + const expiry = upload.complete ? upload.expiresAt : upload.updatedAt + relayIncompleteTTL; + if (expiry <= timestamp) { + await removeRelayUpload(upload); + changed = true; + } + } + for (const message of Object.values(relayState.messages || {})) { + if (message.expiresAt <= timestamp || (!message.complete && message.updatedAt + relayIncompleteTTL <= timestamp)) { + await removeRelayMessage(message); + changed = true; + } + } + if (changed) await persistRelayState(); +} + +async function handle(req, res) { + if (!rateLimit(req, res)) return; + const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`); + const parts = url.pathname.split('/').filter(Boolean); + try { + if (req.method === 'GET' && url.pathname === '/health') { + return json(res, 200, { ok: true, service: 'meets-relay', time: new Date().toISOString() }); + } + if (req.method === 'POST' && url.pathname === '/api/v1/pairing/offers') { + const body = await readBody(req); + if (body.protocolVersion !== 2) return json(res, 426, { error: 'pairing_protocol_upgrade_required' }); + const secretHash = cleanText(body.secretHash, 128); + const publicKey = cleanText(body.publicKey, 256); + const identityKey = cleanText(body.identityKey, 256); + if (!/^[a-f0-9]{64}$/i.test(secretHash) || !publicKey || !identityKey) { + return json(res, 400, { error: 'invalid_pairing_offer' }); + } + const offer = { + id: randomID(), + secretHash: secretHash.toLowerCase(), + macName: cleanText(body.deviceName || 'Mac', 120) || 'Mac', + macPublicKey: publicKey, + macIdentityKey: identityKey, + bootstrap: cleanText(body.bootstrap, 120 * 1024) || null, + protocolVersion: 2, + directEndpoints: [], + description: cleanDescription(body.description), + candidates: cleanCandidates(body.candidates), + client: null, + signals: [], + createdAt: now(), + expiresAt: now() + offerTTL, + consumed: false + }; + offers.set(offer.id, offer); + return json(res, 201, { id: offer.id, expiresAt: new Date(offer.expiresAt).toISOString(), sessionID: null, sessionToken: null, public: publicOffer(offer) }); + } + if (req.method === 'POST' && parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'pairing' && parts[3] === 'offers' && parts[4] && parts[5] === 'claim') { + const offer = offers.get(parts[4]); + if (!offer || offer.expiresAt <= now() || offer.consumed || offer.client) return json(res, 410, { error: 'pairing_offer_expired_or_used' }); + const body = await readBody(req); + if (body.protocolVersion !== 2 || offer.protocolVersion !== 2) return json(res, 426, { error: 'pairing_protocol_upgrade_required' }); + const secretHash = cleanText(body.secretHash, 128).toLowerCase(); + if (secretHash !== offer.secretHash) return json(res, 401, { error: 'invalid_pairing_secret' }); + const publicKey = cleanText(body.publicKey, 256); + const identityKey = cleanText(body.identityKey, 256); + if (!publicKey || !identityKey) return json(res, 400, { error: 'invalid_pairing_client' }); + offer.client = { + name: cleanText(body.deviceName || 'iPhone', 120) || 'iPhone', + publicKey, + identityKey, + description: cleanDescription(body.description), + candidates: cleanCandidates(body.candidates), + claimedAt: now() + }; + offer.consumed = true; + const session = { + id: offer.id, + sessionToken: scopedPairingToken(offer.secretHash, offer.id, 'session'), + relayToken: scopedPairingToken(offer.secretHash, offer.id, 'relay'), + secretHash: offer.secretHash, + offer, + lastMacHeartbeat: now(), + lastClientHeartbeat: now(), + expiresAt: now() + sessionTTL, + signals: [], + lastSignalID: 0, + signalMessageIDs: new Set(), + generationID: null + }; + sessions.set(session.id, session); + relayState.credentials[hash(session.relayToken)] = session.id; + await persistRelayState(); + return json(res, 200, { sessionID: session.id, sessionToken: session.sessionToken, relayToken: session.relayToken, expiresAt: new Date(session.expiresAt).toISOString(), public: publicOffer(offer) }); + } + if (req.method === 'GET' && parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'pairing' && parts[3] === 'offers' && parts[4]) { + const offer = offers.get(parts[4]); + if (!offer || offer.expiresAt <= now()) return json(res, 404, { error: 'pairing_offer_not_found' }); + const secretHash = cleanText(String(req.headers.authorization || '').replace(/^Bearer\s+/i, ''), 128).toLowerCase(); + const session = sessions.get(offer.id); + const claimed = session && secretHash === offer.secretHash; + return json(res, 200, { + id: offer.id, + expiresAt: new Date(offer.expiresAt).toISOString(), + public: publicOffer(offer), + sessionID: claimed ? session.id : null, + sessionToken: claimed ? session.sessionToken : null, + relayToken: claimed ? session.relayToken : null + }); + } + if (parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'relay' && parts[3] === 'sessions' && parts[4]) { + const sessionID = parts[4]; + if (!relaySession(req, sessionID)) return json(res, 401, { error: 'unauthorized' }); + const tail = parts.slice(5); + if (tail[0] === 'messages') { + if (req.method === 'POST' && tail.length === 1) { + const body = await readBody(req); + const id = cleanText(body.id, 64).toLowerCase(); + const direction = ['request', 'response', 'attachment'].includes(body.direction) ? body.direction : null; + const size = Number(body.size); + const count = Number(body.chunkCount); + if (!/^[0-9a-f-]{36}$/.test(id) || !direction || !Number.isSafeInteger(size) || size < 1 || size > relayUploadMaxBytes || !Number.isInteger(count) || count < 1 || count > 100) return json(res, 400, { error: 'invalid_relay_message_manifest' }); + const existing = relayState.messages[messageKey(sessionID, id)]; + if (existing && !existing.acknowledged) { + if (existing.size !== size || existing.chunkCount !== count || existing.direction !== direction) return json(res, 409, { error: 'relay_message_manifest_conflict' }); + return json(res, 200, { id, received: Object.keys(existing.chunks).length, complete: existing.complete }); + } + if (relayUsage() + size > relayMaxBytes || relayUsage(sessionID) + size > relayPairingMaxBytes) return json(res, 507, { error: 'relay_quota_exceeded' }); + const created = { id, sessionID, direction, size, chunkCount: count, createdAt: now(), updatedAt: now(), expiresAt: now() + relayTTL, complete: false, acknowledged: false, reservedBytes: size + count * 28, encryptedBytes: 0, chunks: {} }; + relayState.messages[messageKey(sessionID, id)] = created; + await fs.mkdir(relayMessagePath(created), { recursive: true, mode: 0o700 }); + await persistRelayState(); + return json(res, 201, { id, received: 0, complete: false }); + } + if (req.method === 'GET' && tail.length === 1) { + const direction = url.searchParams.get('direction'); + if (!['request', 'response'].includes(direction)) return json(res, 400, { error: 'invalid_relay_message_direction' }); + await waitForRelayQueue(req, res, sessionID, direction, relayWaitMilliseconds(url)); + if (res.destroyed) return; + const messages = Object.values(relayState.messages || {}).filter(item => item.sessionID === sessionID && item.direction === direction && item.complete && !item.acknowledged); + return json(res, 200, { messages: messages.map(({ id, direction: itemDirection, size, chunkCount, createdAt }) => ({ id, direction: itemDirection, size, chunkCount, createdAt: new Date(createdAt).toISOString() })) }); + } + if (tail.length >= 2) { + const id = cleanText(tail[1] || '', 64).toLowerCase(); + const current = relayState.messages[messageKey(sessionID, id)]; + if (req.method === 'PUT' && tail.length === 4 && tail[2] === 'chunks') { + const index = Number(tail[3]); + if (!current || current.acknowledged || !Number.isInteger(index) || index < 0 || index >= current.chunkCount) return json(res, 404, { error: 'relay_message_not_found' }); + const data = await readBinary(req); + const digest = hash(data); + const previous = current.chunks[index]; + if (previous && previous.hash !== digest) return json(res, 409, { error: 'relay_message_chunk_conflict' }); + if (!previous) { + await fs.writeFile(path.join(relayMessagePath(current), `${index}.bin`), data, { mode: 0o600, flag: 'wx' }); + current.chunks[index] = { hash: digest, size: data.length }; + current.encryptedBytes += data.length; + current.updatedAt = now(); + current.expiresAt = now() + relayTTL; + current.complete = Object.keys(current.chunks).length === current.chunkCount; + await persistRelayState(); + if (current.complete) wakeRelayWaiters(sessionID, current.direction); + } + return json(res, 200, { accepted: true, complete: current.complete }); + } + if (req.method === 'GET' && tail.length === 2) { + if (!current || current.acknowledged || !current.complete) return json(res, 404, { error: 'relay_message_not_found' }); + return json(res, 200, { id: current.id, direction: current.direction, size: current.size, chunkCount: current.chunkCount, createdAt: new Date(current.createdAt).toISOString() }); + } + if (req.method === 'GET' && tail.length === 3 && tail[2] === 'chunks') { + const index = Number(url.searchParams.get('index')); + if (!current || current.acknowledged || !current.complete || !Number.isInteger(index) || !current.chunks[index]) return json(res, 404, { error: 'relay_message_chunk_not_found' }); + const data = await fs.readFile(path.join(relayMessagePath(current), `${index}.bin`)); + res.writeHead(200, { 'content-type': 'application/octet-stream', 'cache-control': 'no-store', 'content-length': data.length }); + return res.end(data); + } + if (req.method === 'POST' && tail.length === 3 && tail[2] === 'ack') { + if (!current || !current.complete) return json(res, 404, { error: 'relay_message_not_found' }); + await removeRelayMessage(current, true); + await persistRelayState(); + return json(res, 200, { acknowledged: true }); + } + if (req.method === 'DELETE' && tail.length === 2) { + if (current) await removeRelayMessage(current); + await persistRelayState(); + return json(res, 200, { deleted: true }); + } + } + } + if (req.method === 'POST' && tail.length === 1 && tail[0] === 'uploads') { + const body = await readBody(req); + const id = cleanText(body.id, 64).toLowerCase(); + const size = Number(body.size); + const count = Number(body.chunkCount); + if (!/^[0-9a-f-]{36}$/.test(id) || !Number.isSafeInteger(size) || size < 1 || size > relayUploadMaxBytes || !Number.isInteger(count) || count < 1 || count > 100) { + return json(res, 400, { error: 'invalid_upload_manifest' }); + } + const key = uploadKey(sessionID, id); + const existing = relayState.uploads[key]; + if (existing && !existing.acknowledged) { + if (existing.size !== size || existing.chunkCount !== count) return json(res, 409, { error: 'upload_manifest_conflict' }); + return json(res, 200, { id, received: Object.keys(existing.chunks).length, complete: existing.complete }); + } + if (relayUsage() + size > relayMaxBytes || relayUsage(sessionID) + size > relayPairingMaxBytes) return json(res, 507, { error: 'relay_quota_exceeded' }); + const upload = { id, sessionID, size, chunkCount: count, createdAt: now(), updatedAt: now(), expiresAt: now() + relayTTL, complete: false, acknowledged: false, reservedBytes: size + count * 28, encryptedBytes: 0, chunks: {} }; + relayState.uploads[key] = upload; + await fs.mkdir(relayUploadPath(upload), { recursive: true, mode: 0o700 }); + await persistRelayState(); + return json(res, 201, { id, received: 0, complete: false }); + } + if (tail.length >= 2 && tail[0] === 'uploads') { + const id = cleanText(tail[1], 64).toLowerCase(); + const upload = relayState.uploads[uploadKey(sessionID, id)]; + if (req.method === 'PUT' && tail.length === 4 && tail[2] === 'chunks') { + const index = Number(tail[3]); + if (!upload || upload.acknowledged || !Number.isInteger(index) || index < 0 || index >= upload.chunkCount) return json(res, 404, { error: 'relay_upload_not_found' }); + const data = await readBinary(req); + const digest = hash(data); + const previous = upload.chunks[index]; + if (previous && previous.hash !== digest) return json(res, 409, { error: 'relay_chunk_conflict' }); + if (!previous) { + await fs.writeFile(path.join(relayUploadPath(upload), `${index}.bin`), data, { mode: 0o600, flag: 'wx' }); + upload.chunks[index] = { hash: digest, size: data.length }; + upload.encryptedBytes += data.length; + upload.updatedAt = now(); + upload.expiresAt = now() + relayTTL; + upload.complete = Object.keys(upload.chunks).length === upload.chunkCount; + await persistRelayState(); + if (upload.complete) wakeRelayWaiters(sessionID, 'uploads'); + } + return json(res, 200, { accepted: true, complete: upload.complete }); + } + if (req.method === 'GET' && tail.length === 2) { + if (!upload || upload.acknowledged || !upload.complete) return json(res, 404, { error: 'relay_upload_not_found' }); + return json(res, 200, { id, size: upload.size, chunkCount: upload.chunkCount, createdAt: new Date(upload.createdAt).toISOString() }); + } + if (req.method === 'GET' && tail.length === 3 && tail[2] === 'chunks') { + const index = Number(url.searchParams.get('index')); + if (!upload || upload.acknowledged || !upload.complete || !Number.isInteger(index) || !upload.chunks[index]) return json(res, 404, { error: 'relay_chunk_not_found' }); + const data = await fs.readFile(path.join(relayUploadPath(upload), `${index}.bin`)); + res.writeHead(200, { 'content-type': 'application/octet-stream', 'cache-control': 'no-store', 'content-length': data.length }); + return res.end(data); + } + if (req.method === 'POST' && tail.length === 3 && tail[2] === 'ack') { + if (!upload || !upload.complete) return json(res, 404, { error: 'relay_upload_not_found' }); + await removeRelayUpload(upload, true); + await persistRelayState(); + return json(res, 200, { acknowledged: true }); + } + if (req.method === 'DELETE' && tail.length === 2) { + if (upload) await removeRelayUpload(upload); + await persistRelayState(); + return json(res, 200, { deleted: true }); + } + } + if (req.method === 'GET' && tail.length === 0) { + if (url.searchParams.get('queue') === 'mac') { + await waitForRelayQueue(req, res, sessionID, 'mac', relayWaitMilliseconds(url)); + if (res.destroyed) return; + } + const uploads = Object.values(relayState.uploads).filter(upload => upload.sessionID === sessionID && upload.complete && !upload.acknowledged); + return json(res, 200, { uploads: uploads.map(({ id, size, chunkCount, createdAt }) => ({ id, size, chunkCount, createdAt: new Date(createdAt).toISOString() })) }); + } + if (req.method === 'DELETE' && tail.length === 0) { + delete relayState.credentials[hash(String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim())]; + for (const upload of Object.values(relayState.uploads).filter(value => value.sessionID === sessionID)) await removeRelayUpload(upload); + for (const message of Object.values(relayState.messages || {}).filter(value => value.sessionID === sessionID)) await removeRelayMessage(message); + await persistRelayState(); + return json(res, 200, { deleted: true }); + } + } + if (parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'pairing' && parts[3] === 'sessions' && parts[4]) { + const session = sessions.get(parts[4]); + if (!session || session.expiresAt <= now()) return json(res, 404, { error: 'pairing_session_not_found' }); + if (!authSession(req, session)) return json(res, 401, { error: 'unauthorized' }); + if (req.method === 'POST' && parts[5] === 'heartbeat') { + const body = await readBody(req); + if (body.protocolVersion !== 2) return json(res, 426, { error: 'pairing_protocol_upgrade_required' }); + const side = body.side === 'mac' ? 'mac' : body.side === 'client' ? 'client' : null; + if (!side) return json(res, 400, { error: 'invalid_heartbeat_side' }); + if (side === 'mac') session.lastMacHeartbeat = now(); else session.lastClientHeartbeat = now(); + session.expiresAt = now() + sessionTTL; + await persistRelayState(); + return json(res, 200, { ok: true, expiresAt: new Date(session.expiresAt).toISOString(), directEndpoints: [], lastMacHeartbeat: session.lastMacHeartbeat, lastClientHeartbeat: session.lastClientHeartbeat }); + } + if (req.method === 'GET' && parts[5] === 'ice-servers') { + if (!turnSharedSecret || !turnHost || !Number.isInteger(turnPort) || turnPort < 1 || turnPort > 65535) { + return json(res, 503, { error: 'turn_not_configured' }); + } + return json(res, 200, turnCredentials(session.id)); + } + if (req.method === 'POST' && parts[5] === 'generation') { + // A fresh generation discards stale SDP/ICE candidates and lets both + // peers renegotiate after a network change or expired TURN credentials. + session.generationID = randomID(); + session.signals = []; + session.signalMessageIDs = new Set(); + session.lastSignalID = 0; + session.expiresAt = now() + sessionTTL; + await persistRelayState(); + return json(res, 200, { generationID: session.generationID }); + } + if (req.method === 'POST' && parts[5] === 'signal') { + const body = await readBody(req); + if (body.protocolVersion !== 2 || !/^[A-Za-z0-9_-]{43}$/.test(cleanText(body.authenticator, 64)) || !/^[0-9a-f-]{36}$/i.test(cleanText(body.messageID, 64))) { + return json(res, 426, { error: 'authenticated_signaling_required' }); + } + if (!session.generationID || cleanText(body.generationID, 80) !== session.generationID) { + return json(res, 409, { error: 'stale_generation' }); + } + const messageID = cleanText(body.messageID, 64).toLowerCase(); + if (session.signalMessageIDs?.has(messageID)) return json(res, 409, { error: 'replayed_signal' }); + const signal = { + id: ++session.lastSignalID, + protocolVersion: 2, + generationID: session.generationID, + messageID, + authenticator: cleanText(body.authenticator, 64), + side: body.side === 'mac' ? 'mac' : body.side === 'client' ? 'client' : null, + description: cleanDescription(body.description), + candidates: cleanCandidates(body.candidates), + createdAt: now() + }; + if (!signal.side || (!signal.description && !signal.candidates.length)) return json(res, 400, { error: 'invalid_signal' }); + session.signalMessageIDs ??= new Set(); + session.signalMessageIDs.add(messageID); + session.signals.push(signal); + session.signals = session.signals.slice(-32); + session.expiresAt = now() + sessionTTL; + await persistRelayState(); + return json(res, 202, { accepted: true }); + } + if (req.method === 'GET' && parts[5] === 'status') { + const since = Number(url.searchParams.get('since') || 0); + return json(res, 200, { + sessionID: session.id, + expiresAt: new Date(session.expiresAt).toISOString(), + generationID: session.generationID, + public: publicOffer(session.offer), + signals: session.signals.filter(signal => signal.id > since), + lastMacHeartbeat: session.lastMacHeartbeat, + lastClientHeartbeat: session.lastClientHeartbeat + }); + } + if (req.method === 'DELETE' && parts[5] === undefined) { + sessions.delete(session.id); + offers.delete(session.id); + delete relayState.credentials[hash(session.relayToken)]; + for (const upload of Object.values(relayState.uploads).filter(value => value.sessionID === session.id)) await removeRelayUpload(upload); + for (const message of Object.values(relayState.messages || {}).filter(value => value.sessionID === session.id)) await removeRelayMessage(message); + await persistRelayState(); + return json(res, 200, { deleted: true }); + } + } + return json(res, 404, { error: 'not_found' }); + } catch (error) { + const status = error.message === 'request_too_large' || error.message === 'relay_chunk_too_large' ? 413 : error.message === 'invalid_json' ? 400 : 500; + if (status === 500) console.error('Relay request failed unexpectedly.'); + return json(res, status, { error: status === 500 ? 'internal_error' : error.message }); + } +} + +const server = http.createServer(handle); +await loadRelayState(); +server.listen(port, host, () => console.log(`Meets Relay listening on ${host}:${port}`)); +setInterval(() => { purge().catch(() => console.error('Relay cleanup failed.')); }, 30_000).unref(); diff --git a/test-relay.mjs b/test-relay.mjs new file mode 100644 index 0000000..0ce8465 --- /dev/null +++ b/test-relay.mjs @@ -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); +});