init
This commit is contained in:
247 files changed
+35538
No files matched your search
@@ -0,0 +1,53 @@
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { hashPassword, verifyPassword } from './password.mjs';
|
||||
|
||||
const owner = Object.freeze({ id: 'owner', username: 'owner' });
|
||||
const fail = (message, status) => Object.assign(new Error(message), { status });
|
||||
export function username(value) {
|
||||
if (typeof value !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9_-]{2,31}$/.test(value)) throw fail('Use a username of 3–32 letters, numbers, underscores or hyphens.', 400);
|
||||
return value.toLowerCase();
|
||||
}
|
||||
export const accountKey = name => `voxharbor:account:v1:${createHash('sha256').update(name).digest('hex')}`;
|
||||
export function createAccounts(config, store) {
|
||||
// Unknown accounts still perform the same password derivation as known accounts.
|
||||
let dummy;
|
||||
const dummyHash = () => config.passwordHash || (dummy ||= hashPassword(randomBytes(32).toString('hex')));
|
||||
async function find(name) {
|
||||
const serialized = await store.get(accountKey(name));
|
||||
if (serialized === null) return null;
|
||||
const record = JSON.parse(serialized);
|
||||
if (record.version !== 1 || record.username !== name || !/^[a-f0-9]{32}$/.test(record.id || '') || !/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/.test(record.passwordHash || '')) throw new Error('Account storage unavailable');
|
||||
return record;
|
||||
}
|
||||
return {
|
||||
async register(input) {
|
||||
if (config.registration === false) throw fail('Registration is currently closed.', 403);
|
||||
if (!config.identityKey) throw fail('Registration is unavailable until encrypted storage is configured.', 409);
|
||||
const name = username(input?.username);
|
||||
const passwordHash = await hashPassword(input?.password).catch(() => { throw fail('Use a password of 16–256 characters.', 400); });
|
||||
const record = { version: 1, id: randomBytes(16).toString('hex'), username: name, passwordHash, createdAt: new Date().toISOString() };
|
||||
// One atomic record owns both the username and ID: concurrent signup cannot replace an account.
|
||||
if (name === 'owner' || !await store.putIfAbsent(accountKey(name), JSON.stringify(record))) throw fail('Account could not be created. Choose another username or sign in.', 409);
|
||||
return { id: record.id, username: name };
|
||||
},
|
||||
async authenticate(input) {
|
||||
let name;
|
||||
try { name = username(input?.username === undefined ? 'owner' : input.username); } catch { name = null; }
|
||||
const record = name && name !== 'owner' ? await find(name) : null;
|
||||
const hash = name === 'owner' && config.passwordHash ? config.passwordHash : record?.passwordHash || await dummyHash();
|
||||
const valid = await verifyPassword(input?.password, hash);
|
||||
if (!valid || !name || (name === 'owner' ? !config.passwordHash : !record)) return null;
|
||||
return name === 'owner' ? owner : { id: record.id, username: record.username };
|
||||
},
|
||||
async principal(session) {
|
||||
// Pre-multi-user sessions belong only to the reserved legacy owner.
|
||||
if (session.userId === undefined) return config.passwordHash ? owner : null;
|
||||
if (session.userId === 'owner') return config.passwordHash && session.username === 'owner' ? owner : null;
|
||||
let name;
|
||||
try { name = username(session.username); } catch { return null; }
|
||||
if (name === 'owner') return null;
|
||||
const record = await find(name);
|
||||
return record && record.id === session.userId ? { id: record.id, username: record.username } : null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { randomBytes, scrypt as scryptCallback, timingSafeEqual } from 'node:crypto';
|
||||
import { promisify } from 'node:util';
|
||||
const scrypt = promisify(scryptCallback);
|
||||
|
||||
export async function hashPassword(password) {
|
||||
if (typeof password !== 'string' || password.length < 16 || password.length > 256) throw new Error('Use 16..256 characters');
|
||||
const salt = randomBytes(16).toString('hex');
|
||||
const key = await scrypt(password, salt, 64);
|
||||
return `scrypt:${salt}:${key.toString('hex')}`;
|
||||
}
|
||||
|
||||
export async function verifyPassword(password, hash) {
|
||||
if (typeof password !== 'string' || password.length > 256) return false;
|
||||
const [, salt, expected] = hash.split(':');
|
||||
const actual = await scrypt(password, salt, 64);
|
||||
return timingSafeEqual(actual, Buffer.from(expected, 'hex'));
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { createHash, createHmac, randomBytes } from 'node:crypto';
|
||||
|
||||
export function createSessions(config, store) {
|
||||
const name = config.secure ? '__Host-voxharbor' : 'voxharbor-local';
|
||||
const namespace = createHmac('sha256', config.secret).update('session-namespace-v1').digest('hex');
|
||||
function key(token) { return `vh:${namespace}:session:${createHash('sha256').update(token).digest('hex')}`; }
|
||||
function tokenFrom(req) {
|
||||
const cookies = (req.headers.cookie || '').split(';').map(s => s.trim());
|
||||
const values = cookies.filter(s => s.startsWith(`${name}=`));
|
||||
const token = values.length === 1 ? values[0].slice(name.length + 1) : '';
|
||||
return /^[a-f0-9]{64}$/.test(token) ? token : null;
|
||||
}
|
||||
function cookie(token, ttl) {
|
||||
return `${name}=${token}; Path=/; HttpOnly; SameSite=Strict; Max-Age=${ttl}${config.secure ? '; Secure' : ''}`;
|
||||
}
|
||||
return {
|
||||
async create(principal = { id: 'owner', username: 'owner' }) {
|
||||
const token = randomBytes(32).toString('hex');
|
||||
const session = { userId: principal.id, username: principal.username, csrf: randomBytes(32).toString('hex'), expires: Date.now() + config.sessionSeconds * 1000 };
|
||||
await store.set(key(token), JSON.stringify(session), config.sessionSeconds);
|
||||
return { session, cookie: cookie(token, config.sessionSeconds) };
|
||||
},
|
||||
async read(req) {
|
||||
const token = tokenFrom(req);
|
||||
if (!token) return null;
|
||||
const value = await store.get(key(token));
|
||||
if (!value) return null;
|
||||
const session = typeof value === 'string' ? JSON.parse(value) : value;
|
||||
return session.expires > Date.now() ? session : null;
|
||||
},
|
||||
async revoke(req) {
|
||||
const token = tokenFrom(req);
|
||||
if (token) await store.delete(key(token));
|
||||
return cookie('', 0);
|
||||
},
|
||||
rateKey(action) { return `vh:${namespace}:rate:${action}:${Math.floor(Date.now() / 60000)}`; },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Production state always lives in the owner's Redis, never the Function filesystem.
|
||||
export function createStore(config) {
|
||||
if (config.memory) {
|
||||
const entries = new Map();
|
||||
function get(key) {
|
||||
const entry = entries.get(key);
|
||||
if (!entry || entry.expires <= Date.now()) { entries.delete(key); return null; }
|
||||
return entry.value;
|
||||
}
|
||||
return {
|
||||
async get(key) { return get(key); },
|
||||
async set(key, value, ttl) { entries.set(key, { value, expires: Date.now() + ttl * 1000 }); },
|
||||
async delete(key) { entries.delete(key); },
|
||||
async putIfAbsent(key, value, ttl) {
|
||||
if (get(key) !== null) return false;
|
||||
entries.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : Infinity });
|
||||
return true;
|
||||
},
|
||||
async compareSet(key, expected, value, ttl) {
|
||||
if (get(key) !== expected) return false;
|
||||
entries.set(key, { value, expires: ttl ? Date.now() + ttl * 1000 : Infinity });
|
||||
return true;
|
||||
},
|
||||
async compareDelete(key, expected) {
|
||||
if (get(key) !== expected) return false;
|
||||
entries.delete(key);
|
||||
return true;
|
||||
},
|
||||
async limit(key, max, ttl) {
|
||||
// Prune development-only state so expired rate keys cannot accumulate.
|
||||
for (const k of entries.keys()) get(k);
|
||||
const count = Number(get(key) || 0) + 1;
|
||||
entries.set(key, { value: count, expires: entries.get(key)?.expires || Date.now() + ttl * 1000 });
|
||||
return count <= max;
|
||||
},
|
||||
};
|
||||
}
|
||||
async function command(args) {
|
||||
const response = await fetch(config.redisUrl, {
|
||||
method: 'POST', redirect: 'error', signal: AbortSignal.timeout(4000),
|
||||
headers: { Authorization: `Bearer ${config.redisToken}`, 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(args),
|
||||
});
|
||||
if (!response.ok) throw new Error('Session storage unavailable');
|
||||
const result = await response.json();
|
||||
if (result.error) throw new Error('Session storage unavailable');
|
||||
return result.result;
|
||||
}
|
||||
return {
|
||||
get: key => command(['GET', key]),
|
||||
set: (key, value, ttl) => command(['SET', key, value, 'EX', ttl]),
|
||||
delete: key => command(['DEL', key]),
|
||||
async putIfAbsent(key, value, ttl) {
|
||||
return (await command(['SET', key, value, 'NX', ...(ttl ? ['EX', ttl] : [])])) === 'OK';
|
||||
},
|
||||
async compareSet(key, expected, value, ttl) {
|
||||
return Number(await command(['EVAL', "if redis.call('GET',KEYS[1])~=ARGV[1] then return 0 end; redis.call('SET',KEYS[1],ARGV[2]); if tonumber(ARGV[3])>0 then redis.call('EXPIRE',KEYS[1],ARGV[3]) end; return 1", 1, key, expected, value, ttl || 0])) === 1;
|
||||
},
|
||||
async compareDelete(key, expected) {
|
||||
return Number(await command(['EVAL', "if redis.call('GET',KEYS[1])==ARGV[1] then return redis.call('DEL',KEYS[1]) end; return 0", 1, key, expected])) === 1;
|
||||
},
|
||||
async limit(key, max, ttl) {
|
||||
const count = await command(['EVAL', "local n=redis.call('INCR',KEYS[1]); if n==1 then redis.call('EXPIRE',KEYS[1],ARGV[1]) end; return n", 1, key, ttl]);
|
||||
return Number(count) <= max;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import { createVault } from '../identity/vault.mjs';
|
||||
import { createPreferences } from '../preferences.mjs';
|
||||
|
||||
export function createUserContext(config, store, principal) {
|
||||
if (!principal || !(principal.id === 'owner' || /^[a-f0-9]{32}$/.test(principal.id))) throw new Error('Invalid account scope');
|
||||
const legacy = principal.id === 'owner';
|
||||
const prefix = legacy ? '' : `voxharbor:user:v1:${principal.id}:`;
|
||||
const scoped = {};
|
||||
for (const method of ['get', 'set', 'delete', 'putIfAbsent', 'compareSet', 'compareDelete', 'limit']) {
|
||||
scoped[method] = (key, ...args) => store[method](prefix + key, ...args);
|
||||
}
|
||||
const scopedConfig = legacy ? config : { ...config, recordScope: principal.id, defaultNickname: principal.username };
|
||||
return { config: scopedConfig, store: scoped, vault: createVault(scopedConfig, scoped), preferences: createPreferences(scopedConfig, scoped) };
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
export function readConfig(env = process.env) {
|
||||
const production = env.VERCEL === '1' || env.NODE_ENV === 'production';
|
||||
const origin = new URL(env.APP_ORIGIN || 'http://localhost:3000');
|
||||
if (origin.origin !== env.APP_ORIGIN || origin.username || origin.password ||
|
||||
(production ? origin.protocol !== 'https:' : !['https:', 'http:'].includes(origin.protocol))) {
|
||||
throw new Error('APP_ORIGIN must be an exact origin (HTTPS in production)');
|
||||
}
|
||||
if (!/^[a-f0-9]{64}$/i.test(env.SESSION_SECRET || '')) throw new Error('SESSION_SECRET must be 32 random hex bytes');
|
||||
if (env.OWNER_PASSWORD_HASH && !/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/.test(env.OWNER_PASSWORD_HASH)) throw new Error('Configure OWNER_PASSWORD_HASH');
|
||||
if (env.ALLOW_REGISTRATION !== undefined && !['0', '1'].includes(env.ALLOW_REGISTRATION)) throw new Error('ALLOW_REGISTRATION must be 0 or 1');
|
||||
// The Vercel Marketplace integration provisions KV_* names by default.
|
||||
// Keep each credential pair together rather than mixing values from two stores.
|
||||
const explicitRedis = Boolean(env.UPSTASH_REDIS_REST_URL || env.UPSTASH_REDIS_REST_TOKEN);
|
||||
const redisUrl = explicitRedis ? env.UPSTASH_REDIS_REST_URL : env.KV_REST_API_URL;
|
||||
const redisToken = explicitRedis ? env.UPSTASH_REDIS_REST_TOKEN : env.KV_REST_API_TOKEN;
|
||||
if (redisUrl && new URL(redisUrl).protocol !== 'https:') throw new Error('Redis requires HTTPS');
|
||||
const memory = !production && env.ALLOW_LOCAL_MEMORY_STORE === '1';
|
||||
if (!memory && (!redisUrl || !redisToken)) throw new Error('Durable Redis sessions are required');
|
||||
for (const key of ['IDENTITY_ENCRYPTION_KEY', 'IDENTITY_PREVIOUS_ENCRYPTION_KEY']) {
|
||||
if (env[key] && !/^[a-f0-9]{64}$/i.test(env[key])) throw new Error(`${key} must be 32 random hex bytes`);
|
||||
}
|
||||
return {
|
||||
origin: origin.origin, secure: origin.protocol === 'https:', production,
|
||||
secret: env.SESSION_SECRET, passwordHash: env.OWNER_PASSWORD_HASH, registration: env.ALLOW_REGISTRATION !== '0',
|
||||
redisUrl, redisToken, memory,
|
||||
sessionSeconds: 900,
|
||||
identityKey: env.IDENTITY_ENCRYPTION_KEY, previousIdentityKey: env.IDENTITY_PREVIOUS_ENCRYPTION_KEY,
|
||||
protocolBinary: !production ? env.PROTOCOL_BINARY_PATH : undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { createServer } from 'node:http';
|
||||
import { readFile } from 'node:fs/promises';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { createStore } from './auth/store.mjs';
|
||||
import { createSessions } from './auth/session.mjs';
|
||||
import { createAccounts } from './auth/accounts.mjs';
|
||||
import { createUserContext } from './auth/user-context.mjs';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { identityOperation, nativeAvailable } from './platform/native-protocol.mjs';
|
||||
import { createProtocolControl } from './protocol/session.mjs';
|
||||
|
||||
const assets = new Map([
|
||||
['/favicon.ico', ['favicon.ico', 'image/x-icon']],
|
||||
...['favicon.svg', 'icons/safari-pinned-tab.svg'].map(file => [`/${file}`, [file, 'image/svg+xml']]),
|
||||
...['favicon-16x16.png', 'favicon-32x32.png', 'apple-touch-icon.png', 'icons/app-192.png', 'icons/app-512.png', 'icons/app-maskable-512.png'].map(file => [`/${file}`, [file, 'image/png']]),
|
||||
['/site.webmanifest', ['site.webmanifest', 'application/manifest+json']],
|
||||
['/', ['index.html', 'text/html; charset=utf-8']],
|
||||
['/app.mjs', ['app.mjs', 'text/javascript; charset=utf-8']],
|
||||
['/workspace.mjs', ['workspace.mjs', 'text/javascript; charset=utf-8']],
|
||||
['/workspace-model.mjs', ['workspace-model.mjs', 'text/javascript; charset=utf-8']],
|
||||
['/style.css', ['style.css', 'text/css; charset=utf-8']],
|
||||
...['ibm-plex-sans-regular', 'ibm-plex-sans-medium', 'ibm-plex-sans-semibold', 'ibm-plex-mono-regular', 'ibm-plex-mono-medium'].map(name => [`/fonts/${name}.ttf`, [`fonts/${name}.ttf`, 'font/ttf']]),
|
||||
...['microphone', 'headphones'].map(name => [`/icons/${name}.svg`, [`icons/${name}.svg`, 'image/svg+xml']]),
|
||||
['/fonts/OFL.txt', ['fonts/OFL.txt', 'text/plain; charset=utf-8']],
|
||||
['/protocol.mjs', ['protocol.mjs', 'text/javascript; charset=utf-8']],
|
||||
['/protocol-connection.mjs', ['protocol-connection.mjs', 'text/javascript; charset=utf-8']],
|
||||
['/channel-order.mjs', ['channel-order.mjs', 'text/javascript; charset=utf-8']],
|
||||
...['audio-recovery.mjs', 'connection-diagnostics.mjs', 'voice.mjs', 'voice-frame.mjs', 'voice-worker.mjs', 'voice-worklet.mjs', 'jitter-buffer.mjs', 'vendor/opus/index.js', 'vendor/opus/generated/libopus.generated.mjs'].map(file => [`/${file}`, [file, 'text/javascript; charset=utf-8']]),
|
||||
...['LICENSE', 'THIRD_PARTY_NOTICES.md', 'COPYING.libopus'].map(file => [`/vendor/opus/${file}`, [`vendor/opus/${file}`, 'text/plain; charset=utf-8']]),
|
||||
]);
|
||||
|
||||
export function createApp(config, store = createStore(config)) {
|
||||
const sessions = createSessions(config, store);
|
||||
const accounts = createAccounts(config, store);
|
||||
async function readSession(req) {
|
||||
const session = await sessions.read(req);
|
||||
if (!session) return null;
|
||||
const principal = await accounts.principal(session);
|
||||
return principal ? { ...session, principal } : null;
|
||||
}
|
||||
const instance = randomUUID();
|
||||
const wss = new WebSocketServer({ noServer: true, maxPayload: 4096, perMessageDeflate: false });
|
||||
const metadata = () => ({
|
||||
node: process.version, platform: process.platform, arch: process.arch, instance,
|
||||
environment: config.production ? 'deployment' : 'local',
|
||||
deployment: process.env.VERCEL_URL || null, region: process.env.VERCEL_REGION || null,
|
||||
sessionStore: config.memory ? 'volatile-development' : 'redis',
|
||||
teamSpeak: 'ts3-opus-experimental',
|
||||
});
|
||||
function originAllowed(req) { return req.headers.origin === config.origin; }
|
||||
function reply(res, status, data, headers = {}) {
|
||||
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', ...headers });
|
||||
res.end(JSON.stringify(data));
|
||||
}
|
||||
async function body(req, maxSize = 2048) {
|
||||
if (req.headers['content-type'] !== 'application/json') throw Object.assign(new Error('Expected JSON'), { status: 415 });
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
if (size > maxSize) throw Object.assign(new Error('Request too large'), { status: 413 });
|
||||
chunks.push(chunk);
|
||||
}
|
||||
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
||||
catch { throw Object.assign(new Error('Invalid JSON'), { status: 400 }); }
|
||||
}
|
||||
const server = createServer(async (req, res) => {
|
||||
res.setHeader('Cache-Control', 'no-store');
|
||||
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||
res.setHeader('X-Frame-Options', 'DENY');
|
||||
res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; style-src 'self'; font-src 'self'; img-src 'self'; manifest-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'");
|
||||
if (config.secure) res.setHeader('Strict-Transport-Security', 'max-age=31536000');
|
||||
try {
|
||||
const url = new URL(req.url, config.origin);
|
||||
// Never accept credentials, alternate destinations, or probe configuration in URLs.
|
||||
if (url.search) return reply(res, 400, { error: 'Query parameters are not accepted' });
|
||||
if (req.method === 'GET' && assets.has(url.pathname)) {
|
||||
const [file, contentType] = assets.get(url.pathname);
|
||||
const content = await readFile(new URL(`../public/${file}`, import.meta.url));
|
||||
res.writeHead(200, { 'Content-Type': contentType });
|
||||
return res.end(content);
|
||||
}
|
||||
if (req.method === 'POST' && !originAllowed(req)) return reply(res, 403, { error: 'Origin rejected' });
|
||||
if (url.pathname === '/api/auth' && req.method === 'GET') return reply(res, 200, { registrationEnabled: config.registration !== false && Boolean(config.identityKey), ownerAvailable: Boolean(config.passwordHash) });
|
||||
if (['/api/login', '/api/register'].includes(url.pathname) && req.method === 'POST') {
|
||||
const registering = url.pathname === '/api/register';
|
||||
if (!await store.limit(sessions.rateKey(registering ? 'registration-global' : 'login-global'), registering ? 10 : 120, 60)) return reply(res, 429, { error: 'Authentication limit reached; try again in one minute' });
|
||||
const input = await body(req);
|
||||
const name = typeof input?.username === 'string' ? input.username.toLowerCase() : 'owner';
|
||||
const bucket = createHash('sha256').update(name).digest('hex');
|
||||
if (!await store.limit(sessions.rateKey(`authentication:${bucket}`), 10, 60)) return reply(res, 429, { error: 'Authentication limit reached; try again in one minute' });
|
||||
const principal = registering ? await accounts.register(input) : await accounts.authenticate(input);
|
||||
if (!principal) return reply(res, 401, { error: 'Invalid username or password' });
|
||||
// Replacing a browser's login revokes its previous session and stops only that session's sockets.
|
||||
const previous = await sessions.read(req);
|
||||
await sessions.revoke(req);
|
||||
if (previous) for (const ws of wss.clients) if (ws.sessionCsrf === previous.csrf) ws.close(4401, 'Session replaced');
|
||||
const result = await sessions.create(principal);
|
||||
return reply(res, registering ? 201 : 200, { csrf: result.session.csrf, user: { username: principal.username } }, { 'Set-Cookie': result.cookie });
|
||||
}
|
||||
const session = await readSession(req);
|
||||
if (!session) return reply(res, 401, { error: 'Sign-in required' });
|
||||
const { vault, preferences, store: userStore } = createUserContext(config, store, session.principal);
|
||||
if (req.method === 'POST' && req.headers['x-csrf-token'] !== session.csrf) return reply(res, 403, { error: 'CSRF check failed' });
|
||||
if (url.pathname === '/api/session' && req.method === 'GET') return reply(res, 200, { csrf: session.csrf, expires: session.expires, user: { username: session.principal.username }, runtime: metadata() });
|
||||
if (url.pathname === '/api/preferences' && req.method === 'GET') return reply(res, 200, await preferences.read());
|
||||
if (url.pathname === '/api/connection' && req.method === 'POST') {
|
||||
if (!await userStore.limit(sessions.rateKey('connection-settings'), 30, 60)) return reply(res, 429, { error: 'Connection save limit reached; try again shortly.' });
|
||||
return reply(res, 200, await preferences.saveConnection(await body(req, 8192)));
|
||||
}
|
||||
if (url.pathname === '/api/preferences' && req.method === 'POST') {
|
||||
if (!await userStore.limit(sessions.rateKey('preferences'), 30, 60)) return reply(res, 429, { error: 'Preference save limit reached; try again shortly.' });
|
||||
return reply(res, 200, await preferences.save(await body(req, 65536)));
|
||||
}
|
||||
if (url.pathname === '/api/preferences/rotate' && req.method === 'POST') { await preferences.rotate(); return reply(res, 200, { rotated: true }); }
|
||||
if (url.pathname === '/api/protocol' && req.method === 'GET') {
|
||||
return reply(res, 200, { nativeAvailable: await nativeAvailable(config), identityEncryptionConfigured: vault.configured(),
|
||||
library: 'ReSpeak/tsclientlib', revision: 'ee3bc6f45a7137db7793ba5593a321df400d53e5', voice: 'opus-synthetic-network-verified' });
|
||||
}
|
||||
if (url.pathname === '/api/identity' && req.method === 'GET') {
|
||||
const identity = await vault.read();
|
||||
return reply(res, 200, { identity: identity ? { ...identity.metadata, createdAt: identity.createdAt } : null });
|
||||
}
|
||||
if (['/api/identity/create', '/api/identity/import'].includes(url.pathname) && req.method === 'POST') {
|
||||
if (!await userStore.limit(sessions.rateKey('identity'), 3, 60)) return reply(res, 429, { error: 'Identity operation limit reached' });
|
||||
if (!vault.configured()) return reply(res, 409, { error: 'Configure IDENTITY_ENCRYPTION_KEY first' });
|
||||
if (await vault.read()) return reply(res, 409, { error: 'An identity already exists; it was not replaced' });
|
||||
let request = { op: 'generate' };
|
||||
if (url.pathname.endsWith('/import')) {
|
||||
const input = await body(req, 20000);
|
||||
if (typeof input?.value !== 'string' || input.value.length > 16384) return reply(res, 400, { error: 'Invalid identity import' });
|
||||
// Official-client INI export or the compatible identity string itself.
|
||||
const match = input.value.match(/^identity\s*=\s*"?([^"\r\n]+)"?\s*$/mi);
|
||||
request = { op: 'import', value: (match ? match[1] : input.value).trim() };
|
||||
}
|
||||
const generated = await identityOperation(config, request);
|
||||
return reply(res, 201, { identity: await vault.initialize(generated) });
|
||||
}
|
||||
if (url.pathname === '/api/identity/export' && req.method === 'POST') {
|
||||
const identity = await vault.read();
|
||||
if (!identity) return reply(res, 404, { error: 'No identity exists' });
|
||||
const exported = await identityOperation(config, { op: 'export', identity: identity.identity });
|
||||
res.writeHead(200, { 'Content-Type': 'application/octet-stream', 'Content-Disposition': 'attachment; filename="VoxHarbor-identity.ini"' });
|
||||
return res.end(`[Identity]\nid=VoxHarbor\nidentity="${exported.value}"\nnickname=VoxHarbor\n`);
|
||||
}
|
||||
if (url.pathname === '/api/identity/rotate' && req.method === 'POST') return reply(res, 200, { identity: await vault.rotate() });
|
||||
if (url.pathname === '/api/logout' && req.method === 'POST') {
|
||||
const cookie = await sessions.revoke(req);
|
||||
for (const ws of wss.clients) if (ws.sessionCsrf === session.csrf) ws.close(4401, 'Session revoked');
|
||||
return reply(res, 200, { signedOut: true }, { 'Set-Cookie': cookie });
|
||||
}
|
||||
return reply(res, 404, { error: 'Route not found' });
|
||||
} catch (error) {
|
||||
// Never emit exception messages that might contain storage credentials or user input.
|
||||
reply(res, error.status || 503, { error: error.status ? error.message : 'Service unavailable; check configuration and storage' });
|
||||
}
|
||||
});
|
||||
server.requestTimeout = 10000;
|
||||
server.headersTimeout = 10000;
|
||||
server.on('upgrade', async (req, socket, head) => {
|
||||
socket.on('error', () => {});
|
||||
socket.setTimeout(10000, () => socket.destroy());
|
||||
function reject(status) {
|
||||
socket.end(`HTTP/1.1 ${status}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
|
||||
}
|
||||
try {
|
||||
if (req.method !== 'GET' || req.url !== '/api/ts3' || !originAllowed(req)) return reject('403 Forbidden');
|
||||
const session = await readSession(req);
|
||||
if (!session) return reject('401 Unauthorized');
|
||||
const context = createUserContext(config, store, session.principal);
|
||||
if (!await context.store.limit(sessions.rateKey('ws'), 60, 60)) return reject('429 Too Many Requests');
|
||||
if (socket.destroyed) return;
|
||||
socket.setTimeout(0);
|
||||
wss.handleUpgrade(req, socket, head, ws => {
|
||||
ws.sessionCsrf = session.csrf;
|
||||
let count = 0;
|
||||
let voiceCount = 0;
|
||||
let windowStart = Date.now();
|
||||
let checking = false;
|
||||
let validatedUntil = Date.now() + 1000;
|
||||
const stopTimers = [];
|
||||
const close = (code, reason) => {
|
||||
if (ws.readyState !== 1) return;
|
||||
ws.close(code, reason);
|
||||
stopTimers.push(setTimeout(() => ws.terminate(), 1000));
|
||||
};
|
||||
const protocol = createProtocolControl(ws, { ...context, csrf: session.csrf, close });
|
||||
const sendMetadata = () => ws.send(JSON.stringify({ type: 'runtime', ...metadata(), connectedAt: new Date().toISOString() }));
|
||||
ws.on('error', () => {});
|
||||
ws.on('close', () => stopTimers.forEach(clearTimeout));
|
||||
ws.on('close', () => { void protocol?.stop().catch(() => {}); });
|
||||
// Cross-instance revocation is rechecked at least once per second, failing closed.
|
||||
const validate = async () => {
|
||||
if (checking) return false;
|
||||
checking = true;
|
||||
try {
|
||||
if (!await readSession(req)) { close(4401, 'Session expired or revoked'); return false; }
|
||||
validatedUntil = Date.now() + 1000;
|
||||
return true;
|
||||
} catch { close(1011, 'Session storage unavailable'); return false; }
|
||||
finally { checking = false; }
|
||||
};
|
||||
stopTimers.push(setInterval(() => { void validate(); }, 1000));
|
||||
stopTimers.push(setTimeout(() => close(4401, 'Session expired'), Math.max(1, session.expires - Date.now())));
|
||||
ws.on('message', async (data, isBinary) => {
|
||||
if (Date.now() - windowStart >= 1000) { count = 0; voiceCount = 0; windowStart = Date.now(); }
|
||||
const exceeded = isBinary ? ++voiceCount > 65 : ++count > 20;
|
||||
if (exceeded || ws.bufferedAmount > 65536) return close(1008, 'Transport capacity exceeded');
|
||||
if (Date.now() >= validatedUntil && !await validate()) return;
|
||||
if (ws.readyState !== 1) return;
|
||||
if (isBinary) return protocol.voice(data);
|
||||
try { await protocol.command(data); } catch { close(1011, 'Protocol command failed'); }
|
||||
});
|
||||
sendMetadata();
|
||||
});
|
||||
} catch { reject('503 Service Unavailable'); }
|
||||
});
|
||||
return { server, wss, sessions };
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
||||
|
||||
const STORAGE_KEY = 'voxharbor:identity:v1:owner';
|
||||
function unavailable(message) { return Object.assign(new Error(message), { status: 503 }); }
|
||||
function keysFor(config) {
|
||||
const values = [config.identityKey, config.previousIdentityKey].filter(Boolean);
|
||||
if (!values.length) throw Object.assign(new Error('Configure a separate IDENTITY_ENCRYPTION_KEY before creating an identity'), { status: 409 });
|
||||
return values.map(value => {
|
||||
if (!/^[a-f0-9]{64}$/i.test(value)) throw unavailable('Identity encryption key is invalid');
|
||||
const key = Buffer.from(value, 'hex');
|
||||
return { key, id: createHash('sha256').update(key).digest('hex').slice(0, 16) };
|
||||
});
|
||||
}
|
||||
export function sealIdentity(config, identity) {
|
||||
const { key, id } = keysFor(config)[0];
|
||||
const iv = randomBytes(12);
|
||||
const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||
cipher.setAAD(Buffer.from(`voxharbor:identity:v1:owner:${id}${config.recordScope ? `:user:${config.recordScope}` : ''}`));
|
||||
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(identity), 'utf8'), cipher.final()]);
|
||||
return JSON.stringify({ version: 1, keyId: id, iv: iv.toString('base64'), ciphertext: ciphertext.toString('base64'), tag: cipher.getAuthTag().toString('base64') });
|
||||
}
|
||||
export function openIdentity(config, serialized) {
|
||||
try {
|
||||
const envelope = typeof serialized === 'string' ? JSON.parse(serialized) : serialized;
|
||||
const { key, id } = keysFor(config).find(item => item.id === envelope.keyId) || {};
|
||||
if (envelope.version !== 1 || !key) throw new Error();
|
||||
const iv = Buffer.from(envelope.iv, 'base64');
|
||||
const tag = Buffer.from(envelope.tag, 'base64');
|
||||
if (iv.length !== 12 || tag.length !== 16) throw new Error();
|
||||
const decipher = createDecipheriv('aes-256-gcm', key, iv);
|
||||
decipher.setAAD(Buffer.from(`voxharbor:identity:v1:owner:${id}${config.recordScope ? `:user:${config.recordScope}` : ''}`));
|
||||
decipher.setAuthTag(tag);
|
||||
const data = JSON.parse(Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, 'base64')), decipher.final()]).toString('utf8'));
|
||||
if (!data.identity || !data.metadata?.uid || !Number.isInteger(data.metadata.level)) throw new Error();
|
||||
return data;
|
||||
} catch { throw unavailable('Identity could not be decrypted. Restore the correct encryption key and ciphertext; no identity was regenerated.'); }
|
||||
}
|
||||
export function createVault(config, store) {
|
||||
return {
|
||||
configured: () => Boolean(config.identityKey),
|
||||
async read() {
|
||||
const record = await store.get(STORAGE_KEY);
|
||||
return record === null ? null : openIdentity(config, record);
|
||||
},
|
||||
async initialize(result) {
|
||||
const record = { identity: result.identity, metadata: result.metadata, createdAt: new Date().toISOString() };
|
||||
const encrypted = sealIdentity(config, record);
|
||||
if (!await store.putIfAbsent(STORAGE_KEY, encrypted)) {
|
||||
throw Object.assign(new Error('An identity already exists; it was not replaced'), { status: 409 });
|
||||
}
|
||||
return { ...record.metadata, createdAt: record.createdAt };
|
||||
},
|
||||
async update(result) {
|
||||
const serialized = await store.get(STORAGE_KEY);
|
||||
if (serialized === null) throw unavailable('Stored identity is missing; reconnect stopped');
|
||||
const current = openIdentity(config, serialized);
|
||||
// An offset upgrade must preserve the actual private key, not just a claimed UID.
|
||||
if (current.metadata.uid !== result.metadata.uid || current.identity.key !== result.identity.key) throw unavailable('Protocol identity changed unexpectedly');
|
||||
const next = sealIdentity(config, { ...current, identity: result.identity, metadata: result.metadata });
|
||||
if (!await store.compareSet(STORAGE_KEY, serialized, next)) throw unavailable('Identity changed concurrently; reconnect stopped');
|
||||
return result.metadata;
|
||||
},
|
||||
async rotate() {
|
||||
const serialized = await store.get(STORAGE_KEY);
|
||||
if (serialized === null) throw Object.assign(new Error('No identity exists'), { status: 404 });
|
||||
const current = openIdentity(config, serialized);
|
||||
if (!await store.compareSet(STORAGE_KEY, serialized, sealIdentity(config, current))) throw unavailable('Identity changed concurrently');
|
||||
return current.metadata;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { access, constants } from 'node:fs/promises';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { StringDecoder } from 'node:string_decoder';
|
||||
|
||||
export function protocolBinary(config) {
|
||||
return config.protocolBinary || fileURLToPath(new URL('../../native/bin/voxharbor-protocol', import.meta.url));
|
||||
}
|
||||
export async function nativeAvailable(config) {
|
||||
try { await access(protocolBinary(config), constants.X_OK); return true; } catch { return false; }
|
||||
}
|
||||
|
||||
export function spawnProtocol(config, request, onEvent) {
|
||||
const child = spawn(protocolBinary(config), [], {
|
||||
stdio: ['pipe', 'pipe', 'ignore'],
|
||||
// Never inherit deployment secrets into the protocol implementation.
|
||||
env: { PATH: '/usr/bin:/bin', RUST_BACKTRACE: '0' },
|
||||
windowsHide: true,
|
||||
});
|
||||
child.stdin.on('error', () => {});
|
||||
let failed;
|
||||
let stopTimer;
|
||||
const watchdog = setTimeout(() => child.kill('SIGKILL'), ((request.seconds || 20) + 5) * 1000);
|
||||
const exited = new Promise(resolve => {
|
||||
child.once('error', () => { failed = new Error('Native protocol executable unavailable'); resolve(-1); });
|
||||
child.once('close', code => resolve(code));
|
||||
});
|
||||
const done = (async () => {
|
||||
let buffer = '';
|
||||
const decoder = new StringDecoder('utf8');
|
||||
try {
|
||||
child.stdin.write(`${JSON.stringify(request)}\n`);
|
||||
for await (const chunk of child.stdout) {
|
||||
buffer += decoder.write(chunk);
|
||||
if (Buffer.byteLength(buffer) > 2 * 1024 * 1024) throw new Error('Native protocol output capacity exceeded');
|
||||
let index;
|
||||
while ((index = buffer.indexOf('\n')) >= 0) {
|
||||
const line = buffer.slice(0, index);
|
||||
buffer = buffer.slice(index + 1);
|
||||
if (line) {
|
||||
const event = JSON.parse(line);
|
||||
await onEvent(event);
|
||||
// Tokio's stdin reader can remain blocked after the connection ends.
|
||||
// Deliver EOF so runtime shutdown completes and the session lease releases.
|
||||
const terminal = event.type === 'error' || (event.type === 'status' && event.status === 'disconnected');
|
||||
if (terminal && !child.stdin.destroyed && !child.stdin.writableEnded) child.stdin.end();
|
||||
}
|
||||
}
|
||||
}
|
||||
const code = await exited;
|
||||
if (failed || code !== 0 || buffer.trim()) throw new Error('Native protocol operation failed');
|
||||
} catch (error) {
|
||||
child.kill('SIGKILL');
|
||||
throw new Error(error.message === 'Native protocol executable unavailable' ? error.message : 'Native protocol operation failed');
|
||||
} finally { clearTimeout(watchdog); clearTimeout(stopTimer); }
|
||||
})();
|
||||
return {
|
||||
done,
|
||||
send(command) {
|
||||
if (child.exitCode !== null || child.stdin.destroyed || child.stdin.writableEnded || stopTimer) return false;
|
||||
// Drop voice before it accumulates in the pipe. Never replay stale microphone audio.
|
||||
if (child.stdin.writableLength > 8192) return false;
|
||||
child.stdin.write(`${JSON.stringify(command)}\n`);
|
||||
return true;
|
||||
},
|
||||
stop() {
|
||||
if (child.exitCode !== null || stopTimer) return;
|
||||
child.stdin.end('{"op":"disconnect"}\n');
|
||||
stopTimer = setTimeout(() => child.kill('SIGKILL'), 2000);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export async function identityOperation(config, request) {
|
||||
let result;
|
||||
const native = spawnProtocol(config, request, event => {
|
||||
if (['identity_internal', 'identity_metadata', 'export_internal'].includes(event.type)) result = event;
|
||||
else if (event.type === 'error') throw new Error('Identity operation failed');
|
||||
});
|
||||
await native.done;
|
||||
if (!result) throw new Error('Native identity response missing');
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto';
|
||||
const STORAGE_KEY = 'voxharbor:preferences:v1:owner';
|
||||
const fail = (message, status = 400) => Object.assign(new Error(message), { status });
|
||||
const plain = value => value && typeof value === 'object' && !Array.isArray(value);
|
||||
const text = (value, max, empty = false) => typeof value === 'string' && value.length <= max && (empty || value.trim()) && !/[\u0000-\u001f\u007f]/.test(value);
|
||||
export function destinationOptions(input) {
|
||||
if (!plain(input) || !text(input.host, 253) || !/^[a-zA-Z0-9.-]+$/.test(input.host) || !Number.isInteger(input.port) || input.port < 1024 || input.port > 65535) throw fail('Enter a hostname or public IPv4 address and a port from 1024 to 65535.');
|
||||
return { host: input.host.toLowerCase(), port: input.port };
|
||||
}
|
||||
export function connectionOptions(input) {
|
||||
if (!plain(input) || !text(input.nickname, 64) || (input.channelId !== undefined && input.channelId !== null && (!Number.isSafeInteger(input.channelId) || input.channelId < 1)) || !text(input.password ?? '', 256, true) || !text(input.channelPassword ?? '', 256, true)) throw fail('Invalid connection settings.');
|
||||
return { ...destinationOptions(input), nickname: input.nickname.trim(), channelId: input.channelId || null, password: input.password || '', channelPassword: input.channelPassword || '' };
|
||||
}
|
||||
export function normalizePreferences(input) {
|
||||
if (!plain(input) || !['system', 'light', 'dark'].includes(input.theme) || !text(input.nickname, 64) || !Array.isArray(input.bookmarks) || input.bookmarks.length > 20) throw fail('Invalid workspace preferences.');
|
||||
const ids = new Set();
|
||||
const bookmarks = input.bookmarks.map(bookmark => {
|
||||
if (!plain(bookmark) || !/^[A-Za-z0-9_-]{1,64}$/.test(bookmark.id || '') || ids.has(bookmark.id) || !text(bookmark.name, 80) || !text(bookmark.nickname, 64) || (bookmark.channelId !== undefined && bookmark.channelId !== null && (!Number.isSafeInteger(bookmark.channelId) || bookmark.channelId < 1)) || !text(bookmark.password ?? '', 256, true) || !text(bookmark.channelPassword ?? '', 256, true)) throw fail('Invalid saved connection.');
|
||||
ids.add(bookmark.id);
|
||||
return { id: bookmark.id, name: bookmark.name.trim(), ...connectionOptions(bookmark) };
|
||||
});
|
||||
let connection = null;
|
||||
if (input.connection !== undefined && input.connection !== null) {
|
||||
if (!/^[a-f0-9]{32}$/.test(input.connection.id || '')) throw fail('Invalid saved connection ID.');
|
||||
connection = { id: input.connection.id, ...connectionOptions(input.connection) };
|
||||
}
|
||||
return { version: 1, theme: input.theme, nickname: input.nickname.trim(), bookmarks, connection };
|
||||
}
|
||||
const defaults = () => ({ version: 1, theme: 'system', nickname: 'VoxHarbor', bookmarks: [], connection: null });
|
||||
function keys(config) {
|
||||
const values = [config.identityKey, config.previousIdentityKey].filter(Boolean);
|
||||
if (!values.length || values.some(value => !/^[a-f0-9]{64}$/i.test(value))) throw fail('A valid identity encryption key is required to save preferences.', 409);
|
||||
return values.map(value => { const key = Buffer.from(value, 'hex'); return { key, id: createHash('sha256').update(key).digest('hex').slice(0, 16) }; });
|
||||
}
|
||||
function seal(config, value) {
|
||||
const { key, id } = keys(config)[0]; const iv = randomBytes(12); const cipher = createCipheriv('aes-256-gcm', key, iv);
|
||||
cipher.setAAD(Buffer.from(`${STORAGE_KEY}:${id}${config.recordScope ? `:user:${config.recordScope}` : ''}`));
|
||||
const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value)), cipher.final()]);
|
||||
return JSON.stringify({ version: 1, keyId: id, iv: iv.toString('base64'), ciphertext: ciphertext.toString('base64'), tag: cipher.getAuthTag().toString('base64') });
|
||||
}
|
||||
function open(config, serialized) {
|
||||
try {
|
||||
const envelope = JSON.parse(serialized); const { key, id } = keys(config).find(item => item.id === envelope.keyId) || {};
|
||||
if (!key || envelope.version !== 1) throw new Error();
|
||||
const iv = Buffer.from(envelope.iv, 'base64'); const tag = Buffer.from(envelope.tag, 'base64'); if (iv.length !== 12 || tag.length !== 16) throw new Error();
|
||||
const decipher = createDecipheriv('aes-256-gcm', key, iv); decipher.setAAD(Buffer.from(`${STORAGE_KEY}:${id}${config.recordScope ? `:user:${config.recordScope}` : ''}`)); decipher.setAuthTag(tag);
|
||||
return normalizePreferences(JSON.parse(Buffer.concat([decipher.update(Buffer.from(envelope.ciphertext, 'base64')), decipher.final()]).toString('utf8')));
|
||||
} catch { throw fail('Saved preferences could not be decrypted. Restore the correct key; existing data was not replaced.', 503); }
|
||||
}
|
||||
function metadata(value) {
|
||||
const redact = ({ password, channelPassword, ...connection }) => ({ ...connection, hasPassword: Boolean(password), hasChannelPassword: Boolean(channelPassword) });
|
||||
return { version: 1, theme: value.theme, nickname: value.nickname, bookmarks: value.bookmarks.map(redact), connection: value.connection ? redact(value.connection) : null };
|
||||
}
|
||||
const revision = serialized => serialized === null ? 'empty' : createHash('sha256').update(serialized).digest('hex');
|
||||
export function createPreferences(config, store) {
|
||||
async function read() { const serialized = await store.get(STORAGE_KEY); return { serialized, value: serialized === null ? { ...defaults(), nickname: config.defaultNickname || 'VoxHarbor' } : open(config, serialized) }; }
|
||||
return {
|
||||
async read() { const previous = await read(); return { ...metadata(previous.value), revision: revision(previous.serialized) }; },
|
||||
async save(input) {
|
||||
const previous = await read();
|
||||
if (input?.revision !== revision(previous.serialized)) throw fail('Preferences changed in another session. Reload before saving again.', 409);
|
||||
// Missing password fields preserve existing ciphertext-backed secrets. Explicit empty strings clear them.
|
||||
const merged = plain(input) && Array.isArray(input.bookmarks) ? { ...input, bookmarks: input.bookmarks.map(bookmark => {
|
||||
const old = previous.value.bookmarks.find(item => item.id === bookmark?.id);
|
||||
const sameServer = old && typeof bookmark?.host === 'string' && old.host === bookmark.host.toLowerCase() && old.port === bookmark.port;
|
||||
const sameChannel = sameServer && old.channelId === (bookmark.channelId || null);
|
||||
return { ...bookmark, password: bookmark?.password === undefined ? (sameServer ? old.password : '') : bookmark.password, channelPassword: bookmark?.channelPassword === undefined ? (sameChannel ? old.channelPassword : '') : bookmark.channelPassword };
|
||||
}) } : input;
|
||||
const value = normalizePreferences({ ...merged, connection: previous.value.connection }); const encrypted = seal(config, value);
|
||||
const saved = previous.serialized === null ? await store.putIfAbsent(STORAGE_KEY, encrypted) : await store.compareSet(STORAGE_KEY, previous.serialized, encrypted);
|
||||
if (!saved) throw fail('Preferences changed in another session. Reload before saving again.', 409);
|
||||
return { ...metadata(value), revision: revision(encrypted) };
|
||||
},
|
||||
async connection(id) {
|
||||
const bookmark = (await read()).value.bookmarks.find(bookmark => bookmark.id === id);
|
||||
if (!bookmark) throw fail('Saved connection not found.', 404);
|
||||
return bookmark;
|
||||
},
|
||||
async activeConnection(id) {
|
||||
const connection = (await read()).value.connection;
|
||||
if (!connection) throw Object.assign(fail('Save connection settings before connecting.', 409), { code: 'connection_required' });
|
||||
if (connection.id !== id) throw Object.assign(fail('Connection settings changed. Reload before connecting.', 409), { code: 'connection_settings_changed' });
|
||||
return connection;
|
||||
},
|
||||
async saveConnection(input) {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const previous = await read();
|
||||
let old = previous.value.connection;
|
||||
if (input?.bookmarkId !== undefined) {
|
||||
if (typeof input.bookmarkId !== 'string') throw fail('Invalid saved connection reference.');
|
||||
old = previous.value.bookmarks.find(bookmark => bookmark.id === input.bookmarkId);
|
||||
if (!old) throw fail('Saved connection not found. Reload before connecting.', 404);
|
||||
}
|
||||
const normalized = connectionOptions(input);
|
||||
const sameServer = old && old.host === normalized.host && old.port === normalized.port;
|
||||
const sameChannel = sameServer && old.channelId === normalized.channelId;
|
||||
const connection = { id: randomBytes(16).toString('hex'), ...normalized,
|
||||
password: input.password === undefined && sameServer ? old.password : normalized.password,
|
||||
channelPassword: input.channelPassword === undefined && sameChannel ? old.channelPassword : normalized.channelPassword };
|
||||
const value = { ...previous.value, nickname: connection.nickname, connection }; const encrypted = seal(config, value);
|
||||
const saved = previous.serialized === null ? await store.putIfAbsent(STORAGE_KEY, encrypted) : await store.compareSet(STORAGE_KEY, previous.serialized, encrypted);
|
||||
if (saved) return { ...metadata(value), revision: revision(encrypted) };
|
||||
}
|
||||
throw fail('Connection settings changed concurrently. Try saving again.', 409);
|
||||
},
|
||||
async updateConnection(id, changes) {
|
||||
for (let attempt = 0; attempt < 3; attempt++) {
|
||||
const previous = await read(); const old = previous.value.connection;
|
||||
if (!old || old.id !== id) return false;
|
||||
const connection = { id, ...connectionOptions({ ...old, ...changes }) };
|
||||
const value = { ...previous.value, nickname: connection.nickname, connection }; const encrypted = seal(config, value);
|
||||
if (await store.compareSet(STORAGE_KEY, previous.serialized, encrypted)) return { ...metadata(value), revision: revision(encrypted) };
|
||||
}
|
||||
return false;
|
||||
},
|
||||
async rotate() {
|
||||
const previous = await read(); if (previous.serialized === null) return;
|
||||
if (!await store.compareSet(STORAGE_KEY, previous.serialized, seal(config, previous.value))) throw fail('Preferences changed concurrently.', 409);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
const id = (value, max = Number.MAX_SAFE_INTEGER) => Number.isSafeInteger(value) && value > 0 && value <= max;
|
||||
const uid = value => value === undefined || /^[A-Za-z0-9+/]{27}=$/.test(value);
|
||||
const text = (value, bytes, empty = false) => typeof value === 'string' && (empty || value.trim().length > 0) && Buffer.byteLength(value) <= bytes && !/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/.test(value);
|
||||
// Construct fresh typed controls. Never forward arbitrary protocol names or arguments.
|
||||
export function normalizeCommand(input) {
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input)) return null;
|
||||
switch (input.type) {
|
||||
case 'join_channel':
|
||||
return id(input.channelId) && (input.password === undefined || text(input.password, 1024, true)) && (input.password?.length ?? 0) <= 256
|
||||
? { type: input.type, channel_id: input.channelId, password: input.password || null } : null;
|
||||
case 'subscribe':
|
||||
return id(input.channelId) && typeof input.subscribed === 'boolean' ? { type: input.type, channel_id: input.channelId, subscribed: input.subscribed } : null;
|
||||
case 'nickname':
|
||||
return text(input.name, 256) && [...input.name].length <= 64 ? { type: input.type, name: input.name.trim() } : null;
|
||||
case 'away':
|
||||
return typeof input.away === 'boolean' && text(input.message ?? '', 500, true) ? { type: input.type, away: input.away, message: input.message || '' } : null;
|
||||
case 'text_message':
|
||||
return ['channel', 'server', 'private'].includes(input.target) && text(input.message, 1000) && (input.target !== 'channel' || id(input.channelId)) && (input.target !== 'private' || (id(input.clientId, 65535) && uid(input.clientUid)))
|
||||
? { type: input.type, target: input.target, channel_id: input.target === 'channel' ? input.channelId : null, client_id: input.target === 'private' ? input.clientId : null, client_uid: input.target === 'private' ? input.clientUid || null : null, message: input.message } : null;
|
||||
case 'poke':
|
||||
return id(input.clientId, 65535) && uid(input.clientUid) && text(input.message, 500, true) ? { type: input.type, client_id: input.clientId, client_uid: input.clientUid || null, message: input.message } : null;
|
||||
default: return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { spawnProtocol, nativeAvailable } from '../platform/native-protocol.mjs';
|
||||
import { resolveTeamSpeak } from '../transport/destination.mjs';
|
||||
import { decodeVoice, encodeVoice } from '../../public/voice-frame.mjs';
|
||||
import { normalizeCommand } from './commands.mjs';
|
||||
|
||||
const LEASE = 'voxharbor:protocol:v1:active-owner';
|
||||
const safeText = value => String(value || '').slice(0, 256);
|
||||
export function createProtocolControl(ws, { config, store, vault, preferences, csrf, close }) {
|
||||
let native;
|
||||
let starting = false;
|
||||
let stopped = false;
|
||||
let leaseToken;
|
||||
let renewal;
|
||||
let liveness;
|
||||
let lastHeartbeat = Date.now();
|
||||
let pendingState;
|
||||
let flush;
|
||||
let audioReady = false;
|
||||
let canSend = false;
|
||||
let connectionId;
|
||||
let audioWindow = 0;
|
||||
let audioCount = 0;
|
||||
const pendingCommands = new Map();
|
||||
const emit = event => {
|
||||
if (ws.readyState !== 1) return;
|
||||
if (ws.bufferedAmount > 1024 * 1024) { close(1008, 'Protocol output capacity exceeded'); return; }
|
||||
ws.send(JSON.stringify(event));
|
||||
};
|
||||
async function release() {
|
||||
clearInterval(renewal);
|
||||
clearInterval(liveness);
|
||||
clearInterval(flush);
|
||||
for (const pending of pendingCommands.values()) clearTimeout(pending.timer);
|
||||
pendingCommands.clear();
|
||||
pendingState = undefined;
|
||||
const token = leaseToken;
|
||||
leaseToken = undefined;
|
||||
if (token) await store.compareDelete(LEASE, token);
|
||||
}
|
||||
async function stop() {
|
||||
stopped = true;
|
||||
clearInterval(liveness);
|
||||
native?.stop();
|
||||
// The lease is held until the child exits, preventing overlapping identities.
|
||||
if (!native && !starting) await release();
|
||||
}
|
||||
function normalizeState(event) {
|
||||
if (!Array.isArray(event.channels) || !Array.isArray(event.participants) || event.channels.length > 4096 || event.participants.length > 4096) throw new Error('State capacity exceeded');
|
||||
return {
|
||||
type: 'ts3_state', sequence: event.sequence, ownClientId: event.ownClientId,
|
||||
server: { name: safeText(event.server?.name) },
|
||||
channels: event.channels.map(channel => ({ id: channel.id, parentId: channel.parentId, name: safeText(channel.name), order: channel.order, subscribed: Boolean(channel.subscribed), codec: channel.codec, passwordProtected: Boolean(channel.passwordProtected), topic: safeText(channel.topic) })),
|
||||
participants: event.participants.map(client => ({ id: client.id, channelId: client.channelId, name: safeText(client.name), inputMuted: Boolean(client.inputMuted), outputMuted: Boolean(client.outputMuted), awayMessage: typeof client.awayMessage === 'string' ? safeText(client.awayMessage) : null, uid: /^[A-Za-z0-9+/]{27}=$/.test(client.uid || '') ? client.uid : null })),
|
||||
};
|
||||
}
|
||||
return {
|
||||
stop,
|
||||
voice(data) {
|
||||
let frame;
|
||||
try { frame = decodeVoice(new Uint8Array(data), 1); }
|
||||
catch { return close(1003, 'Invalid voice frame'); }
|
||||
if (!native || !audioReady || stopped) return;
|
||||
if (Date.now() - audioWindow >= 1000) { audioWindow = Date.now(); audioCount = 0; }
|
||||
if (++audioCount > 65) return close(1008, 'Voice rate exceeded');
|
||||
if (!canSend) return;
|
||||
native.send({ op: 'audio', codec: frame.codec, data: Buffer.from(frame.data).toString('base64') });
|
||||
},
|
||||
async command(data) {
|
||||
let input;
|
||||
try { input = JSON.parse(data.toString('utf8')); } catch { return close(1003, 'Expected a protocol command'); }
|
||||
if (input.csrf !== csrf) return close(4403, 'Protocol CSRF check failed');
|
||||
if (input.type === 'ping') {
|
||||
if (!Number.isSafeInteger(input.nonce) || input.nonce < 0 || input.nonce > 0xffffffff) return close(1003, 'Invalid protocol heartbeat');
|
||||
lastHeartbeat = Date.now();
|
||||
emit({ type: 'ts3_pong', nonce: input.nonce }); return;
|
||||
}
|
||||
if (input.type === 'disconnect') { await stop(); return; }
|
||||
if (input.type === 'command') {
|
||||
const command = normalizeCommand(input.command);
|
||||
if (!Number.isSafeInteger(input.requestId) || input.requestId < 1 || input.requestId > 0xffffffff || !command) return close(1003, 'Invalid client command');
|
||||
if (!native || !audioReady || stopped) return emit({ type: 'ts3_command_result', requestId: input.requestId, ok: false, code: 'not_connected' });
|
||||
if (pendingCommands.size >= 16 || pendingCommands.has(input.requestId)) return emit({ type: 'ts3_command_result', requestId: input.requestId, ok: false, code: 'command_capacity' });
|
||||
const timer = setTimeout(() => {
|
||||
pendingCommands.delete(input.requestId);
|
||||
emit({ type: 'ts3_command_result', requestId: input.requestId, ok: false, code: 'command_timeout' });
|
||||
}, 15000);
|
||||
pendingCommands.set(input.requestId, { timer, command });
|
||||
if (!native.send({ op: 'command', request_id: input.requestId, command })) {
|
||||
clearTimeout(pendingCommands.get(input.requestId).timer); pendingCommands.delete(input.requestId);
|
||||
emit({ type: 'ts3_command_result', requestId: input.requestId, ok: false, code: 'command_not_sent' });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (input.type === 'audio_state') {
|
||||
if (!native || !audioReady || stopped) return;
|
||||
if (typeof input.inputMuted !== 'boolean' || typeof input.outputMuted !== 'boolean') return close(1003, 'Invalid audio state');
|
||||
canSend = false;
|
||||
if (!native.send({ op: 'audio_state', input_muted: input.inputMuted, output_muted: input.outputMuted })) {
|
||||
await stop(); close(1011, 'Audio state could not be applied');
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (input.type !== 'connect') return close(1003, 'Unknown protocol command');
|
||||
if (native || starting || stopped) return;
|
||||
if (!/^[a-f0-9]{32}$/.test(input.connectionId || '') || ['nickname', 'destination', 'password', 'channelId', 'channelPassword'].some(key => Object.hasOwn(input, key)) ||
|
||||
(input.heartbeat !== undefined && typeof input.heartbeat !== 'boolean')) {
|
||||
return emit({ type: 'ts3_error', code: 'invalid_connection_options' });
|
||||
}
|
||||
starting = true;
|
||||
try {
|
||||
const connection = await preferences.activeConnection(input.connectionId);
|
||||
connectionId = connection.id;
|
||||
if (!await nativeAvailable(config)) throw new Error('native_unavailable');
|
||||
if (!await store.limit('voxharbor:protocol:connect-rate', 6, 60)) throw new Error('connection_rate_limit');
|
||||
const identity = await vault.read();
|
||||
if (!identity) throw new Error('identity_required');
|
||||
const target = await resolveTeamSpeak({ ts3Host: connection.host, ts3Port: connection.port });
|
||||
if (stopped || ws.readyState !== 1) return;
|
||||
const token = randomBytes(32).toString('hex');
|
||||
if (!await store.putIfAbsent(LEASE, token, 35)) throw new Error('another_session_is_active');
|
||||
leaseToken = token;
|
||||
if (stopped || ws.readyState !== 1) { await release(); return; }
|
||||
let renewing = false;
|
||||
if (input.heartbeat === true) {
|
||||
lastHeartbeat = Date.now();
|
||||
liveness = setInterval(() => {
|
||||
if (Date.now() - lastHeartbeat < 35000 || stopped) return;
|
||||
emit({ type: 'ts3_error', code: 'owner_transport_timeout', inconclusive: true });
|
||||
void stop().finally(() => close(4000, 'Owner transport heartbeat expired'));
|
||||
}, 10000);
|
||||
}
|
||||
renewal = setInterval(async () => {
|
||||
if (renewing || !leaseToken) return;
|
||||
renewing = true;
|
||||
try {
|
||||
if (!await store.compareSet(LEASE, token, token, 35)) throw new Error();
|
||||
} catch { emit({ type: 'ts3_error', code: 'session_lease_lost' }); await stop(); }
|
||||
finally { renewing = false; }
|
||||
}, 10000);
|
||||
flush = setInterval(() => {
|
||||
if (pendingState) { const next = pendingState; pendingState = undefined; emit(next); }
|
||||
}, 100);
|
||||
native = spawnProtocol(config, {
|
||||
op: 'connect', identity: identity.identity, address: target.address,
|
||||
nickname: connection.nickname, password: connection.password || null, seconds: 240,
|
||||
channel_id: connection.channelId || null, channel_password: connection.channelPassword || null,
|
||||
}, async event => {
|
||||
if (event.type === 'identity_internal') {
|
||||
const metadata = await vault.update(event);
|
||||
emit({ type: 'ts3_identity', ...metadata });
|
||||
} else if (event.type === 'state') pendingState = normalizeState(event);
|
||||
else if (event.type === 'message') {
|
||||
if (!['channel', 'server', 'private', 'poke'].includes(event.target) || !Number.isInteger(event.clientId)) return;
|
||||
emit({ type: 'ts3_message', target: event.target, clientId: event.clientId, targetClientId: event.targetClientId, uid: /^[A-Za-z0-9+/]{27}=$/.test(event.uid || '') ? event.uid : null, targetUid: /^[A-Za-z0-9+/]{27}=$/.test(event.targetUid || '') ? event.targetUid : null, name: safeText(event.name), message: String(event.message || '').slice(0, 4096), channelId: event.channelId });
|
||||
} else if (event.type === 'client_command_result') {
|
||||
if (!pendingCommands.has(event.requestId)) return;
|
||||
const pending = pendingCommands.get(event.requestId);
|
||||
clearTimeout(pending.timer); pendingCommands.delete(event.requestId);
|
||||
if (event.ok && ['join_channel', 'nickname'].includes(pending.command.type)) {
|
||||
const changes = pending.command.type === 'join_channel' ? { channelId: pending.command.channel_id, channelPassword: pending.command.password || '' } : { nickname: pending.command.name };
|
||||
let saved;
|
||||
try { saved = await preferences.updateConnection(connectionId, changes); } catch { /* Server action succeeded; never replay it after a storage failure. */ }
|
||||
if (saved) emit({ type: 'ts3_connection_saved', preferences: saved });
|
||||
else emit({ type: 'ts3_error', code: 'connection_settings_not_saved' });
|
||||
}
|
||||
emit({ type: 'ts3_command_result', requestId: event.requestId, ok: Boolean(event.ok), ...(!event.ok ? { code: event.code === 'command_not_sent' ? 'command_not_sent' : 'server_denied_command', ...(Number.isSafeInteger(event.serverError) ? { serverError: event.serverError } : {}), ...(Number.isSafeInteger(event.missingPermission) ? { missingPermission: event.missingPermission } : {}) } : {}) });
|
||||
}
|
||||
else if (event.type === 'audio_status') {
|
||||
canSend = Boolean(event.canSend);
|
||||
emit({ type: 'ts3_audio_status', canSend, canReceive: Boolean(event.canReceive) });
|
||||
} else if (event.type === 'audio') {
|
||||
if (ws.readyState !== 1 || ws.bufferedAmount > 8192 || ![4, 5].includes(event.codec)) return;
|
||||
const data = Buffer.from(event.data, 'base64');
|
||||
if (data.length > 1275) return;
|
||||
ws.send(encodeVoice({ direction: 2, clientId: event.clientId, sequence: event.sequence, codec: event.codec, whisper: event.whisper, data }), { binary: true });
|
||||
} else if (event.type === 'command_result' && !event.ok) emit({ type: 'ts3_error', code: 'server_permission_or_command_error' });
|
||||
else if (event.type === 'status') {
|
||||
audioReady = event.status === 'connected';
|
||||
if (!audioReady) canSend = false;
|
||||
emit({ type: 'ts3_status', status: safeText(event.status), ...(event.requiredLevel ? { requiredLevel: event.requiredLevel } : {}) });
|
||||
}
|
||||
else if (event.type === 'error' || event.type === 'warning') emit({ type: 'ts3_error', code: safeText(event.code), inconclusive: Boolean(event.inconclusive) });
|
||||
});
|
||||
void native.done.catch(() => emit({ type: 'ts3_error', code: 'native_protocol_failed' })).finally(async () => {
|
||||
if (pendingState) emit(pendingState);
|
||||
await release().catch(() => {});
|
||||
close(1000, 'Protocol session ended');
|
||||
});
|
||||
} catch (error) {
|
||||
await release().catch(() => {});
|
||||
const publicCodes = ['native_unavailable', 'identity_required', 'another_session_is_active', 'connection_rate_limit'];
|
||||
const settingsCode = ['connection_required', 'connection_settings_changed'].includes(error.code) ? error.code : null;
|
||||
emit({ type: 'ts3_error', code: settingsCode || (publicCodes.includes(error.message) ? error.message : 'identity_storage_or_destination_error') });
|
||||
close(1011, 'Protocol setup failed');
|
||||
} finally { starting = false; }
|
||||
},
|
||||
};
|
||||
}
|
||||
Vendored
+25
@@ -0,0 +1,25 @@
|
||||
export type ProtocolCommand =
|
||||
| { type: 'connect'; csrf: string; connectionId: string; heartbeat?: boolean }
|
||||
| { type: 'command'; csrf: string; requestId: number; command: ClientCommand }
|
||||
| { type: 'ping'; csrf: string; nonce: number }
|
||||
| { type: 'disconnect'; csrf: string }
|
||||
| { type: 'audio_state'; csrf: string; inputMuted: boolean; outputMuted: boolean };
|
||||
export type ClientCommand =
|
||||
| { type: 'join_channel'; channelId: number; password?: string }
|
||||
| { type: 'subscribe'; channelId: number; subscribed: boolean }
|
||||
| { type: 'nickname'; name: string }
|
||||
| { type: 'away'; away: boolean; message?: string }
|
||||
| { type: 'text_message'; target: 'channel' | 'server' | 'private'; channelId?: number; clientId?: number; clientUid?: string; message: string }
|
||||
| { type: 'poke'; clientId: number; clientUid?: string; message: string };
|
||||
export type Channel = { id: number; parentId: number; name: string; order: number; subscribed: boolean; codec: number; passwordProtected: boolean; topic: string };
|
||||
export type Participant = { id: number; channelId: number; name: string; inputMuted: boolean; outputMuted: boolean; awayMessage: string | null; uid: string | null };
|
||||
export type ProtocolEvent =
|
||||
| { type: 'ts3_connection_saved'; preferences: unknown }
|
||||
| { type: 'ts3_pong'; nonce: number }
|
||||
| { type: 'ts3_command_result'; requestId: number; ok: boolean; code?: string; serverError?: number; missingPermission?: number }
|
||||
| { type: 'ts3_message'; target: 'channel' | 'server' | 'private' | 'poke'; clientId: number; targetClientId?: number; channelId?: number; name: string; message: string }
|
||||
| { type: 'ts3_status'; status: 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'session_limit' | 'identity_level_increasing'; requiredLevel?: number }
|
||||
| { type: 'ts3_state'; sequence: number; ownClientId: number; server: { name: string }; channels: Channel[]; participants: Participant[] }
|
||||
| { type: 'ts3_identity'; uid: string; level: number }
|
||||
| { type: 'ts3_audio_status'; canSend: boolean; canReceive: boolean }
|
||||
| { type: 'ts3_error'; code: string; inconclusive?: boolean };
|
||||
@@ -0,0 +1,21 @@
|
||||
import { resolve4 } from 'node:dns/promises';
|
||||
import ipaddr from 'ipaddr.js';
|
||||
|
||||
export function publicIPv4(address) {
|
||||
return ipaddr.IPv4.isValidFourPartDecimal(address || '') && ipaddr.parse(address).range() === 'unicast';
|
||||
}
|
||||
export async function resolveTeamSpeak(config, resolver = resolve4) {
|
||||
const port = config.ts3Port;
|
||||
const host = config.ts3Host;
|
||||
if (!host || !Number.isInteger(port) || port < 1024 || port > 65535) throw new Error('Configure an authorized TeamSpeak destination');
|
||||
if (!/^[a-zA-Z0-9.-]{1,253}$/.test(host)) throw new Error('Invalid TeamSpeak hostname');
|
||||
let timeout;
|
||||
try {
|
||||
const addresses = publicIPv4(host) ? [host] : await Promise.race([
|
||||
resolver(host), new Promise((_, reject) => { timeout = setTimeout(() => reject(new Error('Destination resolution timed out')), 3000); }),
|
||||
]);
|
||||
if (!addresses.length || !addresses.every(publicIPv4)) throw new Error('TeamSpeak destination is private or reserved');
|
||||
// The native library receives a numeric SocketAddr and cannot re-resolve or redirect it.
|
||||
return { address: `${addresses[0]}:${port}`, host, port };
|
||||
} finally { clearTimeout(timeout); }
|
||||
}
|
||||
Reference in new issue
Block a user