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
@@ -2,6 +2,7 @@ FROM node:24-alpine
|
|||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production PORT=8080 HOST=0.0.0.0 RELAY_DATA_DIR=/data/relay
|
ENV NODE_ENV=production PORT=8080 HOST=0.0.0.0 RELAY_DATA_DIR=/data/relay
|
||||||
COPY --chown=node:node package.json server.mjs ./
|
COPY --chown=node:node package.json server.mjs ./
|
||||||
|
COPY --chown=node:node public ./public
|
||||||
RUN mkdir -p /data/relay && chown node:node /data/relay
|
RUN mkdir -p /data/relay && chown node:node /data/relay
|
||||||
USER node
|
USER node
|
||||||
EXPOSE 8080
|
EXPOSE 8080
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
# Meets Relay
|
# Meets Relay
|
||||||
|
|
||||||
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.
|
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. The service also serves its same-origin browser account interface from `/`.
|
||||||
|
|
||||||
## Requirements and network setup
|
## Requirements and network setup
|
||||||
|
|
||||||
@@ -32,14 +32,14 @@ The administrator can create time-limited, one-use invitations for other people
|
|||||||
|
|
||||||
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 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.
|
The default relay quotas are 10 GiB total and 1 GiB per pairing. Audio transfers support up to 500 MiB of payload, carried in bounded encrypted chunks. 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.
|
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
|
## Security and privacy
|
||||||
|
|
||||||
- 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.
|
- 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.
|
- Optional APNs support is disabled by default. If enabled, provide its private key through a server-side secret file; never commit provider credentials. Push events contain only the event type and recording ID, not recording content.
|
||||||
- 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 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.
|
- 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.
|
- 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.
|
||||||
|
|||||||
@@ -22,12 +22,18 @@ services:
|
|||||||
RELAY_PAIRING_MAX_BYTES: "1073741824"
|
RELAY_PAIRING_MAX_BYTES: "1073741824"
|
||||||
RELAY_TTL_SECONDS: "604800"
|
RELAY_TTL_SECONDS: "604800"
|
||||||
RELAY_INCOMPLETE_TTL_SECONDS: "86400"
|
RELAY_INCOMPLETE_TTL_SECONDS: "86400"
|
||||||
|
SESSION_TTL_SECONDS: "2592000"
|
||||||
volumes:
|
volumes:
|
||||||
- relay_data:/data/relay
|
- relay_data:/data/relay
|
||||||
secrets:
|
secrets:
|
||||||
- relay_setup_code
|
- relay_setup_code
|
||||||
tmpfs:
|
tmpfs:
|
||||||
- /tmp:rw,noexec,nosuid,size=16m
|
- /tmp:rw,noexec,nosuid,size=16m
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD", "node", "-e", "fetch('http://127.0.0.1:8080/health').then(r => { if (!r.ok) process.exit(1) }).catch(() => process.exit(1))"]
|
||||||
|
interval: 30s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 3
|
||||||
|
|
||||||
volumes:
|
volumes:
|
||||||
relay_data:
|
relay_data:
|
||||||
|
|||||||
+272
@@ -0,0 +1,272 @@
|
|||||||
|
const translations = {
|
||||||
|
de: {
|
||||||
|
secureRelay: 'Sicheres Relay', privateByDesign: 'PRIVAT DURCH DESIGN', title: 'Dein Relay. Deine Verbindung.',
|
||||||
|
intro: 'Verwalte den Zugang zu deinem Meets Relay. Aufnahmen und Transkripte werden hier nicht gespeichert.',
|
||||||
|
signOut: 'Abmelden', signIn: 'Anmelden', invitation: 'Einladung', firstSetup: 'Ersteinrichtung',
|
||||||
|
setupCode: 'Einrichtungscode', inviteCode: 'Einladungscode', username: 'Benutzername', password: 'Passwort',
|
||||||
|
macSetup: 'MAC-EINRICHTUNG', authorizeMac: 'Mac mit Relay verbinden?',
|
||||||
|
authorizeDescription: 'Nach deiner Bestätigung erhält die Meets-App auf diesem Mac eine Relay-Berechtigung. Das Browserfenster gibt keine Zugangstoken weiter.',
|
||||||
|
authorize: 'Mac autorisieren', returnMac: 'Zur Meets-App wechseln', adminConsole: 'RELAY-KONTO', pendingMac: 'Mac wartet auf Freigabe',
|
||||||
|
accounts: 'Konten', accountsHint: 'Mitglieder mit Relay-Zugang', invitations: 'Einladungen',
|
||||||
|
invitationsHint: 'Einmal-Codes laufen nach 24 Stunden ab.', createInvitation: 'Einladung erstellen',
|
||||||
|
footerPrivacy: 'Das Relay leitet ausschließlich Ende-zu-Ende-verschlüsselte Daten weiter.', sourceCode: 'Quellcode',
|
||||||
|
loginTitle: 'Am Relay anmelden', loginDescription: 'Melde dich mit deinem Relay-Konto an.',
|
||||||
|
setupTitle: 'Relay einrichten', setupDescription: 'Erstelle das erste Administratorkonto mit dem privaten Einrichtungscode des Servers.',
|
||||||
|
redeemTitle: 'Einladung annehmen', redeemDescription: 'Erstelle mit deinem einmaligen Einladungscode ein Relay-Konto.',
|
||||||
|
invalidCredentials: 'Anmeldung fehlgeschlagen. Prüfe Benutzername und Passwort.', setupDone: 'Die Ersteinrichtung wurde bereits abgeschlossen.',
|
||||||
|
setupUnavailable: 'Der Einrichtungscode ist auf diesem Server nicht konfiguriert.', invalidSetup: 'Der Einrichtungscode ist ungültig.',
|
||||||
|
invalidInvite: 'Der Einladungscode ist ungültig, abgelaufen oder bereits verwendet.', invalidAccount: 'Benutzername oder Passwort entspricht nicht den Vorgaben. Das Passwort muss mindestens 12 Zeichen haben.',
|
||||||
|
loggedIn: 'Angemeldet.', loggedOut: 'Abgemeldet.', sessionExpired: 'Sitzung abgelaufen. Bitte erneut anmelden.',
|
||||||
|
noAccount: 'Unbekanntes Konto', admin: 'Administrator', member: 'Mitglied', revoke: 'Entziehen',
|
||||||
|
noAccounts: 'Keine weiteren Konten.', noInvitations: 'Keine offenen Einladungen.', used: 'verwendet',
|
||||||
|
expires: 'Läuft ab', invitationCreated: 'Einladung erstellt. Teile diesen Code nur mit der eingeladenen Person:',
|
||||||
|
revokeConfirm: 'Zugang für dieses Konto entziehen? Zugehörige Pairings werden ebenfalls beendet.',
|
||||||
|
revokeInviteConfirm: 'Diese Einladung widerrufen?',
|
||||||
|
deviceInvalid: 'Der Code ist ungültig oder abgelaufen. Starte die Relay-Anmeldung in der Mac-App erneut.',
|
||||||
|
deviceAuthorized: 'Mac wurde autorisiert. Wechsle zurück zur Meets-App.', deviceFailed: 'Die Freigabe konnte nicht abgeschlossen werden.',
|
||||||
|
loginFirst: 'Melde dich zuerst mit deinem Relay-Konto an.', devicePending: 'Bestätige die Anmeldung für diesen Mac.',
|
||||||
|
setupCodeRequired: 'Der private Einrichtungscode wird benötigt.', invitationRequired: 'Der Einladungscode wird benötigt.',
|
||||||
|
currentAccount: 'Du kannst das gerade verwendete Konto nicht selbst entziehen.', loadError: 'Daten konnten nicht geladen werden.'
|
||||||
|
},
|
||||||
|
en: {
|
||||||
|
secureRelay: 'Secure relay', privateByDesign: 'PRIVATE BY DESIGN', title: 'Your relay. Your connection.',
|
||||||
|
intro: 'Manage access to your Meets Relay. Recordings and transcripts are never stored here.',
|
||||||
|
signOut: 'Sign out', signIn: 'Sign in', invitation: 'Invitation', firstSetup: 'Initial setup',
|
||||||
|
setupCode: 'Setup code', inviteCode: 'Invitation code', username: 'Username', password: 'Password',
|
||||||
|
macSetup: 'MAC SETUP', authorizeMac: 'Connect this Mac to the relay?',
|
||||||
|
authorizeDescription: 'After you approve, Meets on this Mac receives relay access. The browser never sends access tokens to the app.',
|
||||||
|
authorize: 'Authorize Mac', returnMac: 'Return to Meets', adminConsole: 'RELAY ACCOUNT', pendingMac: 'Mac waiting for approval',
|
||||||
|
accounts: 'Accounts', accountsHint: 'Members with relay access', invitations: 'Invitations',
|
||||||
|
invitationsHint: 'One-time codes expire after 24 hours.', createInvitation: 'Create invitation',
|
||||||
|
footerPrivacy: 'The relay forwards end-to-end encrypted data only.', sourceCode: 'Source code',
|
||||||
|
loginTitle: 'Sign in to the relay', loginDescription: 'Sign in with your relay account.',
|
||||||
|
setupTitle: 'Set up the relay', setupDescription: 'Create the first administrator account using the server’s private setup code.',
|
||||||
|
redeemTitle: 'Accept invitation', redeemDescription: 'Create a relay account with your one-time invitation code.',
|
||||||
|
invalidCredentials: 'Sign-in failed. Check your username and password.', setupDone: 'Initial setup has already been completed.',
|
||||||
|
setupUnavailable: 'The setup code is not configured on this server.', invalidSetup: 'The setup code is invalid.',
|
||||||
|
invalidInvite: 'The invitation code is invalid, expired, or already used.', invalidAccount: 'The username or password does not meet the requirements. Passwords need at least 12 characters.',
|
||||||
|
loggedIn: 'Signed in.', loggedOut: 'Signed out.', sessionExpired: 'Session expired. Please sign in again.',
|
||||||
|
noAccount: 'Unknown account', admin: 'Administrator', member: 'Member', revoke: 'Revoke',
|
||||||
|
noAccounts: 'No other accounts.', noInvitations: 'No open invitations.', used: 'used',
|
||||||
|
expires: 'Expires', invitationCreated: 'Invitation created. Share this code only with the invited person:',
|
||||||
|
revokeConfirm: 'Revoke access for this account? Its pairings will also be ended.',
|
||||||
|
revokeInviteConfirm: 'Revoke this invitation?',
|
||||||
|
deviceInvalid: 'The code is invalid or expired. Restart relay sign-in in the Mac app.',
|
||||||
|
deviceAuthorized: 'Mac authorized. Return to Meets.', deviceFailed: 'Authorization could not be completed.',
|
||||||
|
loginFirst: 'Sign in to your relay account first.', devicePending: 'Approve the sign-in for this Mac.',
|
||||||
|
setupCodeRequired: 'The private setup code is required.', invitationRequired: 'The invitation code is required.',
|
||||||
|
currentAccount: 'You cannot revoke the account currently in use.', loadError: 'Could not load data.'
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
let language = localStorage.getItem('meets-relay-language') || (navigator.language.toLowerCase().startsWith('de') ? 'de' : 'en');
|
||||||
|
let mode = 'login';
|
||||||
|
let account = null;
|
||||||
|
let deviceCode = '';
|
||||||
|
let callbackState = '';
|
||||||
|
const t = key => translations[language][key] || key;
|
||||||
|
const $ = selector => document.querySelector(selector);
|
||||||
|
const escapeText = value => String(value ?? '').replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);
|
||||||
|
|
||||||
|
function setLanguage(next) {
|
||||||
|
language = next;
|
||||||
|
localStorage.setItem('meets-relay-language', language);
|
||||||
|
document.documentElement.lang = language;
|
||||||
|
document.querySelectorAll('[data-i18n]').forEach(node => { node.textContent = t(node.dataset.i18n); });
|
||||||
|
$('#language').textContent = language === 'de' ? 'DE / EN' : 'EN / DE';
|
||||||
|
updateAuthMode();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function api(path, options = {}) {
|
||||||
|
const response = await fetch(path, {
|
||||||
|
credentials: 'same-origin', cache: 'no-store',
|
||||||
|
...options,
|
||||||
|
headers: { ...(options.body ? { 'content-type': 'application/json' } : {}), ...(options.headers || {}) },
|
||||||
|
body: options.body ? JSON.stringify(options.body) : undefined
|
||||||
|
});
|
||||||
|
const body = await response.json().catch(() => ({}));
|
||||||
|
if (!response.ok) throw Object.assign(new Error(body.error || 'request_failed'), { status: response.status });
|
||||||
|
return body;
|
||||||
|
}
|
||||||
|
|
||||||
|
function showMessage(element, message, isError = false) {
|
||||||
|
element.textContent = message || '';
|
||||||
|
element.classList.toggle('error', isError);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateAuthMode() {
|
||||||
|
const title = mode === 'setup' ? 'setupTitle' : mode === 'redeem' ? 'redeemTitle' : 'loginTitle';
|
||||||
|
const description = mode === 'setup' ? 'setupDescription' : mode === 'redeem' ? 'redeemDescription' : 'loginDescription';
|
||||||
|
$('#auth-title').textContent = t(title);
|
||||||
|
$('#auth-description').textContent = t(description);
|
||||||
|
$('#auth-submit').textContent = t(mode === 'setup' ? 'firstSetup' : mode === 'redeem' ? 'invitation' : 'signIn');
|
||||||
|
$('#setup-code-wrap').classList.toggle('hidden', mode !== 'setup');
|
||||||
|
$('#invite-code-wrap').classList.toggle('hidden', mode !== 'redeem');
|
||||||
|
$('#auth-form').elements.password.autocomplete = mode === 'login' ? 'current-password' : 'new-password';
|
||||||
|
document.querySelectorAll('.auth-tabs button').forEach(button => button.classList.toggle('active', button.dataset.mode === mode));
|
||||||
|
}
|
||||||
|
|
||||||
|
function customError(error) {
|
||||||
|
const errors = {
|
||||||
|
invalid_credentials: 'invalidCredentials', setup_already_completed: 'setupDone',
|
||||||
|
relay_setup_code_not_configured: 'setupUnavailable', invalid_setup_code: 'invalidSetup',
|
||||||
|
invalid_invitation: 'invalidInvite', invalid_account_credentials: 'invalidAccount',
|
||||||
|
unauthorized: 'sessionExpired', cannot_revoke_current_account: 'currentAccount'
|
||||||
|
};
|
||||||
|
return t(errors[error.message] || 'loadError');
|
||||||
|
}
|
||||||
|
|
||||||
|
function toggleAuth(cardMode) {
|
||||||
|
$('#auth-card').classList.toggle('hidden', cardMode === 'device' || Boolean(account));
|
||||||
|
$('#console-card').classList.toggle('hidden', !account);
|
||||||
|
$('#logout').classList.toggle('hidden', !account);
|
||||||
|
if (cardMode && ['login', 'setup', 'redeem'].includes(cardMode)) {
|
||||||
|
mode = cardMode;
|
||||||
|
updateAuthMode();
|
||||||
|
}
|
||||||
|
if (account) {
|
||||||
|
$('#welcome').textContent = `${account.username}`;
|
||||||
|
$('#role').textContent = t(account.role === 'admin' ? 'admin' : 'member');
|
||||||
|
const isAdmin = account.role === 'admin';
|
||||||
|
document.querySelectorAll('.console-section').forEach(section => section.classList.toggle('hidden', !isAdmin));
|
||||||
|
if (isAdmin) refreshAdmin().catch(error => showMessage($('#console-message'), customError(error), true));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadSession() {
|
||||||
|
try {
|
||||||
|
const response = await api('/api/v1/web/session');
|
||||||
|
account = response.account;
|
||||||
|
toggleAuth();
|
||||||
|
} catch {
|
||||||
|
account = null;
|
||||||
|
const status = await api('/api/v1/web/status');
|
||||||
|
document.querySelector('[data-mode="setup"]').classList.toggle('hidden', status.setupCompleted);
|
||||||
|
mode = status.setupCompleted ? 'login' : 'setup';
|
||||||
|
toggleAuth(mode);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function refreshAdmin() {
|
||||||
|
const [accounts, invitations] = await Promise.all([
|
||||||
|
api('/api/v1/web/admin/accounts'), api('/api/v1/web/admin/invitations')
|
||||||
|
]);
|
||||||
|
const others = accounts.accounts.filter(item => item.id !== account.id);
|
||||||
|
$('#accounts').replaceChildren();
|
||||||
|
if (!others.length) $('#accounts').innerHTML = `<li class="empty">${escapeText(t('noAccounts'))}</li>`;
|
||||||
|
for (const item of others) {
|
||||||
|
const row = document.createElement('li');
|
||||||
|
row.innerHTML = `<span><strong>${escapeText(item.username)}</strong><small>${escapeText(t(item.role === 'admin' ? 'admin' : 'member'))}</small></span><button class="button danger small">${escapeText(t('revoke'))}</button>`;
|
||||||
|
row.querySelector('button').addEventListener('click', () => revokeAccount(item));
|
||||||
|
$('#accounts').append(row);
|
||||||
|
}
|
||||||
|
$('#invitations').replaceChildren();
|
||||||
|
const active = invitations.invitations.filter(item => !item.used);
|
||||||
|
if (!active.length) $('#invitations').innerHTML = `<li class="empty">${escapeText(t('noInvitations'))}</li>`;
|
||||||
|
for (const item of active) {
|
||||||
|
const row = document.createElement('li');
|
||||||
|
row.innerHTML = `<span><strong>${escapeText(t('expires'))}: ${escapeText(new Date(item.expiresAt).toLocaleString(language))}</strong><small>${escapeText(new Date(item.createdAt).toLocaleString(language))}</small></span><button class="button danger small">${escapeText(t('revoke'))}</button>`;
|
||||||
|
row.querySelector('button').addEventListener('click', () => revokeInvitation(item));
|
||||||
|
$('#invitations').append(row);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function revokeAccount(item) {
|
||||||
|
if (!confirm(t('revokeConfirm'))) return;
|
||||||
|
try { await api(`/api/v1/web/admin/accounts/${encodeURIComponent(item.id)}`, { method: 'DELETE' }); await refreshAdmin(); }
|
||||||
|
catch (error) { showMessage($('#console-message'), customError(error), true); }
|
||||||
|
}
|
||||||
|
async function revokeInvitation(item) {
|
||||||
|
if (!confirm(t('revokeInviteConfirm'))) return;
|
||||||
|
try { await api(`/api/v1/web/admin/invitations/${encodeURIComponent(item.id)}`, { method: 'DELETE' }); await refreshAdmin(); }
|
||||||
|
catch (error) { showMessage($('#console-message'), customError(error), true); }
|
||||||
|
}
|
||||||
|
|
||||||
|
function devicePage() {
|
||||||
|
const params = new URLSearchParams(location.search);
|
||||||
|
const userCode = (params.get('user_code') || '').toUpperCase();
|
||||||
|
callbackState = params.get('state') || '';
|
||||||
|
if (!userCode) return false;
|
||||||
|
$('#device-card').classList.remove('hidden');
|
||||||
|
$('#device-code').textContent = userCode;
|
||||||
|
$('#auth-card').classList.add('hidden');
|
||||||
|
$('#console-card').classList.add('hidden');
|
||||||
|
$('#authorize').addEventListener('click', () => authorizeDevice(userCode));
|
||||||
|
if (callbackState) $('#return-mac').dataset.state = callbackState;
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authorizeDevice(userCode) {
|
||||||
|
showMessage($('#device-message'), '');
|
||||||
|
if (!account) {
|
||||||
|
showMessage($('#device-message'), t('loginFirst'), true);
|
||||||
|
$('#auth-card').classList.remove('hidden');
|
||||||
|
$('#auth-form').elements.username.focus();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
$('#authorize').disabled = true;
|
||||||
|
try {
|
||||||
|
await api('/api/v1/web/device/authorize', { method: 'POST', body: { userCode } });
|
||||||
|
$('#authorize').classList.add('hidden');
|
||||||
|
$('#return-mac').classList.remove('hidden');
|
||||||
|
showMessage($('#device-message'), t('deviceAuthorized'));
|
||||||
|
} catch (error) {
|
||||||
|
$('#authorize').disabled = false;
|
||||||
|
showMessage($('#device-message'), customError(error), true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
$('#auth-form').addEventListener('submit', async event => {
|
||||||
|
event.preventDefault();
|
||||||
|
const form = new FormData(event.currentTarget);
|
||||||
|
const body = Object.fromEntries(form.entries());
|
||||||
|
if (mode === 'setup' && !body.setupCode) return showMessage($('#auth-message'), t('setupCodeRequired'), true);
|
||||||
|
if (mode === 'redeem' && !body.invitationCode) return showMessage($('#auth-message'), t('invitationRequired'), true);
|
||||||
|
const endpoint = mode === 'setup' ? '/api/v1/web/setup' : mode === 'redeem' ? '/api/v1/web/redeem' : '/api/v1/web/session';
|
||||||
|
$('#auth-submit').disabled = true;
|
||||||
|
try {
|
||||||
|
const response = await api(endpoint, { method: 'POST', body });
|
||||||
|
account = response.account;
|
||||||
|
if (mode === 'setup') document.querySelector('[data-mode="setup"]').classList.add('hidden');
|
||||||
|
toggleAuth();
|
||||||
|
showMessage($('#console-message'), t('loggedIn'));
|
||||||
|
if ($('#device-card').classList.contains('hidden') === false) showMessage($('#device-message'), t('devicePending'));
|
||||||
|
} catch (error) { showMessage($('#auth-message'), customError(error), true); }
|
||||||
|
finally { $('#auth-submit').disabled = false; }
|
||||||
|
});
|
||||||
|
|
||||||
|
document.querySelectorAll('.auth-tabs button').forEach(button => button.addEventListener('click', () => {
|
||||||
|
mode = button.dataset.mode;
|
||||||
|
updateAuthMode();
|
||||||
|
showMessage($('#auth-message'), '');
|
||||||
|
}));
|
||||||
|
|
||||||
|
$('#language').addEventListener('click', () => setLanguage(language === 'de' ? 'en' : 'de'));
|
||||||
|
$('#logout').addEventListener('click', async () => {
|
||||||
|
try { await api('/api/v1/web/session', { method: 'DELETE' }); } catch {}
|
||||||
|
account = null;
|
||||||
|
toggleAuth(await api('/api/v1/web/status').then(status => status.setupCompleted ? 'login' : 'setup'));
|
||||||
|
showMessage($('#auth-message'), t('loggedOut'));
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#create-invitation').addEventListener('click', async () => {
|
||||||
|
try {
|
||||||
|
const invitation = await api('/api/v1/web/admin/invitations', { method: 'POST', body: {} });
|
||||||
|
const output = $('#new-invitation');
|
||||||
|
output.innerHTML = `<span>${escapeText(t('invitationCreated'))}</span><code>${escapeText(invitation.code)}</code><button class="button small" type="button">${language === 'de' ? 'Kopieren' : 'Copy'}</button>`;
|
||||||
|
output.classList.remove('hidden');
|
||||||
|
output.querySelector('button').addEventListener('click', async () => { await navigator.clipboard.writeText(invitation.code); });
|
||||||
|
await refreshAdmin();
|
||||||
|
} catch (error) { showMessage($('#console-message'), customError(error), true); }
|
||||||
|
});
|
||||||
|
|
||||||
|
$('#return-mac').addEventListener('click', () => {
|
||||||
|
const state = $('#return-mac').dataset.state;
|
||||||
|
if (state) location.href = `audiorecordermac://relay-setup?state=${encodeURIComponent(state)}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
setLanguage(language);
|
||||||
|
const isDevicePage = devicePage();
|
||||||
|
loadSession().then(() => {
|
||||||
|
if (isDevicePage && account) showMessage($('#device-message'), t('devicePending'));
|
||||||
|
}).catch(error => showMessage($('#auth-message'), customError(error), true));
|
||||||
@@ -0,0 +1,91 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="de">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light dark">
|
||||||
|
<title>Meets Relay</title>
|
||||||
|
<link rel="stylesheet" href="/assets/styles.css">
|
||||||
|
<script src="/assets/app.js" defer></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<main class="shell">
|
||||||
|
<header class="topbar">
|
||||||
|
<a class="brand" href="/" aria-label="Meets Relay">
|
||||||
|
<span class="brand-icon">M</span>
|
||||||
|
<span><strong>Meets Relay</strong><small data-i18n="secureRelay">Sicheres Relay</small></span>
|
||||||
|
</a>
|
||||||
|
<div class="top-actions">
|
||||||
|
<button class="language" id="language" type="button" aria-label="Language">DE / EN</button>
|
||||||
|
<button class="button quiet hidden" id="logout" type="button" data-i18n="signOut">Abmelden</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section class="hero">
|
||||||
|
<div class="eyebrow" data-i18n="privateByDesign">PRIVAT DURCH DESIGN</div>
|
||||||
|
<h1 data-i18n="title">Dein Relay. Deine Verbindung.</h1>
|
||||||
|
<p data-i18n="intro">Verwalte den Zugang zu deinem Meets Relay. Aufnahmen und Transkripte werden hier nicht gespeichert.</p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card hidden" id="auth-card">
|
||||||
|
<div class="card-heading">
|
||||||
|
<div><h2 id="auth-title">Anmelden</h2><p id="auth-description"></p></div>
|
||||||
|
</div>
|
||||||
|
<nav class="auth-tabs" id="auth-tabs" aria-label="Account">
|
||||||
|
<button type="button" data-mode="login" class="active" data-i18n="signIn">Anmelden</button>
|
||||||
|
<button type="button" data-mode="redeem" data-i18n="invitation">Einladung</button>
|
||||||
|
<button type="button" data-mode="setup" data-i18n="firstSetup">Ersteinrichtung</button>
|
||||||
|
</nav>
|
||||||
|
<form id="auth-form" autocomplete="on">
|
||||||
|
<label class="hidden" id="setup-code-wrap"><span data-i18n="setupCode">Einrichtungscode</span><input name="setupCode" autocomplete="one-time-code"></label>
|
||||||
|
<label class="hidden" id="invite-code-wrap"><span data-i18n="inviteCode">Einladungscode</span><input name="invitationCode" autocomplete="one-time-code"></label>
|
||||||
|
<label><span data-i18n="username">Benutzername</span><input name="username" autocomplete="username" minlength="3" maxlength="64" required></label>
|
||||||
|
<label><span data-i18n="password">Passwort</span><input name="password" type="password" autocomplete="current-password" minlength="12" required></label>
|
||||||
|
<button class="button primary" type="submit" id="auth-submit">Anmelden</button>
|
||||||
|
</form>
|
||||||
|
<p class="message" id="auth-message" role="status" aria-live="polite"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card hidden" id="device-card">
|
||||||
|
<div class="eyebrow" data-i18n="macSetup">MAC-EINRICHTUNG</div>
|
||||||
|
<h2 data-i18n="authorizeMac">Mac mit Relay verbinden?</h2>
|
||||||
|
<p data-i18n="authorizeDescription">Nach deiner Bestätigung erhält die Meets-App auf diesem Mac eine Relay-Berechtigung. Das Browserfenster gibt keine Zugangstoken weiter.</p>
|
||||||
|
<div class="device-code" id="device-code"></div>
|
||||||
|
<p class="muted" id="device-account"></p>
|
||||||
|
<div class="actions">
|
||||||
|
<button class="button primary" id="authorize" type="button" data-i18n="authorize">Mac autorisieren</button>
|
||||||
|
<button class="button quiet hidden" id="return-mac" type="button" data-i18n="returnMac">Zur Meets-App wechseln</button>
|
||||||
|
</div>
|
||||||
|
<p class="message" id="device-message" role="status" aria-live="polite"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section class="card hidden" id="console-card">
|
||||||
|
<div class="card-heading">
|
||||||
|
<div><div class="eyebrow" data-i18n="adminConsole">RELAY-KONTO</div><h2 id="welcome"></h2></div>
|
||||||
|
<span class="role" id="role"></span>
|
||||||
|
</div>
|
||||||
|
<div class="device-pending hidden" id="pending-device">
|
||||||
|
<div><strong data-i18n="pendingMac">Mac wartet auf Freigabe</strong><p id="pending-code"></p></div>
|
||||||
|
<button class="button primary" id="authorize-pending" type="button" data-i18n="authorize">Autorisieren</button>
|
||||||
|
</div>
|
||||||
|
<div class="console-grid">
|
||||||
|
<section class="console-section">
|
||||||
|
<div class="section-title"><div><h3 data-i18n="accounts">Konten</h3><p data-i18n="accountsHint">Mitglieder mit Relay-Zugang</p></div></div>
|
||||||
|
<ul class="item-list" id="accounts"></ul>
|
||||||
|
</section>
|
||||||
|
<section class="console-section">
|
||||||
|
<div class="section-title"><div><h3 data-i18n="invitations">Einladungen</h3><p data-i18n="invitationsHint">Einmal-Codes laufen nach 24 Stunden ab.</p></div><button class="button small" id="create-invitation" type="button" data-i18n="createInvitation">Einladung erstellen</button></div>
|
||||||
|
<div class="one-time-code hidden" id="new-invitation"></div>
|
||||||
|
<ul class="item-list" id="invitations"></ul>
|
||||||
|
</section>
|
||||||
|
</div>
|
||||||
|
<p class="message" id="console-message" role="status" aria-live="polite"></p>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<footer>
|
||||||
|
<span data-i18n="footerPrivacy">Das Relay leitet ausschließlich Ende-zu-Ende-verschlüsselte Daten weiter.</span>
|
||||||
|
<span><a href="https://git.maddin.app/maddin/Meets-Relay" rel="noreferrer" data-i18n="sourceCode">Quellcode</a></span>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
:root {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
|
||||||
|
color: #182127;
|
||||||
|
background: #f0f4f5;
|
||||||
|
font-synthesis: none;
|
||||||
|
text-rendering: optimizeLegibility;
|
||||||
|
--muted: #657279;
|
||||||
|
--line: #e1e8ea;
|
||||||
|
--accent: #087e8b;
|
||||||
|
}
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
body { margin: 0; min-height: 100vh; background: radial-gradient(ellipse at 70% -20%, #d9edf0 0, transparent 50%), #f4f6f7; }
|
||||||
|
button, input { font: inherit; }
|
||||||
|
.shell { width: min(960px, calc(100% - 40px)); margin: auto; }
|
||||||
|
.topbar { height: 82px; display: flex; align-items: center; justify-content: space-between; border-bottom: 1px solid #dce4e6; }
|
||||||
|
.brand { display: inline-flex; align-items: center; gap: 12px; color: inherit; text-decoration: none; }
|
||||||
|
.brand-icon { width: 38px; height: 38px; display: grid; place-items: center; border-radius: 12px; color: #fff; font-weight: 750; background: linear-gradient(145deg, #21a2a8, #126475); box-shadow: 0 5px 14px #137c8a44; }
|
||||||
|
.brand strong, .brand small { display: block; }
|
||||||
|
.brand small { margin-top: 3px; color: var(--muted); font-size: 12px; }
|
||||||
|
.top-actions { display: flex; align-items: center; gap: 10px; }
|
||||||
|
.language { border: 0; padding: 9px 10px; border-radius: 9px; background: transparent; color: #47565d; cursor: pointer; font-size: 12px; font-weight: 700; }
|
||||||
|
.hero { padding: 48px 0 30px; }
|
||||||
|
.eyebrow { color: var(--accent); font-size: 10px; letter-spacing: .13em; font-weight: 750; }
|
||||||
|
h1 { margin: 11px 0 8px; font-size: clamp(30px, 5vw, 43px); letter-spacing: -.045em; line-height: 1.08; }
|
||||||
|
.hero p { margin: 0; max-width: 600px; color: var(--muted); font-size: 16px; line-height: 1.5; }
|
||||||
|
.card { margin: 14px 0 26px; padding: 26px; border: 1px solid #e1e8e9; border-radius: 18px; background: #fff; box-shadow: 0 12px 40px #16363b0b; }
|
||||||
|
.card h2 { margin: 5px 0; font-size: 22px; letter-spacing: -.025em; }
|
||||||
|
.card-heading { display: flex; justify-content: space-between; align-items: center; gap: 16px; }
|
||||||
|
.card-heading p, .console-section p { margin: 5px 0 0; color: var(--muted); font-size: 13px; }
|
||||||
|
.auth-tabs { display: flex; gap: 5px; margin: 22px 0 18px; border-bottom: 1px solid var(--line); }
|
||||||
|
.auth-tabs button { border: 0; padding: 10px 12px; color: var(--muted); background: none; border-bottom: 2px solid transparent; cursor: pointer; }
|
||||||
|
.auth-tabs button.active { border-color: var(--accent); color: #116d77; font-weight: 650; }
|
||||||
|
form { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; align-items: end; }
|
||||||
|
label { display: grid; gap: 7px; color: #47565d; font-size: 13px; }
|
||||||
|
label input { width: 100%; min-height: 42px; padding: 10px 11px; border: 1px solid #cdd8da; border-radius: 9px; background: #fff; outline: none; }
|
||||||
|
label input:focus { border-color: #168894; box-shadow: 0 0 0 3px #16889420; }
|
||||||
|
.button { min-height: 38px; padding: 9px 13px; border: 1px solid #d3dddf; border-radius: 9px; background: #fff; color: #334249; cursor: pointer; font-weight: 620; }
|
||||||
|
.button:hover { background: #f4f8f8; }
|
||||||
|
.button:disabled { opacity: .55; cursor: wait; }
|
||||||
|
.button.primary { border-color: var(--accent); background: var(--accent); color: #fff; }
|
||||||
|
.button.primary:hover { background: #076d79; }
|
||||||
|
.button.quiet { border-color: transparent; background: transparent; color: #4b5d64; }
|
||||||
|
.button.danger { border-color: #f1d3d0; color: #aa3d34; }
|
||||||
|
.button.small { min-height: 32px; padding: 6px 10px; font-size: 12px; }
|
||||||
|
#auth-submit { grid-column: 1 / -1; justify-self: start; min-width: 150px; }
|
||||||
|
.message { min-height: 18px; margin: 12px 0 0; color: #42726e; font-size: 13px; }
|
||||||
|
.message.error { color: #b33e35; }
|
||||||
|
.role { padding: 6px 9px; border-radius: 20px; background: #e9f4f3; color: #26736e; font-size: 11px; font-weight: 700; }
|
||||||
|
.console-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 35px; margin-top: 24px; }
|
||||||
|
.console-section { min-width: 0; }
|
||||||
|
.section-title { display: flex; align-items: center; justify-content: space-between; gap: 10px; min-height: 52px; }
|
||||||
|
.section-title h3 { margin: 0; font-size: 16px; }
|
||||||
|
.section-title p { font-size: 12px; }
|
||||||
|
.item-list { list-style: none; padding: 0; margin: 12px 0 0; border-top: 1px solid var(--line); }
|
||||||
|
.item-list li { min-height: 56px; display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 9px 0; border-bottom: 1px solid var(--line); }
|
||||||
|
.item-list li span, .item-list small { display: block; }
|
||||||
|
.item-list small { margin-top: 4px; color: var(--muted); font-size: 11px; }
|
||||||
|
.item-list .empty { color: var(--muted); font-size: 13px; }
|
||||||
|
.device-pending { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-top: 20px; padding: 14px; border: 1px solid #dce9e8; border-radius: 12px; background: #f5faf9; }
|
||||||
|
.device-pending p { margin: 4px 0 0; color: var(--muted); font-family: ui-monospace, monospace; letter-spacing: .08em; }
|
||||||
|
.device-code { margin: 22px 0 10px; padding: 17px; border-radius: 12px; background: #f0f6f6; color: #176a70; font: 700 clamp(22px, 5vw, 34px)/1.1 ui-monospace, SFMono-Regular, monospace; letter-spacing: .12em; text-align: center; }
|
||||||
|
.muted { color: var(--muted); font-size: 13px; }
|
||||||
|
.actions { display: flex; flex-wrap: wrap; gap: 10px; margin-top: 18px; }
|
||||||
|
.one-time-code { display: grid; gap: 8px; margin-top: 12px; padding: 14px; border-radius: 10px; background: #eff7f4; color: #40544c; font-size: 13px; }
|
||||||
|
.one-time-code code { font-size: 18px; font-weight: 700; overflow-wrap: anywhere; }
|
||||||
|
footer { display: flex; justify-content: space-between; gap: 20px; padding: 20px 0 35px; color: var(--muted); font-size: 12px; }
|
||||||
|
footer a { color: #426a70; text-decoration: none; }
|
||||||
|
.hidden { display: none !important; }
|
||||||
|
@media (max-width: 680px) {
|
||||||
|
.shell { width: min(100% - 28px, 560px); }
|
||||||
|
.topbar { height: 68px; }
|
||||||
|
.hero { padding: 36px 0 22px; }
|
||||||
|
.card { padding: 18px; border-radius: 14px; }
|
||||||
|
form, .console-grid { grid-template-columns: 1fr; }
|
||||||
|
#auth-submit { grid-column: auto; }
|
||||||
|
.auth-tabs { overflow-x: auto; }
|
||||||
|
.auth-tabs button { flex: 0 0 auto; padding-inline: 8px; font-size: 13px; }
|
||||||
|
.section-title { align-items: flex-start; }
|
||||||
|
footer { flex-direction: column; gap: 8px; }
|
||||||
|
}
|
||||||
|
@media (prefers-color-scheme: dark) {
|
||||||
|
:root { color: #e7eeee; background: #0c1518; --muted: #9baaae; --line: #273638; --accent: #35a8ab; }
|
||||||
|
body { background: radial-gradient(ellipse at 70% -20%, #17393b 0, transparent 52%), #101a1c; }
|
||||||
|
.topbar { border-color: #263638; }
|
||||||
|
.card { background: #172224; border-color: #263638; box-shadow: 0 12px 40px #0003; }
|
||||||
|
label { color: #c1cdcf; }
|
||||||
|
label input, .button { background: #1d2b2d; border-color: #354649; color: #e5eeee; }
|
||||||
|
.button:hover { background: #26383a; }
|
||||||
|
.button.primary { background: #16818a; border-color: #16818a; color: white; }
|
||||||
|
.device-code { background: #203437; color: #8bd3d1; }
|
||||||
|
.device-pending, .one-time-code { background: #1c2c2d; border-color: #304343; }
|
||||||
|
.role { background: #203736; color: #9ad1c7; }
|
||||||
|
.language, .button.quiet { color: #b8c7c9; }
|
||||||
|
}
|
||||||
+478
-28
@@ -1,7 +1,9 @@
|
|||||||
import http from 'node:http';
|
import http from 'node:http';
|
||||||
|
import http2 from 'node:http2';
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import fs from 'node:fs/promises';
|
import fs from 'node:fs/promises';
|
||||||
import path from 'node:path';
|
import path from 'node:path';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
import { promisify } from 'node:util';
|
import { promisify } from 'node:util';
|
||||||
|
|
||||||
const port = Number(process.env.PORT || 8080);
|
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 relayRoot = process.env.RELAY_DATA_DIR || '/data/relay';
|
||||||
const relayMaxBytes = Number(process.env.RELAY_MAX_BYTES || 10 * 1024 * 1024 * 1024);
|
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 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 relayChunkMaxBytes = 4 * 1024 * 1024 + 64;
|
||||||
const relayTTL = Number(process.env.RELAY_TTL_SECONDS || 604800) * 1000;
|
const relayTTL = Number(process.env.RELAY_TTL_SECONDS || 604800) * 1000;
|
||||||
const relayIncompleteTTL = Number(process.env.RELAY_INCOMPLETE_TTL_SECONDS || 86400) * 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 refreshTokenTTL = 90 * 24 * 60 * 60 * 1000;
|
||||||
const invitationTTL = Number(process.env.INVITATION_TTL_SECONDS || 86400) * 1000;
|
const invitationTTL = Number(process.env.INVITATION_TTL_SECONDS || 86400) * 1000;
|
||||||
const setupCodeFile = process.env.RELAY_SETUP_CODE_FILE || '';
|
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 offers = new Map();
|
||||||
const sessions = new Map();
|
const sessions = new Map();
|
||||||
|
const webSessions = new Map();
|
||||||
|
const deviceAuthorizations = new Map();
|
||||||
|
const deviceAuthorizationCodes = new Map();
|
||||||
const rateBuckets = new Map();
|
const rateBuckets = new Map();
|
||||||
|
const rateLimitLogWindows = new Map();
|
||||||
const loginBuckets = new Map();
|
const loginBuckets = new Map();
|
||||||
const accountAccessTokens = new Map();
|
const accountAccessTokens = new Map();
|
||||||
const relayWaiters = 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 relayWrite = Promise.resolve();
|
||||||
let setupPending = false;
|
let setupPending = false;
|
||||||
|
|
||||||
@@ -78,7 +88,10 @@ function restoreSession(saved) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function persistRelayState() {
|
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 });
|
await fs.mkdir(relayRoot, { recursive: true, mode: 0o700 });
|
||||||
const temporary = path.join(relayRoot, `state-${process.pid}.tmp`);
|
const temporary = path.join(relayRoot, `state-${process.pid}.tmp`);
|
||||||
const state = {
|
const state = {
|
||||||
@@ -95,7 +108,7 @@ async function loadRelayState() {
|
|||||||
await fs.mkdir(relayRoot, { recursive: true, mode: 0o700 });
|
await fs.mkdir(relayRoot, { recursive: true, mode: 0o700 });
|
||||||
try {
|
try {
|
||||||
const saved = JSON.parse(await fs.readFile(path.join(relayRoot, 'state.json'), 'utf8'));
|
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 || []) {
|
for (const savedSession of saved.pairingSessions || []) {
|
||||||
const session = restoreSession(savedSession);
|
const session = restoreSession(savedSession);
|
||||||
if (!session) continue;
|
if (!session) continue;
|
||||||
@@ -104,9 +117,11 @@ async function loadRelayState() {
|
|||||||
relayState.credentials[hash(session.relayToken)] = session.id;
|
relayState.credentials[hash(session.relayToken)] = session.id;
|
||||||
if (!session.accountID && relayState.setupCompleted) session.accountID = Object.keys(relayState.accounts)[0] || null;
|
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) {
|
} 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;
|
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'); }
|
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) {
|
function readBinary(req, limit = relayChunkMaxBytes) {
|
||||||
return new Promise((resolve, reject) => {
|
return new Promise((resolve, reject) => {
|
||||||
let size = 0;
|
let size = 0;
|
||||||
@@ -307,15 +379,64 @@ function clientIP(req) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function rateLimit(req, res) {
|
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 timestamp = now();
|
||||||
const recent = (rateBuckets.get(key) || []).filter(value => timestamp - value < 60_000);
|
const recent = (rateBuckets.get(key) || []).filter(value => timestamp - value < 60_000);
|
||||||
// The Mac polls an active, short-lived offer while the iPhone camera is
|
// Keep noisy relay chunk transfers from consuming the budget for pairing,
|
||||||
// open. Thirty requests per minute was too low for that legitimate flow
|
// authentication, and heartbeats. Chunk requests remain bounded separately
|
||||||
// and caused a second pairing attempt to receive 429 after about one
|
// because one large encrypted transfer can legitimately use many requests.
|
||||||
// minute. Keep abuse protection, but allow several simultaneous pairings.
|
if (recent.length >= limit) {
|
||||||
if (recent.length >= 600) {
|
const logWindow = rateLimitLogWindows.get(bucket);
|
||||||
json(res, 429, { error: 'rate_limited' });
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
recent.push(timestamp);
|
recent.push(timestamp);
|
||||||
@@ -387,6 +508,68 @@ async function verifyPassword(password, account) {
|
|||||||
function publicAccount(account) {
|
function publicAccount(account) {
|
||||||
return { id: account.id, username: account.username, role: account.role, createdAt: account.createdAt };
|
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) {
|
function issueAccountTokens(accountID) {
|
||||||
const accessToken = crypto.randomBytes(32).toString('base64url');
|
const accessToken = crypto.randomBytes(32).toString('base64url');
|
||||||
const refreshToken = crypto.randomBytes(48).toString('base64url');
|
const refreshToken = crypto.randomBytes(48).toString('base64url');
|
||||||
@@ -421,6 +604,8 @@ async function purge() {
|
|||||||
sessions.delete(id);
|
sessions.delete(id);
|
||||||
offers.delete(id);
|
offers.delete(id);
|
||||||
delete relayState.credentials[hash(session.relayToken)];
|
delete relayState.credentials[hash(session.relayToken)];
|
||||||
|
delete relayState.pushDevices[id];
|
||||||
|
delete relayState.pushEvents[id];
|
||||||
sessionsChanged = true;
|
sessionsChanged = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -453,6 +638,169 @@ async function handle(req, res) {
|
|||||||
if (req.method === 'GET' && url.pathname === '/health') {
|
if (req.method === 'GET' && url.pathname === '/health') {
|
||||||
return json(res, 200, { ok: true, service: 'meets-relay', time: new Date().toISOString() });
|
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 (req.method === 'POST' && url.pathname === '/api/v1/auth/setup') {
|
||||||
if (!accountRateLimit(req, res, 'setup', 5)) return;
|
if (!accountRateLimit(req, res, 'setup', 5)) return;
|
||||||
if (relayState.setupCompleted || setupPending) return json(res, 409, { error: 'setup_already_completed' });
|
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) {
|
for (const session of [...sessions.values()]) if (session.accountID === target.id) {
|
||||||
sessions.delete(session.id); offers.delete(session.id);
|
sessions.delete(session.id); offers.delete(session.id);
|
||||||
delete relayState.credentials[hash(session.relayToken)];
|
delete relayState.credentials[hash(session.relayToken)];
|
||||||
|
delete relayState.pushDevices[session.id]; delete relayState.pushEvents[session.id];
|
||||||
}
|
}
|
||||||
await persistRelayState();
|
await persistRelayState();
|
||||||
return json(res, 200, { revoked: true });
|
return json(res, 200, { revoked: true });
|
||||||
@@ -673,6 +1022,68 @@ async function handle(req, res) {
|
|||||||
const sessionID = parts[4];
|
const sessionID = parts[4];
|
||||||
if (!relaySession(req, sessionID)) return json(res, 401, { error: 'unauthorized' });
|
if (!relaySession(req, sessionID)) return json(res, 401, { error: 'unauthorized' });
|
||||||
const tail = parts.slice(5);
|
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 (tail[0] === 'messages') {
|
||||||
if (req.method === 'POST' && tail.length === 1) {
|
if (req.method === 'POST' && tail.length === 1) {
|
||||||
const body = await readBody(req);
|
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 direction = ['request', 'response', 'attachment'].includes(body.direction) ? body.direction : null;
|
||||||
const size = Number(body.size);
|
const size = Number(body.size);
|
||||||
const count = Number(body.chunkCount);
|
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)];
|
const existing = relayState.messages[messageKey(sessionID, id)];
|
||||||
if (existing && !existing.acknowledged) {
|
if (existing && !existing.acknowledged) {
|
||||||
if (existing.size !== size || existing.chunkCount !== count || existing.direction !== direction) return json(res, 409, { error: 'relay_message_manifest_conflict' });
|
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 });
|
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 reservedBytes = size + count * 28;
|
||||||
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: {} };
|
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;
|
relayState.messages[messageKey(sessionID, id)] = created;
|
||||||
await fs.mkdir(relayMessagePath(created), { recursive: true, mode: 0o700 });
|
await fs.mkdir(relayMessagePath(created), { recursive: true, mode: 0o700 });
|
||||||
await persistRelayState();
|
await persistRelayState();
|
||||||
@@ -712,9 +1124,17 @@ async function handle(req, res) {
|
|||||||
const previous = current.chunks[index];
|
const previous = current.chunks[index];
|
||||||
if (previous && previous.hash !== digest) return json(res, 409, { error: 'relay_message_chunk_conflict' });
|
if (previous && previous.hash !== digest) return json(res, 409, { error: 'relay_message_chunk_conflict' });
|
||||||
if (!previous) {
|
if (!previous) {
|
||||||
await fs.writeFile(path.join(relayMessagePath(current), `${index}.bin`), data, { mode: 0o600, flag: 'wx' });
|
if (data.length === 0 || current.encryptedBytes + data.length > current.reservedBytes) return json(res, 413, { error: 'relay_message_size_exceeded' });
|
||||||
current.chunks[index] = { hash: digest, size: data.length };
|
// Reserve in memory before awaiting disk I/O so concurrent chunk
|
||||||
|
// requests cannot both pass the aggregate-size check.
|
||||||
current.encryptedBytes += data.length;
|
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.updatedAt = now();
|
||||||
current.expiresAt = now() + relayTTL;
|
current.expiresAt = now() + relayTTL;
|
||||||
current.complete = Object.keys(current.chunks).length === current.chunkCount;
|
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 id = cleanText(body.id, 64).toLowerCase();
|
||||||
const size = Number(body.size);
|
const size = Number(body.size);
|
||||||
const count = Number(body.chunkCount);
|
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' });
|
return json(res, 400, { error: 'invalid_upload_manifest' });
|
||||||
}
|
}
|
||||||
|
if (!validRPCMetadata) return json(res, 400, { error: 'invalid_upload_operation' });
|
||||||
const key = uploadKey(sessionID, id);
|
const key = uploadKey(sessionID, id);
|
||||||
const existing = relayState.uploads[key];
|
const existing = relayState.uploads[key];
|
||||||
if (existing && !existing.acknowledged) {
|
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 });
|
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 reservedBytes = size + count * 28;
|
||||||
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: {} };
|
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;
|
relayState.uploads[key] = upload;
|
||||||
await fs.mkdir(relayUploadPath(upload), { recursive: true, mode: 0o700 });
|
await fs.mkdir(relayUploadPath(upload), { recursive: true, mode: 0o700 });
|
||||||
await persistRelayState();
|
await persistRelayState();
|
||||||
@@ -779,9 +1220,15 @@ async function handle(req, res) {
|
|||||||
const previous = upload.chunks[index];
|
const previous = upload.chunks[index];
|
||||||
if (previous && previous.hash !== digest) return json(res, 409, { error: 'relay_chunk_conflict' });
|
if (previous && previous.hash !== digest) return json(res, 409, { error: 'relay_chunk_conflict' });
|
||||||
if (!previous) {
|
if (!previous) {
|
||||||
await fs.writeFile(path.join(relayUploadPath(upload), `${index}.bin`), data, { mode: 0o600, flag: 'wx' });
|
if (data.length === 0 || upload.encryptedBytes + data.length > upload.reservedBytes) return json(res, 413, { error: 'relay_upload_size_exceeded' });
|
||||||
upload.chunks[index] = { hash: digest, size: data.length };
|
|
||||||
upload.encryptedBytes += data.length;
|
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.updatedAt = now();
|
||||||
upload.expiresAt = now() + relayTTL;
|
upload.expiresAt = now() + relayTTL;
|
||||||
upload.complete = Object.keys(upload.chunks).length === upload.chunkCount;
|
upload.complete = Object.keys(upload.chunks).length === upload.chunkCount;
|
||||||
@@ -819,10 +1266,12 @@ async function handle(req, res) {
|
|||||||
if (res.destroyed) return;
|
if (res.destroyed) return;
|
||||||
}
|
}
|
||||||
const uploads = Object.values(relayState.uploads).filter(upload => upload.sessionID === sessionID && upload.complete && !upload.acknowledged);
|
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) {
|
if (req.method === 'DELETE' && tail.length === 0) {
|
||||||
delete relayState.credentials[hash(String(req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim())];
|
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 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);
|
for (const message of Object.values(relayState.messages || {}).filter(value => value.sessionID === sessionID)) await removeRelayMessage(message);
|
||||||
await persistRelayState();
|
await persistRelayState();
|
||||||
@@ -905,6 +1354,8 @@ async function handle(req, res) {
|
|||||||
if (req.method === 'DELETE' && parts[5] === undefined) {
|
if (req.method === 'DELETE' && parts[5] === undefined) {
|
||||||
sessions.delete(session.id);
|
sessions.delete(session.id);
|
||||||
offers.delete(session.id);
|
offers.delete(session.id);
|
||||||
|
delete relayState.pushDevices[session.id];
|
||||||
|
delete relayState.pushEvents[session.id];
|
||||||
delete relayState.credentials[hash(session.relayToken)];
|
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 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);
|
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' });
|
return json(res, 404, { error: 'not_found' });
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
const status = error.message === 'request_too_large' || error.message === 'relay_chunk_too_large' ? 413 : error.message === 'invalid_json' ? 400 : 500;
|
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: error.message || 'internal_error' });
|
||||||
return json(res, status, { error: safeError });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const server = http.createServer(handle);
|
const server = http.createServer(handle);
|
||||||
await loadRelayState();
|
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();
|
setInterval(() => { purge().catch(error => console.error('Relay cleanup failed:', error)); }, 30_000).unref();
|
||||||
+117
-2
@@ -82,6 +82,24 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
|
|||||||
assert.equal(claimResponse.status, 200);
|
assert.equal(claimResponse.status, 200);
|
||||||
const claim = await claimResponse.json();
|
const claim = await claimResponse.json();
|
||||||
assert.ok(claim.relayToken);
|
assert.ok(claim.relayToken);
|
||||||
|
const secondSecretHash = crypto.createHash('sha256').update('second-pairing-secret').digest('hex');
|
||||||
|
const secondOfferResponse = await postJSON(`${base}/api/v1/pairing/offers`, {
|
||||||
|
protocolVersion: 2,
|
||||||
|
secretHash: secondSecretHash,
|
||||||
|
publicKey: 'mac-key-two',
|
||||||
|
identityKey: 'mac-identity-two'
|
||||||
|
}, owner.accessToken);
|
||||||
|
assert.equal(secondOfferResponse.status, 201);
|
||||||
|
const secondOffer = await secondOfferResponse.json();
|
||||||
|
const secondClaimResponse = await postJSON(`${base}/api/v1/pairing/offers/${secondOffer.id}/claim`, {
|
||||||
|
protocolVersion: 2,
|
||||||
|
secretHash: secondSecretHash,
|
||||||
|
publicKey: 'phone-key-two',
|
||||||
|
identityKey: 'phone-identity-two'
|
||||||
|
});
|
||||||
|
assert.equal(secondClaimResponse.status, 200);
|
||||||
|
const secondClaim = await secondClaimResponse.json();
|
||||||
|
assert.ok(secondClaim.relayToken);
|
||||||
const persistedPairing = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8')).pairingSessions[0];
|
const persistedPairing = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8')).pairingSessions[0];
|
||||||
assert.equal(persistedPairing.sessionToken, undefined);
|
assert.equal(persistedPairing.sessionToken, undefined);
|
||||||
assert.equal(persistedPairing.relayToken, undefined);
|
assert.equal(persistedPairing.relayToken, undefined);
|
||||||
@@ -203,6 +221,47 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
|
|||||||
const attachmentAck = await postJSON(`${attachmentPath}/${attachmentID}/ack`, {}, claim.relayToken);
|
const attachmentAck = await postJSON(`${attachmentPath}/${attachmentID}/ack`, {}, claim.relayToken);
|
||||||
assert.equal(attachmentAck.status, 200);
|
assert.equal(attachmentAck.status, 200);
|
||||||
|
|
||||||
|
// Exercise the supported maximum audio size as bounded opaque chunks. Keep
|
||||||
|
// only one chunk buffer in memory while the relay stages the full payload.
|
||||||
|
const maximumAudioBytes = 500 * 1024 * 1024;
|
||||||
|
const audioChunkSize = 3 * 1024 * 1024;
|
||||||
|
const audioChunkCount = Math.ceil(maximumAudioBytes / audioChunkSize);
|
||||||
|
const largeAudioID = crypto.randomUUID();
|
||||||
|
const largeAudioManifest = await postJSON(messagePath, {
|
||||||
|
id: largeAudioID,
|
||||||
|
direction: 'attachment',
|
||||||
|
size: maximumAudioBytes,
|
||||||
|
chunkCount: audioChunkCount
|
||||||
|
}, claim.relayToken);
|
||||||
|
assert.equal(largeAudioManifest.status, 201);
|
||||||
|
let remainingAudioBytes = maximumAudioBytes;
|
||||||
|
let lastEncryptedChunk;
|
||||||
|
const reusableEncryptedChunk = Buffer.alloc(audioChunkSize + 16);
|
||||||
|
for (let index = 0; index < audioChunkCount; index++) {
|
||||||
|
const plaintextLength = Math.min(audioChunkSize, remainingAudioBytes);
|
||||||
|
const encryptedLength = plaintextLength + 16;
|
||||||
|
reusableEncryptedChunk.fill(index & 0xff, 0, encryptedLength);
|
||||||
|
const encryptedChunk = reusableEncryptedChunk.subarray(0, encryptedLength);
|
||||||
|
const response = await fetch(`${messagePath}/${largeAudioID}/chunks/${index}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { authorization: `Bearer ${claim.relayToken}`, 'content-type': 'application/octet-stream' },
|
||||||
|
body: encryptedChunk
|
||||||
|
});
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
if (index === audioChunkCount - 1) lastEncryptedChunk = Buffer.from(encryptedChunk);
|
||||||
|
remainingAudioBytes -= plaintextLength;
|
||||||
|
}
|
||||||
|
assert.equal(remainingAudioBytes, 0);
|
||||||
|
const largeAudioStatus = await fetch(`${messagePath}/${largeAudioID}`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||||
|
assert.equal(largeAudioStatus.status, 200);
|
||||||
|
assert.equal((await largeAudioStatus.json()).chunkCount, audioChunkCount);
|
||||||
|
const lastAudioChunkResponse = await fetch(`${messagePath}/${largeAudioID}/chunks?index=${audioChunkCount - 1}`, {
|
||||||
|
headers: { authorization: `Bearer ${claim.relayToken}` }
|
||||||
|
});
|
||||||
|
assert.deepEqual(Buffer.from(await lastAudioChunkResponse.arrayBuffer()), lastEncryptedChunk);
|
||||||
|
const largeAudioAck = await postJSON(`${messagePath}/${largeAudioID}/ack`, {}, claim.relayToken);
|
||||||
|
assert.equal(largeAudioAck.status, 200);
|
||||||
|
|
||||||
let listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
let listing = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||||
assert.deepEqual((await listing.json()).uploads.map(upload => upload.id), [id]);
|
assert.deepEqual((await listing.json()).uploads.map(upload => upload.id), [id]);
|
||||||
const chunk = await fetch(`${relayPath}/uploads/${id}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
const chunk = await fetch(`${relayPath}/uploads/${id}/chunks?index=0`, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||||
@@ -215,11 +274,67 @@ test('relay persists opaque chunks, acknowledges and revokes pairings', async t
|
|||||||
assert.equal(revoke.status, 200);
|
assert.equal(revoke.status, 200);
|
||||||
const unauthorized = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
const unauthorized = await fetch(relayPath, { headers: { authorization: `Bearer ${claim.relayToken}` } });
|
||||||
assert.equal(unauthorized.status, 401);
|
assert.equal(unauthorized.status, 401);
|
||||||
|
|
||||||
|
// Exhaust the general-purpose IP bucket and verify it cannot block the
|
||||||
|
// paired session heartbeat, which has its own pairing budget.
|
||||||
|
let defaultLimitReached = false;
|
||||||
|
let defaultLimitResponse;
|
||||||
|
for (let attempt = 0; attempt < 610; attempt++) {
|
||||||
|
const response = await fetch(`${base}/health`);
|
||||||
|
if (response.status === 429) {
|
||||||
|
defaultLimitReached = true;
|
||||||
|
defaultLimitResponse = response;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
assert.equal(response.status, 200);
|
||||||
|
}
|
||||||
|
assert.equal(defaultLimitReached, true);
|
||||||
|
assert.equal(defaultLimitResponse.headers.get('retry-after'), '60');
|
||||||
|
assert.deepEqual(await defaultLimitResponse.json(), { error: 'rate_limited', retryAfterSeconds: 60 });
|
||||||
|
const heartbeatAfterDefaultLimit = await postJSON(
|
||||||
|
`${sessionPath}/heartbeat`,
|
||||||
|
{ protocolVersion: 2, side: 'client' },
|
||||||
|
claim.sessionToken
|
||||||
|
);
|
||||||
|
assert.equal(heartbeatAfterDefaultLimit.status, 200);
|
||||||
|
|
||||||
|
// Flood one authenticated pairing while another pairing continues to poll
|
||||||
|
// concurrently from the same simulated public IP. The session-scoped limit
|
||||||
|
// must reject only the busy pairing and keep the other inbox responsive.
|
||||||
|
const sessionScopedRelayPath = `${base}/api/v1/relay/sessions/${offer.id}/messages?direction=request`;
|
||||||
|
const sameNATHeaders = { authorization: `Bearer ${claim.relayToken}`, 'x-forwarded-for': '203.0.113.19' };
|
||||||
|
const secondSessionRelayPath = `${base}/api/v1/relay/sessions/${secondOffer.id}/messages?direction=request`;
|
||||||
|
const secondSessionHeaders = { authorization: `Bearer ${secondClaim.relayToken}`, 'x-forwarded-for': '203.0.113.19' };
|
||||||
|
let sessionLimitReached = false;
|
||||||
|
for (let batch = 0; batch < 19 && !sessionLimitReached; batch++) {
|
||||||
|
const [responses, independentResponses] = await Promise.all([
|
||||||
|
Promise.all(Array.from({ length: 100 }, () => fetch(sessionScopedRelayPath, { headers: sameNATHeaders }))),
|
||||||
|
Promise.all(Array.from({ length: 50 }, () => fetch(secondSessionRelayPath, { headers: secondSessionHeaders })))
|
||||||
|
]);
|
||||||
|
assert.ok(independentResponses.every(response => response.status === 200), 'The independent pairing must remain responsive during the concurrent flood.');
|
||||||
|
sessionLimitReached = responses.some(response => response.status === 429);
|
||||||
|
}
|
||||||
|
assert.equal(sessionLimitReached, true);
|
||||||
|
const otherSessionPoll = await fetch(secondSessionRelayPath, { headers: secondSessionHeaders });
|
||||||
|
assert.equal(otherSessionPoll.status, 200);
|
||||||
|
|
||||||
|
// The Mac's long poll uses the session root. Keep that high-frequency
|
||||||
|
// endpoint in its own budget so a stuck poll cannot throttle iPhone RPCs.
|
||||||
|
const macQueuePollPath = `${base}/api/v1/relay/sessions/${secondOffer.id}?queue=mac&wait=0`;
|
||||||
|
const macQueuePolls = await Promise.all(Array.from({ length: 190 }, () => fetch(macQueuePollPath, { headers: secondSessionHeaders })));
|
||||||
|
assert.ok(macQueuePolls.some(response => response.status === 429), 'The Mac queue poll must remain bounded.');
|
||||||
|
const rpcAfterQueueFlood = await fetch(secondSessionRelayPath, { headers: secondSessionHeaders });
|
||||||
|
assert.equal(rpcAfterQueueFlood.status, 200, 'A Mac queue poll flood must not block iPhone relay RPCs.');
|
||||||
|
|
||||||
const revokePairing = await fetch(sessionPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
const revokePairing = await fetch(sessionPath, { method: 'DELETE', headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||||
assert.equal(revokePairing.status, 200);
|
assert.equal(revokePairing.status, 200);
|
||||||
|
const revokeSecondPairing = await fetch(`${base}/api/v1/pairing/sessions/${secondOffer.id}`, {
|
||||||
|
method: 'DELETE', headers: { authorization: `Bearer ${secondClaim.sessionToken}` }
|
||||||
|
});
|
||||||
|
assert.equal(revokeSecondPairing.status, 200);
|
||||||
const afterUnpair = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
|
const afterUnpair = JSON.parse(await readFile(path.join(dataDir, 'state.json'), 'utf8'));
|
||||||
assert.equal(afterUnpair.pushDevices, undefined);
|
assert.equal(afterUnpair.pushDevices[offer.id], undefined);
|
||||||
assert.equal(afterUnpair.pushEvents, undefined);
|
assert.equal(afterUnpair.pushEvents[offer.id], undefined);
|
||||||
const revokedStatus = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
const revokedStatus = await fetch(`${sessionPath}/status`, { headers: { authorization: `Bearer ${claim.sessionToken}` } });
|
||||||
assert.equal(revokedStatus.status, 404);
|
assert.equal(revokedStatus.status, 404);
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user