Add relay account access control
This commit is contained in:
1 parent
17342f9457
commit
9e49118e8e
5 files changed
+306
-66
No files matched your search
+211
-7
@@ -2,6 +2,7 @@ import http from 'node:http';
|
||||
import crypto from 'node:crypto';
|
||||
import fs from 'node:fs/promises';
|
||||
import path from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
|
||||
const port = Number(process.env.PORT || 8080);
|
||||
const host = process.env.HOST || '0.0.0.0';
|
||||
@@ -21,12 +22,20 @@ const relayUploadMaxBytes = 350 * 1024 * 1024;
|
||||
const relayChunkMaxBytes = 4 * 1024 * 1024 + 64;
|
||||
const relayTTL = Number(process.env.RELAY_TTL_SECONDS || 604800) * 1000;
|
||||
const relayIncompleteTTL = Number(process.env.RELAY_INCOMPLETE_TTL_SECONDS || 86400) * 1000;
|
||||
const 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 offers = new Map();
|
||||
const sessions = new Map();
|
||||
const rateBuckets = new Map();
|
||||
const loginBuckets = new Map();
|
||||
const accountAccessTokens = new Map();
|
||||
const relayWaiters = new Map();
|
||||
let relayState = { credentials: {}, uploads: {}, messages: {} };
|
||||
let relayState = { credentials: {}, uploads: {}, messages: {}, 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'))
|
||||
@@ -44,7 +53,8 @@ function persistentSession(session) {
|
||||
offer: session.offer,
|
||||
lastMacHeartbeat: session.lastMacHeartbeat,
|
||||
lastClientHeartbeat: session.lastClientHeartbeat,
|
||||
expiresAt: session.expiresAt
|
||||
expiresAt: session.expiresAt,
|
||||
accountID: session.accountID || null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -62,7 +72,8 @@ function restoreSession(saved) {
|
||||
signals: [],
|
||||
lastSignalID: 0,
|
||||
signalMessageIDs: new Set(),
|
||||
generationID: null
|
||||
generationID: null,
|
||||
accountID: saved.accountID || null
|
||||
};
|
||||
}
|
||||
|
||||
@@ -84,14 +95,16 @@ 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 || {} };
|
||||
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 };
|
||||
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;
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') console.error('Relay state could not be loaded; check volume permissions and backup integrity.');
|
||||
}
|
||||
@@ -103,6 +116,8 @@ function relaySession(req, sessionID) {
|
||||
return relayState.credentials[hash(supplied)] === sessionID;
|
||||
}
|
||||
|
||||
function base64url(value) { return Buffer.from(value).toString('base64url'); }
|
||||
|
||||
function readBinary(req, limit = relayChunkMaxBytes) {
|
||||
return new Promise((resolve, reject) => {
|
||||
let size = 0;
|
||||
@@ -336,6 +351,61 @@ function authSession(req, session) {
|
||||
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 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;
|
||||
@@ -383,7 +453,139 @@ 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 === '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)];
|
||||
}
|
||||
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);
|
||||
@@ -400,6 +602,7 @@ async function handle(req, res) {
|
||||
macIdentityKey: identityKey,
|
||||
bootstrap: cleanText(body.bootstrap, 120 * 1024) || null,
|
||||
protocolVersion: 2,
|
||||
accountID: account.id,
|
||||
directEndpoints: [],
|
||||
description: cleanDescription(body.description),
|
||||
candidates: cleanCandidates(body.candidates),
|
||||
@@ -436,6 +639,7 @@ async function handle(req, res) {
|
||||
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(),
|
||||
@@ -711,12 +915,12 @@ 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;
|
||||
if (status === 500) console.error('Relay request failed unexpectedly.');
|
||||
return json(res, status, { error: status === 500 ? 'internal_error' : error.message });
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
const server = http.createServer(handle);
|
||||
await loadRelayState();
|
||||
server.listen(port, host, () => console.log(`Meets Relay listening on ${host}:${port}`));
|
||||
setInterval(() => { purge().catch(() => console.error('Relay cleanup failed.')); }, 30_000).unref();
|
||||
setInterval(() => { purge().catch(error => console.error('Relay cleanup failed:', error)); }, 30_000).unref();
|
||||
Reference in new issue
Block a user