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
+5
-4
@@ -1,6 +1,7 @@
|
||||
# Hostname configured by your own reverse proxy and DNS.
|
||||
# Path to a private, one-time administrator setup-code file.
|
||||
RELAY_SETUP_CODE_FILE=./secrets/relay-setup-code
|
||||
|
||||
# Separately operated TURN service. No TURN host or secret is bundled.
|
||||
TURN_HOST=turn.example.net
|
||||
TURN_PORT=3478
|
||||
|
||||
# Use a long random secret shared with your TURN server.
|
||||
TURN_SHARED_SECRET=replace-with-a-random-secret
|
||||
TURN_SHARED_SECRET=replace-with-a-long-random-secret
|
||||
@@ -1,62 +1,56 @@
|
||||
# Meets Relay
|
||||
|
||||
Self-hostable encrypted relay service for Meets pairing and synchronization. The service stores pairing metadata and encrypted transfer chunks; application data is encrypted by the clients before it reaches this server.
|
||||
Self-hostable relay for pairing and synchronization between the Meets Mac backend and its paired iPhone app. Recording content and RPC payloads are end-to-end encrypted by the clients before transfer. The relay stores encrypted chunks and the metadata required to route them.
|
||||
|
||||
## Docker Compose
|
||||
## Requirements and network setup
|
||||
|
||||
Requirements: Docker Compose, a public HTTPS URL configured by the operator's reverse proxy, and a separately operated TURN server for networks where direct WebRTC connectivity is unavailable. The reverse proxy, DNS, TLS certificate, firewall and TURN service are intentionally outside this project.
|
||||
- Docker Engine with Docker Compose v2.
|
||||
- A public HTTPS hostname configured by you in a reverse proxy.
|
||||
- A TURN service you operate separately if your network requires TURN.
|
||||
|
||||
Copy `.env.example` to `.env`, set your TURN hostname and port, and create a unique shared secret that matches your TURN service (for example, `openssl rand -hex 32`). Keep `.env` private; it is ignored by Git.
|
||||
DNS, TLS certificates, reverse proxy, firewall rules, and TURN are deliberately outside this project. The container listens on loopback by default. Do not expose its HTTP port directly to the internet.
|
||||
|
||||
```yaml
|
||||
services:
|
||||
meets-relay:
|
||||
image: git.maddin.app/maddin/meets-relay:latest
|
||||
restart: unless-stopped
|
||||
env_file: [.env]
|
||||
read_only: true
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cap_drop: [ALL]
|
||||
pids_limit: 64
|
||||
mem_limit: 512m
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
environment:
|
||||
PORT: "8080"
|
||||
RELAY_DATA_DIR: /data/relay
|
||||
RELAY_MAX_BYTES: "10737418240"
|
||||
RELAY_PAIRING_MAX_BYTES: "1073741824"
|
||||
RELAY_TTL_SECONDS: "604800"
|
||||
RELAY_INCOMPLETE_TTL_SECONDS: "86400"
|
||||
volumes:
|
||||
- relay_data:/data/relay
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,size=16m
|
||||
## First start
|
||||
|
||||
volumes:
|
||||
relay_data:
|
||||
```
|
||||
1. Create a private deployment directory and copy `.env.example` to `.env`.
|
||||
2. Set `TURN_HOST`, `TURN_PORT`, `TURN_SHARED_SECRET`, and `RELAY_SETUP_CODE_FILE` in `.env`. The TURN secret must match the separately operated TURN service.
|
||||
3. Create the one-time administrator setup code outside the repository:
|
||||
|
||||
Set a reverse-proxy route from your own HTTPS hostname to `127.0.0.1:8080`. Configure that HTTPS base URL in the Meets Mac app before generating a new pairing QR code. Existing pairings retain their relay address.
|
||||
```sh
|
||||
mkdir -p secrets
|
||||
openssl rand -base64 32 > secrets/relay-setup-code
|
||||
chmod 600 secrets/relay-setup-code
|
||||
```
|
||||
|
||||
The default quotas above cap stored data at 10 GiB total and 1 GiB per pairing. Choose values appropriate for your host. Completed transfers expire after seven days; incomplete transfers expire after one day. Pairings expire after 30 days without a heartbeat. Keep the named volume in backups if you need to retain pairings across host replacement.
|
||||
Set `RELAY_SETUP_CODE_FILE=./secrets/relay-setup-code`. Keep this file private and back it up securely until the first administrator account is created. The Docker daemon must be able to read it.
|
||||
4. Start the service with `docker compose up -d`.
|
||||
5. In the Meets app, enter your own HTTPS relay URL. Create the first administrator account using the setup code. The setup code is one-use; after account creation, setup is permanently disabled.
|
||||
|
||||
The administrator can create time-limited, one-use invitations for other people and revoke member accounts. There is no open registration. Accounts control who can create and claim pairings on this relay. Each pairing remains cryptographically isolated by its own random pairing secret.
|
||||
|
||||
## Compose deployment
|
||||
|
||||
The supplied Compose file uses a read-only root filesystem, an unprivileged container user, no Linux capabilities, a process limit, a memory limit, and a private named volume. Only the relay data volume and a small temporary filesystem are writable. Edit resource limits to suit your host, while retaining the other restrictions.
|
||||
|
||||
The default relay quotas are 10 GiB total and 1 GiB per pairing. Completed transfers expire after seven days; incomplete transfers expire after one day. Pairings expire after 30 days without a heartbeat. The named volume contains account and pairing state plus encrypted transfer data. Back it up securely if you need to preserve pairings across host replacement.
|
||||
|
||||
Set your reverse proxy to forward your HTTPS hostname to `127.0.0.1:8080`. Configure that same HTTPS base URL in the Mac app before creating new pairings. Existing pairings keep the relay address embedded when they were created.
|
||||
|
||||
## Security and privacy
|
||||
|
||||
- HTTPS must be terminated by the operator's reverse proxy. Keep the container port bound to loopback unless the host firewall and TLS termination are configured deliberately.
|
||||
- Transfer chunks are end-to-end encrypted by the clients. The relay cannot decrypt recording content.
|
||||
- The relay does not provide push notifications and does not accept or store APNs device tokens.
|
||||
- The relay does not run a TURN server. WebRTC signaling remains available for connection setup; configure `TURN_HOST`, `TURN_PORT` and `TURN_SHARED_SECRET` for a separately operated TURN service. The relay itself does not route or decrypt WebRTC media. Direct or STUN-only connections may work without TURN depending on the network.
|
||||
- The image runs as an unprivileged user, with a read-only root filesystem, no Linux capabilities and only `/data/relay` writable.
|
||||
- Do not expose the health or API endpoints through a proxy that adds caching. Configure `Cache-Control: no-store` for API traffic.
|
||||
- This service has no administrator account or remote shell. Restrict Docker access on the host; Docker administration is equivalent to host root.
|
||||
- Transfer chunks are end-to-end encrypted. The relay cannot decrypt recordings, transcripts, notes, or RPC content. It can observe traffic metadata such as pairing identifiers, sizes, chunk counts, and timestamps.
|
||||
- Self-hosted deployments do not enable or configure push notifications and do not accept or persist APNs device registrations.
|
||||
- The relay does not contain a TURN server. Configure the hostname, port, and shared secret of a separately operated TURN service. Depending on the network, direct or STUN-only connectivity may work without TURN.
|
||||
- The relay HTTP API must be protected by HTTPS at your reverse proxy. Keep the container port bound to loopback. Disable proxy caching for API routes.
|
||||
- Account passwords are stored as scrypt hashes with individual salts. Refresh tokens are stored hashed. Setup, login, invitations, and other sensitive operations are rate limited.
|
||||
- The administrator setup code is read from a Docker secret, not an environment value. Do not put it in source control or logs.
|
||||
- Docker host access is equivalent to host administrator access. Restrict membership in the Docker administration group.
|
||||
|
||||
## Operations
|
||||
|
||||
Health check: `GET /health`. Logs contain operational errors only. The relay does not log request bodies, authorization headers, pairing secrets or recording contents.
|
||||
`GET /health` provides a health check. The service does not log request bodies, authorization headers, setup codes, pairing secrets, or recording content.
|
||||
|
||||
Build locally with `docker compose build`; run with `docker compose up -d`. To update, pull the selected image tag and recreate the service. Pin a version tag or image digest for reproducible deployments.
|
||||
Run `docker compose up -d`; update with `docker compose pull && docker compose up -d`. Pin a version tag or image digest for reproducible deployments. To build and publish a multi-architecture image, use `scripts/publish-image.sh <version-tag>` after configuring access to the image registry and Docker Buildx.
|
||||
|
||||
## License
|
||||
|
||||
|
||||
+9
-4
@@ -1,7 +1,7 @@
|
||||
services:
|
||||
meets-relay:
|
||||
build: .
|
||||
image: git.maddin.app/maddin/meets-relay:latest
|
||||
build: .
|
||||
restart: unless-stopped
|
||||
env_file:
|
||||
- .env
|
||||
@@ -15,18 +15,23 @@ services:
|
||||
- "127.0.0.1:8080:8080"
|
||||
environment:
|
||||
PORT: "8080"
|
||||
RELAY_SETUP_CODE_FILE: /run/secrets/relay_setup_code
|
||||
INVITATION_TTL_SECONDS: "86400"
|
||||
RELAY_DATA_DIR: /data/relay
|
||||
RELAY_MAX_BYTES: "10737418240"
|
||||
RELAY_PAIRING_MAX_BYTES: "1073741824"
|
||||
RELAY_TTL_SECONDS: "604800"
|
||||
RELAY_INCOMPLETE_TTL_SECONDS: "86400"
|
||||
TURN_HOST: "${TURN_HOST:?Set TURN_HOST to the hostname of your separately operated TURN service}"
|
||||
TURN_PORT: "${TURN_PORT:-3478}"
|
||||
TURN_SHARED_SECRET: "${TURN_SHARED_SECRET:?Set TURN_SHARED_SECRET for your TURN service}"
|
||||
volumes:
|
||||
- relay_data:/data/relay
|
||||
secrets:
|
||||
- relay_setup_code
|
||||
tmpfs:
|
||||
- /tmp:rw,noexec,nosuid,size=16m
|
||||
|
||||
volumes:
|
||||
relay_data:
|
||||
|
||||
secrets:
|
||||
relay_setup_code:
|
||||
file: ${RELAY_SETUP_CODE_FILE:?Set RELAY_SETUP_CODE_FILE to a private one-time setup-code file}
|
||||
+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();
|
||||
+44
-8
@@ -1,7 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdtemp, readFile, rm } from 'node:fs/promises';
|
||||
import { mkdtemp, readFile, rm, writeFile } from 'node:fs/promises';
|
||||
import crypto from 'node:crypto';
|
||||
import net from 'node:net';
|
||||
import os from 'node:os';
|
||||
@@ -12,11 +12,13 @@ const serverPath = fileURLToPath(new URL('./server.mjs', import.meta.url));
|
||||
|
||||
test('relay persists opaque chunks, acknowledges and revokes pairings', async t => {
|
||||
const dataDir = await mkdtemp(path.join(os.tmpdir(), 'audiorecorder-relay-'));
|
||||
const setupCodeFile = path.join(dataDir, 'setup-code');
|
||||
await writeFile(setupCodeFile, 'test-one-time-setup-code', { mode: 0o600 });
|
||||
const probe = net.createServer();
|
||||
await new Promise(resolve => probe.listen(0, '127.0.0.1', resolve));
|
||||
const port = probe.address().port;
|
||||
await new Promise(resolve => probe.close(resolve));
|
||||
const env = { ...process.env, PORT: String(port), HOST: '127.0.0.1', RELAY_DATA_DIR: dataDir, TURN_HOST: '127.0.0.1', TURN_PORT: '3478', TURN_SHARED_SECRET: 'test-only' };
|
||||
const env = { ...process.env, PORT: String(port), HOST: '127.0.0.1', RELAY_DATA_DIR: dataDir, RELAY_SETUP_CODE_FILE: setupCodeFile, TURN_HOST: 'turn.test.invalid', TURN_PORT: '3478', TURN_SHARED_SECRET: 'test-only', APNS_ENABLED: 'false' };
|
||||
let child;
|
||||
const start = async () => {
|
||||
child = spawn(process.execPath, [serverPath], { env, stdio: 'ignore' });
|
||||
@@ -41,10 +43,34 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
|
||||
t.after(async () => { await stop(); await rm(dataDir, { recursive: true, force: true }); });
|
||||
await start();
|
||||
const base = `http://127.0.0.1:${port}`;
|
||||
const setupResponses = await Promise.all([
|
||||
postJSON(`${base}/api/v1/auth/setup`, { setupCode: 'test-one-time-setup-code', username: 'owner', password: 'correct-horse-battery' }),
|
||||
postJSON(`${base}/api/v1/auth/setup`, { setupCode: 'test-one-time-setup-code', username: 'attacker', password: 'correct-horse-battery' })
|
||||
]);
|
||||
assert.deepEqual(setupResponses.map(response => response.status).sort(), [201, 409]);
|
||||
const setupResponse = setupResponses.find(response => response.status === 201);
|
||||
const owner = await setupResponse.json();
|
||||
assert.equal(owner.account.role, 'admin');
|
||||
const repeatedSetup = await postJSON(`${base}/api/v1/auth/setup`, { setupCode: 'test-one-time-setup-code', username: 'attacker', password: 'correct-horse-battery' });
|
||||
assert.equal(repeatedSetup.status, 409);
|
||||
const unauthorizedOffer = await postJSON(`${base}/api/v1/pairing/offers`, { protocolVersion: 2, secretHash: 'a'.repeat(64), publicKey: 'mac-key', identityKey: 'mac-identity' });
|
||||
assert.equal(unauthorizedOffer.status, 401);
|
||||
const invitationResponse = await postJSON(`${base}/api/v1/admin/invitations`, {}, owner.accessToken);
|
||||
assert.equal(invitationResponse.status, 201);
|
||||
const invitation = await invitationResponse.json();
|
||||
const memberResponses = await Promise.all([
|
||||
postJSON(`${base}/api/v1/auth/redeem`, { invitationCode: invitation.code, username: 'member', password: 'another-correct-password' }),
|
||||
postJSON(`${base}/api/v1/auth/redeem`, { invitationCode: invitation.code, username: 'member2', password: 'another-correct-password' })
|
||||
]);
|
||||
assert.deepEqual(memberResponses.map(response => response.status).sort(), [201, 401]);
|
||||
const memberResponse = memberResponses.find(response => response.status === 201);
|
||||
assert.equal((await memberResponse.json()).account.role, 'member');
|
||||
const repeatedInvitation = await postJSON(`${base}/api/v1/auth/redeem`, { invitationCode: invitation.code, username: 'member2', password: 'another-correct-password' });
|
||||
assert.equal(repeatedInvitation.status, 401);
|
||||
const secretHash = crypto.createHash('sha256').update('test-pairing-secret').digest('hex');
|
||||
const legacyOffer = await postJSON(`${base}/api/v1/pairing/offers`, { secretHash, publicKey: 'mac-key', identityKey: 'mac-identity' });
|
||||
const legacyOffer = await postJSON(`${base}/api/v1/pairing/offers`, { secretHash, publicKey: 'mac-key', identityKey: 'mac-identity' }, owner.accessToken);
|
||||
assert.equal(legacyOffer.status, 426);
|
||||
const offerResponse = await postJSON(`${base}/api/v1/pairing/offers`, { protocolVersion: 2, secretHash, publicKey: 'mac-key', identityKey: 'mac-identity', directEndpoints: ['http://192.168.1.2:8787'] });
|
||||
const offerResponse = await postJSON(`${base}/api/v1/pairing/offers`, { protocolVersion: 2, secretHash, publicKey: 'mac-key', identityKey: 'mac-identity', directEndpoints: ['http://192.168.1.2:8787'] }, owner.accessToken);
|
||||
assert.equal(offerResponse.status, 201);
|
||||
const offer = await offerResponse.json();
|
||||
assert.deepEqual(offer.public.directEndpoints, []);
|
||||
@@ -63,10 +89,20 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
|
||||
assert.equal((await claimedOffer.json()).sessionToken, claim.sessionToken);
|
||||
|
||||
const sessionPath = `${base}/api/v1/pairing/sessions/${offer.id}`;
|
||||
const forbiddenPush = await fetch(`${base}/api/v1/relay/sessions/${offer.id}/push-devices`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.equal(forbiddenPush.status, 404);
|
||||
const forbiddenNotification = await postJSON(`${base}/api/v1/relay/sessions/${offer.id}/notifications`, { eventID: crypto.randomUUID(), eventType: 'completed', recordingID: crypto.randomUUID() }, claim.relayToken);
|
||||
assert.equal(forbiddenNotification.status, 404);
|
||||
const pushPath = `${base}/api/v1/relay/sessions/${offer.id}/push-devices`;
|
||||
const unauthenticatedPushStatus = await fetch(pushPath);
|
||||
assert.equal(unauthenticatedPushStatus.status, 401);
|
||||
const pushStatus = await fetch(pushPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||
assert.equal(pushStatus.status, 404);
|
||||
const deviceToken = 'ab'.repeat(32);
|
||||
const pushRegistration = await postJSON(pushPath, { token: deviceToken, environment: 'production', bundleID: 'com.example.Meets' }, claim.relayToken);
|
||||
assert.equal(pushRegistration.status, 404);
|
||||
const persistedPushState = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
|
||||
assert.deepEqual(persistedPushState.pushDevices || {}, {});
|
||||
const malformedNotification = await postJSON(`${base}/api/v1/relay/sessions/${offer.id}/notifications`, { eventID: 'bad', eventType: 'completed' }, claim.relayToken);
|
||||
assert.equal(malformedNotification.status, 404);
|
||||
const unavailableNotification = await postJSON(`${base}/api/v1/relay/sessions/${offer.id}/notifications`, { eventID: crypto.randomUUID(), eventType: 'completed', recordingID: crypto.randomUUID() }, claim.relayToken);
|
||||
assert.equal(unavailableNotification.status, 404);
|
||||
const legacyHeartbeat = await postJSON(`${sessionPath}/heartbeat`, { side: 'client' }, claim.sessionToken);
|
||||
assert.equal(legacyHeartbeat.status, 426);
|
||||
const heartbeat = await postJSON(`${sessionPath}/heartbeat`, { protocolVersion: 2, side: 'client', directEndpoints: ['http://192.168.1.2:8787'] }, claim.sessionToken);
|
||||
|
||||
Reference in new issue
Block a user