This commit is contained in:
Meghdad committed 2026-11-01 19:43:03 +03:30
commit 22fe85bb92
247 files changed
+35538

No files matched your search

+22
View File
@@ -0,0 +1,22 @@
// Local, disposable QA page. Synthetic audio only: no microphone, owner data or network server.
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
const root = new URL('../', import.meta.url);
const files = new Map([
['/qa.mjs', 'tests/fixtures/audio-browser-qa.mjs'],
['/probe.mjs', 'tests/fixtures/playback-probe.mjs'],
...['voice-worker.mjs', 'voice-frame.mjs', 'voice-worklet.mjs', 'jitter-buffer.mjs', 'vendor/opus/index.js', 'vendor/opus/generated/libopus.generated.mjs'].map(file => [`/${file}`, `public/${file}`]),
]);
const server = createServer(async (req, res) => {
res.setHeader('Content-Security-Policy', "default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; worker-src 'self'; connect-src 'self'; style-src 'self'; base-uri 'none'; frame-ancestors 'none'");
res.setHeader('Cache-Control', 'no-store'); res.setHeader('X-Content-Type-Options', 'nosniff');
if (req.method !== 'GET') { res.writeHead(405); res.end(); return; }
if (req.url === '/') {
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('<!doctype html><html lang="en"><title>VoxHarbor silent audio QA</title><h1>Silent browser audio test</h1><p>Synthetic signal only. No microphone access, audible playback or TeamSpeak connection.</p><button id="run">Run silent pipeline test</button><pre id="result" role="status">Ready</pre><script type="module" src="/qa.mjs"></script></html>'); return;
}
if (!files.has(req.url)) { res.writeHead(404); res.end(); return; }
try { res.setHeader('Content-Type', 'text/javascript; charset=utf-8'); res.end(await readFile(new URL(files.get(req.url), root))); }
catch { res.writeHead(404); res.end(); }
});
server.listen(3147, '127.0.0.1', () => console.log('Silent audio QA: http://localhost:3147'));
+15
View File
@@ -0,0 +1,15 @@
#!/usr/bin/env bash
set -eu
# Build-time toolchain only. No credentials are sent to the Rust distribution service.
if ! command -v rustup >/dev/null 2>&1 && [ ! -x "$HOME/.cargo/bin/rustup" ]; then
installer="$(mktemp)"
curl --proto '=https' --tlsv1.2 --fail --silent --show-error https://sh.rustup.rs -o "$installer"
sh "$installer" -y --profile minimal --default-toolchain 1.96.0 --no-modify-path
rm -f "$installer"
else
if [ -x "$HOME/.cargo/bin/rustup" ]; then
"$HOME/.cargo/bin/rustup" toolchain install 1.96.0 --profile minimal --no-self-update
else
rustup toolchain install 1.96.0 --profile minimal --no-self-update
fi
fi
+26
View File
@@ -0,0 +1,26 @@
import { spawnSync } from 'node:child_process';
import { chmod, copyFile, mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
const root = fileURLToPath(new URL('../', import.meta.url));
function run(command, args, env = process.env) {
const result = spawnSync(command, args, { cwd: root, env, stdio: 'inherit' });
if (result.status !== 0) throw new Error(`Native build step failed: ${command}`);
}
const allowed = ['PATH', 'HOME', 'TMPDIR', 'CARGO_HOME', 'RUSTUP_HOME', 'LANG', 'LC_ALL', 'CC', 'CXX', 'AR', 'CFLAGS', 'CXXFLAGS', 'MACOSX_DEPLOYMENT_TARGET', 'SDKROOT', 'RUSTUP_OVERRIDE_UNIX_FALLBACK_SETTINGS'];
let env = { ...Object.fromEntries(allowed.filter(key => process.env[key]).map(key => [key, process.env[key]])), CARGO_REGISTRIES_CRATES_IO_PROTOCOL: 'sparse' };
if (process.env.VERCEL === '1') {
run('bash', ['scripts/bootstrap-rust.sh'], env);
env.PATH = `${process.env.HOME}/.cargo/bin:${env.PATH}`;
env.RUSTUP_TOOLCHAIN = '1.96.0';
} else if (existsSync('/opt/homebrew/opt/rustup/bin/cargo')) {
env.PATH = `/opt/homebrew/opt/rustup/bin:${env.PATH}`;
}
run('cargo', ['build', '--manifest-path', 'native/Cargo.toml', '--locked', '--release'], env);
await mkdir(new URL('../native/bin/', import.meta.url), { recursive: true });
const target = new URL('../native/bin/voxharbor-protocol', import.meta.url);
await copyFile(new URL('../native/target/release/voxharbor-protocol', import.meta.url), target);
await chmod(target, 0o755);
console.log('Native protocol executable packaged for this platform.');
if (process.platform === 'linux') run('ldd', [fileURLToPath(target)]);
+11
View File
@@ -0,0 +1,11 @@
import { readdir } from 'node:fs/promises';
import { spawnSync } from 'node:child_process';
async function files(path) {
const entries = await readdir(path, { withFileTypes: true });
return (await Promise.all(entries.map(entry => entry.isDirectory() ? files(`${path}/${entry.name}`) : `${path}/${entry.name}`))).flat();
}
for (const file of (await Promise.all(['api', 'src', 'scripts', 'tests', 'public'].map(files))).flat().filter(file => file.endsWith('.mjs'))) {
const result = spawnSync(process.execPath, ['--check', file], { stdio: 'inherit' });
if (result.status !== 0) process.exit(1);
}
console.log('JavaScript syntax checks passed');
+14
View File
@@ -0,0 +1,14 @@
import { readConfig } from '../src/config.mjs';
import { createApp } from '../src/http-adapter.mjs';
let config;
try { config = readConfig(); }
catch (error) {
console.error(`Cannot start VoxHarbor: ${error.message}`);
console.error('For local owner setup, run: npm run owner:setup');
console.error('Review .env.example for the remaining configuration.');
process.exit(1);
}
const { server } = createApp(config);
const url = new URL(config.origin);
if (url.hostname !== 'localhost' || url.protocol !== 'http:') throw new Error('Local dev requires http://localhost:<port>');
server.listen(Number(url.port || 80), '127.0.0.1', () => console.log(`VoxHarbor feasibility lab: ${config.origin}`));
+51
View File
@@ -0,0 +1,51 @@
// Reproducible vector and raster versions of VoxHarbor's waveform mark.
// Uses Node built-ins only; no external image service or build-time dependency.
import { mkdir, writeFile } from 'node:fs/promises';
import { deflateSync } from 'node:zlib';
const root = new URL('../public/', import.meta.url);
const background = [23, 24, 24]; const accent = [236, 131, 81];
const bars = [[14, 20, 4, 24], [22, 14, 4, 36], [30, 18, 4, 28], [38, 10, 4, 44], [46, 23, 4, 18]];
const shapes = bars.map(([x, y, width, height]) => `<rect x="${x}" y="${y}" width="${width}" height="${height}" rx="2"/>`).join('');
await mkdir(new URL('icons/', root), { recursive: true });
await writeFile(new URL('favicon.svg', root), `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><rect width="64" height="64" rx="14" fill="#171818"/><g fill="#ec8351">${shapes}</g></svg>\n`);
await writeFile(new URL('icons/safari-pinned-tab.svg', root), `<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64"><g fill="#000">${shapes}</g></svg>\n`);
const table = Array.from({ length: 256 }, (_, n) => { for (let k = 0; k < 8; k++) n = (n & 1) ? 0xedb88320 ^ (n >>> 1) : n >>> 1; return n >>> 0; });
function chunk(type, data) {
const tag = Buffer.from(type); let crc = 0xffffffff;
for (const byte of Buffer.concat([tag, data])) crc = table[(crc ^ byte) & 255] ^ (crc >>> 8);
const length = Buffer.alloc(4); length.writeUInt32BE(data.length);
const checksum = Buffer.alloc(4); checksum.writeUInt32BE((crc ^ 0xffffffff) >>> 0);
return Buffer.concat([length, tag, data, checksum]);
}
function inside(x, y, left, top, width, height, radius) {
const dx = Math.max(left + radius - x, 0, x - (left + width - radius));
const dy = Math.max(top + radius - y, 0, y - (top + height - radius));
return dx * dx + dy * dy <= radius * radius;
}
function png(size, { rounded = false, scale = 1 } = {}) {
const stride = size * 4 + 1; const pixels = Buffer.alloc(stride * size); const samples = 4;
for (let y = 0; y < size; y++) for (let x = 0; x < size; x++) {
let red = 0, green = 0, blue = 0, alpha = 0;
for (let sy = 0; sy < samples; sy++) for (let sx = 0; sx < samples; sx++) {
const px = (x + (sx + .5) / samples) * 64 / size; const py = (y + (sy + .5) / samples) * 64 / size;
if (rounded && !inside(px, py, 0, 0, 64, 64, 14)) continue;
const mx = (px - 32) / scale + 32; const my = (py - 32) / scale + 32;
const color = bars.some(([left, top, width, height]) => inside(mx, my, left, top, width, height, 2)) ? accent : background;
red += color[0]; green += color[1]; blue += color[2]; alpha++;
}
const offset = y * stride + 1 + x * 4;
if (alpha) { pixels[offset] = Math.round(red / alpha); pixels[offset + 1] = Math.round(green / alpha); pixels[offset + 2] = Math.round(blue / alpha); pixels[offset + 3] = Math.round(alpha * 255 / (samples * samples)); }
}
const header = Buffer.alloc(13); header.writeUInt32BE(size, 0); header.writeUInt32BE(size, 4); header[8] = 8; header[9] = 6;
return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]), chunk('IHDR', header), chunk('IDAT', deflateSync(pixels, { level: 9 })), chunk('IEND', Buffer.alloc(0))]);
}
for (const [path, size, options] of [
['favicon-16x16.png', 16, { rounded: true }], ['favicon-32x32.png', 32, { rounded: true }],
['apple-touch-icon.png', 180, {}], ['icons/app-192.png', 192, {}], ['icons/app-512.png', 512, {}], ['icons/app-maskable-512.png', 512, { scale: .8 }],
]) await writeFile(new URL(path, root), png(size, options));
const sizes = [16, 32, 48]; const images = sizes.map(size => png(size, { rounded: true }));
const icoHeader = Buffer.alloc(6); icoHeader.writeUInt16LE(1, 2); icoHeader.writeUInt16LE(sizes.length, 4);
let offset = 6 + sizes.length * 16;
const directory = sizes.map((size, i) => { const entry = Buffer.alloc(16); entry[0] = size; entry[1] = size; entry.writeUInt16LE(1, 4); entry.writeUInt16LE(32, 6); entry.writeUInt32LE(images[i].length, 8); entry.writeUInt32LE(offset, 12); offset += images[i].length; return entry; });
await writeFile(new URL('favicon.ico', root), Buffer.concat([icoHeader, ...directory, ...images]));
console.log('Generated VoxHarbor favicons, touch icons, app icons and pinned-tab mark.');
+29
View File
@@ -0,0 +1,29 @@
import { hashPassword } from '../src/auth/password.mjs';
import { saveLocalOwner } from './local-owner-config.mjs';
if (!process.stdin.isTTY) throw new Error('Run in an interactive terminal');
process.stdout.write('Owner password (16+ characters, hidden): ');
process.stdin.setRawMode(true);
process.stdin.resume();
let password = '';
process.stdin.setEncoding('utf8');
process.stdin.on('data', async data => {
for (const character of data) {
if (character === '\u0003') process.exit(130);
if (character === '\r' || character === '\n') {
process.stdin.setRawMode(false);
process.stdin.pause();
try {
const hash = await hashPassword(password);
password = '';
if (process.argv.includes('--save')) {
await saveLocalOwner(hash);
console.log('\nOwner password hash saved to .env.local; session secret rotated. Run npm run dev, then sign in with the password you entered.');
} else console.log(`\nOWNER_PASSWORD_HASH=${hash}`);
}
catch (error) { console.error(`\n${error.message}`); process.exitCode = 1; }
return;
}
if (character === '\u007f') password = password.slice(0, -1);
else if (password.length <= 256) password += character;
}
});
+20
View File
@@ -0,0 +1,20 @@
export function hiddenPrompt(label) {
if (!process.stdin.isTTY) throw new Error('Run in an interactive terminal');
process.stdout.write(`${label} (hidden): `);
return new Promise(resolve => {
let value = '';
process.stdin.setRawMode(true); process.stdin.setEncoding('utf8'); process.stdin.resume();
function input(data) {
for (const character of data) {
if (character === '\u0003') process.exit(130);
if (character === '\r' || character === '\n') {
process.stdin.removeListener('data', input); process.stdin.setRawMode(false); process.stdin.pause();
process.stdout.write('\n'); resolve(value); return;
}
if (character === '\u007f') value = value.slice(0, -1);
else if (value.length < 256) value += character;
}
}
process.stdin.on('data', input);
});
}
+22
View File
@@ -0,0 +1,22 @@
import { randomBytes } from 'node:crypto';
import { readFile, writeFile, rename } from 'node:fs/promises';
import { parseEnv } from 'node:util';
const path = new URL('../.env.local', import.meta.url);
let source;
try { source = await readFile(path, 'utf8'); }
catch (error) {
if (error.code !== 'ENOENT') throw error;
source = await readFile(new URL('../.env.example', import.meta.url), 'utf8');
}
const existing = parseEnv(source).IDENTITY_ENCRYPTION_KEY;
if (/^[a-f0-9]{64}$/i.test(existing || '')) {
console.log('IDENTITY_ENCRYPTION_KEY is already configured; it was preserved.');
} else {
if (existing) throw new Error('An existing identity key value is invalid; correct it manually instead of regenerating it.');
source = source.replace(/^[\t ]*(?:export[\t ]+)?IDENTITY_ENCRYPTION_KEY[\t ]*=.*$/gm, '').trimEnd();
const temporary = new URL(`../.env.local.${randomBytes(8).toString('hex')}.tmp`, import.meta.url);
await writeFile(temporary, `${source}\nIDENTITY_ENCRYPTION_KEY=${randomBytes(32).toString('hex')}\n`, { mode: 0o600, flag: 'wx' });
await rename(temporary, path);
console.log('Added a separate identity encryption key to .env.local. Back it up securely; no private identity was created.');
}
+34
View File
@@ -0,0 +1,34 @@
import { randomBytes } from 'node:crypto';
import { readFile, writeFile, rename, unlink } from 'node:fs/promises';
export function updateOwnerConfig(source, hash, secret) {
if (!/^scrypt:[a-f0-9]{32}:[a-f0-9]{128}$/.test(hash)) throw new Error('Invalid owner password hash');
if (!/^[a-f0-9]{64}$/.test(secret)) throw new Error('Invalid session secret');
let result = source;
for (const [key, value] of Object.entries({ OWNER_PASSWORD_HASH: hash, SESSION_SECRET: secret })) {
// Replace all active assignments, including duplicates and optional dotenv export syntax.
const assignment = new RegExp(`^[\\t ]*(?:export[\\t ]+)?${key}[\\t ]*=.*$`, 'gm');
result = result.replace(assignment, '').trimEnd();
result += `\n${key}=${value}\n`;
}
return result;
}
export async function saveLocalOwner(hash, directory = new URL('../', import.meta.url)) {
const destination = new URL('.env.local', directory);
let source;
try { source = await readFile(destination, 'utf8'); }
catch (error) {
if (error.code !== 'ENOENT') throw error;
source = await readFile(new URL('.env.example', directory), 'utf8');
}
// Replacing the password also revokes sessions using the previous credentials.
const updated = updateOwnerConfig(source, hash, randomBytes(32).toString('hex'));
const temporary = new URL(`.env.local.${randomBytes(8).toString('hex')}.tmp`, directory);
try {
await writeFile(temporary, updated, { mode: 0o600, flag: 'wx' });
await rename(temporary, destination);
} finally {
await unlink(temporary).catch(error => { if (error.code !== 'ENOENT') throw error; });
}
}
+2
View File
@@ -0,0 +1,2 @@
import { packageSource } from './package-source.mjs';
await packageSource('deployment');
+2
View File
@@ -0,0 +1,2 @@
import { packageSource } from './package-source.mjs';
await packageSource('publication');
+21
View File
@@ -0,0 +1,21 @@
import { createHash } from 'node:crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import { join } from 'node:path';
import { auditPublication } from './publication-audit.mjs';
import { projectRoot } from './source-files.mjs';
export async function packageSource(kind) {
const report = await auditPublication({ checkGit: kind === 'publication' });
if (!report.passed) { console.error(JSON.stringify({ passed: false, issues: report.issues }, null, 2)); throw new Error('Source audit failed. No package was published or pushed.'); }
const stamp = new Date().toISOString().replace(/[:.]/g, '-');
const destination = join(projectRoot, '.local', `${kind}-${stamp}`, 'VoxHarbor');
await mkdir(destination, { recursive: true, mode: 0o700 }); const manifest = [];
for (const path of report.files) {
const bytes = report.sources.get(path); // Copy the exact audited bytes, not a later filesystem version.
await mkdir(join(destination, path, '..'), { recursive: true }); await writeFile(join(destination, path), bytes);
manifest.push({ path, bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
}
await writeFile(join(destination, 'SOURCE_MANIFEST.json'), JSON.stringify({ createdAt: new Date().toISOString(), files: manifest }, null, 2) + '\n');
console.log(`${kind === 'publication' ? 'Public source' : 'Deployment source'}: ${destination}`);
console.log(`${manifest.length} source files. No Git metadata, private configuration, identities, evidence, dependencies or local binaries.`);
return destination;
}
+8
View File
@@ -0,0 +1,8 @@
import { copyFile, mkdir } from 'node:fs/promises';
const dest = new URL('../public/vendor/opus/', import.meta.url);
const source = new URL('../node_modules/libopus-wasm/', import.meta.url);
await mkdir(new URL('generated/', dest), { recursive: true });
for (const [from, to] of [['dist/index.js', 'index.js'], ['dist/generated/libopus.generated.mjs', 'generated/libopus.generated.mjs'], ['LICENSE', 'LICENSE'], ['THIRD_PARTY_NOTICES.md', 'THIRD_PARTY_NOTICES.md']]) {
await copyFile(new URL(from, source), new URL(to, dest));
}
console.log('Pinned Opus browser codec and license notices packaged.');
+60
View File
@@ -0,0 +1,60 @@
import { createHash } from 'node:crypto';
import { readFile } from 'node:fs/promises';
import { parseEnv } from 'node:util';
import { spawnSync } from 'node:child_process';
import { join } from 'node:path';
import { collectSourceFiles, privatePath, projectRoot } from './source-files.mjs';
export function inspectContent(path, bytes, privateValues = []) {
const findings = new Set(); const text = bytes.toString('utf8');
for (const value of privateValues) {
if (typeof value !== 'string' || value.length < 4) continue;
if ([value, Buffer.from(value).toString('base64'), encodeURIComponent(value)].some(encoded => bytes.includes(Buffer.from(encoded)))) findings.add('local-private-value');
}
if (/\b(?:gh[pousr]_[A-Za-z0-9]{30,}|github_pat_[A-Za-z0-9_]{40,}|AKIA[0-9A-Z]{16})\b/.test(text)) findings.add('credential-format');
if (/scrypt:[a-f0-9]{32}:[a-f0-9]{128}/i.test(text)) findings.add('password-hash');
if (/^\s*identity\s*=\s*["']?[A-Za-z0-9+/]{40,}/m.test(text)) findings.add('identity-export');
// Upstream crypto tests contain intentional published fixtures. Local-value matching still applies there.
if (!path.startsWith('native/vendor/') && /-----BEGIN (?:EC |RSA |OPENSSH )?PRIVATE KEY-----/.test(text)) findings.add('private-key');
const publishedCodec = path === 'public/vendor/opus/generated/libopus.generated.mjs' && createHash('sha256').update(bytes).digest('hex') === '0041fc800ccd26f56b27eaeb1834c8c6854e5167d48cd628a4f98ec5b590c6f1';
if (!path.startsWith('native/vendor/') && !publishedCodec && /\/Users\/[^/\s]+\//.test(text)) findings.add('personal-filesystem-path');
if (/https:\/\/[a-z0-9-]+-[a-z0-9]{9}-[a-z0-9-]+\.vercel\.app/i.test(text)) findings.add('private-deployment-url');
return [...findings].map(rule => ({ path, rule }));
}
async function knownPrivateValues(root) {
const values = [root];
try {
const env = parseEnv(await readFile(join(root, '.env.local'), 'utf8'));
for (const [key, value] of Object.entries(env)) if (/SECRET|TOKEN|PASSWORD|ENCRYPTION_KEY|REDIS.*URL|TS3.*HOST/.test(key)) values.push(value);
} catch (error) { if (error.code !== 'ENOENT') throw new Error('Private configuration could not be checked; no values were printed.'); }
try {
const identity = JSON.parse(await readFile(join(root, '.local/identity.enc.json'), 'utf8'));
if (identity.ciphertext) values.push(identity.ciphertext);
} catch (error) { if (error.code !== 'ENOENT') throw new Error('Local identity exclusion check failed; no contents were printed.'); }
return values;
}
function git(root, args) { return spawnSync('git', args, { cwd: root, encoding: null, maxBuffer: 16 * 1024 * 1024 }); }
export async function auditPublication({ root = projectRoot, checkGit = true } = {}) {
const files = await collectSourceFiles(root); const privateValues = await knownPrivateValues(root); const issues = [];
const allowed = new Set(files); const sources = new Map();
for (const path of files) { const bytes = await readFile(join(root, path)); sources.set(path, bytes); issues.push(...inspectContent(path, bytes, privateValues)); }
let history = 'not-checked'; let gitCandidateCount = null;
if (checkGit) {
const candidates = git(root, ['ls-files', '--cached', '--others', '--exclude-standard', '-z']);
if (candidates.status !== 0) throw new Error('Cannot inspect Git publication candidates. No Git state was changed.');
const paths = [...new Set(candidates.stdout.toString('utf8').split('\0').filter(Boolean))]; gitCandidateCount = paths.length;
for (const path of paths) {
if (privatePath(path)) issues.push({ path, rule: 'private-git-path' });
if (!allowed.has(path)) issues.push({ path, rule: 'outside-source-allowlist' });
}
const staged = git(root, ['diff', '--cached', '--name-only', '--diff-filter=ACMR', '-z']);
if (staged.status !== 0) throw new Error('Cannot inspect staged publication paths.');
for (const path of staged.stdout.toString('utf8').split('\0').filter(Boolean)) {
const blob = git(root, ['show', `:${path}`]);
if (blob.status !== 0) issues.push({ path, rule: 'staged-content-unavailable' });
else issues.push(...inspectContent(path, blob.stdout, privateValues).map(issue => ({ ...issue, snapshot: 'staged' })));
}
history = git(root, ['rev-parse', '--verify', 'HEAD']).status === 0 ? 'existing-history-requires-separate-review' : 'no-commits';
}
return { passed: issues.length === 0, sourceFileCount: files.length, gitCandidateCount, history, issues, files, sources };
}
+6
View File
@@ -0,0 +1,6 @@
import { auditPublication } from './publication-audit.mjs';
try {
const { files, sources, ...report } = await auditPublication();
console.log(JSON.stringify(report, null, 2));
if (!report.passed) process.exitCode = 1;
} catch (error) { console.error(error.message); process.exitCode = 1; }
+32
View File
@@ -0,0 +1,32 @@
import { readdir, lstat } from 'node:fs/promises';
import { resolve, join } from 'node:path';
import { fileURLToPath } from 'node:url';
export const projectRoot = fileURLToPath(new URL('../', import.meta.url));
const roots = ['api', 'src', 'public', 'scripts', 'tests', 'docs', 'native/src', 'native/vendor'];
const top = ['.gitignore', '.vercelignore', '.env.example', 'LICENSE', 'THIRD_PARTY_NOTICES.md', 'SECURITY.md', 'CONTRIBUTING.md', 'README.md', 'IMPLEMENTATION_PLAN.md', 'package.json', 'package-lock.json', 'vercel.json', 'native/Cargo.toml', 'native/Cargo.lock', 'native/README.md'];
export function privatePath(path) {
return /(^|\/)(\.git|\.local|\.idea|\.vscode|node_modules|target|coverage|evidence)(\/|$)/.test(path) ||
/^(native\/bin|docs\/verification)(\/|$)/.test(path) ||
/(^|\/)\.env(?:\.|$)/.test(path) && path !== '.env.example' ||
/\.(?:log|har|pem|key|p12|pfx|wav|mp3|ogg|enc\.json)$/i.test(path) || /(^|\/)identity\.ini$/i.test(path);
}
export async function collectSourceFiles(root = projectRoot) {
root = resolve(root); const files = [];
async function add(path) {
const info = await lstat(join(root, path));
if (!info.isFile() || info.isSymbolicLink() || privatePath(path)) throw new Error(`Unsupported public source path: ${path}`);
files.push(path);
}
async function walk(path) {
if (!(await lstat(join(root, path))).isDirectory()) throw new Error(`Not a source directory: ${path}`);
for (const entry of await readdir(join(root, path), { withFileTypes: true })) {
if (entry.name.startsWith('.') || ['node_modules', 'target', 'bin'].includes(entry.name)) continue;
const child = `${path}/${entry.name}`;
if (privatePath(child)) throw new Error(`Private material inside source tree: ${child}`);
if (entry.isDirectory()) await walk(child); else await add(child);
}
}
for (const directory of roots) await walk(directory);
for (const path of top) await add(path);
return files.sort();
}
+74
View File
@@ -0,0 +1,74 @@
import { hiddenPrompt } from './hidden-prompt.mjs';
import { writeFile } from 'node:fs/promises';
import { WebSocket } from 'ws';
// Explicit owner login; never read browser cookies or save passwords/session tokens.
const origin = new URL(process.argv[2]);
if (origin.protocol !== 'https:' || origin.origin !== process.argv[2]) throw new Error('Pass the exact production HTTPS origin');
const seconds = Number(process.argv[3] || 60);
if (!Number.isInteger(seconds) || seconds < 5 || seconds > 280) throw new Error('Duration must be 5..280 seconds');
if (!process.stdin.isTTY) throw new Error('An interactive hidden password prompt is required');
let password = await hiddenPrompt('Owner password');
let cookie;
let csrf;
async function request(path, body) {
const response = await fetch(new URL(path, origin), {
method: body === undefined ? 'GET' : 'POST', redirect: 'error', signal: AbortSignal.timeout(15000),
headers: { Origin: origin.origin, ...(cookie ? { Cookie: cookie } : {}),
...(body === undefined ? {} : { 'Content-Type': 'application/json', ...(csrf ? { 'X-CSRF-Token': csrf } : {}) }) },
...(body === undefined ? {} : { body: JSON.stringify(body) }),
});
if (!response.ok) throw new Error(`HTTP ${response.status} on ${path}`);
if (path === '/api/login') cookie = response.headers.get('set-cookie')?.split(';')[0];
return response.json();
}
const result = { testedAt: new Date().toISOString(), origin: origin.origin, environment: 'actual-vercel-production',
microphoneEnabled: false, listening: false, events: [], snapshots: 0, maxChannels: 0, maxParticipants: 0, incomingVoicePackets: 0 };
const record = event => result.events.push({ at: new Date().toISOString(), ...event });
try {
({ csrf } = await request('/api/login', { password })); password = '';
result.runtime = (await request('/api/session')).runtime;
result.capabilities = await request('/api/protocol');
result.identityBefore = (await request('/api/identity')).identity;
if (!result.identityBefore) throw new Error('Create/import the production identity through the owner UI first');
const settings = await request('/api/preferences');
if (!settings.connection) throw new Error('Save a connection through the owner UI before verification');
await new Promise((resolve, reject) => {
const socket = new WebSocket(new URL('/api/ts3', origin).href.replace('https:', 'wss:'), {
origin: origin.origin, headers: { Cookie: cookie }, handshakeTimeout: 15000,
});
const deadline = setTimeout(() => { record({ type: 'test_stop' }); socket.close(1000, 'Verification window finished'); }, seconds * 1000);
const watchdog = setTimeout(() => { socket.terminate(); reject(new Error('Protocol transport did not close')); }, (seconds + 10) * 1000);
socket.on('open', () => socket.send(JSON.stringify({ type: 'connect', csrf, connectionId: settings.connection.id })));
socket.on('message', (data, binary) => {
if (binary) { result.incomingVoicePackets++; return; }
const event = JSON.parse(data.toString());
if (event.type === 'ts3_state') {
result.snapshots++;
result.maxChannels = Math.max(result.maxChannels, event.channels.length);
result.maxParticipants = Math.max(result.maxParticipants, event.participants.length);
result.lastSequence = event.sequence;
} else if (event.type === 'ts3_status') record({ type: event.type, status: event.status });
else if (event.type === 'ts3_error') record({ type: event.type, code: event.code, inconclusive: event.inconclusive === true });
else if (event.type === 'ts3_audio_status') record({ type: event.type, canSend: event.canSend, canReceive: event.canReceive });
else if (event.type === 'ts3_identity') result.connectedIdentity = { uid: event.uid, level: event.level };
});
socket.on('error', () => record({ type: 'transport_error' }));
socket.on('close', code => {
clearTimeout(deadline); clearTimeout(watchdog); record({ type: 'transport_close', code }); resolve();
});
});
result.identityAfter = (await request('/api/identity')).identity;
result.identityPreserved = result.identityAfter?.uid === result.identityBefore.uid;
result.connected = result.events.some(event => event.status === 'connected');
} catch (error) {
result.failure = error.message;
process.exitCode = 1;
} finally {
if (cookie && csrf) await request('/api/logout', {}).catch(() => {});
}
result.passed = Boolean(result.connected && result.identityPreserved && !result.failure && !result.events.some(event => ['ts3_error', 'transport_error'].includes(event.type)));
if (!result.passed) process.exitCode = 1;
const json = JSON.stringify(result, null, 2) + '\n';
if (process.argv[4]) await writeFile(process.argv[4], json);
console.log(json);
+45
View File
@@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import { WebSocket } from 'ws';
const url = new URL(process.argv[2]);
if (url.protocol !== 'https:' || url.origin !== process.argv[2]) throw new Error('Pass the exact HTTPS deployment origin');
const checks = [];
async function http(name, path, expected, options = {}) {
const response = await fetch(new URL(path, url), { ...options, redirect: 'error', signal: AbortSignal.timeout(15000) });
assert.equal(response.status, expected, `${name}: expected ${expected}, got ${response.status}`);
checks.push({ name, status: response.status });
return response;
}
function upgrade(name, origin, expected) {
return new Promise((resolve, reject) => {
const client = new WebSocket(`${url.origin.replace('https:', 'wss:')}/api/ts3`, { origin, handshakeTimeout: 15000 });
client.on('error', () => {});
client.once('unexpected-response', (_req, response) => {
response.resume();
client.terminate();
try {
assert.equal(response.statusCode, expected, name);
checks.push({ name, status: response.statusCode });
resolve();
} catch (error) { reject(error); }
});
client.once('open', () => { client.terminate(); reject(new Error(`${name}: unauthorized upgrade succeeded`)); });
client.once('error', reject);
});
}
try {
const shell = await http('public-sign-in-shell', '/', 200);
assert.match(await shell.text(), /<label for="username">Username<\/label>/);
const csp = shell.headers.get('content-security-policy') || '';
await http('unauthenticated-session', '/api/session', 401);
await http('unauthenticated-connection-settings', '/api/connection', 401, { method: 'POST', headers: { Origin: url.origin } });
await http('cross-origin-login', '/api/login', 403, { method: 'POST', headers: { Origin: 'https://example.invalid' } });
await http('query-credential-rejection', '/api/session?token=nonsecret-test', 400);
await upgrade('unauthenticated-websocket', url.origin, 401);
await upgrade('cross-origin-websocket', 'https://example.invalid', 403);
assert.match(csp, /frame-ancestors 'none'/);
console.log(JSON.stringify({ testedAt: new Date().toISOString(), origin: url.origin, status: 'passed', checks }, null, 2));
} catch (error) {
console.error(JSON.stringify({ testedAt: new Date().toISOString(), origin: url.origin, status: 'failed', checks, error: error.message }, null, 2));
process.exitCode = 1;
}
+76
View File
@@ -0,0 +1,76 @@
import { WebSocket } from 'ws';
import { writeFile } from 'node:fs/promises';
import { hiddenPrompt } from './hidden-prompt.mjs';
import { ProtocolConnection } from '../public/protocol-connection.mjs';
const origin = new URL(process.argv[2]);
if (origin.protocol !== 'https:' || origin.origin !== process.argv[2]) throw new Error('Pass an exact production HTTPS origin');
const seconds = Number(process.argv[3] || 315);
if (!Number.isInteger(seconds) || seconds < 300 || seconds > 700) throw new Error('Recovery verification needs 300..700 seconds');
let password = await hiddenPrompt('Production owner password');
let cookie; let csrf; let connection; let interrupt; let end;
const report = { testedAt: new Date().toISOString(), origin: origin.origin, microphoneEnabled: false, listening: false,
phases: [], transports: [], protocolErrors: [], incomingVoice: 0, outgoingVoice: 0, capObserved: false, abruptInterruption: false };
async function api(path, input, signal) {
const response = await fetch(new URL(path, origin), { redirect: 'error', signal: signal || AbortSignal.timeout(15000),
method: input === undefined ? 'GET' : 'POST',
headers: { Origin: origin.origin, ...(cookie ? { Cookie: cookie } : {}), ...(input === undefined ? {} : { 'Content-Type': 'application/json', ...(csrf ? { 'X-CSRF-Token': csrf } : {}) }) },
...(input === undefined ? {} : { body: JSON.stringify(input) }),
});
if (!response.ok) throw Object.assign(new Error(`HTTP ${response.status} on ${path}`), { status: response.status });
if (path === '/api/login') cookie = response.headers.get('set-cookie')?.split(';')[0];
return response.json();
}
try {
({ csrf } = await api('/api/login', { password })); password = '';
report.identityBefore = (await api('/api/identity')).identity;
if (!report.identityBefore) throw new Error('An existing production identity is required');
let transport;
connection = new ProtocolConnection({
url: origin.origin.replace('https:', 'wss:') + '/api/ts3',
session: async ({ signal }) => { const session = await api('/api/session', undefined, signal); csrf = session.csrf; return session; },
socket: url => {
const socket = new WebSocket(url, { origin: origin.origin, headers: { Cookie: cookie }, handshakeTimeout: 15000 });
transport = { openedAt: new Date().toISOString(), snapshots: 0, maxChannels: 0, maxParticipants: 0 };
const entry = transport;
report.transports.push(transport);
const send = socket.send.bind(socket); socket.send = data => { if (typeof data !== 'string') report.outgoingVoice++; return send(data); };
socket.on('close', code => { entry.closedAt = new Date().toISOString(); entry.closeCode = code; });
return socket;
},
phase: phase => {
report.phases.push({ at: new Date().toISOString(), ...phase });
console.log(`Recovery: ${phase.state}${phase.delay ? ` (${Math.ceil(phase.delay / 1000)}s)` : ''}`);
},
expired: () => { report.authExpired = true; },
event: event => {
if (event instanceof ArrayBuffer) { report.incomingVoice++; return; }
if (event.type === 'runtime') report.runtime = { node: event.node, platform: event.platform, arch: event.arch, region: event.region, deployment: event.deployment };
else if (event.type === 'ts3_status' && event.status === 'session_limit') report.capObserved = true;
else if (event.type === 'ts3_error') report.protocolErrors.push({ at: new Date().toISOString(), code: event.code });
else if (event.type === 'ts3_audio_status' && (event.canSend || event.canReceive)) report.unexpectedAudioPermission = true;
else if (event.type === 'ts3_state') {
transport.snapshots++; transport.maxChannels = Math.max(transport.maxChannels, event.channels.length); transport.maxParticipants = Math.max(transport.maxParticipants, event.participants.length);
if (report.capObserved && !report.abruptInterruption && !interrupt) interrupt = setTimeout(() => {
if (!connection.connected) return;
report.abruptInterruption = true; console.log('Interrupting this verification socket only.'); connection.socket.terminate();
}, 30000);
}
},
});
const settings = await api('/api/preferences');
if (!settings.connection) throw new Error('Save a connection through the owner UI before verification');
connection.start({ connectionId: settings.connection.id });
await new Promise(resolve => { end = setTimeout(resolve, seconds * 1000); });
report.recovered = connection.connected; connection.stop();
report.identityAfter = (await api('/api/identity')).identity;
report.identityPreserved = report.identityBefore.uid === report.identityAfter?.uid;
report.passed = report.recovered && report.capObserved && report.abruptInterruption && report.transports.filter(item => item.snapshots > 0).length >= 3 && report.identityPreserved && !report.authExpired && !report.incomingVoice && !report.outgoingVoice && !report.unexpectedAudioPermission;
} catch (error) { report.failure = error.message; report.passed = false; }
finally {
clearTimeout(interrupt); clearTimeout(end); connection?.stop(); password = '';
if (cookie && csrf) await api('/api/logout', {}).catch(() => {});
}
if (process.argv[4]) await writeFile(process.argv[4], JSON.stringify(report, null, 2) + '\n');
console.log(JSON.stringify(report, null, 2));
if (!report.passed) process.exitCode = 1;
+49
View File
@@ -0,0 +1,49 @@
// Local-only simulated protocol fixture. No real TS3 identities or network connections.
import { mkdtemp, writeFile, symlink, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { randomBytes } from 'node:crypto';
import { hashPassword } from '../src/auth/password.mjs';
import { readConfig } from '../src/config.mjs';
import { createStore } from '../src/auth/store.mjs';
import { createVault } from '../src/identity/vault.mjs';
import { createPreferences } from '../src/preferences.mjs';
import { createApp } from '../src/http-adapter.mjs';
if (process.env.VERCEL || process.env.NODE_ENV === 'production') throw new Error('This simulated fixture is local-only.');
const directory = await mkdtemp(join(tmpdir(), 'voxharbor-render-fixture-'));
await symlink(process.execPath, join(directory, 'node'));
const binary = join(directory, 'protocol');
const ownUid = 'AAAAAAAAAAAAAAAAAAAAAAAAAAA='; const peerUid = 'BBBBBBBBBBBBBBBBBBBBBBBBBBB=';
await writeFile(binary, `#!${directory}/node
const readline = require('node:readline');
const emit = value => console.log(JSON.stringify(value));
let first = true; let sequence = 0;
const snapshot = () => emit({type:'state',sequence:++sequence,ownClientId:1,server:{name:'Local rendering fixture — SIMULATED'},channels:[{id:411,parentId:0,name:'Rendering verification (simulated)',topic:'No TeamSpeak connection or human recipients',order:0,subscribed:true,codec:4,passwordProtected:false}],participants:[{id:1,channelId:411,name:'Fixture owner (simulated)',uid:'${ownUid}',inputMuted:true,outputMuted:true},{id:2,channelId:411,name:'<strong>Literal sender</strong>',uid:'${peerUid}',inputMuted:true,outputMuted:true}]});
(async () => { for await (const line of readline.createInterface({input:process.stdin})) {
const request = JSON.parse(line);
if (first) { first=false; emit({type:'status',status:'connected'}); snapshot(); continue; }
if (request.op==='disconnect') break;
if (request.op==='command') {
emit({type:'client_command_result',requestId:request.request_id,ok:true});
if(request.command.type==='text_message') emit({type:'message',target:request.command.target,clientId:2,targetClientId:1,uid:'${peerUid}',targetUid:'${ownUid}',name:'<strong>Literal sender</strong>',channelId:411,message:'Fixture reply: <img src=x> [b]literal[/b]'});
}
if(request.op==='audio_state') emit({type:'audio_status',canSend:false,canReceive:false});
} })().catch(()=>process.exit(1));
`, { mode: 0o700 });
const config = readConfig({ APP_ORIGIN: 'http://localhost:3151', OWNER_PASSWORD_HASH: await hashPassword('workspace-render-fixture-only'), SESSION_SECRET: randomBytes(32).toString('hex'), IDENTITY_ENCRYPTION_KEY: randomBytes(32).toString('hex'), ALLOW_LOCAL_MEMORY_STORE: '1' });
config.protocolBinary = binary;
const store = createStore(config);
// A deliberately synthetic payload for the fake executable, held in volatile memory only.
await createVault(config, store).initialize({ identity: { simulated: true }, metadata: { uid: ownUid, level: 16 } });
await createPreferences(config, store).saveConnection({ host: '1.1.1.1', port: 9987, nickname: 'Fixture owner' });
const app = createApp(config, store);
app.server.listen(3151, '127.0.0.1', () => console.log('SIMULATED rendering fixture: http://localhost:3151 (no real TS3 network or identity)'));
let stopping = false;
async function stop() {
if (stopping) return; stopping = true;
for (const client of app.wss.clients) client.terminate();
app.server.closeAllConnections(); await new Promise(resolve => app.server.close(resolve));
await rm(directory, { recursive: true, force: true }); process.stdin.pause();
}
process.stdin.setEncoding('utf8'); process.stdin.resume(); process.stdin.on('data', data => { if (data.trim() === 'quit') void stop(); });
process.once('SIGINT', () => { void stop(); }); process.once('SIGTERM', () => { void stop(); });