1377 lines
73 KiB
JavaScript
1377 lines
73 KiB
JavaScript
import http from 'node:http';
|
||
import http2 from 'node:http2';
|
||
import crypto from 'node:crypto';
|
||
import fs from 'node:fs/promises';
|
||
import path from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
import { promisify } from 'node:util';
|
||
|
||
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);
|
||
// Audio payloads are capped at 500 MiB; allow additional room for AEAD tags.
|
||
const relayUploadMaxBytes = 512 * 1024 * 1024;
|
||
const relayMaxChunkCount = 170;
|
||
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 scrypt = promisify(crypto.scrypt);
|
||
const accessTokenTTL = 15 * 60 * 1000;
|
||
const refreshTokenTTL = 90 * 24 * 60 * 60 * 1000;
|
||
const invitationTTL = Number(process.env.INVITATION_TTL_SECONDS || 86400) * 1000;
|
||
const setupCodeFile = process.env.RELAY_SETUP_CODE_FILE || '';
|
||
const webSessionTTL = 8 * 60 * 60 * 1000;
|
||
const webRoot = path.join(path.dirname(fileURLToPath(import.meta.url)), 'public');
|
||
const offers = new Map();
|
||
const sessions = new Map();
|
||
const webSessions = new Map();
|
||
const deviceAuthorizations = new Map();
|
||
const deviceAuthorizationCodes = new Map();
|
||
const rateBuckets = new Map();
|
||
const rateLimitLogWindows = new Map();
|
||
const loginBuckets = new Map();
|
||
const accountAccessTokens = new Map();
|
||
const relayWaiters = new Map();
|
||
let relayState = { credentials: {}, uploads: {}, messages: {}, pushDevices: {}, pushEvents: {}, accounts: {}, invitations: {}, refreshTokens: {}, setupCompleted: false };
|
||
let relayWrite = Promise.resolve();
|
||
let setupPending = false;
|
||
|
||
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,
|
||
accountID: session.accountID || null
|
||
};
|
||
}
|
||
|
||
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,
|
||
accountID: saved.accountID || null
|
||
};
|
||
}
|
||
|
||
async function persistRelayState() {
|
||
// Keep this write's rejection for its caller, but recover the queue before
|
||
// scheduling the next snapshot so one filesystem failure does not poison
|
||
// every future persistence attempt.
|
||
relayWrite = relayWrite.catch(() => {}).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 || {}, pushDevices: apnsConfiguration() ? (saved.pushDevices || {}) : {}, pushEvents: apnsConfiguration() ? (saved.pushEvents || {}) : {}, accounts: saved.accounts || {}, invitations: saved.invitations || {}, refreshTokens: saved.refreshTokens || {}, setupCompleted: saved.setupCompleted === true || Object.keys(saved.accounts || {}).length > 0 };
|
||
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;
|
||
if (!session.accountID && relayState.setupCompleted) session.accountID = Object.keys(relayState.accounts)[0] || null;
|
||
}
|
||
if (!apnsConfiguration() && (Object.keys(saved.pushDevices || {}).length > 0 || Object.keys(saved.pushEvents || {}).length > 0)) {
|
||
await persistRelayState();
|
||
}
|
||
} catch (error) {
|
||
if (error.code !== 'ENOENT') console.error('Could not load relay state:', error);
|
||
}
|
||
}
|
||
|
||
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 apnsConfiguration() {
|
||
return process.env.APNS_ENABLED === 'true' && Boolean(process.env.APNS_TEAM_ID && process.env.APNS_KEY_ID && process.env.APNS_TOPIC && process.env.APNS_PRIVATE_KEY_PATH);
|
||
}
|
||
|
||
async function apnsConfigured() {
|
||
if (!apnsConfiguration()) return false;
|
||
try {
|
||
const key = await fs.readFile(process.env.APNS_PRIVATE_KEY_PATH, 'utf8');
|
||
return key.includes('BEGIN PRIVATE KEY');
|
||
} catch { return false; }
|
||
}
|
||
|
||
function base64url(value) { return Buffer.from(value).toString('base64url'); }
|
||
|
||
async function sendAPNs(device, event) {
|
||
if (!apnsConfiguration()) throw new Error('apns_not_configured');
|
||
const privateKey = await fs.readFile(process.env.APNS_PRIVATE_KEY_PATH, 'utf8');
|
||
const header = base64url(JSON.stringify({ alg: 'ES256', kid: process.env.APNS_KEY_ID }));
|
||
const claims = base64url(JSON.stringify({ iss: process.env.APNS_TEAM_ID, iat: Math.floor(now() / 1000) }));
|
||
const input = `${header}.${claims}`;
|
||
const signature = crypto.sign('sha256', Buffer.from(input), { key: privateKey, dsaEncoding: 'ieee-p1363' }).toString('base64url');
|
||
const token = `${input}.${signature}`;
|
||
const host = device.environment === 'sandbox' ? 'api.sandbox.push.apple.com' : 'api.push.apple.com';
|
||
const client = http2.connect(`https://${host}`);
|
||
client.setTimeout(15_000, () => client.destroy(new Error('apns_timeout')));
|
||
try {
|
||
await new Promise((resolve, reject) => {
|
||
client.once('connect', resolve);
|
||
client.once('error', reject);
|
||
});
|
||
await new Promise((resolve, reject) => {
|
||
const request = client.request({
|
||
':method': 'POST',
|
||
':path': `/3/device/${device.token}`,
|
||
authorization: `bearer ${token}`,
|
||
'apns-topic': process.env.APNS_TOPIC,
|
||
'apns-push-type': 'alert',
|
||
'apns-priority': '10',
|
||
'apns-id': event.eventID,
|
||
'content-type': 'application/json'
|
||
});
|
||
let status = 0;
|
||
let responseBody = '';
|
||
request.on('response', headers => { status = Number(headers[':status'] || 0); });
|
||
request.setEncoding('utf8');
|
||
request.on('data', chunk => { responseBody += chunk; });
|
||
request.on('end', () => status >= 200 && status < 300 ? resolve() : reject(new Error(`apns_http_${status}:${responseBody.slice(0, 200)}`)));
|
||
request.on('error', reject);
|
||
const title = event.type === 'failed' ? 'Verarbeitung fehlgeschlagen' : event.type === 'test' ? 'AudioRecorder – Test' : 'Aufnahme fertig';
|
||
const body = event.type === 'failed' ? 'Eine Aufnahme konnte nicht verarbeitet werden.' : event.type === 'test' ? 'Apple-Mitteilungen sind eingerichtet.' : 'Eine Aufnahme wurde vollständig verarbeitet.';
|
||
const payload = { aps: { alert: { title, body }, sound: 'default' }, eventType: event.type };
|
||
if (event.recordingID) payload.recordingID = event.recordingID;
|
||
request.end(JSON.stringify(payload));
|
||
});
|
||
} finally {
|
||
client.close();
|
||
}
|
||
}
|
||
|
||
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 url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);
|
||
const parts = url.pathname.split('/').filter(Boolean);
|
||
const isRelayRoute = parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'relay';
|
||
const isRelayChunk = isRelayRoute && parts.includes('chunks');
|
||
const isRelayQueuePoll = isRelayRoute && parts[3] === 'sessions' && !parts[5] &&
|
||
req.method === 'GET' && url.searchParams.get('queue') === 'mac';
|
||
const isPairingRoute = parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'pairing';
|
||
const isAuthRoute = parts[0] === 'api' && parts[1] === 'v1' && ['auth', 'web'].includes(parts[2]);
|
||
const bucket = isRelayChunk ? 'relay-chunk'
|
||
: isRelayQueuePoll ? 'relay-wait'
|
||
: isRelayRoute ? 'relay-control'
|
||
: isPairingRoute ? 'pairing'
|
||
: isAuthRoute ? 'auth'
|
||
: 'default';
|
||
const limit = bucket === 'relay-chunk' ? 6_000
|
||
: bucket === 'relay-wait' ? 180
|
||
: bucket === 'relay-control' ? 1_800
|
||
: bucket === 'pairing' ? 300
|
||
: bucket === 'auth' ? 120
|
||
: 600;
|
||
// All clients behind the same NAT can share one public IP. Once a relay
|
||
// credential is valid, scope relay traffic to its paired session so one
|
||
// busy pairing cannot make other pairings appear rate-limited. Invalid or
|
||
// missing credentials remain protected by the pre-authentication IP bucket.
|
||
const relaySessionID = isRelayRoute
|
||
? relayState.credentials[hash(bearer(req))]
|
||
: null;
|
||
const key = relaySessionID
|
||
? `session:${relaySessionID}:${bucket}`
|
||
: `${clientIP(req)}:${bucket}`;
|
||
const routeClass = isRelayRoute
|
||
? parts[3] !== 'sessions' ? 'relay-other'
|
||
: parts[5] === 'messages' ? (parts[7] === 'chunks' ? 'relay-message-chunks' : 'relay-messages')
|
||
: parts[5] === 'uploads' ? (parts[7] === 'chunks' ? 'relay-upload-chunks' : 'relay-uploads')
|
||
: parts[5] ? `relay-${parts[5]}`
|
||
: 'relay-session-root'
|
||
: null;
|
||
const timestamp = now();
|
||
const recent = (rateBuckets.get(key) || []).filter(value => timestamp - value < 60_000);
|
||
// Keep noisy relay chunk transfers from consuming the budget for pairing,
|
||
// authentication, and heartbeats. Chunk requests remain bounded separately
|
||
// because one large encrypted transfer can legitimately use many requests.
|
||
if (recent.length >= limit) {
|
||
const logWindow = rateLimitLogWindows.get(bucket);
|
||
if (!logWindow || timestamp - logWindow.startedAt >= 60_000) {
|
||
console.warn(JSON.stringify({
|
||
event: 'rate_limit_rejected',
|
||
bucket,
|
||
method: req.method,
|
||
...(routeClass ? { routeClass } : {}),
|
||
suppressedSincePreviousLog: logWindow?.suppressed || 0
|
||
}));
|
||
rateLimitLogWindows.set(bucket, { startedAt: timestamp, suppressed: 0 });
|
||
} else {
|
||
logWindow.suppressed += 1;
|
||
}
|
||
res.setHeader('retry-after', '60');
|
||
json(res, 429, { error: 'rate_limited', retryAfterSeconds: 60 });
|
||
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)));
|
||
}
|
||
|
||
function bearer(req) { return String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim(); }
|
||
function safeEqualString(a, b) {
|
||
const left = Buffer.from(String(a));
|
||
const right = Buffer.from(String(b));
|
||
return left.length === right.length && crypto.timingSafeEqual(left, right);
|
||
}
|
||
function accountForRequest(req) {
|
||
const token = bearer(req);
|
||
if (!token) return null;
|
||
const entry = accountAccessTokens.get(hash(token));
|
||
if (!entry || entry.expiresAt <= now()) {
|
||
if (entry) accountAccessTokens.delete(hash(token));
|
||
return null;
|
||
}
|
||
const account = relayState.accounts[entry.accountID];
|
||
return account && !account.disabledAt ? account : null;
|
||
}
|
||
function accountRateLimit(req, res, scope, limit = 20) {
|
||
const key = `${scope}:${clientIP(req)}`;
|
||
const timestamp = now();
|
||
const recent = (loginBuckets.get(key) || []).filter(value => timestamp - value < 60_000);
|
||
if (recent.length >= limit) { json(res, 429, { error: 'auth_rate_limited' }); return false; }
|
||
recent.push(timestamp);
|
||
loginBuckets.set(key, recent);
|
||
return true;
|
||
}
|
||
async function passwordDigest(password, salt) {
|
||
return (await scrypt(password, salt, 64, { N: 1 << 15, r: 8, p: 1, maxmem: 64 * 1024 * 1024 })).toString('hex');
|
||
}
|
||
async function verifyPassword(password, account) {
|
||
if (typeof password !== 'string' || password.length > 1024) return false;
|
||
return safeEqualString(await passwordDigest(password, account.passwordSalt), account.passwordHash);
|
||
}
|
||
function publicAccount(account) {
|
||
return { id: account.id, username: account.username, role: account.role, createdAt: account.createdAt };
|
||
}
|
||
function browserSessionCookie(token, maxAge = 8 * 60 * 60) {
|
||
return `__Host-meets_relay_session=${token}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${maxAge}`;
|
||
}
|
||
function browserSession(req) {
|
||
const cookieName = '__Host-meets_relay_session=';
|
||
const token = String(req.headers.cookie || '').split(';').map(value => value.trim()).find(value => value.startsWith(cookieName))?.slice(cookieName.length);
|
||
const session = token ? webSessions.get(hash(token)) : null;
|
||
if (!session || session.expiresAt <= now()) {
|
||
if (token) webSessions.delete(hash(token));
|
||
return null;
|
||
}
|
||
const account = relayState.accounts[session.accountID];
|
||
return account && !account.disabledAt ? { account, token } : null;
|
||
}
|
||
function requireWebAccount(req, res, role = null) {
|
||
const session = browserSession(req);
|
||
if (!session || (role && session.account.role !== role)) { json(res, 401, { error: 'unauthorized' }); return null; }
|
||
return session;
|
||
}
|
||
function validBrowserOrigin(req) {
|
||
const origin = req.headers.origin;
|
||
if (!origin) return false;
|
||
try {
|
||
const parsed = new URL(origin);
|
||
return parsed.host.toLowerCase() === String(req.headers.host || '').toLowerCase() &&
|
||
(parsed.protocol === 'https:' || parsed.hostname === 'localhost' || parsed.hostname === '127.0.0.1');
|
||
} catch { return false; }
|
||
}
|
||
function requireBrowserMutation(req, res) {
|
||
if (!validBrowserOrigin(req)) { json(res, 403, { error: 'invalid_origin' }); return false; }
|
||
return true;
|
||
}
|
||
function createBrowserSession(res, account) {
|
||
const token = crypto.randomBytes(32).toString('base64url');
|
||
webSessions.set(hash(token), { accountID: account.id, expiresAt: now() + webSessionTTL });
|
||
res.setHeader('set-cookie', browserSessionCookie(token));
|
||
}
|
||
function expireBrowserSession(req, res) {
|
||
const session = browserSession(req);
|
||
if (session) webSessions.delete(hash(session.token));
|
||
res.setHeader('set-cookie', browserSessionCookie('', 0));
|
||
}
|
||
function validUsernameAndPassword(usernameValue, passwordValue) {
|
||
const username = cleanText(usernameValue, 64).toLowerCase();
|
||
const password = typeof passwordValue === 'string' ? passwordValue : '';
|
||
return /^[a-z0-9][a-z0-9._-]{2,63}$/.test(username) && password.length >= 12 && password.length <= 1024
|
||
? { username, password } : null;
|
||
}
|
||
function makeDeviceUserCode() {
|
||
const alphabet = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||
const bytes = crypto.randomBytes(8);
|
||
return `${Array.from(bytes.subarray(0, 4), value => alphabet[value % alphabet.length]).join('')}-${Array.from(bytes.subarray(4), value => alphabet[value % alphabet.length]).join('')}`;
|
||
}
|
||
function purgeDeviceAuthorizations() {
|
||
for (const [key, value] of deviceAuthorizations) {
|
||
if (value.expiresAt <= now() || value.consumedAt) {
|
||
deviceAuthorizations.delete(key);
|
||
deviceAuthorizationCodes.delete(value.userCode);
|
||
}
|
||
}
|
||
for (const [key, value] of webSessions) if (value.expiresAt <= now()) webSessions.delete(key);
|
||
}
|
||
function issueAccountTokens(accountID) {
|
||
const accessToken = crypto.randomBytes(32).toString('base64url');
|
||
const refreshToken = crypto.randomBytes(48).toString('base64url');
|
||
const accessExpiresAt = now() + accessTokenTTL;
|
||
const refreshExpiresAt = now() + refreshTokenTTL;
|
||
accountAccessTokens.set(hash(accessToken), { accountID, expiresAt: accessExpiresAt });
|
||
relayState.refreshTokens[hash(refreshToken)] = { accountID, expiresAt: refreshExpiresAt };
|
||
return { accessToken, refreshToken, accessExpiresAt: new Date(accessExpiresAt).toISOString(), refreshExpiresAt: new Date(refreshExpiresAt).toISOString() };
|
||
}
|
||
function requireAccount(req, res, role = null) {
|
||
const account = accountForRequest(req);
|
||
if (!account || (role && account.role !== role)) { json(res, 401, { error: 'unauthorized' }); return null; }
|
||
return account;
|
||
}
|
||
async function readSetupCode() {
|
||
if (!setupCodeFile) return '';
|
||
try { return (await fs.readFile(setupCodeFile, 'utf8')).trim(); } catch { return ''; }
|
||
}
|
||
|
||
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)];
|
||
delete relayState.pushDevices[id];
|
||
delete relayState.pushEvents[id];
|
||
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 === 'GET' && ['/', '/device', '/assets/app.js', '/assets/styles.css'].includes(url.pathname)) {
|
||
const file = url.pathname === '/assets/app.js' ? 'app.js' : url.pathname === '/assets/styles.css' ? 'styles.css' : 'index.html';
|
||
const type = file.endsWith('.js') ? 'text/javascript; charset=utf-8' : file.endsWith('.css') ? 'text/css; charset=utf-8' : 'text/html; charset=utf-8';
|
||
const data = await fs.readFile(path.join(webRoot, file));
|
||
res.writeHead(200, {
|
||
'content-type': type,
|
||
'content-length': data.length,
|
||
'cache-control': 'no-store',
|
||
'content-security-policy': "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; form-action 'self'; base-uri 'none'; frame-ancestors 'none'; object-src 'none'",
|
||
'referrer-policy': 'no-referrer',
|
||
'x-content-type-options': 'nosniff',
|
||
'x-frame-options': 'DENY',
|
||
'permissions-policy': 'camera=(), microphone=(), geolocation=()'
|
||
});
|
||
return res.end(data);
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/web/status') {
|
||
purgeDeviceAuthorizations();
|
||
return json(res, 200, { setupCompleted: relayState.setupCompleted, authenticated: Boolean(browserSession(req)) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname.startsWith('/api/v1/web/')) {
|
||
if (!requireBrowserMutation(req, res)) return;
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/web/session') {
|
||
if (!accountRateLimit(req, res, 'web-login', 10)) return;
|
||
const body = await readBody(req);
|
||
const username = cleanText(body.username, 64).toLowerCase();
|
||
const account = Object.values(relayState.accounts).find(value => value.username === username && !value.disabledAt);
|
||
const valid = account ? await verifyPassword(body.password, account) : safeEqualString(await passwordDigest(typeof body.password === 'string' ? body.password.slice(0, 1024) : '', '0'.repeat(32)), '0'.repeat(128));
|
||
if (!account || !valid) return json(res, 401, { error: 'invalid_credentials' });
|
||
createBrowserSession(res, account);
|
||
return json(res, 200, { account: publicAccount(account) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/web/setup') {
|
||
if (!accountRateLimit(req, res, 'web-setup', 5)) return;
|
||
if (relayState.setupCompleted || setupPending) return json(res, 409, { error: 'setup_already_completed' });
|
||
const body = await readBody(req);
|
||
setupPending = true;
|
||
try {
|
||
const expectedCode = await readSetupCode();
|
||
const suppliedCode = typeof body.setupCode === 'string' ? body.setupCode : '';
|
||
const credentials = validUsernameAndPassword(body.username, body.password);
|
||
if (!expectedCode) return json(res, 503, { error: 'relay_setup_code_not_configured' });
|
||
if (!safeEqualString(suppliedCode, expectedCode)) return json(res, 401, { error: 'invalid_setup_code' });
|
||
if (!credentials) return json(res, 400, { error: 'invalid_account_credentials' });
|
||
const id = randomID();
|
||
const passwordSalt = crypto.randomBytes(16).toString('hex');
|
||
const account = { id, username: credentials.username, role: 'admin', passwordSalt, passwordHash: await passwordDigest(credentials.password, passwordSalt), createdAt: new Date().toISOString() };
|
||
relayState.accounts[id] = account;
|
||
relayState.setupCompleted = true;
|
||
for (const session of sessions.values()) if (!session.accountID) session.accountID = id;
|
||
await persistRelayState();
|
||
createBrowserSession(res, account);
|
||
return json(res, 201, { account: publicAccount(account) });
|
||
} finally { setupPending = false; }
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/web/redeem') {
|
||
if (!accountRateLimit(req, res, 'web-redeem', 10)) return;
|
||
const body = await readBody(req);
|
||
const invitationCode = typeof body.invitationCode === 'string' ? body.invitationCode.trim() : '';
|
||
const invitation = relayState.invitations[hash(invitationCode)];
|
||
const credentials = validUsernameAndPassword(body.username, body.password);
|
||
if (!invitation || invitation.expiresAt <= now() || invitation.usedAt) return json(res, 401, { error: 'invalid_invitation' });
|
||
if (!credentials || Object.values(relayState.accounts).some(value => value.username === credentials.username)) return json(res, 400, { error: 'invalid_account_credentials' });
|
||
invitation.usedAt = now();
|
||
const id = randomID();
|
||
const passwordSalt = crypto.randomBytes(16).toString('hex');
|
||
const account = { id, username: credentials.username, role: 'member', passwordSalt, passwordHash: await passwordDigest(credentials.password, passwordSalt), createdAt: new Date().toISOString(), invitedBy: invitation.createdBy };
|
||
relayState.accounts[id] = account;
|
||
await persistRelayState();
|
||
createBrowserSession(res, account);
|
||
return json(res, 201, { account: publicAccount(account) });
|
||
}
|
||
if (req.method === 'DELETE' && url.pathname === '/api/v1/web/session') {
|
||
expireBrowserSession(req, res);
|
||
return json(res, 200, { ok: true });
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/web/session') {
|
||
const session = requireWebAccount(req, res);
|
||
return session ? json(res, 200, { account: publicAccount(session.account) }) : undefined;
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/device/start') {
|
||
if (!accountRateLimit(req, res, 'device-start', 10)) return;
|
||
purgeDeviceAuthorizations();
|
||
if (deviceAuthorizations.size >= 10_000) return json(res, 503, { error: 'device_authorization_capacity_reached' });
|
||
let userCode;
|
||
do { userCode = makeDeviceUserCode(); } while (deviceAuthorizationCodes.has(userCode));
|
||
const deviceCode = crypto.randomBytes(32).toString('base64url');
|
||
const expiresAt = now() + 15 * 60 * 1000;
|
||
const authorization = { userCode, deviceCodeHash: hash(deviceCode), expiresAt, status: 'pending', accountID: null, consumedAt: null };
|
||
deviceAuthorizations.set(authorization.deviceCodeHash, authorization);
|
||
deviceAuthorizationCodes.set(userCode, authorization);
|
||
return json(res, 201, { deviceCode, userCode, expiresIn: 900, interval: 2 });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/web/device/authorize') {
|
||
const session = requireWebAccount(req, res);
|
||
if (!session) return;
|
||
const body = await readBody(req);
|
||
const userCode = cleanText(body.userCode, 16).toUpperCase();
|
||
const authorization = deviceAuthorizationCodes.get(userCode);
|
||
if (!authorization || authorization.expiresAt <= now() || authorization.status !== 'pending') return json(res, 404, { error: 'device_code_invalid_or_expired' });
|
||
authorization.status = 'authorized';
|
||
authorization.accountID = session.account.id;
|
||
return json(res, 200, { authorized: true, account: publicAccount(session.account) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/device/token') {
|
||
const body = await readBody(req);
|
||
const deviceCode = typeof body.deviceCode === 'string' ? body.deviceCode : '';
|
||
const authorization = deviceAuthorizations.get(hash(deviceCode));
|
||
if (!authorization || authorization.expiresAt <= now()) return json(res, 400, { error: 'expired_token' });
|
||
if (authorization.status === 'pending') return json(res, 400, { error: 'authorization_pending' });
|
||
if (authorization.status !== 'authorized' || authorization.consumedAt) return json(res, 400, { error: 'invalid_device_code' });
|
||
const account = relayState.accounts[authorization.accountID];
|
||
if (!account || account.disabledAt) return json(res, 400, { error: 'invalid_device_code' });
|
||
authorization.consumedAt = now();
|
||
const tokens = issueAccountTokens(account.id);
|
||
return json(res, 200, { account: publicAccount(account), ...tokens });
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/web/admin/accounts') {
|
||
const session = requireWebAccount(req, res, 'admin');
|
||
if (!session) return;
|
||
return json(res, 200, { accounts: Object.values(relayState.accounts).filter(value => !value.disabledAt).map(publicAccount) });
|
||
}
|
||
if (req.method === 'DELETE' && parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'web' && parts[3] === 'admin' && parts[4] === 'accounts' && parts[5]) {
|
||
const session = requireWebAccount(req, res, 'admin');
|
||
if (!session) return;
|
||
const target = relayState.accounts[parts[5]];
|
||
if (!target || target.id === session.account.id) return json(res, target ? 400 : 404, { error: target ? 'cannot_revoke_current_account' : 'account_not_found' });
|
||
target.disabledAt = new Date().toISOString();
|
||
for (const [key, value] of Object.entries(relayState.refreshTokens)) if (value.accountID === target.id) delete relayState.refreshTokens[key];
|
||
for (const [key, value] of accountAccessTokens) if (value.accountID === target.id) accountAccessTokens.delete(key);
|
||
for (const auth of deviceAuthorizations.values()) if (auth.accountID === target.id) auth.status = 'denied';
|
||
for (const pairing of [...sessions.values()]) if (pairing.accountID === target.id) {
|
||
sessions.delete(pairing.id); offers.delete(pairing.id);
|
||
delete relayState.pushDevices[pairing.id]; delete relayState.pushEvents[pairing.id]; delete relayState.credentials[hash(pairing.relayToken)];
|
||
for (const upload of Object.values(relayState.uploads).filter(value => value.sessionID === pairing.id)) await removeRelayUpload(upload);
|
||
for (const message of Object.values(relayState.messages || {}).filter(value => value.sessionID === pairing.id)) await removeRelayMessage(message);
|
||
}
|
||
await persistRelayState();
|
||
return json(res, 200, { deleted: true });
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/web/admin/invitations') {
|
||
const session = requireWebAccount(req, res, 'admin');
|
||
if (!session) return;
|
||
return json(res, 200, { invitations: Object.values(relayState.invitations).filter(value => !value.revokedAt).map(value => ({ id: value.id, expiresAt: new Date(value.expiresAt).toISOString(), createdAt: value.createdAt, used: Boolean(value.usedAt) })) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/web/admin/invitations') {
|
||
const session = requireWebAccount(req, res, 'admin');
|
||
if (!session) return;
|
||
const code = crypto.randomBytes(24).toString('base64url');
|
||
const id = randomID();
|
||
const expiresAt = now() + invitationTTL;
|
||
relayState.invitations[hash(code)] = { id, createdBy: session.account.id, createdAt: new Date().toISOString(), expiresAt };
|
||
await persistRelayState();
|
||
return json(res, 201, { id, code, expiresAt: new Date(expiresAt).toISOString() });
|
||
}
|
||
if (req.method === 'DELETE' && parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'web' && parts[3] === 'admin' && parts[4] === 'invitations' && parts[5]) {
|
||
const session = requireWebAccount(req, res, 'admin');
|
||
if (!session) return;
|
||
const entry = Object.entries(relayState.invitations).find(([, value]) => value.id === parts[5]);
|
||
if (entry) { entry[1].revokedAt = now(); await persistRelayState(); }
|
||
return json(res, 200, { deleted: Boolean(entry) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/setup') {
|
||
if (!accountRateLimit(req, res, 'setup', 5)) return;
|
||
if (relayState.setupCompleted || setupPending) return json(res, 409, { error: 'setup_already_completed' });
|
||
const body = await readBody(req);
|
||
if (relayState.setupCompleted || setupPending) return json(res, 409, { error: 'setup_already_completed' });
|
||
setupPending = true;
|
||
try {
|
||
const suppliedCode = typeof body.setupCode === 'string' ? body.setupCode : '';
|
||
const expectedCode = await readSetupCode();
|
||
if (!expectedCode) return json(res, 503, { error: 'relay_setup_code_not_configured' });
|
||
if (!safeEqualString(suppliedCode, expectedCode)) return json(res, 401, { error: 'invalid_setup_code' });
|
||
const username = cleanText(body.username, 64).toLowerCase();
|
||
const password = typeof body.password === 'string' ? body.password : '';
|
||
if (!/^[a-z0-9][a-z0-9._-]{2,63}$/.test(username) || password.length < 12 || password.length > 1024) {
|
||
return json(res, 400, { error: 'invalid_account_credentials' });
|
||
}
|
||
const id = randomID();
|
||
const passwordSalt = crypto.randomBytes(16).toString('hex');
|
||
const account = { id, username, role: 'admin', passwordSalt, passwordHash: await passwordDigest(password, passwordSalt), createdAt: new Date().toISOString() };
|
||
relayState.accounts[id] = account;
|
||
relayState.setupCompleted = true;
|
||
// Preserve pre-account pairings and their queued ciphertext when the
|
||
// relay is upgraded in place. The first administrator owns legacy state.
|
||
for (const session of sessions.values()) if (!session.accountID) session.accountID = id;
|
||
const tokens = issueAccountTokens(id);
|
||
await persistRelayState();
|
||
return json(res, 201, { account: publicAccount(account), ...tokens });
|
||
} finally {
|
||
setupPending = false;
|
||
}
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/login') {
|
||
if (!accountRateLimit(req, res, 'login', 10)) return;
|
||
const body = await readBody(req);
|
||
const username = cleanText(body.username, 64).toLowerCase();
|
||
const account = Object.values(relayState.accounts).find(value => value.username === username && !value.disabledAt);
|
||
const valid = account ? await verifyPassword(body.password, account) : safeEqualString(await passwordDigest(typeof body.password === 'string' ? body.password.slice(0, 1024) : '', '0'.repeat(32)), '0'.repeat(128));
|
||
if (!account || !valid) return json(res, 401, { error: 'invalid_credentials' });
|
||
return json(res, 200, { account: publicAccount(account), ...issueAccountTokens(account.id) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/refresh') {
|
||
if (!accountRateLimit(req, res, 'refresh', 30)) return;
|
||
const body = await readBody(req);
|
||
const supplied = typeof body.refreshToken === 'string' ? body.refreshToken : '';
|
||
const key = hash(supplied);
|
||
const existing = relayState.refreshTokens[key];
|
||
if (!existing || existing.expiresAt <= now()) return json(res, 401, { error: 'invalid_refresh_token' });
|
||
const account = relayState.accounts[existing.accountID];
|
||
if (!account || account.disabledAt) return json(res, 401, { error: 'invalid_refresh_token' });
|
||
delete relayState.refreshTokens[key];
|
||
const tokens = issueAccountTokens(account.id);
|
||
await persistRelayState();
|
||
return json(res, 200, { account: publicAccount(account), ...tokens });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/logout') {
|
||
const body = await readBody(req);
|
||
const token = bearer(req);
|
||
if (token) accountAccessTokens.delete(hash(token));
|
||
const refreshToken = typeof body.refreshToken === 'string' ? body.refreshToken : '';
|
||
if (refreshToken) delete relayState.refreshTokens[hash(refreshToken)];
|
||
await persistRelayState();
|
||
return json(res, 200, { ok: true });
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/auth/me') {
|
||
const account = requireAccount(req, res);
|
||
return account ? json(res, 200, { account: publicAccount(account) }) : undefined;
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/auth/redeem') {
|
||
if (!accountRateLimit(req, res, 'redeem', 10)) return;
|
||
const body = await readBody(req);
|
||
const code = typeof body.invitationCode === 'string' ? body.invitationCode.trim() : '';
|
||
const invitationKey = hash(code);
|
||
const invitation = relayState.invitations[invitationKey];
|
||
if (!invitation || invitation.expiresAt <= now() || invitation.usedAt) return json(res, 401, { error: 'invalid_invitation' });
|
||
const username = cleanText(body.username, 64).toLowerCase();
|
||
const password = typeof body.password === 'string' ? body.password : '';
|
||
if (!/^[a-z0-9][a-z0-9._-]{2,63}$/.test(username) || password.length < 12 || password.length > 1024 || Object.values(relayState.accounts).some(value => value.username === username)) {
|
||
return json(res, 400, { error: 'invalid_account_credentials' });
|
||
}
|
||
invitation.usedAt = now();
|
||
const id = randomID();
|
||
const passwordSalt = crypto.randomBytes(16).toString('hex');
|
||
const account = { id, username, role: 'member', passwordSalt, passwordHash: await passwordDigest(password, passwordSalt), createdAt: new Date().toISOString(), invitedBy: invitation.createdBy };
|
||
relayState.accounts[id] = account;
|
||
const tokens = issueAccountTokens(id);
|
||
await persistRelayState();
|
||
return json(res, 201, { account: publicAccount(account), ...tokens });
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/admin/invitations') {
|
||
const account = requireAccount(req, res, 'admin');
|
||
if (!account) return;
|
||
return json(res, 200, { invitations: Object.entries(relayState.invitations).filter(([, value]) => !value.revokedAt).map(([key, value]) => ({ id: value.id, expiresAt: new Date(value.expiresAt).toISOString(), createdAt: value.createdAt, used: Boolean(value.usedAt), codeHash: key })) });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/admin/invitations') {
|
||
const account = requireAccount(req, res, 'admin');
|
||
if (!account) return;
|
||
const code = crypto.randomBytes(24).toString('base64url');
|
||
const id = randomID();
|
||
const expiresAt = now() + invitationTTL;
|
||
relayState.invitations[hash(code)] = { id, createdBy: account.id, createdAt: new Date().toISOString(), expiresAt };
|
||
await persistRelayState();
|
||
return json(res, 201, { id, code, expiresAt: new Date(expiresAt).toISOString() });
|
||
}
|
||
if (req.method === 'DELETE' && parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'admin' && parts[3] === 'invitations' && parts[4]) {
|
||
const account = requireAccount(req, res, 'admin');
|
||
if (!account) return;
|
||
const entry = Object.entries(relayState.invitations).find(([, value]) => value.id === parts[4]);
|
||
if (entry) { entry[1].revokedAt = now(); await persistRelayState(); }
|
||
return json(res, 200, { deleted: Boolean(entry) });
|
||
}
|
||
if (req.method === 'GET' && url.pathname === '/api/v1/admin/accounts') {
|
||
const account = requireAccount(req, res, 'admin');
|
||
if (!account) return;
|
||
return json(res, 200, { accounts: Object.values(relayState.accounts).filter(value => !value.disabledAt).map(publicAccount) });
|
||
}
|
||
if (req.method === 'DELETE' && parts[0] === 'api' && parts[1] === 'v1' && parts[2] === 'admin' && parts[3] === 'accounts' && parts[4]) {
|
||
const account = requireAccount(req, res, 'admin');
|
||
if (!account) return;
|
||
const target = relayState.accounts[parts[4]];
|
||
if (!target || target.id === account.id) return json(res, target ? 400 : 404, { error: target ? 'cannot_revoke_current_account' : 'account_not_found' });
|
||
target.disabledAt = new Date().toISOString();
|
||
for (const [key, value] of Object.entries(relayState.refreshTokens)) if (value.accountID === target.id) delete relayState.refreshTokens[key];
|
||
for (const [key, value] of accountAccessTokens) if (value.accountID === target.id) accountAccessTokens.delete(key);
|
||
for (const session of [...sessions.values()]) if (session.accountID === target.id) {
|
||
sessions.delete(session.id); offers.delete(session.id);
|
||
delete relayState.credentials[hash(session.relayToken)];
|
||
delete relayState.pushDevices[session.id]; delete relayState.pushEvents[session.id];
|
||
}
|
||
await persistRelayState();
|
||
return json(res, 200, { revoked: true });
|
||
}
|
||
if (req.method === 'POST' && url.pathname === '/api/v1/pairing/offers') {
|
||
const account = requireAccount(req, res);
|
||
if (!account) return;
|
||
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,
|
||
accountID: account.id,
|
||
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,
|
||
accountID: offer.accountID,
|
||
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] === 'push-devices') {
|
||
if (!apnsConfiguration()) return json(res, 404, { error: 'not_found' });
|
||
relayState.pushDevices[sessionID] ??= [];
|
||
if (req.method === 'GET' && tail.length === 1) {
|
||
return json(res, 200, { configured: await apnsConfigured(), registered: relayState.pushDevices[sessionID].length });
|
||
}
|
||
if (req.method === 'POST' && tail.length === 1) {
|
||
const body = await readBody(req);
|
||
const token = cleanText(body.token, 256).toLowerCase();
|
||
const environment = body.environment;
|
||
if (body.bundleID !== (process.env.APNS_TOPIC || 'com.example.Meets') || !['sandbox', 'production'].includes(environment) || !/^[a-f0-9]{32,256}$/.test(token)) {
|
||
return json(res, 400, { error: 'invalid_push_device' });
|
||
}
|
||
const devices = relayState.pushDevices[sessionID].filter(device => device.token !== token);
|
||
devices.push({ token, environment, bundleID: body.bundleID, updatedAt: now() });
|
||
relayState.pushDevices[sessionID] = devices.slice(-8);
|
||
await persistRelayState();
|
||
return json(res, 200, { registered: true });
|
||
}
|
||
if (req.method === 'DELETE' && tail.length === 1) {
|
||
const body = await readBody(req);
|
||
const token = cleanText(body.token, 256).toLowerCase();
|
||
relayState.pushDevices[sessionID] = relayState.pushDevices[sessionID].filter(device => device.token !== token);
|
||
await persistRelayState();
|
||
return json(res, 200, { unregistered: true });
|
||
}
|
||
}
|
||
if (tail[0] === 'notifications' && req.method === 'POST' && tail.length === 1) {
|
||
if (!apnsConfiguration()) return json(res, 404, { error: 'not_found' });
|
||
const body = await readBody(req);
|
||
const eventID = cleanText(body.eventID, 64).toLowerCase();
|
||
const type = body.eventType;
|
||
const recordingID = body.recordingID == null ? null : cleanText(body.recordingID, 64);
|
||
if (!/^[0-9a-f-]{36}$/.test(eventID) || !['completed', 'failed', 'test'].includes(type) || (type !== 'test' && !/^[0-9a-f-]{36}$/i.test(recordingID || ''))) {
|
||
return json(res, 400, { error: 'invalid_notification_event' });
|
||
}
|
||
if (!await apnsConfigured()) return json(res, 503, { error: 'apns_not_configured' });
|
||
relayState.pushEvents[sessionID] ??= {};
|
||
if (relayState.pushEvents[sessionID][eventID]) return json(res, 200, { accepted: true, duplicate: true });
|
||
const devices = relayState.pushDevices[sessionID] || [];
|
||
if (devices.length === 0) return json(res, 404, { error: 'no_registered_push_devices' });
|
||
const event = { eventID, type, recordingID };
|
||
let failedDevice;
|
||
try {
|
||
for (const device of devices) {
|
||
failedDevice = device;
|
||
await sendAPNs(device, event);
|
||
}
|
||
} catch (error) {
|
||
if (String(error.message).includes('Unregistered') || String(error.message).includes('BadDeviceToken')) {
|
||
relayState.pushDevices[sessionID] = devices.filter(device => device.token !== failedDevice?.token);
|
||
await persistRelayState();
|
||
}
|
||
console.error('APNs delivery failed:', error.message);
|
||
return json(res, 502, { error: 'apns_delivery_failed' });
|
||
}
|
||
relayState.pushEvents[sessionID][eventID] = { acceptedAt: now() };
|
||
const cutoff = now() - 7 * 24 * 60 * 60 * 1000;
|
||
relayState.pushEvents[sessionID] = Object.fromEntries(Object.entries(relayState.pushEvents[sessionID]).filter(([, saved]) => saved.acceptedAt >= cutoff).slice(-256));
|
||
await persistRelayState();
|
||
return json(res, 202, { accepted: true });
|
||
}
|
||
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 > relayMaxChunkCount) 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 });
|
||
}
|
||
const reservedBytes = size + count * 28;
|
||
if (relayUsage() + reservedBytes > relayMaxBytes || relayUsage(sessionID) + reservedBytes > 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, 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) {
|
||
if (data.length === 0 || current.encryptedBytes + data.length > current.reservedBytes) return json(res, 413, { error: 'relay_message_size_exceeded' });
|
||
// Reserve in memory before awaiting disk I/O so concurrent chunk
|
||
// requests cannot both pass the aggregate-size check.
|
||
current.encryptedBytes += data.length;
|
||
try {
|
||
await fs.writeFile(path.join(relayMessagePath(current), `${index}.bin`), data, { mode: 0o600, flag: 'wx' });
|
||
} catch (error) {
|
||
current.encryptedBytes -= data.length;
|
||
throw error;
|
||
}
|
||
current.chunks[index] = { hash: digest, size: 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);
|
||
const method = body.method == null ? null : cleanText(body.method, 8).toUpperCase();
|
||
const uploadPath = body.path == null ? null : cleanText(body.path, 512);
|
||
const correlationID = body.correlationID == null ? null : cleanText(body.correlationID, 64).toLowerCase();
|
||
const headers = body.headers == null ? null : body.headers;
|
||
const hasRPCMetadata = method !== null || uploadPath !== null || correlationID !== null || headers !== null;
|
||
const supportedUploadPath = typeof uploadPath === 'string' && (
|
||
uploadPath === '/api/v1/recordings' ||
|
||
uploadPath === '/api/v1/recordings/import' ||
|
||
/^\/api\/v1\/recordings\/[0-9a-f-]{36}\/audio$/.test(uploadPath) ||
|
||
/^\/api\/v1\/recordings\/[0-9a-f-]{36}\/context-documents$/.test(uploadPath)
|
||
);
|
||
const validRPCMetadata = !hasRPCMetadata || (
|
||
['POST', 'PUT'].includes(method) &&
|
||
supportedUploadPath &&
|
||
/^[0-9a-f-]{36}$/.test(correlationID || '') &&
|
||
headers && typeof headers === 'object' && !Array.isArray(headers) &&
|
||
Object.keys(headers).length === 1 &&
|
||
Object.entries(headers).every(([key, value]) => key.toLowerCase() === 'content-type' && typeof value === 'string' && value.length <= 128 && !/[\r\n]/.test(value))
|
||
);
|
||
if (!/^[0-9a-f-]{36}$/.test(id) || !Number.isSafeInteger(size) || size < 1 || size > relayUploadMaxBytes || !Number.isInteger(count) || count < 1 || count > relayMaxChunkCount) {
|
||
return json(res, 400, { error: 'invalid_upload_manifest' });
|
||
}
|
||
if (!validRPCMetadata) return json(res, 400, { error: 'invalid_upload_operation' });
|
||
const key = uploadKey(sessionID, id);
|
||
const existing = relayState.uploads[key];
|
||
if (existing && !existing.acknowledged) {
|
||
if (existing.size !== size || existing.chunkCount !== count || existing.method !== method || existing.path !== uploadPath || existing.correlationID !== correlationID) return json(res, 409, { error: 'upload_manifest_conflict' });
|
||
return json(res, 200, { id, received: Object.keys(existing.chunks).length, complete: existing.complete });
|
||
}
|
||
const reservedBytes = size + count * 28;
|
||
if (relayUsage() + reservedBytes > relayMaxBytes || relayUsage(sessionID) + reservedBytes > relayPairingMaxBytes) return json(res, 507, { error: 'relay_quota_exceeded' });
|
||
const upload = { id, sessionID, size, chunkCount: count, method, path: uploadPath, headers: hasRPCMetadata ? headers : null, correlationID, createdAt: now(), updatedAt: now(), expiresAt: now() + relayTTL, complete: false, acknowledged: false, reservedBytes, 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) {
|
||
if (data.length === 0 || upload.encryptedBytes + data.length > upload.reservedBytes) return json(res, 413, { error: 'relay_upload_size_exceeded' });
|
||
upload.encryptedBytes += data.length;
|
||
try {
|
||
await fs.writeFile(path.join(relayUploadPath(upload), `${index}.bin`), data, { mode: 0o600, flag: 'wx' });
|
||
} catch (error) {
|
||
upload.encryptedBytes -= data.length;
|
||
throw error;
|
||
}
|
||
upload.chunks[index] = { hash: digest, size: 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, method, path, headers, correlationID, createdAt }) => ({ id, size, chunkCount, method, path, headers, correlationID, 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())];
|
||
delete relayState.pushDevices[sessionID];
|
||
delete relayState.pushEvents[sessionID];
|
||
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.pushDevices[session.id];
|
||
delete relayState.pushEvents[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;
|
||
return json(res, status, { error: error.message || 'internal_error' });
|
||
}
|
||
}
|
||
|
||
const server = http.createServer(handle);
|
||
await loadRelayState();
|
||
server.listen(port, host, () => console.log(`AudioRecorder handshake listening on ${host}:${port}`));
|
||
setInterval(() => { purge().catch(error => console.error('Relay cleanup failed:', error)); }, 30_000).unref();
|