Update relay to current MacClient implementation
This commit is contained in:
1 parent
9e49118e8e
commit
a571721d4c
8 files changed
+1062
-33
No files matched your search
+478
-28
@@ -1,7 +1,9 @@
|
||||
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);
|
||||
@@ -18,7 +20,9 @@ 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;
|
||||
// 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;
|
||||
@@ -27,13 +31,19 @@ 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: {}, accounts: {}, invitations: {}, refreshTokens: {}, setupCompleted: false };
|
||||
let relayState = { credentials: {}, uploads: {}, messages: {}, pushDevices: {}, pushEvents: {}, accounts: {}, invitations: {}, refreshTokens: {}, setupCompleted: false };
|
||||
let relayWrite = Promise.resolve();
|
||||
let setupPending = false;
|
||||
|
||||
@@ -78,7 +88,10 @@ function restoreSession(saved) {
|
||||
}
|
||||
|
||||
async function persistRelayState() {
|
||||
relayWrite = relayWrite.then(async () => {
|
||||
// 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 = {
|
||||
@@ -95,7 +108,7 @@ 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 || {}, accounts: saved.accounts || {}, invitations: saved.invitations || {}, refreshTokens: saved.refreshTokens || {}, setupCompleted: saved.setupCompleted === true || Object.keys(saved.accounts || {}).length > 0 };
|
||||
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;
|
||||
@@ -104,9 +117,11 @@ async function loadRelayState() {
|
||||
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('Relay state could not be loaded; check volume permissions and backup integrity.');
|
||||
if (error.code !== 'ENOENT') console.error('Could not load relay state:', error);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -116,8 +131,65 @@ function relaySession(req, sessionID) {
|
||||
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;
|
||||
@@ -307,15 +379,64 @@ function clientIP(req) {
|
||||
}
|
||||
|
||||
function rateLimit(req, res) {
|
||||
const key = clientIP(req);
|
||||
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);
|
||||
// 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' });
|
||||
// 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);
|
||||
@@ -387,6 +508,68 @@ async function verifyPassword(password, account) {
|
||||
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');
|
||||
@@ -421,6 +604,8 @@ async function purge() {
|
||||
sessions.delete(id);
|
||||
offers.delete(id);
|
||||
delete relayState.credentials[hash(session.relayToken)];
|
||||
delete relayState.pushDevices[id];
|
||||
delete relayState.pushEvents[id];
|
||||
sessionsChanged = true;
|
||||
}
|
||||
}
|
||||
@@ -453,6 +638,169 @@ async function handle(req, res) {
|
||||
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' });
|
||||
@@ -579,6 +927,7 @@ async function handle(req, res) {
|
||||
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 });
|
||||
@@ -673,6 +1022,68 @@ async function handle(req, res) {
|
||||
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);
|
||||
@@ -680,14 +1091,15 @@ async function handle(req, res) {
|
||||
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' });
|
||||
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 });
|
||||
}
|
||||
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: {} };
|
||||
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();
|
||||
@@ -712,9 +1124,17 @@ async function handle(req, res) {
|
||||
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 };
|
||||
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;
|
||||
@@ -752,17 +1172,38 @@ async function handle(req, res) {
|
||||
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) {
|
||||
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) return json(res, 409, { error: 'upload_manifest_conflict' });
|
||||
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 });
|
||||
}
|
||||
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: {} };
|
||||
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();
|
||||
@@ -779,9 +1220,15 @@ async function handle(req, res) {
|
||||
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 };
|
||||
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;
|
||||
@@ -819,10 +1266,12 @@ async function handle(req, res) {
|
||||
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() })) });
|
||||
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();
|
||||
@@ -905,6 +1354,8 @@ async function handle(req, res) {
|
||||
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);
|
||||
@@ -915,12 +1366,11 @@ async function handle(req, res) {
|
||||
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;
|
||||
const safeError = status === 413 ? (error.message === 'relay_chunk_too_large' ? 'relay_chunk_too_large' : 'request_too_large') : status === 400 ? 'invalid_json' : 'internal_error';
|
||||
return json(res, status, { error: safeError });
|
||||
return json(res, status, { error: error.message || 'internal_error' });
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer(handle);
|
||||
await loadRelayState();
|
||||
server.listen(port, host, () => console.log(`Meets Relay listening on ${host}:${port}`));
|
||||
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();
|
||||
Reference in new issue
Block a user