diff options
| author | Doan Luu Duc Tai <doan@luuduct.ai> | 2026-10-31 12:25:30 -0500 |
|---|---|---|
| committer | Doan Luu Duc Tai <doan@luuduct.ai> | 2026-10-31 12:25:30 -0500 |
| commit | 9139398d465f5899cc31bc4cdd54daa7392ca550 (patch) | |
| tree | debf0b15a969e8c64e3b3597f4eb7953b7f047e1 | |
| parent | ef61fc5aca6eca613a055c507a060b70bd537a37 (diff) | |
Migrate browser code and tests to strict TypeScript
31 files changed, 1775 insertions, 615 deletions
@@ -23,3 +23,4 @@ /dist/ *.swp .DS_Store +/node_modules/ @@ -22,7 +22,8 @@ STACK GETTING STARTED Install Rust through rustup, Podman, Git, and GnuPG on a Linux development - machine. Chat builds also need a GCC-compatible C compiler, Linux UAPI + machine, plus Node >=22.18.0 and npm for the TypeScript browser build. + Chat builds also need a GCC-compatible C compiler, Linux UAPI headers, libclang, pkg-config, make, Perl, curl, tar, and OpenSSL 3.5+ development libraries for native workspace checks. The pinned toolchain includes rustfmt, Clippy, and the static x86_64 Linux target. @@ -53,7 +54,8 @@ DEVELOPMENT AND PRODUCTION backup recipients, and secret-setting names. See docs/CONFIGURATION.txt. var/ contains private persistent data, container storage, temporary work, and exports. Generated TLS private keys are runtime data under var/. - .env, var/, .tools/, target/, bin/, and dist/ are excluded from Git. + .env, var/, .tools/, target/, bin/, dist/, and node_modules/ are excluded + from Git. Browser code and tests are TypeScript; see docs/TYPESCRIPT.txt. The four services are Caddy, cgit, SearXNG, and the Rust chat server. The management command is Rust. SearXNG and the cgit container's upstream supervisor retain @@ -61,7 +63,7 @@ DEVELOPMENT AND PRODUCTION Build and test on the development machine. Deploy prebuilt release archives. The production host needs Podman, Git, and GnuPG, but no Rust - toolchain or Cargo. + toolchain, Cargo, Node, npm, or TypeScript. CHECKS AND LICENSES @@ -70,7 +72,9 @@ CHECKS AND LICENSES cargo stack check cargo stack release - Check runs formatting, Clippy, tests, rustdoc, cargo-deny, and cargo-about. + Check builds and checks TypeScript, then runs Rust formatting, Clippy, tests, + rustdoc, cargo-deny, and cargo-about. npm development dependencies are pinned + in package-lock.json; run npm audit to check their advisories. THIRD-PARTY-LICENSES.html is generated from Cargo.lock and about.hbs. Human-readable license headings use GNU's names. SPDX identifiers and original third-party legal texts retain their exact spelling. diff --git a/crates/chat-crypto/README.txt b/crates/chat-crypto/README.txt index a08d850..114544d 100644 --- a/crates/chat-crypto/README.txt +++ b/crates/chat-crypto/README.txt @@ -45,11 +45,12 @@ CHECKS FROM THE WORKSPACE ROOT cargo test --locked -p stack-chat-crypto cargo run --locked -p stack-chat-crypto sh infra/chat/build-openssl-wasi.sh - PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node crates/chat-crypto/tests/browser.mjs + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:crypto cargo stack check Native builds require OpenSSL >=3.5 development files and libclang. The cross-build script supports an x86_64 GNU/Linux development host. - Browser tooling is excluded from the public source tree and releases. + Installed browser tooling is excluded from source archives and releases. + The TypeScript tests and locked toolchain declarations are public. The probe uses public fixture credentials and creates temporary identities in memory. It does not open the root .env or use the canonical RSA key. diff --git a/crates/chat-crypto/browser/protocol.d.ts b/crates/chat-crypto/browser/protocol.d.ts new file mode 100644 index 0000000..6803c4c --- /dev/null +++ b/crates/chat-crypto/browser/protocol.d.ts @@ -0,0 +1,57 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +declare namespace StackChat { + interface Credentials { file: string; password: string } + interface Identity { public: string; fingerprint: string; owner: string; name: string } + interface Session { public: string; fingerprint: string; name: string; id: string; token: string; owner: boolean; expires_seconds: number } + interface Configuration { owner: string | null; origin: string; protocol: string } + interface Conversation { id: string; public: string; profile?: string | null; total: number; visitor_sent: number; owner_sent: number } + interface Message { seq: number; id: string; sender: string; ciphertext: string } + interface SendRequest { op: 'send'; conversation: string; id: string; ciphertext: string } + interface Api { + config: { request: { op: 'config' }; response: Configuration }; + challenge: { request: { op: 'challenge'; public: string; setup_token?: string | undefined }; response: { id: string; challenge: string } }; + authenticate: { request: { op: 'authenticate'; id: string; signature: string }; response: { token: string; id: string; owner: boolean; expires_seconds: number } }; + profile: { request: { op: 'profile'; conversation: string; ciphertext: string }; response: { stored: boolean } }; + inbox: { request: { op: 'inbox' }; response: { conversations: Conversation[] } }; + history: { request: { op: 'history'; conversation: string; count: number; before: number }; response: { conversation: Conversation; messages: Message[] } }; + send: { request: SendRequest; response: { seq: number; conversation: Conversation } }; + lock: { request: { op: 'lock' }; response: { locked: boolean } }; + } + interface Protected extends Credentials { origin: string } + interface Decryption { payload: string; signer: string } + type DecryptionEntry = Decryption | { error: string }; + interface Crypto { + create: { request: { op: 'create'; origin: string; name: string; password: string; owner: string }; response: { file: string } }; + open: { request: Protected & { op: 'open' }; response: Identity }; + proof: { request: Protected & { op: 'proof'; challenge: string }; response: { signature: string } }; + encrypt: { request: Protected & { op: 'encrypt'; recipient: string; payload: string }; response: { ciphertext: string } }; + decrypt: { request: Protected & { op: 'decrypt'; sender: string; ciphertext: string }; response: Decryption }; + decrypt_batch: { request: Protected & { op: 'decrypt_batch'; messages: { sender: string; ciphertext: string }[] }; response: { messages: DecryptionEntry[] } }; + } + type ApiRequest = Api[keyof Api]['request']; + type CryptoRequest = Crypto[keyof Crypto]['request']; + type CryptoResult = Crypto[keyof Crypto]['response']; + type WorkerResponse = { result: CryptoResult } | { error: string }; + interface WorkerRequest { bytes: ArrayBuffer; request: CryptoRequest } + interface Execution { output: string; randomCalls: number; randomBytes: number } + interface Wasi { + runCommand(bytes: ArrayBuffer, request: CryptoRequest): Promise<unknown>; + runProbe(bytes: ArrayBuffer): Promise<Execution>; + } +} + +declare var stackChatWasi: Readonly<StackChat.Wasi>; diff --git a/crates/chat-crypto/browser/wasi.mjs b/crates/chat-crypto/browser/wasi.ts index 80d1299..a037519 100644 --- a/crates/chat-crypto/browser/wasi.mjs +++ b/crates/chat-crypto/browser/wasi.ts @@ -15,8 +15,8 @@ // @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0 -async function execute(bytes, input) { - let memory; +async function execute(bytes: ArrayBuffer, input: string): Promise<StackChat.Execution> { + let memory: WebAssembly.Memory | undefined; let output = ''; let errors = ''; const stdoutDecoder = new TextDecoder('utf-8', { fatal: true }); @@ -25,19 +25,24 @@ async function execute(bytes, input) { let position = 0; let randomCalls = 0; let randomBytes = 0; - const data = () => new DataView(memory.buffer); - const put32 = (address, value) => data().setUint32(address, value, true); - const noEntries = (count, size) => { put32(count, 0); put32(size, 0); return 0; }; + const memoryBuffer = (): ArrayBuffer => { + if (!memory) throw new Error('WASI memory is unavailable'); + return memory.buffer; + }; + const data = (): DataView => new DataView(memoryBuffer()); + const put32 = (address: number, value: number) => data().setUint32(address, value, true); + const noEntries = (count: number, size: number) => { put32(count, 0); put32(size, 0); return 0; }; class Exit extends Error { - constructor(code) { super(`WASI exit ${code}`); this.code = code; } + readonly code: number; + constructor(code: number) { super(`WASI exit ${code}`); this.code = code; } } - const wasi = { + const wasi: Record<string, WebAssembly.ImportValue> = { args_sizes_get: noEntries, environ_sizes_get: noEntries, args_get: () => 0, environ_get: () => 0, - random_get(address, length) { - const buffer = new Uint8Array(memory.buffer, address, length); + random_get(address: number, length: number) { + const buffer = new Uint8Array(memoryBuffer(), address, length); for (let offset = 0; offset < length; offset += 65536) { crypto.getRandomValues(buffer.subarray(offset, Math.min(offset + 65536, length))); } @@ -45,20 +50,20 @@ async function execute(bytes, input) { randomBytes += length; return 0; }, - clock_time_get(clock, precision, address) { + clock_time_get(clock: number, _precision: bigint, address: number) { if (clock !== 0 && clock !== 1) return 52; const milliseconds = clock === 0 ? Date.now() : performance.now(); data().setBigUint64(address, BigInt(Math.floor(milliseconds * 1000000)), true); return 0; }, - clock_res_get(clock, address) { data().setBigUint64(address, 1000000n, true); return 0; }, - fd_write(fd, vectors, count, written) { + clock_res_get(_clock: number, address: number) { data().setBigUint64(address, 1000000n, true); return 0; }, + fd_write(fd: number, vectors: number, count: number, written: number) { if (fd !== 1 && fd !== 2) return 8; let total = 0; for (let index = 0; index < count; index += 1) { const address = data().getUint32(vectors + index * 8, true); const length = data().getUint32(vectors + index * 8 + 4, true); - const text = (fd === 1 ? stdoutDecoder : stderrDecoder).decode(new Uint8Array(memory.buffer, address, length), { stream: true }); + const text = (fd === 1 ? stdoutDecoder : stderrDecoder).decode(new Uint8Array(memoryBuffer(), address, length), { stream: true }); if (fd === 1) output += text; else errors += text; total += length; if (output.length + errors.length > 1048576) throw new Error('Probe output exceeded its limit'); @@ -66,36 +71,36 @@ async function execute(bytes, input) { put32(written, total); return 0; }, - fd_read(fd, vectors, count, read) { + fd_read(fd: number, vectors: number, count: number, read: number) { if (fd !== 0) return 8; let total = 0; for (let index = 0; index < count && position < stdin.length; index += 1) { const address = data().getUint32(vectors + index * 8, true); const capacity = data().getUint32(vectors + index * 8 + 4, true); const length = Math.min(capacity, stdin.length - position); - new Uint8Array(memory.buffer, address, length).set(stdin.subarray(position, position + length)); + new Uint8Array(memoryBuffer(), address, length).set(stdin.subarray(position, position + length)); position += length; total += length; } put32(read, total); return 0; }, - fd_fdstat_get(fd, address) { + fd_fdstat_get(fd: number, address: number) { if (fd > 2) return 8; - new Uint8Array(memory.buffer, address, 24).fill(0); + new Uint8Array(memoryBuffer(), address, 24).fill(0); data().setUint8(address, 2); return 0; }, - fd_fdstat_set_flags: fd => fd <= 2 ? 0 : 8, + fd_fdstat_set_flags: (fd: number) => fd <= 2 ? 0 : 8, fd_prestat_get: () => 8, fd_prestat_dir_name: () => 8, - fd_close: fd => fd <= 2 ? 0 : 8, + fd_close: (fd: number) => fd <= 2 ? 0 : 8, fd_seek: () => 70, fd_tell: () => 70, fd_filestat_get: () => 8, path_open: () => 76, sched_yield: () => 0, - proc_exit(code) { throw new Exit(code); }, + proc_exit(code: number) { throw new Exit(code); }, }; for (const name of [ 'fd_readdir', 'fd_advise', 'fd_allocate', 'fd_datasync', 'fd_sync', @@ -111,16 +116,19 @@ async function execute(bytes, input) { } } const instance = await WebAssembly.instantiate(module, { wasi_snapshot_preview1: wasi }); - memory = instance.exports.memory; - try { instance.exports._start(); } - catch (error) { if (!(error instanceof Exit) || error.code !== 0) throw new Error(`${error.message}: ${errors}`); } + const exportedMemory = instance.exports['memory']; + const start = instance.exports['_start']; + if (!(exportedMemory instanceof WebAssembly.Memory) || typeof start !== 'function') throw new Error('Invalid WASI exports'); + memory = exportedMemory; + try { start(); } + catch (error) { if (!(error instanceof Exit) || error.code !== 0) throw new Error(`${error instanceof Error ? error.message : 'WASI execution failed'}: ${errors}`); } output += stdoutDecoder.decode(); errors += stderrDecoder.decode(); stdin.fill(0); return { output, randomCalls, randomBytes }; } -async function runProbe(bytes) { +async function runProbe(bytes: ArrayBuffer) { const result = await execute(bytes, ''); if (!result.output.startsWith('PASS: backend=OpenSSL ') || result.randomCalls === 0) { throw new Error('OpenSSL probe did not pass'); @@ -128,12 +136,13 @@ async function runProbe(bytes) { return result; } -async function runCommand(bytes, request) { +async function runCommand(bytes: ArrayBuffer, request: StackChat.CryptoRequest): Promise<unknown> { const input = JSON.stringify(request); if (input.length > 8388608) throw new Error('Crypto request exceeds its limit'); const result = await execute(bytes, input); - const response = JSON.parse(result.output); - if (response.error) throw new Error(response.error); + const response: unknown = JSON.parse(result.output); + if (typeof response !== 'object' || response === null || Array.isArray(response)) throw new Error('Invalid crypto response'); + if ('error' in response) throw new Error(typeof response.error === 'string' ? response.error : 'Cryptographic operation failed'); return response; } diff --git a/crates/chat-crypto/tests/browser.mjs b/crates/chat-crypto/tests/browser.ts index 4fd2ee5..75095ce 100644 --- a/crates/chat-crypto/tests/browser.mjs +++ b/crates/chat-crypto/tests/browser.ts @@ -17,10 +17,11 @@ import { createServer } from 'node:http'; import { readFile } from 'node:fs/promises'; import { resolve } from 'node:path'; import assert from 'node:assert/strict'; -import { chromium } from '../../../.tools/browser/node_modules/playwright/index.mjs'; +import { chromium } from 'playwright'; +import { serverOrigin } from '../../../tests/browser-support.js'; -const assets = new Map([ - ['/wasi.mjs', [resolve('crates/chat-crypto/browser/wasi.mjs'), 'text/javascript']], +const assets = new Map<string, [string, string]>([ + ['/wasi.mjs', [resolve('var/build/typescript/crates/chat-crypto/browser/wasi.js'), 'text/javascript']], ['/probe.wasm', [resolve('target/wasm32-wasip1/release/stack-chat-crypto.wasm'), 'application/wasm']], ]); const server = createServer(async (request, response) => { @@ -30,24 +31,25 @@ const server = createServer(async (request, response) => { response.end('<!doctype html><title>Local cryptographic compatibility test</title>'); return; } - const asset = assets.get(request.url); + const asset = assets.get(request.url || ''); if (!asset) { response.writeHead(404); response.end(); return; } response.setHeader('Content-Type', asset[1]); response.end(await readFile(asset[0])); }); -await new Promise(resolveReady => server.listen(0, '127.0.0.1', resolveReady)); -const origin = `http://127.0.0.1:${server.address().port}`; +await new Promise<void>(resolveReady => server.listen(0, '127.0.0.1', resolveReady)); +const origin = serverOrigin(server); const browser = await chromium.launch({headless: true, channel: "chromium"}); const deadline = setTimeout(() => browser.close(), 120000); try { const page = await browser.newPage(); - const external = []; + const external: string[] = []; page.on('request', request => { if (!request.url().startsWith(origin + '/')) external.push(request.url()); }); await page.goto(origin); const result = await page.evaluate(async () => { - await import('/wasi.mjs'); + const host = '/wasi.mjs'; + await import(host); const { runProbe } = globalThis.stackChatWasi; const bytes = await (await fetch('/probe.wasm', { cache: 'no-store' })).arrayBuffer(); const valid = await runProbe(bytes); @@ -55,16 +57,16 @@ try { const getRandomValues = crypto.getRandomValues; let rejected = false; crypto.getRandomValues = () => { throw new Error('Entropy unavailable'); }; - try { await runProbe(bytes); } catch (error) { rejected = error.message.includes("Entropy unavailable"); } + try { await runProbe(bytes); } catch (error) { rejected = (error instanceof Error ? error.message : String(error)).includes("Entropy unavailable"); } finally { crypto.getRandomValues = getRandomValues; } const modified = new Uint8Array(bytes.slice(0)); const pattern = new TextEncoder().encode('random_get'); - const offset = modified.findIndex((value, index) => pattern.every((byte, position) => modified[index + position] === byte)); + const offset = modified.findIndex((_value, index) => pattern.every((byte, position) => modified[index + position] === byte)); if (offset < 0) throw new Error('Expected entropy import was not found'); modified.set(new TextEncoder().encode('reject_get'), offset); let unknownImportRejected = false; - try { await runProbe(modified); } - catch (error) { unknownImportRejected = error.message.includes('Unsupported WASI import: wasi_snapshot_preview1.reject_get'); } + try { await runProbe(modified.buffer); } + catch (error) { unknownImportRejected = (error instanceof Error ? error.message : String(error)).includes('Unsupported WASI import: wasi_snapshot_preview1.reject_get'); } return { valid, again, rejected, unknownImportRejected }; }); assert.match(result.valid.output, /^PASS: backend=OpenSSL 3\.6\.5;/); diff --git a/crates/chat-server/src/http.rs b/crates/chat-server/src/http.rs index 7394b71..cb21b1f 100644 --- a/crates/chat-server/src/http.rs +++ b/crates/chat-server/src/http.rs @@ -93,59 +93,94 @@ async fn api(State(app): State<App>, headers: HeaderMap, Json(request): Json<Val } } -async fn asset(State(app): State<App>, uri: axum::http::Uri) -> Response { - if uri.path() == "/THIRD-PARTY-LICENSES.html" { - let Some(origin) = app.public.get("SITE_ORIGIN") else { - return secured(StatusCode::INTERNAL_SERVER_ERROR.into_response()); - }; - return secured( - Redirect::permanent(&format!("{origin}/THIRD-PARTY-LICENSES.html")).into_response(), - ); +fn packaged_asset<'a>(root: &Path, packaged: &'a str, development: &'a str) -> &'a str { + if root.join(packaged).is_file() { + packaged + } else { + development } - let (path, mime) = match uri.path() { - "/" => ( +} + +fn asset_location(root: &Path, path: &str) -> Option<(&'static str, &'static str)> { + let assets = [ + ( + "/", + "bin/chat/web/index.html", "crates/chat-server/web/index.html", "text/html; charset=utf-8", ), - "/app.js" => ( - "crates/chat-server/web/app.js", + ( + "/app.js", + "bin/chat/web/app.js", + "var/build/typescript/crates/chat-server/web/app.js", "text/javascript; charset=utf-8", ), - "/worker.js" => ( - "crates/chat-server/web/worker.js", + ( + "/worker.js", + "bin/chat/web/worker.js", + "var/build/typescript/crates/chat-server/web/worker.js", "text/javascript; charset=utf-8", ), - "/wasi.mjs" => ( - "crates/chat-crypto/browser/wasi.mjs", + ( + "/wasi.mjs", + "bin/chat/wasi.mjs", + "var/build/typescript/crates/chat-crypto/browser/wasi.js", "text/javascript; charset=utf-8", ), - "/style.css" => ( + ( + "/style.css", + "bin/chat/web/style.css", "crates/chat-server/web/style.css", "text/css; charset=utf-8", ), - "/crypto.wasm" => ( - if app.root.join("bin/chat/crypto.wasm").is_file() { - "bin/chat/crypto.wasm" - } else { - "target/wasm32-wasip1/release/stack-chat-crypto.wasm" - }, + ( + "/crypto.wasm", + "bin/chat/crypto.wasm", + "target/wasm32-wasip1/release/stack-chat-crypto.wasm", "application/wasm", ), - "/javascript.html" => ( + ( + "/javascript.html", + "bin/chat/web/javascript.html", "crates/chat-server/web/javascript.html", "text/html; charset=utf-8", ), - "/SOURCE.tar.gz" => ( - if app.root.join("bin/chat/SOURCE.tar.gz").is_file() { - "bin/chat/SOURCE.tar.gz" - } else { - "var/build/chat-source.tar.gz" - }, + ( + "/SOURCE.tar.gz", + "bin/chat/SOURCE.tar.gz", + "var/build/chat-source.tar.gz", "application/gzip", ), - "/LIMITATIONS.txt" => ("docs/CHAT-APPLICATION.txt", "text/plain; charset=utf-8"), - "/LICENSE" => ("LICENSE", "text/plain; charset=utf-8"), - _ => return secured(StatusCode::NOT_FOUND.into_response()), + ( + "/LIMITATIONS.txt", + "docs/CHAT-APPLICATION.txt", + "docs/CHAT-APPLICATION.txt", + "text/plain; charset=utf-8", + ), + ( + "/LICENSE", + "LICENSE", + "LICENSE", + "text/plain; charset=utf-8", + ), + ]; + assets + .into_iter() + .find(|(route, _, _, _)| *route == path) + .map(|(_, packaged, development, mime)| (packaged_asset(root, packaged, development), mime)) +} + +async fn asset(State(app): State<App>, uri: axum::http::Uri) -> Response { + if uri.path() == "/THIRD-PARTY-LICENSES.html" { + let Some(origin) = app.public.get("SITE_ORIGIN") else { + return secured(StatusCode::INTERNAL_SERVER_ERROR.into_response()); + }; + return secured( + Redirect::permanent(&format!("{origin}/THIRD-PARTY-LICENSES.html")).into_response(), + ); + } + let Some((path, mime)) = asset_location(&app.root, uri.path()) else { + return secured(StatusCode::NOT_FOUND.into_response()); }; if matches!(uri.path(), "/" | "/javascript.html") { let Ok(bytes) = tokio::fs::read(app.root.join(path)).await else { diff --git a/crates/chat-server/tests/browser.mjs b/crates/chat-server/tests/browser.ts index b0a9041..74a9df2 100644 --- a/crates/chat-server/tests/browser.mjs +++ b/crates/chat-server/tests/browser.ts @@ -21,16 +21,18 @@ import { resolve, join } from 'node:path'; import { randomBytes } from 'node:crypto'; import { spawn, execFileSync, spawnSync, execFile } from 'node:child_process'; import { promisify } from 'node:util'; -import { chromium, firefox } from '../../../.tools/browser/node_modules/playwright/index.mjs'; +import { chromium, firefox, type Browser, type BrowserContext, type Page } from 'playwright'; +import { libreJSAddon, list, record, requestBody, required, serverOrigin, string } from '../../../tests/browser-support.js'; const run = promisify(execFile); -const packaged = Boolean(process.env.CHAT_TEST_ROOT); -let root = packaged ? resolve(process.env.CHAT_TEST_ROOT) : await mkdtemp(join(tmpdir(), 'stack-chat-e2e-')); +const testRoot = process.env['CHAT_TEST_ROOT']; +const packaged = Boolean(testRoot); +let root = testRoot ? resolve(testRoot) : await mkdtemp(join(tmpdir(), 'stack-chat-e2e-')); const initialRoot = root; const token = packaged - ? (await readFile(join(root,'.env'),'utf8')).split('\n').find(line => line.startsWith('CHAT_SETUP_TOKEN=')).slice('CHAT_SETUP_TOKEN='.length) + ? (await readFile(join(root,'.env'),'utf8')).split('\n').find(line => line.startsWith('CHAT_SETUP_TOKEN='))?.slice('CHAT_SETUP_TOKEN='.length) || '' : randomBytes(32).toString('hex'); -const origin = process.env.CHAT_TEST_ORIGIN || `http://127.0.0.1:${process.env.CHAT_TEST_PORT || '9081'}`; +const origin = process.env['CHAT_TEST_ORIGIN'] || `http://127.0.0.1:${process.env['CHAT_TEST_PORT'] || '9081'}`; if (packaged) { const fixture = await readFile(join(root,'.env'),'utf8'); const address = new URL(origin); @@ -48,14 +50,15 @@ if (packaged) { } else { await writeFile(join(root, '.env'), `CHAT_ORIGIN=${origin}\nCHAT_SETUP_TOKEN=${token}\n`, {mode:0o600}); for (const path of ['crates','target','docs','web','LICENSE']) await symlink(resolve(path), join(root,path)); - await mkdir(join(root,'var/build'), {recursive:true}); + await mkdir(join(root,'var'), {recursive:true}); + await symlink(resolve('var/build'),join(root,'var/build')); } -async function stack(...args) { +async function stack(...args: string[]) { return run(join(root,'bin/stack'),args,{cwd:root,env:{...process.env,GNUPGHOME:gpgHome},maxBuffer:8*1024*1024,timeout:300000}); } async function restorePackage() { const listed = await run('gpg',['--no-options','--homedir',gpgHome,'--with-colons','--list-keys']); - const fingerprint = listed.stdout.split('\n').find(line => line.startsWith('fpr:')).split(':')[9]; + const fingerprint = required(required(listed.stdout.split('\n').find(line => line.startsWith('fpr:')), 'Missing key fingerprint').split(':')[9], 'Missing key fingerprint field'); const key = join(testHome,'recipient.asc'); const exported = await run('gpg',['--no-options','--homedir',gpgHome,'--armor','--export',fingerprint]); await writeFile(key,exported.stdout); @@ -73,15 +76,15 @@ async function restorePackage() { await launchServer(); console.log(`PASS: compiler-free HTTPS stack recovered from encrypted export ${restorations}.`); } -let server; +let server: ReturnType<typeof spawn> | undefined; let serverErrors = ''; async function verifyGateway() { const url = new URL(origin); const args = ['--noproxy','*','--silent','--show-error','--fail']; if (url.hostname.endsWith('.localhost')) { - const state = JSON.parse(await readFile(join(root,'var/state.json'),'utf8')); + const state = record(JSON.parse(await readFile(join(root,'var/state.json'),'utf8'))); const certificate = join(testHome,'gateway-ca.crt'); - await run('podman',['--root',join(root,'var/podman/storage'),'--runroot',join(root,'var/podman/run'),'cp',`${state.project}-caddy:/data/caddy/pki/authorities/local/root.crt`,certificate]); + await run('podman',['--root',join(root,'var/podman/storage'),'--runroot',join(root,'var/podman/run'),'cp',`${string(state['project'])}-caddy:/data/caddy/pki/authorities/local/root.crt`,certificate]); args.push('--cacert',certificate,'--resolve',`${url.hostname}:${url.port}:127.0.0.1`); } const health = await run('curl',[...args,origin + '/healthz']); @@ -98,23 +101,24 @@ async function launchServer() { throw failure; } server = spawn(resolve('target/debug/stack-chat-server'), ['--root',root,'--bind',new URL(origin).host], {stdio:['ignore','pipe','pipe']}); - server.stderr.on('data', bytes => { serverErrors += bytes.toString(); }); + server.stderr?.on('data', bytes => { serverErrors += bytes.toString(); }); await Promise.race([ - new Promise((ready, reject) => { server.stdout.once('data', ready); server.once('exit', () => reject(new Error(serverErrors || 'Server exited'))); }), + new Promise<void>((ready, reject) => { server?.stdout?.once('data', () => ready()); server?.once('exit', () => reject(new Error(serverErrors || 'Server exited'))); }), new Promise((_, reject) => setTimeout(() => reject(new Error('Server did not start')), 20000).unref()), ]); } async function stopServer() { if (packaged) { await stack('down'); return; } + if (!server) return; if (server.exitCode !== null || server.signalCode !== null) return; - const stopped = new Promise(done => server.once('exit',done)); + const stopped = new Promise<void>(done => server?.once('exit', () => done())); server.kill('SIGINT'); await stopped; } await launchServer(); -const libre = process.env.CHAT_LIBREJS === '1'; -let persistent; -let browser; +const libre = process.env['CHAT_LIBREJS'] === '1'; +let persistent: BrowserContext | undefined; +let browser: Browser | { close(): Promise<void> }; if (libre) { const profile = join(testHome,'firefox-profile'); await mkdir(join(profile,'extensions'),{recursive:true}); @@ -124,63 +128,64 @@ if (libre) { 'extensions.update.enabled':false,'app.update.auto':false,'datareporting.healthreport.uploadEnabled':false, 'browser.sessionstore.resume_from_crash':false, }}); - browser = { close: () => persistent.close() }; + browser = { close: () => required(persistent, 'Missing Firefox context').close() }; } else { browser = await chromium.launch({headless:true,channel:'chromium'}); } const deadline = setTimeout(() => browser.close(), 300000); -const contexts = []; -const external = []; -const errors = []; -const bodies = []; +const contexts: BrowserContext[] = []; +const external: string[] = []; +const errors: string[] = []; +const bodies: ReturnType<typeof requestBody>[] = []; async function page() { - const context = persistent || await browser.newContext({acceptDownloads:true,ignoreHTTPSErrors:packaged}); + const context = required(persistent || await ('newContext' in browser ? browser.newContext({acceptDownloads:true,ignoreHTTPSErrors:packaged}) : Promise.reject(new Error('Missing browser context'))), 'Missing browser context'); contexts.push(context); const page = await context.newPage(); page.setDefaultTimeout(90000); page.on('pageerror', error => errors.push(error.message)); const navigate = page.goto.bind(page); - page.goto = async (...args) => { + page.goto = async (...args: Parameters<Page['goto']>) => { for (let attempt = 0; ; attempt += 1) { try { return await navigate(...args); } - catch (error) { if (attempt >= 2 || !error.message.includes('ERR_NETWORK_CHANGED')) throw error; } + catch (error) { if (attempt >= 2 || !(error instanceof Error && error.message.includes('ERR_NETWORK_CHANGED'))) throw error; } } }; page.on('request', request => { if (!request.url().startsWith(origin + '/')) external.push(request.url()); - if (request.url() === origin + '/api') bodies.push(JSON.parse(request.postData())); + if (request.url() === origin + '/api') bodies.push(requestBody(required(request.postData(), 'Missing API body'))); }); return page; } -async function waitEntry(page) { await page.locator('#create-choice').waitFor({state:'visible'}); } -async function waitStatus(page, text) { await page.waitForFunction(value => document.getElementById('status').textContent.includes(value), text); } -async function create(page, name, owner = false) { +async function waitEntry(page: Page) { await page.locator('#create-choice').waitFor({state:'visible'}); } +async function waitStatus(page: Page, text: string) { await page.waitForFunction(value => document.getElementById('status')?.textContent?.includes(value), text); } +async function create(page: Page, name: string, owner = false) { const previousAuthentications = bodies.filter(body => body.op === 'authenticate').length; if (owner) await page.fill('#setup-token', token); else await page.click('#create-choice'); await page.fill('#name', name); await page.fill('#new-password', password); await page.fill('#confirm-password', password); - const downloaded = Promise.race([page.waitForEvent('download'), page.waitForFunction(() => /failed|timed out/i.test(document.getElementById('status').textContent)).then(async () => { throw new Error(await page.locator('#status').textContent()); })]); + const downloaded = Promise.race([page.waitForEvent('download'), page.waitForFunction(() => /failed|timed out/i.test(document.getElementById('status')?.textContent || '')).then(async () => { throw new Error(await page.locator('#status').textContent() || 'Missing status'); })]); await page.click('#create-form button'); const download = await downloaded; - const bytes = await readFile(await download.path()); - const envelope = JSON.parse(bytes.toString()); - assert.ok(envelope.format.startsWith('stack-chat-file/v2;')); + const bytes = await readFile(required(await download.path(), 'Missing download')); + const envelope = record(JSON.parse(bytes.toString())); + const ciphertext = list(envelope['ciphertext']).map(string); + assert.ok(string(envelope['format']).startsWith('stack-chat-file/v2;')); assert.ok(bytes.toString().startsWith('{\n "format"')); - assert.ok(Array.isArray(envelope.ciphertext)); - assert.ok(envelope.ciphertext.length > 1); - assert.ok(envelope.ciphertext.slice(0,-1).every(chunk => chunk.length === 80)); - assert.ok(envelope.ciphertext.at(-1).length > 0 && envelope.ciphertext.at(-1).length <= 80); + assert.ok(Array.isArray(ciphertext)); + assert.ok(ciphertext.length > 1); + assert.ok(ciphertext.slice(0,-1).every(chunk => chunk.length === 80)); + assert.ok(required(ciphertext.at(-1), 'Missing final chunk').length > 0 && required(ciphertext.at(-1), 'Missing final chunk').length <= 80); await waitStatus(page,'Reopen your downloaded'); assert.equal(await page.locator('#chat').isVisible(), false); assert.equal(bodies.filter(body => body.op === 'authenticate').length,previousAuthentications); return {name:'identity.chat',mimeType:'application/octet-stream',buffer:bytes}; } -async function unlock(page, file, phrase = password) { +async function unlock(page: Page, file: { name: string; mimeType: string; buffer: Buffer }, phrase = password) { await page.setInputFiles('#file', file); await page.fill('#password', phrase); await page.click('#unlock-form button'); } -async function storageEmpty(page) { +async function storageEmpty(page: Page) { assert.equal(await page.evaluate(() => localStorage.length + sessionStorage.length),0); assert.deepEqual(await page.evaluate(() => indexedDB.databases()),[]); assert.equal(await page.evaluate(async () => (await navigator.serviceWorker.getRegistrations()).length),0); @@ -196,10 +201,10 @@ async function verifyLibreJS() { } else if (request.url === '/executed') { executed = true; response.end('unexpected'); } else { response.setHeader('Content-Type','text/html'); response.end('<!doctype html><script src="/control.js"></script><p>Unlicensed external-script rejection control.</p>'); } }); - await new Promise(done => controlServer.listen(0,'127.0.0.1',done)); - const controlPage = await persistent.newPage(); + await new Promise<void>(done => controlServer.listen(0,'127.0.0.1',done)); + const controlPage = await required(persistent, 'Missing Firefox context').newPage(); try { - await controlPage.goto(`http://127.0.0.1:${controlServer.address().port}/`); + await controlPage.goto(serverOrigin(controlServer) + '/'); await controlPage.waitForTimeout(1500); assert.equal(await controlPage.evaluate(() => window.unlicensedControl),undefined,'LibreJS must reject the unlicensed control'); assert.equal(executed,false); @@ -207,14 +212,21 @@ async function verifyLibreJS() { } try { if (libre) await verifyLibreJS(); + const malformed = await page(); + await malformed.route('**/api', route => route.fulfill({ json: { owner: 42, origin, protocol: 'stack-chat/v1' } })); + await malformed.goto(origin); + await waitStatus(malformed, 'Invalid owner configuration'); + assert.equal(await malformed.locator('#create-choice').isVisible(), false); + await storageEmpty(malformed); + await malformed.close(); const owner = await page(); const response = await owner.goto(origin); await owner.locator('#owner-choice').waitFor({state:'visible'}).catch(async error => { throw new Error(`${error.message}; status=${await owner.locator('#status').textContent()}`); }); await owner.click('#owner-choice'); - assert.match(response.headers()['cache-control'], /no-store/); - assert.match(response.headers()['content-security-policy'], /frame-ancestors 'none'/); + assert.match(required(response, 'Missing response').headers()['cache-control'] || '', /no-store/); + assert.match(required(response, 'Missing response').headers()['content-security-policy'] || '', /frame-ancestors 'none'/); await owner.locator('#setup-token').waitFor({state:'visible'}); - assert.match(await owner.locator('#create-title').textContent(),/owner only/); + assert.match(await owner.locator('#create-title').textContent() || '',/owner only/); assert.equal(await owner.locator('.introduction h1').count(),0); assert.equal(await owner.locator('.libre-badge a[rel=jslicense]').count(),1); assert.equal(await owner.locator('.source-footer a[rel=jslicense]').count(),0); @@ -222,7 +234,7 @@ try { const ownerFile = await create(owner,'Doan',true); await unlock(owner,ownerFile); await waitStatus(owner,'Unlocked in memory only'); - assert.match(await owner.locator('#who').textContent(), /OWNER/); + assert.match(await owner.locator('#who').textContent() || '', /OWNER/); const visitor = await page(); await visitor.goto(origin); await waitEntry(visitor); @@ -234,7 +246,7 @@ try { await unlock(visitor,visitorFile); await waitStatus(visitor,'Unlocked in memory only'); assert.equal(await visitor.locator('#messages li').count(),0); - assert.match(await visitor.locator('#counts').textContent(),/Total: 0/); + assert.match(await visitor.locator('#counts').textContent() || '',/Total: 0/); const malicious = '<script>window.chatInjection = true</script> hello λ'; await visitor.fill('#text',malicious); await visitor.click('#send-form button'); @@ -242,8 +254,20 @@ try { await owner.click('#refresh-inbox'); await owner.locator('#conversations button').first().click(); await waitStatus(owner,'Conversation opened'); - assert.match(await owner.locator('#thread-name').textContent(),/A friend/); + assert.match(await owner.locator('#thread-name').textContent() || '',/A friend/); assert.equal(await owner.locator('#messages li').count(),0); + await owner.route('**/api', async route => { + const body = requestBody(required(route.request().postData(), 'Missing API body')); + if (body.op === 'history') { + const response = record(await (await route.fetch()).json()); + await route.fulfill({ json: { ...response, conversation: { ...record(response['conversation']), total: '1' } } }); + } else await route.continue(); + }); + await owner.fill('#history-count','1'); + await owner.click('#history-form button'); + await waitStatus(owner, 'Invalid response count: total'); + assert.equal(await owner.locator('#messages li').count(),0); + await owner.unroute('**/api'); await owner.fill('#history-count','1'); await owner.click('#history-form button'); await waitStatus(owner,'Selected history decrypted'); @@ -256,20 +280,20 @@ try { await visitor.click('#history-form button'); await waitStatus(visitor,'Selected history decrypted'); assert.equal(await visitor.locator('#messages li').count(),2); - assert.match(await visitor.locator('#counts').textContent(),/Total: 2 \| Sent: 1 \| Received: 1/); + assert.match(await visitor.locator('#counts').textContent() || '',/Total: 2 \| Sent: 1 \| Received: 1/); let interrupted = false; await visitor.route('**/api',async route => { - const body = route.request().postDataJSON(); + const body = requestBody(required(route.request().postData(), 'Missing API request')); if (body.op === 'send' && !interrupted) { interrupted = true; await route.fetch(); await route.abort(); } else await route.continue(); }); await visitor.fill('#text','Safe retry after a lost response'); await visitor.click('#send-form button'); await visitor.locator('#retry').waitFor({state:'visible'}); - await visitor.waitForFunction(() => !document.getElementById('retry').disabled); + await visitor.waitForFunction(() => !document.querySelector<HTMLButtonElement>('#retry')?.disabled); await visitor.click('#retry'); await waitStatus(visitor,'Encrypted message stored'); - assert.match(await visitor.locator('#counts').textContent(),/Total: 3/); + assert.match(await visitor.locator('#counts').textContent() || '',/Total: 3/); await visitor.reload(); await waitEntry(visitor); assert.equal(await visitor.locator('#messages li').count(),0); @@ -278,12 +302,12 @@ try { await visitor.click('#open-choice'); await unlock(visitor,visitorFile); await waitStatus(visitor,'Unlocked in memory only'); - assert.match(await visitor.locator('#counts').textContent(),/Total: 3/); + assert.match(await visitor.locator('#counts').textContent() || '',/Total: 3/); assert.equal(await visitor.locator('#messages li').count(),0); await visitor.fill('#history-count','1'); await visitor.click('#history-form button'); await waitStatus(visitor,'Selected history decrypted'); - assert.match(await visitor.locator('#messages p').textContent(),/Safe retry/); + assert.match(await visitor.locator('#messages p').textContent() || '',/Safe retry/); await visitor.click('#older'); await waitStatus(visitor,'Selected history decrypted'); assert.equal(await visitor.locator('#messages li').count(),2); @@ -305,7 +329,7 @@ try { await visitor.click('#open-choice'); await unlock(visitor,visitorFile); await waitStatus(visitor,'Unlocked in memory only'); - assert.match(await visitor.locator('#counts').textContent(),/Total: 3/); + assert.match(await visitor.locator('#counts').textContent() || '',/Total: 3/); await visitor.fill('#history-count','3'); await visitor.click('#history-form button'); await waitStatus(visitor,'Selected history decrypted'); @@ -318,7 +342,7 @@ try { await owner.click('#owner-open'); await unlock(owner,ownerFile); await waitStatus(owner,'Unlocked in memory only'); - assert.match(await owner.locator('#who').textContent(),/OWNER/); + assert.match(await owner.locator('#who').textContent() || '',/OWNER/); await visitor.fill('#history-count','3'); await visitor.click('#history-form button'); await visitor.click('#lock'); @@ -326,7 +350,7 @@ try { assert.equal(await visitor.locator('#messages li').count(),0); await visitor.goto(origin + '/LIMITATIONS.txt'); await visitor.goBack(); - await visitor.waitForFunction(() => !document.getElementById('entry').hidden); + await visitor.waitForFunction(() => document.getElementById('entry')?.hidden === false); assert.equal(await visitor.locator('#messages li').count(),0); assert.equal(await visitor.locator('#password').inputValue(),''); assert.equal(await visitor.locator('#chat').isVisible(),false); @@ -368,7 +392,7 @@ try { } const blocked = await visitor.request.post(origin + '/api',{data:{op:'config'},headers:{Origin:'https://foreign.invalid'}}); assert.equal(blocked.status(),403); - const administrative = (...args) => packaged + const administrative = (...args: string[]) => packaged ? spawnSync(join(root,'bin/stack'),['chat',...args],{cwd:root,encoding:'utf8'}) : spawnSync(resolve('target/debug/stack-chat-server'),['--root',root,'--bind',new URL(origin).host,...args],{encoding:'utf8'}); const registered = administrative('--owner-fingerprint'); @@ -402,14 +426,13 @@ try { await waitStatus(visitor,'Pinned owner key differs'); assert.equal(await visitor.locator('#chat').isVisible(),false); assert.equal(serverErrors,''); - if (process.env.CHAT_SCREENSHOT) await visitor.screenshot({path:resolve('.tools/chat-preview.png'),fullPage:true}); + if (process.env['CHAT_SCREENSHOT']) await visitor.screenshot({path:resolve('.tools/chat-preview.png'),fullPage:true}); if (libre) { - const extensions = JSON.parse(await readFile(join(testHome,'firefox-profile','extensions.json'),'utf8')); - const addon = extensions.addons.find(addon => addon.id === 'jid1-KtlZuoiikVfFew@jetpack'); + const addon = libreJSAddon(await readFile(join(testHome,'firefox-profile','extensions.json'),'utf8')); assert.ok(addon?.active,'LibreJS must actually be active'); console.log(`LibreJS ${addon.version} is active in Firefox; complete chat workflow succeeded.`); } - console.log('PASS: real browser/WASI owner setup, protected file recovery, wrong password, visitor/owner encrypted messages, safe text rendering, N=0, counts, dynamic 0-to-total selection and 50-row batching, pagination, retry deduplication, reload, live SQLite snapshot restoration and both identity recoveries, explicit lock, owner setup/access, backend-only reset guards and fresh registration, old key-pin rejection, origin rejection, no browser storage or external requests, no private uploads or database plaintext.'); + console.log('PASS: real browser/WASI owner setup, protected file recovery, wrong password, visitor/owner encrypted messages, safe text rendering, N=0, counts, dynamic 0-to-total selection and 50-row batching, pagination, retry deduplication, reload, live SQLite snapshot restoration and both identity recoveries, explicit lock, owner setup/access, backend-only reset guards and fresh registration, old key-pin rejection, origin rejection, malformed configuration and history rejection, no browser storage or external requests, no private uploads or database plaintext.'); } finally { clearTimeout(deadline); await browser.close(); diff --git a/crates/chat-server/tests/progress.mjs b/crates/chat-server/tests/progress.ts index 0ee5614..59c939d 100644 --- a/crates/chat-server/tests/progress.mjs +++ b/crates/chat-server/tests/progress.ts @@ -14,22 +14,23 @@ // along with this program. If not, see <https://www.gnu.org/licenses/>. import assert from 'node:assert/strict'; -import { createServer } from 'node:http'; +import { createServer, type ServerResponse } from 'node:http'; import { readFile, writeFile, mkdir, mkdtemp, rm } from 'node:fs/promises'; import { tmpdir } from 'node:os'; import { join, resolve } from 'node:path'; -import { chromium, firefox } from '../../../.tools/browser/node_modules/playwright/index.mjs'; +import { chromium, firefox, type BrowserContext, type Page } from 'playwright'; +import { libreJSAddon, required, serverOrigin } from '../../../tests/browser-support.js'; -const libre = process.env.CHAT_LIBREJS === '1'; +const libre = process.env['CHAT_LIBREJS'] === '1'; const profile = await mkdtemp(join(tmpdir(),'stack-chat-progress-')); const bytes = await readFile(resolve('target/wasm32-wasip1/release/stack-chat-crypto.wasm')); let mode = 'known'; -let transfer; -let configuration; -let configReady; -let signalConfig; -let origin; -const errors = []; +let transfer: ServerResponse | undefined; +let configuration: ServerResponse | undefined; +let configReady: Promise<void> | undefined; +let signalConfig: (() => void) | undefined; +let origin = ''; +const errors: string[] = []; const server = createServer(async (request,response) => { response.setHeader('Cache-Control','no-store'); if (request.url === '/crypto.wasm') { @@ -40,20 +41,20 @@ const server = createServer(async (request,response) => { response.write(bytes.subarray(0,1048576)); return; } - if (request.url === '/api') { configuration = response; signalConfig(); return; } - const assets = { '/':'crates/chat-server/web/index.html','/app.js':'crates/chat-server/web/app.js','/style.css':'crates/chat-server/web/style.css' }; - const path = assets[request.url]; + if (request.url === '/api') { configuration = response; required(signalConfig, 'Missing configuration signal')(); return; } + const assets: Record<string, string> = { '/':'crates/chat-server/web/index.html','/app.js':'var/build/typescript/crates/chat-server/web/app.js','/style.css':'crates/chat-server/web/style.css' }; + const path = assets[request.url || '']; if (!path) { response.writeHead(404); response.end(); return; } - const mime = request.url === '/' ? 'text/html' : request.url.endsWith('.js') ? 'text/javascript' : 'text/css'; + const mime = request.url === '/' ? 'text/html' : request.url?.endsWith('.js') ? 'text/javascript' : 'text/css'; response.setHeader('Content-Type',mime); let source = await readFile(resolve(path),'utf8'); if (request.url === '/') source = source.replaceAll('{{SITE_ORIGIN}}',origin); response.end(source); }); -await new Promise(done => server.listen(0,'127.0.0.1',done)); -origin = `http://127.0.0.1:${server.address().port}`; +await new Promise<void>(done => server.listen(0,'127.0.0.1',done)); +origin = serverOrigin(server); let browser; -let context; +let context: BrowserContext; if (libre) { await mkdir(join(profile,'extensions')); const addon = await readFile(resolve('.tools/librejs.xpi')); @@ -64,7 +65,7 @@ if (libre) { browser = await chromium.launch({headless:true,channel:'chromium'}); context = await browser.newContext(); } -async function open(selected) { +async function open(selected: 'known' | 'unknown' | 'failure') { mode = selected; configuration = undefined; configReady = new Promise(done => { signalConfig = done; }); @@ -74,16 +75,16 @@ async function open(selected) { await page.goto(origin); return page; } -async function waitStatus(page,part) { - await page.waitForFunction(value => document.getElementById('status').textContent.includes(value),part); - return page.locator('#status').textContent(); +async function waitStatus(page: Page, part: string) { + await page.waitForFunction(value => document.getElementById('status')?.textContent?.includes(value),part); + return await page.locator('#status').textContent() || ''; } -async function complete(page,offset) { - transfer.end(bytes.subarray(offset)); +async function complete(page: Page, offset: number) { + required(transfer, 'Missing transfer').end(bytes.subarray(offset)); await waitStatus(page,'Connecting to chat'); await configReady; - configuration.setHeader('Content-Type','application/json'); - configuration.end(JSON.stringify({origin,owner:''})); + required(configuration, 'Missing configuration').setHeader('Content-Type','application/json'); + required(configuration, 'Missing configuration').end(JSON.stringify({origin,owner:'',protocol:'stack-chat/v1'})); await page.locator('#owner-choice').waitFor({state:'visible'}); assert.equal(await page.locator('#status').textContent(),''); assert.equal(await page.evaluate(async () => (await wasm).byteLength),bytes.length); @@ -93,11 +94,11 @@ try { const known = await open('known'); assert.match(await waitStatus(known,'1.0 /'),/\[#{3}-{17}\] 19%/); await known.clock.fastForward(44000); - transfer.write(bytes.subarray(1048576,2097152)); + required(transfer, 'Missing transfer').write(bytes.subarray(1048576,2097152)); assert.match(await waitStatus(known,'2.0 /'),/39%/); await known.screenshot({path:resolve('.tools/chat-download-progress.png'),fullPage:true}); await known.clock.fastForward(44000); - assert.ok(!(await known.locator('#status').textContent()).includes('stalled')); + assert.ok(!(await known.locator('#status').textContent() || '').includes('stalled')); await complete(known,2097152); const unknown = await open('unknown'); assert.equal(await waitStatus(unknown,'1.0 MiB received'),'Downloading cryptographic module... 1.0 MiB received'); @@ -110,13 +111,12 @@ try { await waitStatus(stalled,'1.0 /'); await stalled.clock.fastForward(45001); await waitStatus(stalled,'stalled for 45 seconds'); - assert.match(await stalled.locator('#status').textContent(),/reload/); + assert.match(await stalled.locator('#status').textContent() || '',/reload/); assert.equal(await stalled.locator('#owner-choice').isVisible(),false); await stalled.close(); assert.deepEqual(errors,[]); if (libre) { - const state = JSON.parse(await readFile(join(profile,'extensions.json'),'utf8')); - assert.ok(state.addons.find(addon => addon.id === 'jid1-KtlZuoiikVfFew@jetpack')?.active); + assert.ok(libreJSAddon(await readFile(join(profile,'extensions.json'),'utf8')).active); } console.log(`PASS: ${libre ? 'Firefox/LibreJS' : 'Chromium'} streamed percentage/bar/MiB, unknown length, exact byte recovery, slow continuous transfer, idle timeout, HTTP failure, and connection phase.`); } finally { diff --git a/crates/chat-server/web/app.js b/crates/chat-server/web/app.js deleted file mode 100644 index 4b0da63..0000000 --- a/crates/chat-server/web/app.js +++ /dev/null @@ -1,421 +0,0 @@ -// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> -// -// This program is free software: you can redistribute it and/or modify -// it under the terms of the GNU Affero General Public License as -// published by the Free Software Foundation, either version 3 of the -// License, or (at your option) any later version. -// -// This program is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU Affero General Public License for more details. -// -// You should have received a copy of the GNU Affero General Public License -// along with this program. If not, see <https://www.gnu.org/licenses/>. - -// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0 - -const element = id => document.getElementById(id); -const show = (id, visible = true) => { element(id).hidden = !visible; }; -const status = message => { element('status').textContent = message; }; -let config; -let wasm; -let credentials; -let session; -let selected; -let before = 0; -let pendingFile; -let setupToken; -let pendingSend; -let generation = 0; -let busy = false; -const workers = new Map(); -const blobs = new Set(); - -async function api(request) { - const current = generation; - const response = await fetch('/api', { - method: 'POST', credentials: 'omit', cache: 'no-store', redirect: 'error', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ ...request, token: session?.token }), - signal: AbortSignal.timeout(20000), - }); - const result = await response.json(); - if (current !== generation) throw new Error('Session locked'); - if (!response.ok || result.error) throw new Error(result.error || 'Server request failed'); - return result; -} - -async function cryptoOperation(request) { - const current = generation; - const bytes = await wasm; - if (current !== generation) throw new Error('Session locked'); - return new Promise((resolve, reject) => { - const worker = new Worker('/worker.js'); - - const stop = () => { worker.terminate(); workers.delete(worker); clearTimeout(timer); }; - const timer = setTimeout(() => { stop(); reject(new Error('Cryptographic operation timed out')); }, 90000); - workers.set(worker, () => { stop(); reject(new Error('Session locked')); }); - worker.onerror = () => { stop(); reject(new Error('Cryptographic worker failed')); }; - worker.onmessage = event => { - stop(); - if (current !== generation) { reject(new Error('Session locked')); return; } - if (event.data.error) reject(new Error(event.data.error)); else resolve(event.data.result); - }; - worker.postMessage({ bytes, request }); - }); -} - -function protectRequest(op, fields) { - if (!credentials) throw new Error('Unlock your identity file first'); - return { op, ...credentials, origin: location.origin, ...fields }; -} - -function clearState() { - generation += 1; - busy = false; - for (const button of document.querySelectorAll('button')) button.disabled = false; - for (const cancel of workers.values()) cancel(); - workers.clear(); - for (const url of blobs) URL.revokeObjectURL(url); - blobs.clear(); - credentials = undefined; - session = undefined; - selected = undefined; - pendingFile = undefined; - pendingSend = undefined; - setupToken = undefined; - before = 0; - element('history-count').max = '0'; - element('history-range').textContent = 'Latest messages (0-0)'; - for (const input of document.querySelectorAll('input,textarea')) { - if (input.id === 'history-count') input.value = '0'; else input.value = ''; - } - for (const id of ['messages', 'conversations', 'who', 'fingerprint', 'counts', 'thread-name', 'conversation-fingerprint']) element(id).replaceChildren(); - for (const id of ['create', 'unlock', 'chat', 'thread', 'inbox', 'older', 'retry', 'owner-access']) show(id, false); - show('entry', Boolean(config?.owner)); - show('owner-entry'); - status('Locked. Select your file and enter its password to return.'); -} - -function action(id, callback) { - element(id).addEventListener(id.endsWith('-form') ? 'submit' : 'click', async event => { - event.preventDefault(); - if (busy) return; - busy = true; - status('Working locally...'); - const current = generation; - for (const button of document.querySelectorAll('button:not(#lock)')) button.disabled = true; - try { await callback(); } - catch (error) { if (generation === current) status(error.message); } - finally { - if (generation === current) { - busy = false; - for (const button of document.querySelectorAll('button')) button.disabled = false; - } - } - }); -} - -function download(file) { - const url = URL.createObjectURL(new Blob([file], { type: 'application/octet-stream' })); - blobs.add(url); - const link = document.createElement('a'); - link.href = url; - link.download = 'stack-chat-identity.chat'; - link.click(); - setTimeout(() => { URL.revokeObjectURL(url); blobs.delete(url); }, 30000); -} - -async function createIdentity() { - const password = element('new-password').value; - if (password !== element('confirm-password').value) throw new Error('Passwords do not match'); - if (!config.owner && element('setup-label').hidden) throw new Error('Owner setup is required first'); - setupToken = !config.owner ? element('setup-token').value : undefined; - status('Generating your purpose-specific identity and protecting its file...'); - const result = await cryptoOperation({ op: 'create', origin: location.origin, name: element('name').value, password, owner: config.owner || '' }); - pendingFile = result.file; - download(result.file); - element('create-form').reset(); - show('create', false); - show('unlock'); - element('reopen-note').textContent = 'Your file was downloaded. Reopen that exact saved file and enter its password before any message can be sent. Keep a safe backup.'; - status('Reopen your downloaded identity file to verify recovery.'); -} - -async function unlockIdentity() { - const file = element('file').files[0]; - if (!file || file.size > 262144) throw new Error('Choose an identity file no larger than 256 KiB'); - const fileText = await file.text(); - if (pendingFile && fileText !== pendingFile) throw new Error('Reopen the exact identity file you just downloaded'); - const candidate = { file: fileText, password: element('password').value }; - element('unlock-form').reset(); - status('Unlocking locally and verifying your identity...'); - const identity = await cryptoOperation({ op: 'open', ...candidate, origin: location.origin }); - if (config.owner && identity.owner !== config.owner) throw new Error('Pinned owner key differs from this server. Stop and verify the change with Doan.'); - const challenge = await api({ op: 'challenge', public: identity.public, setup_token: setupToken }); - const proof = await cryptoOperation({ op: 'proof', ...candidate, origin: location.origin, challenge: challenge.challenge }); - const authenticated = await api({ op: 'authenticate', id: challenge.id, signature: proof.signature }); - if (authenticated.id !== identity.fingerprint || typeof authenticated.owner !== 'boolean') throw new Error('Authenticated identity mismatch'); - credentials = candidate; - session = { ...identity, ...authenticated }; - pendingFile = undefined; - setupToken = undefined; - config = await api({ op: 'config' }); - show('entry', false); - show('owner-entry', false); - show('owner-access', false); - show('unlock', false); - show('chat'); - element('who').textContent = `${identity.name} [${session.owner === true ? 'OWNER' : 'VISITOR'}]`; - element('fingerprint').textContent = `Identity: ${identity.fingerprint}`; - if (authenticated.owner) { - session.owner = true; - show('inbox'); - await inbox(); - } else { - session.owner = false; - const profile = await cryptoOperation(protectRequest('encrypt', { recipient: config.owner, payload: JSON.stringify({ v: 1, kind: 'profile', origin: location.origin, conversation: session.id, sender: session.id, name: identity.name }) })); - await api({ op: 'profile', conversation: session.id, ciphertext: profile.ciphertext }); - selected = { id: session.id, public: identity.public }; - element('conversation-fingerprint').textContent = `Conversation: ${session.id}`; - show('thread'); - element('thread-name').textContent = 'You <-> Doan'; - await loadHistory(0); - } - status('Unlocked in memory only. No history loaded automatically. Lock or leave to forget this session.'); -} - -function checkedPayload(payload, kind, conversation, sender) { - const value = JSON.parse(payload); - if (value.v !== 1 || value.kind !== kind || value.origin !== location.origin || value.conversation !== conversation || value.sender !== sender) throw new Error('Signed message binding mismatch'); - return value; -} - -async function inbox() { - const result = await api({ op: 'inbox' }); - element('conversations').replaceChildren(); - for (const conversation of result.conversations) { - const button = document.createElement('button'); - button.textContent = `${conversation.id.slice(0, 12)} / ${conversation.total} messages`; - button.addEventListener('click', async () => { - if (busy) return; - if (pendingSend) { status('Retry the pending message, or lock before switching conversations.'); return; } - busy = true; - const current = generation; - status('Opening conversation...'); - try { - selected = conversation; - element('conversation-fingerprint').textContent = `Conversation: ${conversation.id}`; - element('thread-name').textContent = `Doan <-> ${conversation.id.slice(0, 12)}`; - pendingSend = undefined; - element('text').value = ''; - show('retry', false); - element('messages').replaceChildren(); - show('thread'); - let name = conversation.id.slice(0, 12); - if (conversation.profile) { - const result = await cryptoOperation(protectRequest('decrypt', { sender: conversation.public, ciphertext: conversation.profile })); - if (result.signer !== conversation.id) throw new Error('Profile signer fingerprint mismatch'); - const profile = checkedPayload(result.payload, 'profile', conversation.id, conversation.id); - if (typeof profile.name !== 'string' || profile.name.length > 80) throw new Error('Invalid encrypted profile'); - name = profile.name; - } - element('thread-name').textContent = `Doan <-> ${name}`; - await loadHistory(0); - status('Conversation opened. Choose how many messages to load.'); - } catch (error) { status(error.message); } - finally { if (generation === current) busy = false; } - }); - element('conversations').append(button); - } -} - -function counters(conversation) { - if (!Number.isSafeInteger(conversation.total) || conversation.total < 0 || conversation.total > 10000) throw new Error('Invalid conversation count'); - element('history-count').max = String(conversation.total); - element('history-range').textContent = `Latest messages (0-${conversation.total})`; - const sent = session.owner ? conversation.owner_sent : conversation.visitor_sent; - const received = session.owner ? conversation.visitor_sent : conversation.owner_sent; - element('counts').textContent = `Total: ${conversation.total} | Sent: ${sent} | Received: ${received}`; -} - -async function renderHistoryBatch(messages) { - const requests = messages.map(message => ({ sender: message.sender === selected.id ? selected.public : config.owner, ciphertext: message.ciphertext })); - const decrypted = await cryptoOperation(protectRequest('decrypt_batch', { messages: requests })); - for (let index = 0; index < messages.length; index += 1) { - const message = messages[index]; - const item = document.createElement('li'); - const label = document.createElement('small'); - label.textContent = `#${message.seq} / ${message.sender === session.id ? 'YOU' : 'THEM'}`; - const text = document.createElement('p'); - try { - const entry = decrypted.messages[index]; - if (entry.signer !== message.sender) throw new Error('Sender fingerprint mismatch'); - if (entry.error) throw new Error('Invalid ciphertext or signature'); - const payload = checkedPayload(entry.payload, 'message', selected.id, message.sender); - if (payload.id !== message.id || typeof payload.text !== 'string' || new TextEncoder().encode(payload.text).length > 8192) throw new Error('Message binding mismatch'); - text.textContent = payload.text; - } catch { text.textContent = '[Message rejected: invalid ciphertext, signature, or conversation binding.]'; } - item.append(label, text); - element('messages').prepend(item); - } -} - -async function refreshCounts() { - const conversation = selected.id; - const result = await api({ op: 'history', conversation, count: 0, before: 0 }); - if (selected?.id === conversation) counters(result.conversation); - return result.conversation; -} - -async function loadHistory(count, cursor = 0) { - if (!selected) throw new Error('Choose a conversation first'); - const conversation = await refreshCounts(); - if (!Number.isSafeInteger(count) || count < 0 || count > conversation.total) throw new Error(`Choose 0 to ${conversation.total} messages`); - if (!cursor) { element('messages').replaceChildren(); before = 0; } - if (count === 0) { - element('history-count').value = '0'; - show('older', false); - status('No message history loaded.'); - return; - } - let remaining = count; - let next = cursor; - let exhausted = false; - while (remaining > 0) { - const size = Math.min(50, remaining); - const result = await api({ op: 'history', conversation: selected.id, count: size, before: next }); - counters(result.conversation); - if (!Array.isArray(result.messages) || result.messages.length > size) throw new Error('Invalid history response'); - if (!result.messages.length) { exhausted = true; break; } - const sequence = Math.min(...result.messages.map(message => message.seq)); - if (!Number.isSafeInteger(sequence) || sequence <= 0 || (next > 0 && sequence >= next)) throw new Error('Invalid history cursor'); - status(`Decrypting and verifying selected messages locally (${count - remaining + result.messages.length}/${count})...`); - await renderHistoryBatch(result.messages); - remaining -= result.messages.length; - next = sequence; - before = next; - if (result.messages.length < size) { exhausted = true; break; } - } - show('older', !exhausted && element('messages').children.length < Number(element('history-count').max)); - status('Selected history decrypted and verified locally.'); -} - -async function submitPending() { - if (!pendingSend) throw new Error('No pending message'); - const result = await api(pendingSend); - counters(result.conversation); - pendingSend = undefined; - element('text').value = ''; - show('retry', false); - status('Encrypted message stored. Load history to read messages.'); -} - -async function send() { - if (!selected) throw new Error('Choose a conversation first'); - if (pendingSend) throw new Error('Retry or lock before composing another message'); - const text = element('text').value; - if (!text.trim() || new TextEncoder().encode(text).length > 8192) throw new Error('Enter 1 to 8192 UTF-8 bytes of text'); - const id = Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join(''); - const recipient = session.owner ? selected.public : config.owner; - status('Signing and encrypting for both participants locally...'); - const result = await cryptoOperation(protectRequest('encrypt', { recipient, payload: JSON.stringify({ v: 1, kind: 'message', origin: location.origin, conversation: selected.id, sender: session.id, id, text }) })); - pendingSend = { op: 'send', conversation: selected.id, id, ciphertext: result.ciphertext }; - show('retry'); - await submitPending(); -} - -function ownerSetup() { - show('entry', false); - show('owner-entry', false); - show('unlock', false); - show('create', !config.owner); - show('owner-access', Boolean(config.owner)); - show('setup-label', !config.owner); - element('create-title').textContent = 'Create the owner identity (owner only)'; - status(''); -} - -action('create-choice', async () => { show('entry', false); show('owner-entry', false); show('setup-label', false); element('create-title').textContent = 'Create a new chat'; show('create'); status(''); }); -action('open-choice', async () => { show('entry', false); show('owner-entry', false); show('unlock'); status(''); }); -action('owner-choice', async () => { window.history.replaceState(null, '', '#setup'); ownerSetup(); }); -action('owner-open', async () => { show('owner-access', false); show('unlock'); status(''); }); -action('create-form', createIdentity); -action('unlock-form', unlockIdentity); -element('history-count').addEventListener('focus', () => { - const current = generation; - if (session && selected && !busy) refreshCounts().catch(error => { if (current === generation) status(error.message); }); -}); -action('history-form', () => loadHistory(Number(element('history-count').value))); -action('send-form', send); -action('retry', submitPending); -action('refresh-inbox', inbox); -action('older', () => loadHistory(Number(element('history-count').value), before)); -element('lock').addEventListener('click', () => { if (session) api({ op: 'lock' }).catch(() => {}); clearState(); }); -window.addEventListener('pagehide', clearState); -window.addEventListener('pageshow', event => { if (event.persisted) clearState(); }); - -async function downloadCrypto() { - const controller = new AbortController(); - let timer; - let reader; - const refreshTimeout = () => { - clearTimeout(timer); - timer = setTimeout(() => controller.abort(), 45000); - }; - try { - refreshTimeout(); - const response = await fetch('/crypto.wasm', { cache: 'no-store', credentials: 'omit', signal: controller.signal }); - if (!response.ok) throw new Error(`Cryptographic module download failed (HTTP ${response.status}). Reload to try again.`); - const length = response.headers.get('content-encoding') ? 0 : Number(response.headers.get('content-length')); - const total = Number.isSafeInteger(length) && length > 0 ? length : 0; - const chunks = []; - let received = 0; - const progress = () => { - const loaded = (received / 1048576).toFixed(1); - if (total) { - const percent = Math.min(100, Math.floor(received * 100 / total)); - const filled = Math.floor(percent / 5); - status(`Downloading cryptographic module... [${'#'.repeat(filled)}${'-'.repeat(20 - filled)}] ${percent}% (${loaded} / ${(total / 1048576).toFixed(1)} MiB)`); - } else status(`Downloading cryptographic module... ${loaded} MiB received`); - }; - progress(); - reader = response.body.getReader(); - for (;;) { - const { done, value } = await reader.read(); - if (done) break; - refreshTimeout(); - chunks.push(value); - received += value.byteLength; - progress(); - } - if (!received) throw new Error('The cryptographic module download was empty. Reload to try again.'); - const bytes = new Uint8Array(received); - let offset = 0; - for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } - return bytes.buffer; - } catch (error) { - if (controller.signal.aborted) throw new Error('Cryptographic module download stalled for 45 seconds. Check your connection and reload to try again.'); - throw error; - } finally { - clearTimeout(timer); - reader?.releaseLock(); - } -} - -async function start() { - wasm = downloadCrypto(); - await wasm; - status('Cryptographic module downloaded. Connecting to chat...'); - config = await api({ op: 'config' }); - if (config.origin !== location.origin) throw new Error('Server origin mismatch'); - show('owner-entry'); - show('entry', Boolean(config.owner)); - status(''); - if (location.hash === '#setup') ownerSetup(); -} - -start().catch(error => status(error.message)); - -// @license-end diff --git a/crates/chat-server/web/app.ts b/crates/chat-server/web/app.ts new file mode 100644 index 0000000..79a827e --- /dev/null +++ b/crates/chat-server/web/app.ts @@ -0,0 +1,560 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +// @license magnet:?xt=urn:btih:0b31508aeb0634b347b8270c7bee4d411b5d4109&dn=agpl-3.0.txt AGPL-3.0 + +function element(id: string): HTMLElement { + const value = document.getElementById(id); + if (!value) throw new Error(`Missing interface element: ${id}`); + return value; +} + +function input(id: string): HTMLInputElement { + const value = element(id); + if (!(value instanceof HTMLInputElement)) throw new Error(`Expected input: ${id}`); + return value; +} + +function form(id: string): HTMLFormElement { + const value = element(id); + if (!(value instanceof HTMLFormElement)) throw new Error(`Expected form: ${id}`); + return value; +} + +function messageInput(): HTMLTextAreaElement { + const value = element('text'); + if (!(value instanceof HTMLTextAreaElement)) throw new Error('Missing message input'); + return value; +} + +const show = (id: string, visible = true): void => { element(id).hidden = !visible; }; +const setStatus = (message: string): void => { element('status').textContent = message; }; +const errorMessage = (error: unknown): string => error instanceof Error ? error.message : 'Unexpected operation failure'; +let config: StackChat.Configuration | undefined; +let wasm: Promise<ArrayBuffer> | undefined; +let credentials: StackChat.Credentials | undefined; +let session: StackChat.Session | undefined; +let selected: StackChat.Conversation | undefined; +let before = 0; +let pendingFile: string | undefined; +let setupToken: string | undefined; +let pendingSend: StackChat.SendRequest | undefined; +let generation = 0; +let busy = false; +const workers = new Map<Worker, () => void>(); +const blobs = new Set<string>(); + +function configuration(): StackChat.Configuration { + if (!config) throw new Error('Chat configuration is not loaded'); + return config; +} + +function ownerKey(): string { + const owner = configuration().owner; + if (!owner) throw new Error('Owner setup is required first'); + return owner; +} + +function activeSession(): StackChat.Session { + if (!session) throw new Error('Unlock your identity file first'); + return session; +} + +function conversation(): StackChat.Conversation { + if (!selected) throw new Error('Choose a conversation first'); + return selected; +} + +function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function record(value: unknown): Record<string, unknown> { + if (!isRecord(value)) throw new Error('Invalid response object'); + return value; +} + +function stringField(value: Record<string, unknown>, key: string): string { + const field = value[key]; + if (typeof field !== 'string') throw new Error(`Invalid response field: ${key}`); + return field; +} + +function countField(value: Record<string, unknown>, key: string): number { + const field = value[key]; + if (typeof field !== 'number' || !Number.isSafeInteger(field) || field < 0) throw new Error(`Invalid response count: ${key}`); + return field; +} + +function booleanField(value: Record<string, unknown>, key: string): boolean { + const field = value[key]; + if (typeof field !== 'boolean') throw new Error(`Invalid response flag: ${key}`); + return field; +} + +function arrayField(value: Record<string, unknown>, key: string): unknown[] { + const field: unknown = value[key]; + if (!Array.isArray(field)) throw new Error(`Invalid response list: ${key}`); + return field; +} + +function decodeConversation(value: unknown): StackChat.Conversation { + const item = record(value); + const total = countField(item, 'total'); + const visitor = countField(item, 'visitor_sent'); + const owner = countField(item, 'owner_sent'); + if (total > 10000 || visitor + owner !== total) throw new Error('Invalid conversation count'); + const profile = item['profile']; + if (profile !== undefined && profile !== null && typeof profile !== 'string') throw new Error('Invalid conversation profile'); + return { id: stringField(item, 'id'), public: stringField(item, 'public'), total, visitor_sent: visitor, owner_sent: owner, ...(profile === undefined ? {} : { profile }) }; +} + +function decodeMessage(value: unknown): StackChat.Message { + const item = record(value); + return { seq: countField(item, 'seq'), id: stringField(item, 'id'), sender: stringField(item, 'sender'), ciphertext: stringField(item, 'ciphertext') }; +} + +function decodeDecryption(value: unknown): StackChat.Decryption { + const item = record(value); + return { signer: stringField(item, 'signer'), payload: stringField(item, 'payload') }; +} + +const apiReaders: { [K in keyof StackChat.Api]: (value: unknown) => StackChat.Api[K]['response'] } = { + config(value) { + const item = record(value); + const owner = item['owner']; + if (owner !== null && typeof owner !== 'string') throw new Error('Invalid owner configuration'); + return { owner, origin: stringField(item, 'origin'), protocol: stringField(item, 'protocol') }; + }, + challenge(value) { const item = record(value); return { id: stringField(item, 'id'), challenge: stringField(item, 'challenge') }; }, + authenticate(value) { const item = record(value); return { token: stringField(item, 'token'), id: stringField(item, 'id'), owner: booleanField(item, 'owner'), expires_seconds: countField(item, 'expires_seconds') }; }, + profile(value) { return { stored: booleanField(record(value), 'stored') }; }, + inbox(value) { return { conversations: arrayField(record(value), 'conversations').map(decodeConversation) }; }, + history(value) { const item = record(value); return { conversation: decodeConversation(item['conversation']), messages: arrayField(item, 'messages').map(decodeMessage) }; }, + send(value) { const item = record(value); return { seq: countField(item, 'seq'), conversation: decodeConversation(item['conversation']) }; }, + lock(value) { return { locked: booleanField(record(value), 'locked') }; }, +}; + +const cryptoReaders: { [K in keyof StackChat.Crypto]: (value: unknown) => StackChat.Crypto[K]['response'] } = { + create(value) { return { file: stringField(record(value), 'file') }; }, + open(value) { const item = record(value); return { public: stringField(item, 'public'), fingerprint: stringField(item, 'fingerprint'), owner: stringField(item, 'owner'), name: stringField(item, 'name') }; }, + proof(value) { return { signature: stringField(record(value), 'signature') }; }, + encrypt(value) { return { ciphertext: stringField(record(value), 'ciphertext') }; }, + decrypt: decodeDecryption, + decrypt_batch(value) { + return { messages: arrayField(record(value), 'messages').map(entry => { + const item = record(entry); + return 'error' in item ? { error: stringField(item, 'error') } : decodeDecryption(item); + }) }; + }, +}; + +async function api<K extends keyof StackChat.Api>(request: StackChat.Api[K]['request'] & { op: K }): Promise<StackChat.Api[K]['response']> { + const current = generation; + const response = await fetch('/api', { + method: 'POST', credentials: 'omit', cache: 'no-store', redirect: 'error', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ...request, token: session?.token }), + signal: AbortSignal.timeout(20000), + }); + const result = record(await response.json()); + if (current !== generation) throw new Error('Session locked'); + if (!response.ok || result['error']) throw new Error(typeof result['error'] === 'string' ? result['error'] : 'Server request failed'); + return apiReaders[request.op](result); +} + +async function cryptoOperation<K extends keyof StackChat.Crypto>(request: StackChat.Crypto[K]['request'] & { op: K }): Promise<StackChat.Crypto[K]['response']> { + const current = generation; + if (!wasm) throw new Error('Cryptographic module is not loaded'); + const bytes = await wasm; + if (current !== generation) throw new Error('Session locked'); + return new Promise<StackChat.Crypto[K]['response']>((resolve, reject) => { + const worker = new Worker('/worker.js'); + + const stop = () => { worker.terminate(); workers.delete(worker); clearTimeout(timer); }; + const timer = setTimeout(() => { stop(); reject(new Error('Cryptographic operation timed out')); }, 90000); + workers.set(worker, () => { stop(); reject(new Error('Session locked')); }); + worker.onerror = () => { stop(); reject(new Error('Cryptographic worker failed')); }; + worker.onmessage = (event: MessageEvent<unknown>) => { + stop(); + if (current !== generation) { reject(new Error('Session locked')); return; } + try { + const message = record(event.data); + if ('error' in message) throw new Error(stringField(message, 'error')); + resolve(cryptoReaders[request.op](message['result'])); + } catch (error) { reject(error); } + }; + worker.postMessage({ bytes, request }); + }); +} + +function protectRequest<K extends 'encrypt' | 'decrypt' | 'decrypt_batch'>(op: K, fields: Omit<StackChat.Crypto[K]['request'], keyof StackChat.Protected | 'op'>): StackChat.Protected & { op: K } & typeof fields { + if (!credentials) throw new Error('Unlock your identity file first'); + return { op, ...credentials, origin: location.origin, ...fields }; +} + +function clearState() { + generation += 1; + busy = false; + for (const button of document.querySelectorAll('button')) button.disabled = false; + for (const cancel of workers.values()) cancel(); + workers.clear(); + for (const url of blobs) URL.revokeObjectURL(url); + blobs.clear(); + credentials = undefined; + session = undefined; + selected = undefined; + pendingFile = undefined; + pendingSend = undefined; + setupToken = undefined; + before = 0; + input('history-count').max = '0'; + element('history-range').textContent = 'Latest messages (0-0)'; + for (const input of document.querySelectorAll<HTMLInputElement | HTMLTextAreaElement>('input,textarea')) { + if (input.id === 'history-count') input.value = '0'; else input.value = ''; + } + for (const id of ['messages', 'conversations', 'who', 'fingerprint', 'counts', 'thread-name', 'conversation-fingerprint']) element(id).replaceChildren(); + for (const id of ['create', 'unlock', 'chat', 'thread', 'inbox', 'older', 'retry', 'owner-access']) show(id, false); + show('entry', Boolean(config?.owner)); + show('owner-entry'); + setStatus('Locked. Select your file and enter its password to return.'); +} + +function action(id: string, callback: () => Promise<void>): void { + element(id).addEventListener(id.endsWith('-form') ? 'submit' : 'click', async event => { + event.preventDefault(); + if (busy) return; + busy = true; + setStatus('Working locally...'); + const current = generation; + for (const button of document.querySelectorAll<HTMLButtonElement>('button:not(#lock)')) button.disabled = true; + try { await callback(); } + catch (error) { if (generation === current) setStatus(errorMessage(error)); } + finally { + if (generation === current) { + busy = false; + for (const button of document.querySelectorAll('button')) button.disabled = false; + } + } + }); +} + +function download(file: string): void { + const url = URL.createObjectURL(new Blob([file], { type: 'application/octet-stream' })); + blobs.add(url); + const link = document.createElement('a'); + link.href = url; + link.download = 'stack-chat-identity.chat'; + link.click(); + setTimeout(() => { URL.revokeObjectURL(url); blobs.delete(url); }, 30000); +} + +async function createIdentity() { + const password = input('new-password').value; + if (password !== input('confirm-password').value) throw new Error('Passwords do not match'); + if (!configuration().owner && element('setup-label').hidden) throw new Error('Owner setup is required first'); + setupToken = !configuration().owner ? input('setup-token').value : undefined; + setStatus('Generating your purpose-specific identity and protecting its file...'); + const result = await cryptoOperation({ op: 'create', origin: location.origin, name: input('name').value, password, owner: configuration().owner || '' }); + pendingFile = result.file; + download(result.file); + form('create-form').reset(); + show('create', false); + show('unlock'); + element('reopen-note').textContent = 'Your file was downloaded. Reopen that exact saved file and enter its password before any message can be sent. Keep a safe backup.'; + setStatus('Reopen your downloaded identity file to verify recovery.'); +} + +async function unlockIdentity() { + const file = input('file').files?.[0]; + if (!file || file.size > 262144) throw new Error('Choose an identity file no larger than 256 KiB'); + const fileText = await file.text(); + if (pendingFile && fileText !== pendingFile) throw new Error('Reopen the exact identity file you just downloaded'); + const candidate = { file: fileText, password: input('password').value }; + form('unlock-form').reset(); + setStatus('Unlocking locally and verifying your identity...'); + const identity = await cryptoOperation({ op: 'open', ...candidate, origin: location.origin }); + if (configuration().owner && identity.owner !== configuration().owner) throw new Error('Pinned owner key differs from this server. Stop and verify the change with Doan.'); + const challenge = await api({ op: 'challenge', public: identity.public, setup_token: setupToken }); + const proof = await cryptoOperation({ op: 'proof', ...candidate, origin: location.origin, challenge: challenge.challenge }); + const authenticated = await api({ op: 'authenticate', id: challenge.id, signature: proof.signature }); + if (authenticated.id !== identity.fingerprint || typeof authenticated.owner !== 'boolean') throw new Error('Authenticated identity mismatch'); + credentials = candidate; + session = { ...identity, ...authenticated }; + pendingFile = undefined; + setupToken = undefined; + config = await api({ op: 'config' }); + show('entry', false); + show('owner-entry', false); + show('owner-access', false); + show('unlock', false); + show('chat'); + element('who').textContent = `${identity.name} [${activeSession().owner === true ? 'OWNER' : 'VISITOR'}]`; + element('fingerprint').textContent = `Identity: ${identity.fingerprint}`; + if (authenticated.owner) { + activeSession().owner = true; + show('inbox'); + await inbox(); + } else { + activeSession().owner = false; + const profile = await cryptoOperation(protectRequest('encrypt', { recipient: ownerKey(), payload: JSON.stringify({ v: 1, kind: 'profile', origin: location.origin, conversation: activeSession().id, sender: activeSession().id, name: identity.name }) })); + await api({ op: 'profile', conversation: activeSession().id, ciphertext: profile.ciphertext }); + selected = { id: activeSession().id, public: identity.public, total: 0, visitor_sent: 0, owner_sent: 0 }; + element('conversation-fingerprint').textContent = `Conversation: ${activeSession().id}`; + show('thread'); + element('thread-name').textContent = 'You <-> Doan'; + await loadHistory(0); + } + setStatus('Unlocked in memory only. No history loaded automatically. Lock or leave to forget this session.'); +} + +function checkedPayload(payload: string, kind: 'profile', conversation: string, sender: string): { name: string }; +function checkedPayload(payload: string, kind: 'message', conversation: string, sender: string): { id: string; text: string }; +function checkedPayload(payload: string, kind: 'profile' | 'message', conversation: string, sender: string): { name: string } | { id: string; text: string } { + const value = record(JSON.parse(payload)); + if (value['v'] !== 1 || value['kind'] !== kind || value['origin'] !== location.origin || value['conversation'] !== conversation || value['sender'] !== sender) throw new Error('Signed message binding mismatch'); + if (kind === 'profile') return { name: stringField(value, 'name') }; + return { id: stringField(value, 'id'), text: stringField(value, 'text') }; +} + +async function inbox() { + const result = await api({ op: 'inbox' }); + element('conversations').replaceChildren(); + for (const conversation of result.conversations) { + const button = document.createElement('button'); + button.textContent = `${conversation.id.slice(0, 12)} / ${conversation.total} messages`; + button.addEventListener('click', async () => { + if (busy) return; + if (pendingSend) { setStatus('Retry the pending message, or lock before switching conversations.'); return; } + busy = true; + const current = generation; + setStatus('Opening conversation...'); + try { + selected = conversation; + element('conversation-fingerprint').textContent = `Conversation: ${conversation.id}`; + element('thread-name').textContent = `Doan <-> ${conversation.id.slice(0, 12)}`; + pendingSend = undefined; + messageInput().value = ''; + show('retry', false); + element('messages').replaceChildren(); + show('thread'); + let name = conversation.id.slice(0, 12); + if (conversation.profile) { + const result = await cryptoOperation(protectRequest('decrypt', { sender: conversation.public, ciphertext: conversation.profile })); + if (result.signer !== conversation.id) throw new Error('Profile signer fingerprint mismatch'); + const profile = checkedPayload(result.payload, 'profile', conversation.id, conversation.id); + if (typeof profile.name !== 'string' || profile.name.length > 80) throw new Error('Invalid encrypted profile'); + name = profile.name; + } + element('thread-name').textContent = `Doan <-> ${name}`; + await loadHistory(0); + setStatus('Conversation opened. Choose how many messages to load.'); + } catch (error) { setStatus(errorMessage(error)); } + finally { if (generation === current) busy = false; } + }); + element('conversations').append(button); + } +} + +function counters(conversation: StackChat.Conversation): void { + if (!Number.isSafeInteger(conversation.total) || conversation.total < 0 || conversation.total > 10000) throw new Error('Invalid conversation count'); + input('history-count').max = String(conversation.total); + element('history-range').textContent = `Latest messages (0-${conversation.total})`; + const sent = activeSession().owner ? conversation.owner_sent : conversation.visitor_sent; + const received = activeSession().owner ? conversation.visitor_sent : conversation.owner_sent; + element('counts').textContent = `Total: ${conversation.total} | Sent: ${sent} | Received: ${received}`; +} + +async function renderHistoryBatch(messages: StackChat.Message[]): Promise<void> { + const requests = messages.map(message => ({ sender: message.sender === conversation().id ? conversation().public : ownerKey(), ciphertext: message.ciphertext })); + const decrypted = await cryptoOperation(protectRequest('decrypt_batch', { messages: requests })); + for (let index = 0; index < messages.length; index += 1) { + const message = messages[index]; + if (!message) throw new Error('Missing history message'); + const item = document.createElement('li'); + const label = document.createElement('small'); + label.textContent = `#${message.seq} / ${message.sender === activeSession().id ? 'YOU' : 'THEM'}`; + const text = document.createElement('p'); + try { + const entry = decrypted.messages[index]; + if (!entry || 'error' in entry) throw new Error('Invalid ciphertext or signature'); + if (entry.signer !== message.sender) throw new Error('Sender fingerprint mismatch'); + const payload = checkedPayload(entry.payload, 'message', conversation().id, message.sender); + if (payload.id !== message.id || typeof payload.text !== 'string' || new TextEncoder().encode(payload.text).length > 8192) throw new Error('Message binding mismatch'); + text.textContent = payload.text; + } catch { text.textContent = '[Message rejected: invalid ciphertext, signature, or conversation binding.]'; } + item.append(label, text); + element('messages').prepend(item); + } +} + +async function refreshCounts() { + const conversationId = conversation().id; + const result = await api({ op: 'history', conversation: conversationId, count: 0, before: 0 }); + if (selected?.id === conversationId) counters(result.conversation); + return result.conversation; +} + +async function loadHistory(count: number, cursor = 0): Promise<void> { + if (!selected) throw new Error('Choose a conversation first'); + const currentConversation = await refreshCounts(); + if (!Number.isSafeInteger(count) || count < 0 || count > currentConversation.total) throw new Error(`Choose 0 to ${currentConversation.total} messages`); + if (!cursor) { element('messages').replaceChildren(); before = 0; } + if (count === 0) { + input('history-count').value = '0'; + show('older', false); + setStatus('No message history loaded.'); + return; + } + let remaining = count; + let next = cursor; + let exhausted = false; + while (remaining > 0) { + const size = Math.min(50, remaining); + const result = await api({ op: 'history', conversation: conversation().id, count: size, before: next }); + counters(result.conversation); + if (!Array.isArray(result.messages) || result.messages.length > size) throw new Error('Invalid history response'); + if (!result.messages.length) { exhausted = true; break; } + const sequence = Math.min(...result.messages.map(message => message.seq)); + if (!Number.isSafeInteger(sequence) || sequence <= 0 || (next > 0 && sequence >= next)) throw new Error('Invalid history cursor'); + setStatus(`Decrypting and verifying selected messages locally (${count - remaining + result.messages.length}/${count})...`); + await renderHistoryBatch(result.messages); + remaining -= result.messages.length; + next = sequence; + before = next; + if (result.messages.length < size) { exhausted = true; break; } + } + show('older', !exhausted && element('messages').children.length < Number(input('history-count').max)); + setStatus('Selected history decrypted and verified locally.'); +} + +async function submitPending() { + if (!pendingSend) throw new Error('No pending message'); + const result = await api(pendingSend); + counters(result.conversation); + pendingSend = undefined; + messageInput().value = ''; + show('retry', false); + setStatus('Encrypted message stored. Load history to read messages.'); +} + +async function send() { + if (!selected) throw new Error('Choose a conversation first'); + if (pendingSend) throw new Error('Retry or lock before composing another message'); + const text = messageInput().value; + if (!text.trim() || new TextEncoder().encode(text).length > 8192) throw new Error('Enter 1 to 8192 UTF-8 bytes of text'); + const id = Array.from(crypto.getRandomValues(new Uint8Array(32)), byte => byte.toString(16).padStart(2, '0')).join(''); + const recipient = activeSession().owner ? conversation().public : ownerKey(); + setStatus('Signing and encrypting for both participants locally...'); + const result = await cryptoOperation(protectRequest('encrypt', { recipient, payload: JSON.stringify({ v: 1, kind: 'message', origin: location.origin, conversation: conversation().id, sender: activeSession().id, id, text }) })); + pendingSend = { op: 'send', conversation: conversation().id, id, ciphertext: result.ciphertext }; + show('retry'); + await submitPending(); +} + +function ownerSetup() { + show('entry', false); + show('owner-entry', false); + show('unlock', false); + show('create', !configuration().owner); + show('owner-access', Boolean(configuration().owner)); + show('setup-label', !configuration().owner); + element('create-title').textContent = 'Create the owner identity (owner only)'; + setStatus(''); +} + +action('create-choice', async () => { show('entry', false); show('owner-entry', false); show('setup-label', false); element('create-title').textContent = 'Create a new chat'; show('create'); setStatus(''); }); +action('open-choice', async () => { show('entry', false); show('owner-entry', false); show('unlock'); setStatus(''); }); +action('owner-choice', async () => { window.history.replaceState(null, '', '#setup'); ownerSetup(); }); +action('owner-open', async () => { show('owner-access', false); show('unlock'); setStatus(''); }); +action('create-form', createIdentity); +action('unlock-form', unlockIdentity); +element('history-count').addEventListener('focus', () => { + const current = generation; + if (session && selected && !busy) refreshCounts().catch(error => { if (current === generation) setStatus(errorMessage(error)); }); +}); +action('history-form', () => loadHistory(Number(input('history-count').value))); +action('send-form', send); +action('retry', submitPending); +action('refresh-inbox', inbox); +action('older', () => loadHistory(Number(input('history-count').value), before)); +element('lock').addEventListener('click', () => { if (session) api({ op: 'lock' }).catch(() => {}); clearState(); }); +window.addEventListener('pagehide', clearState); +window.addEventListener('pageshow', event => { if (event.persisted) clearState(); }); + +async function downloadCrypto() { + const controller = new AbortController(); + let timer: ReturnType<typeof setTimeout> | undefined; + let reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>> | undefined; + const refreshTimeout = () => { + clearTimeout(timer); + timer = setTimeout(() => controller.abort(), 45000); + }; + try { + refreshTimeout(); + const response = await fetch('/crypto.wasm', { cache: 'no-store', credentials: 'omit', signal: controller.signal }); + if (!response.ok) throw new Error(`Cryptographic module download failed (HTTP ${response.status}). Reload to try again.`); + const length = response.headers.get('content-encoding') ? 0 : Number(response.headers.get('content-length')); + const total = Number.isSafeInteger(length) && length > 0 ? length : 0; + const chunks: Uint8Array<ArrayBuffer>[] = []; + let received = 0; + const progress = () => { + const loaded = (received / 1048576).toFixed(1); + if (total) { + const percent = Math.min(100, Math.floor(received * 100 / total)); + const filled = Math.floor(percent / 5); + setStatus(`Downloading cryptographic module... [${'#'.repeat(filled)}${'-'.repeat(20 - filled)}] ${percent}% (${loaded} / ${(total / 1048576).toFixed(1)} MiB)`); + } else setStatus(`Downloading cryptographic module... ${loaded} MiB received`); + }; + progress(); + if (!response.body) throw new Error('Cryptographic module response has no body'); + reader = response.body.getReader(); + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + refreshTimeout(); + chunks.push(value); + received += value.byteLength; + progress(); + } + if (!received) throw new Error('The cryptographic module download was empty. Reload to try again.'); + const bytes = new Uint8Array(received); + let offset = 0; + for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; } + return bytes.buffer; + } catch (error) { + if (controller.signal.aborted) throw new Error('Cryptographic module download stalled for 45 seconds. Check your connection and reload to try again.'); + throw error; + } finally { + clearTimeout(timer); + reader?.releaseLock(); + } +} + +async function start() { + wasm = downloadCrypto(); + await wasm; + setStatus('Cryptographic module downloaded. Connecting to chat...'); + config = await api({ op: 'config' }); + if (configuration().origin !== location.origin) throw new Error('Server origin mismatch'); + show('owner-entry'); + show('entry', Boolean(configuration().owner)); + setStatus(''); + if (location.hash === '#setup') ownerSetup(); +} + +start().catch(error => setStatus(errorMessage(error))); + +// @license-end diff --git a/crates/chat-server/web/javascript.html b/crates/chat-server/web/javascript.html index 644e5a1..b39504c 100644 --- a/crates/chat-server/web/javascript.html +++ b/crates/chat-server/web/javascript.html @@ -23,6 +23,7 @@ along with this program. If not, see <https://www.gnu.org/licenses/>. <tr><td><a href="/worker.js">worker.js</a></td><td><a href="https://www.gnu.org/licenses/agpl-3.0.html">GNU-AGPL-3.0</a></td><td><a href="/SOURCE.tar.gz">Complete corresponding source</a></td></tr> <tr><td><a href="/wasi.mjs">wasi.mjs</a></td><td><a href="https://www.gnu.org/licenses/agpl-3.0.html">GNU-AGPL-3.0</a></td><td><a href="/SOURCE.tar.gz">Complete corresponding source</a></td></tr> </tbody></table></div> +<p>The readable JavaScript is compiled from the included TypeScript sources. The source archive includes shared protocol declarations, compiler configurations, the npm lock, and build/test scripts. No third-party JavaScript runs in the browser. Node, npm, and the pinned TypeScript compiler are development tools; the production server serves prebuilt scripts.</p> <p>The WebAssembly module is compiled from the Rust workspace and unmodified OpenSSL 3.6.5, under their respective free software licenses. The source archive includes first-party sources, Cargo dependencies, the OpenSSL source archive, build scripts, and notices. General-purpose Rust and WASI SDK tools are documented with verified download locations in CHAT-OPENSSL-MIGRATION.txt.</p> <p><a href="{{SITE_ORIGIN}}/THIRD-PARTY-LICENSES.html">Third-party licenses</a> / <a href="/SOURCE.tar.gz">Source archive</a> / <a href="/">Return</a></p> </main></body></html> diff --git a/crates/chat-server/web/worker.js b/crates/chat-server/web/worker.ts index 64e0795..d4367bf 100644 --- a/crates/chat-server/web/worker.js +++ b/crates/chat-server/web/worker.ts @@ -17,7 +17,7 @@ importScripts('/wasi.mjs'); -self.onmessage = async event => { +self.onmessage = async (event: MessageEvent<StackChat.WorkerRequest>) => { try { const result = await self.stackChatWasi.runCommand(event.data.bytes, event.data.request); self.postMessage({ result }); diff --git a/docs/CHAT-APPLICATION.txt b/docs/CHAT-APPLICATION.txt index 27ab61f..7ebac77 100644 --- a/docs/CHAT-APPLICATION.txt +++ b/docs/CHAT-APPLICATION.txt @@ -25,8 +25,9 @@ EXPERIMENTAL PRIVATE CHAT WHAT EXISTS A Rust HTTP server and a Rust cryptographic command compiled to WASI. - Small, readable, free JavaScript modules implement the browser interface and - a capability-limited WASI host. Text is displayed through textContent. + Strict TypeScript implements the browser interface and a capability-limited + WASI host, compiled to small, readable, free JavaScript classic scripts. + Build configuration and source licensing are documented in TYPESCRIPT.txt. Text is displayed through textContent. SearXNG and the other existing services are unchanged. Startup shows an ASCII download bar, percentage, and received/total MiB @@ -377,7 +378,8 @@ LICENSES, SOURCE, AND VERIFICATION The yellow GNU LibreJS-compliant badge links to the GNU project and exposes a hover/focus explanation distinguishing software freedom from security. A source archive is built by infra/chat/build-source.sh from an explicit - source allowlist, Cargo-vendored dependencies, and the original verified + source allowlist, TypeScript sources/configurations/npm lock, Cargo-vendored + dependencies, and the original verified OpenSSL archive. It excludes .env, .git, keys, target files, runtime data, downloaded browser tools, and exports. .env.example is public. The original dependency license texts are preserved. GNU-friendly human-readable names @@ -393,12 +395,13 @@ LICENSES, SOURCE, AND VERIFICATION Run the normal strict workspace check, then browser tests: cargo stack check - PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node crates/chat-crypto/tests/browser.mjs - PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node crates/chat-server/tests/browser.mjs - PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node crates/chat-server/tests/progress.mjs + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:crypto + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:chat + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:progress - Browser automation additionally needs Node, Playwright under .tools/browser, - and its browser downloads under .tools/browsers. These are development tools + Browser automation additionally needs Node and the root locked Playwright + development dependency, with browser downloads under .tools/browsers. See + TYPESCRIPT.txt for installation and the strict TypeScript build. These tools are excluded from releases. The fixtures use temporary isolated installation roots with one temporary .env each, and remove their private data on completion. They listen on loopback port 9081 by default (override with CHAT_TEST_PORT), diff --git a/docs/CHAT-OPENSSL-MIGRATION.txt b/docs/CHAT-OPENSSL-MIGRATION.txt index d2901c4..8c9ee28 100644 --- a/docs/CHAT-OPENSSL-MIGRATION.txt +++ b/docs/CHAT-OPENSSL-MIGRATION.txt @@ -224,9 +224,9 @@ REPRODUCE FROM THE STACK ROOT cargo test --locked -p stack-chat-crypto cargo run --locked -p stack-chat-crypto sh infra/chat/build-openssl-wasi.sh - npm install --prefix .tools/browser --save-exact playwright@1.64.1 - PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" .tools/browser/node_modules/.bin/playwright install chromium - PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node crates/chat-crypto/tests/browser.mjs + npm run build + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node_modules/.bin/playwright install chromium + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:crypto cargo stack check The build script pins archive versions and hashes, configures static OpenSSL, diff --git a/docs/CHAT-PRODUCTION.txt b/docs/CHAT-PRODUCTION.txt index 8830920..cf8fc17 100644 --- a/docs/CHAT-PRODUCTION.txt +++ b/docs/CHAT-PRODUCTION.txt @@ -42,14 +42,16 @@ BUILD ON THE WORKSTATION Current releases require an x86_64 GNU/Linux build host and matching target. Use the pinned Rust toolchain, Podman, Git, GnuPG, a GCC-compatible C compiler, - Linux UAPI headers, libclang, pkg-config, make, Perl, curl, and tar. Native + Linux UAPI headers, libclang, pkg-config, make, Perl, curl, tar, Node >=22.18.0, + and npm. Native workspace checks need OpenSSL 3.5+ development libraries. Browser testing - additionally needs Node, Playwright, Chromium, and Firefox. These tools remain + additionally needs the pinned Playwright, Chromium, and Firefox. These tools remain on the workstation; production does not need Cargo or a compiler. cargo stack release - This runs formatting, strict Clippy, all workspace tests, rustdoc, cargo-deny, + This first builds/checks TypeScript, then runs formatting, strict Clippy, + all workspace tests, rustdoc, cargo-deny, and cargo-about. It then builds static native binaries, the WASI module, corresponding sources, the chat/cgit images, and the complete image export. THIRD-PARTY-LICENSES.html is regenerated from the full workspace before @@ -201,7 +203,7 @@ VERIFICATION HTTPS_PORT=8443, and LOCAL_HTTP_PORT=8180: ./bin/stack up --production - CHAT_TEST_ROOT=/absolute/disposable/stack CHAT_TEST_ORIGIN=https://chat.fixture.localhost:8443 PLAYWRIGHT_BROWSERS_PATH=.tools/browsers node crates/chat-server/tests/browser.mjs + CHAT_TEST_ROOT=/absolute/disposable/stack CHAT_TEST_ORIGIN=https://chat.fixture.localhost:8443 PLAYWRIGHT_BROWSERS_PATH=.tools/browsers npm run test:chat Run from the source checkout for the harness and Playwright installation. Add CHAT_LIBREJS=1 for Firefox with the actual GNU LibreJS add-on. That test diff --git a/docs/POLICY.txt b/docs/POLICY.txt index 16d97c2..1f54398 100644 --- a/docs/POLICY.txt +++ b/docs/POLICY.txt @@ -23,7 +23,9 @@ PROJECT CONVENTIONS file carries the AGPL copyright and permission header. LICENSE is the unmodified license text. Binary public keys and empty WKD policy files retain their protocol format. Generated Cargo.lock retains Cargo's own - metadata as well as the project notice. + metadata as well as the project notice. JSON npm manifests carry the legal + notice in a top-level // metadata field; compiler JSONC files use the usual + header syntax. Keep generated JavaScript legal markers when compiling. Do not add explanatory source comments. Express intent through structure and names. Legal headers are the required exception. Use .txt for prose @@ -58,6 +60,11 @@ STRICTNESS The dependency allowlist retains the requested permissive licenses and Zlib; an unused allowance may produce an informational audit warning. + Browser logic and automation use strict TypeScript configurations with + separate browser/worker/Node environments and checked untrusted responses. + npm dependencies are exact, development-only, integrity-locked, and installed + with lifecycle scripts disabled. See TYPESCRIPT.txt for the build contract. + Human license names follow https://www.gnu.org/licenses/license-list.html. In particular, display Expat License for SPDX MIT. Do not alter original copyright notices, legal texts, crate metadata, or machine SPDX identifiers. diff --git a/docs/TYPESCRIPT.txt b/docs/TYPESCRIPT.txt new file mode 100644 index 0000000..d50ea95 --- /dev/null +++ b/docs/TYPESCRIPT.txt @@ -0,0 +1,128 @@ +Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> + +This program is free software: you can redistribute it and/or modify +it under the terms of the GNU Affero General Public License as +published by the Free Software Foundation, either version 3 of the +License, or (at your option) any later version. + +This program is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU Affero General Public License for more details. + +You should have received a copy of the GNU Affero General Public License +along with this program. If not, see <https://www.gnu.org/licenses/>. + +TYPESCRIPT BROWSER TOOLCHAIN + + All first-party browser logic and browser automation are TypeScript. + Rust still implements cryptography, the API, backups, and deployment. + Browsers execute JavaScript generated by TypeScript; TypeScript adds + compile-time checks and does not replace validation of untrusted input. + +SOURCE LAYOUT + + crates/chat-server/web/app.ts + Interface, session state, history, downloads, and API validation. + crates/chat-server/web/worker.ts + One-shot cryptographic worker; its lifetime ends after each request. + crates/chat-crypto/browser/wasi.ts + Restricted browser WASI host for the unchanged Rust/OpenSSL module. + crates/chat-crypto/browser/protocol.d.ts + Shared API and cryptographic request/response contracts. Declarations + emit no JavaScript and are checked for both browser environments. + crates/chat-crypto/tests/browser.ts + Real WebAssembly compatibility, entropy, and capability tests. + crates/chat-server/tests/browser.ts + Complete browser chat and recovery tests, including GNU LibreJS. + crates/chat-server/tests/progress.ts + Download progress and failure tests, including GNU LibreJS. + tests/browser-support.ts + Checked fixture parsing and typed browser-automation helpers. + + tsconfig.json supplies shared strict checks. The browser, worker, and + test configurations use separate DOM, WebWorker, and Node environments. + Production browser builds cannot accidentally rely on Node APIs. + strict, unchecked indexed access, exact optional properties, unused + declarations/parameters, implicit returns, switch fallthrough, implicit + overrides, and indexed-property access are checked. Type errors prevent + emission. No suppression directives or untyped escape hatches are used. + +DEVELOPMENT + + Install Node >=22.18.0 and npm on the development machine. Root package.json + and package-lock.json pin TypeScript 7.0.2, Playwright 1.64.1, Node type + declarations, platform compiler packages, and their integrity hashes. + There are no npm application/runtime dependencies. TypeScript and + Playwright use the Apache License, Version 2.0; Node declarations and + undici-types use the Expat License. Original notices remain in the + installed packages. SPDX identifiers retain their required spelling. + + Build and check all TypeScript, including browser tests: + + npm run build + + infra/chat/build-typescript.sh installs the locked development packages + with lifecycle scripts disabled, checks all three configurations, and + emits JavaScript under var/build/typescript. The npm cache stays under + .tools/npm-cache. node_modules and generated outputs are ignored by Git. + Generated scripts are readable and unminified; no bundler is needed. + + cargo stack check includes this build, then the strict Rust checks and + cargo-about license generation. cargo stack release builds TypeScript + before packaging the complete production release. + + Check without installing packages or emitting output after npm run build: + + npm run check + + Fetch the pinned Playwright browser versions once: + + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" node_modules/.bin/playwright install chromium firefox + + After building the native chat server and WASI module: + + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:crypto + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:chat + PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:progress + CHAT_LIBREJS=1 PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:chat + CHAT_LIBREJS=1 PLAYWRIGHT_BROWSERS_PATH="$PWD/.tools/browsers" npm run test:progress + + LibreJS variants require the signed Mozilla extension at + .tools/librejs.xpi as documented in CHAT-APPLICATION.txt. The complete + chat test proves LibreJS is active and rejects an unlicensed control. + Run chat variants sequentially because they share the default test port. + npm audit checks the development dependency lock separately from + cargo-deny; it does not audit Rust, browser-delivered code, or containers. + +RELEASES, SOURCE, AND LIBREJS + + Generated app.js, worker.js, and wasi.mjs keep their existing public URLs. + They preserve the AGPL headers and recognized @license/@license-end + markers. The JavaScript license table links each generated file to its + complete corresponding TypeScript and Rust source archive. Classic scripts + and importScripts remain in use for LibreJS compatibility; the migration + introduces no runtime module loader or third-party browser scripts. + + Local native-server tests serve generated files from var/build/typescript. + The release packages those files into bin/chat/web and bin/chat/wasi.mjs. + Containers serve the packaged files. HTML and CSS are copied explicitly, + so TypeScript source files are not substituted for executable JavaScript. + /SOURCE.tar.gz includes TypeScript, shared declarations, all compiler + configurations, the npm lock, tests and build scripts, together with the + existing Cargo-vendored dependencies and verified OpenSSL source archive. + Node/npm/TypeScript are general-purpose development tools, documented and + pinned here; their installed copies and downloaded browsers are excluded. + + Source exports, releases, and backups carry the root npm manifests and + TypeScript configurations. Release activation and restored prebuilt images + need no Node, npm, TypeScript, or Rust installation on the destination. + They retain the single private root .env and existing persistent data. + The source archive excludes that .env, credentials, runtime databases, + exports, .git, node_modules, and build/cache directories. The root + .env.example remains public. No additional environment file is introduced. + + Test the actual generated JavaScript after any compiler upgrade. Static + types cannot guarantee privacy, security, or LibreJS recognition. Browser + storage restrictions, protocol validation, and algorithm choices continue + to be enforced by the existing runtime and Rust implementation. diff --git a/infra/chat/build-source.sh b/infra/chat/build-source.sh index 6f24dcd..e173774 100644 --- a/infra/chat/build-source.sh +++ b/infra/chat/build-source.sh @@ -23,7 +23,7 @@ cargo vendor --locked var/build/chat-vendor | sed 's|directory = "var/build/chat cp "$ROOT/.tools/wasi-source/openssl.tar.gz" "$BUILD/chat-openssl-3.6.5.tar.gz" printf '%s %s\n' a2157c2830efdec3788939b00c9b0638306d3f0bbb76dc4832ee503bb397df98 "$BUILD/chat-openssl-3.6.5.tar.gz" | sha256sum --check source_list="$BUILD/chat-source-files.txt" -find Cargo.toml Cargo.lock rust-toolchain.toml .cargo .gitignore .gitattributes src crates infra web docs README.txt LICENSE deny.toml about.toml about.hbs .env.example -type f -print > "$source_list" +find package.json package-lock.json tsconfig.json tsconfig.browser.json tsconfig.worker.json tsconfig.tests.json tests Cargo.toml Cargo.lock rust-toolchain.toml .cargo .gitignore .gitattributes src crates infra web docs README.txt LICENSE deny.toml about.toml about.hbs .env.example -type f -print > "$source_list" tar -czf "$BUILD/chat-source.tar.gz.pending" --verbatim-files-from -T "$source_list" -C "$BUILD" chat-vendor chat-vendor-config.txt chat-openssl-3.6.5.tar.gz mv "$BUILD/chat-source.tar.gz.pending" "$BUILD/chat-source.tar.gz" sha256sum "$BUILD/chat-source.tar.gz" diff --git a/infra/chat/build-typescript.sh b/infra/chat/build-typescript.sh new file mode 100644 index 0000000..d9d44ad --- /dev/null +++ b/infra/chat/build-typescript.sh @@ -0,0 +1,24 @@ +#!/bin/sh +# Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +# +# This program is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as +# published by the Free Software Foundation, either version 3 of the +# License, or (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with this program. If not, see <https://www.gnu.org/licenses/>. + +set -eu +ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)" +cd "$ROOT" +npm ci --ignore-scripts --no-audit --no-fund --cache "$ROOT/.tools/npm-cache" +npm run check +node_modules/.bin/tsc -p tsconfig.browser.json +node_modules/.bin/tsc -p tsconfig.worker.json +node_modules/.bin/tsc -p tsconfig.tests.json diff --git a/infra/containers/chat/Containerfile b/infra/containers/chat/Containerfile index a63683e..31724b5 100644 --- a/infra/containers/chat/Containerfile +++ b/infra/containers/chat/Containerfile @@ -17,8 +17,8 @@ FROM scratch COPY server /app/bin/server COPY crypto.wasm /app/bin/chat/crypto.wasm COPY SOURCE.tar.gz /app/bin/chat/SOURCE.tar.gz -COPY web /app/crates/chat-server/web -COPY wasi.mjs /app/crates/chat-crypto/browser/wasi.mjs +COPY web /app/bin/chat/web +COPY wasi.mjs /app/bin/chat/wasi.mjs COPY CHAT-APPLICATION.txt /app/docs/CHAT-APPLICATION.txt COPY CHAT-PRODUCTION.txt /app/docs/CHAT-PRODUCTION.txt COPY LICENSE /app/LICENSE diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..240cca5 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,458 @@ +{ + "//": [ + "Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai>", + "", + "This program is free software: you can redistribute it and/or modify", + "it under the terms of the GNU Affero General Public License as", + "published by the Free Software Foundation, either version 3 of the", + "License, or (at your option) any later version.", + "", + "This program is distributed in the hope that it will be useful,", + "but WITHOUT ANY WARRANTY; without even the implied warranty of", + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", + "GNU Affero General Public License for more details.", + "", + "You should have received a copy of the GNU Affero General Public License", + "along with this program. If not, see <https://www.gnu.org/licenses/>." + ], + "name": "stack-browser", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "stack-browser", + "version": "0.1.0", + "license": "AGPL-3.0-or-later", + "devDependencies": { + "@types/node": "26.6.6", + "playwright": "1.64.1", + "typescript": "7.0.2" + }, + "engines": { + "node": ">=22.18.0" + } + }, + "node_modules/@types/node": { + "version": "26.6.6", + "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.6.tgz", + "integrity": "sha512-MzQj+8Kx3XI40OmUAE6Qoh58ZMNstNNMwn2nfd3qWsfe7nDNSqJNzes4njhz6AHwrSHOffSLwXU6yb474Q4aog==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~8.9.0" + } + }, + "node_modules/@typescript/typescript-aix-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-aix-ppc64/-/typescript-aix-ppc64-7.0.2.tgz", + "integrity": "sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-arm64/-/typescript-darwin-arm64-7.0.2.tgz", + "integrity": "sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-darwin-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-darwin-x64/-/typescript-darwin-x64-7.0.2.tgz", + "integrity": "sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-arm64/-/typescript-freebsd-arm64-7.0.2.tgz", + "integrity": "sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-freebsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-freebsd-x64/-/typescript-freebsd-x64-7.0.2.tgz", + "integrity": "sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm/-/typescript-linux-arm-7.0.2.tgz", + "integrity": "sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-arm64/-/typescript-linux-arm64-7.0.2.tgz", + "integrity": "sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-loong64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-loong64/-/typescript-linux-loong64-7.0.2.tgz", + "integrity": "sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-mips64el": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-mips64el/-/typescript-linux-mips64el-7.0.2.tgz", + "integrity": "sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-ppc64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-ppc64/-/typescript-linux-ppc64-7.0.2.tgz", + "integrity": "sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-riscv64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-riscv64/-/typescript-linux-riscv64-7.0.2.tgz", + "integrity": "sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-s390x": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-s390x/-/typescript-linux-s390x-7.0.2.tgz", + "integrity": "sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-linux-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-linux-x64/-/typescript-linux-x64-7.0.2.tgz", + "integrity": "sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-arm64/-/typescript-netbsd-arm64-7.0.2.tgz", + "integrity": "sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-netbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-netbsd-x64/-/typescript-netbsd-x64-7.0.2.tgz", + "integrity": "sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-arm64/-/typescript-openbsd-arm64-7.0.2.tgz", + "integrity": "sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-openbsd-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-openbsd-x64/-/typescript-openbsd-x64-7.0.2.tgz", + "integrity": "sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-sunos-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-sunos-x64/-/typescript-sunos-x64-7.0.2.tgz", + "integrity": "sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-arm64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-arm64/-/typescript-win32-arm64-7.0.2.tgz", + "integrity": "sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/@typescript/typescript-win32-x64": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/@typescript/typescript-win32-x64/-/typescript-win32-x64-7.0.2.tgz", + "integrity": "sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "Apache-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=16.20.0" + } + }, + "node_modules/playwright": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.64.1.tgz", + "integrity": "sha512-HCrVhHr5QQuwYoswEUGTb7gGp522yflbv/ST8nF4sFWGuLjQCt17Q/EubpGGSNKYn1tsTCPZxqHhHCfVURu7UA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "playwright-core": "1.64.1" + }, + "bin": { + "playwright": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/playwright-core": { + "version": "1.64.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.64.1.tgz", + "integrity": "sha512-BC4s8y6SEVA6Q1rSxZTto8hI1KUI3xXlHGZgvGqP4IqPdI/a6FX9H29IDNz7vKo9l21b6LfYosScPL6M3xxyDQ==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "playwright-core": "cli.js" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/typescript": { + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-7.0.2.tgz", + "integrity": "sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc" + }, + "engines": { + "node": ">=16.20.0" + }, + "optionalDependencies": { + "@typescript/typescript-aix-ppc64": "7.0.2", + "@typescript/typescript-darwin-arm64": "7.0.2", + "@typescript/typescript-darwin-x64": "7.0.2", + "@typescript/typescript-freebsd-arm64": "7.0.2", + "@typescript/typescript-freebsd-x64": "7.0.2", + "@typescript/typescript-linux-arm": "7.0.2", + "@typescript/typescript-linux-arm64": "7.0.2", + "@typescript/typescript-linux-loong64": "7.0.2", + "@typescript/typescript-linux-mips64el": "7.0.2", + "@typescript/typescript-linux-ppc64": "7.0.2", + "@typescript/typescript-linux-riscv64": "7.0.2", + "@typescript/typescript-linux-s390x": "7.0.2", + "@typescript/typescript-linux-x64": "7.0.2", + "@typescript/typescript-netbsd-arm64": "7.0.2", + "@typescript/typescript-netbsd-x64": "7.0.2", + "@typescript/typescript-openbsd-arm64": "7.0.2", + "@typescript/typescript-openbsd-x64": "7.0.2", + "@typescript/typescript-sunos-x64": "7.0.2", + "@typescript/typescript-win32-arm64": "7.0.2", + "@typescript/typescript-win32-x64": "7.0.2" + } + }, + "node_modules/undici-types": { + "version": "8.9.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", + "integrity": "sha512-KTDyRTYX8sWmKXAikPHHSyc63CRPETMctyjKFupcC6OBLXT3xsN0e9aF7m+mIXutFWpUXuedtowG7iLOzp0kQg==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..98cad2c --- /dev/null +++ b/package.json @@ -0,0 +1,38 @@ +{ + "//": [ + "Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai>", + "", + "This program is free software: you can redistribute it and/or modify", + "it under the terms of the GNU Affero General Public License as", + "published by the Free Software Foundation, either version 3 of the", + "License, or (at your option) any later version.", + "", + "This program is distributed in the hope that it will be useful,", + "but WITHOUT ANY WARRANTY; without even the implied warranty of", + "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the", + "GNU Affero General Public License for more details.", + "", + "You should have received a copy of the GNU Affero General Public License", + "along with this program. If not, see <https://www.gnu.org/licenses/>." + ], + "name": "stack-browser", + "version": "0.1.0", + "private": true, + "type": "module", + "license": "AGPL-3.0-or-later", + "engines": { + "node": ">=22.18.0" + }, + "scripts": { + "build": "sh infra/chat/build-typescript.sh", + "check": "tsc -p tsconfig.browser.json --noEmit && tsc -p tsconfig.worker.json --noEmit && tsc -p tsconfig.tests.json --noEmit", + "test:crypto": "node var/build/typescript/crates/chat-crypto/tests/browser.js", + "test:chat": "node var/build/typescript/crates/chat-server/tests/browser.js", + "test:progress": "node var/build/typescript/crates/chat-server/tests/progress.js" + }, + "devDependencies": { + "@types/node": "26.6.6", + "playwright": "1.64.1", + "typescript": "7.0.2" + } +} diff --git a/src/chat.rs b/src/chat.rs index be852d5..0739f22 100644 --- a/src/chat.rs +++ b/src/chat.rs @@ -50,6 +50,7 @@ pub(crate) fn environment( } pub(crate) fn build(project: &Project) -> Result<()> { + process::run(project.command("sh")?.arg("infra/chat/build-typescript.sh"))?; process::run(project.command("sh")?.arg("infra/chat/build-native.sh"))?; let wasm_build = if project .root @@ -79,7 +80,18 @@ pub(crate) fn package(project: &Project) -> Result<()> { ), ("var/build/chat-source.tar.gz", "SOURCE.tar.gz"), ("infra/containers/chat/Containerfile", "Containerfile"), - ("crates/chat-crypto/browser/wasi.mjs", "wasi.mjs"), + ( + "var/build/typescript/crates/chat-crypto/browser/wasi.js", + "wasi.mjs", + ), + ( + "var/build/typescript/crates/chat-server/web/app.js", + "web/app.js", + ), + ( + "var/build/typescript/crates/chat-server/web/worker.js", + "web/worker.js", + ), ("web/THIRD-PARTY-LICENSES.html", "THIRD-PARTY-LICENSES.html"), ("docs/CHAT-APPLICATION.txt", "CHAT-APPLICATION.txt"), ("docs/CHAT-PRODUCTION.txt", "CHAT-PRODUCTION.txt"), @@ -87,10 +99,12 @@ pub(crate) fn package(project: &Project) -> Result<()> { ] { files::copy_tree(&project.root.join(source), &directory.join(target))?; } - files::copy_tree( - &project.root.join("crates/chat-server/web"), - &directory.join("web"), - )?; + for name in ["index.html", "style.css", "javascript.html"] { + files::copy_tree( + &project.root.join("crates/chat-server/web").join(name), + &directory.join("web").join(name), + )?; + } Ok(()) } diff --git a/src/files.rs b/src/files.rs index fa441f0..81c57b0 100644 --- a/src/files.rs +++ b/src/files.rs @@ -30,6 +30,12 @@ use walkdir::WalkDir; pub(crate) const SOURCE: &[&str] = &[ "Cargo.toml", "Cargo.lock", + "package.json", + "package-lock.json", + "tsconfig.json", + "tsconfig.browser.json", + "tsconfig.worker.json", + "tsconfig.tests.json", "rust-toolchain.toml", ".cargo", ".gitignore", diff --git a/src/main.rs b/src/main.rs index 5ee1f9e..e6323e2 100644 --- a/src/main.rs +++ b/src/main.rs @@ -293,6 +293,7 @@ fn licenses(project: &Project) -> Result<()> { } fn check(project: &Project) -> Result<()> { + process::run(project.command("sh")?.arg("infra/chat/build-typescript.sh"))?; process::run( project .command("cargo")? diff --git a/tests/browser-support.ts b/tests/browser-support.ts new file mode 100644 index 0000000..223b2b8 --- /dev/null +++ b/tests/browser-support.ts @@ -0,0 +1,65 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. + +import assert from 'node:assert/strict'; +import type { Server } from 'node:http'; + +export function required<T>(value: T | undefined | null, message: string): T { + assert.ok(value !== undefined && value !== null, message); + return value; +} + +function isRecord(value: unknown): value is Record<string, unknown> { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +export function record(value: unknown): Record<string, unknown> { + assert.ok(isRecord(value)); + return value; +} + +export function string(value: unknown): string { + assert.equal(typeof value, 'string'); + if (typeof value !== 'string') throw new Error('Expected string'); + return value; +} + +export function list(value: unknown): unknown[] { + assert.ok(Array.isArray(value)); + return value; +} + +export function serverOrigin(server: Server): string { + const address = server.address(); + assert.ok(address && typeof address !== 'string'); + return `http://127.0.0.1:${address.port}`; +} + +export function requestBody(text: string): { op: string; count: number; [key: string]: unknown } { + const value = record(JSON.parse(text)); + return { ...value, op: string(value['op']), count: typeof value['count'] === 'number' ? value['count'] : 0 }; +} + +export function libreJSAddon(text: string): { active: boolean; version: string } { + const addon = list(record(JSON.parse(text))['addons']).map(record).find(value => value['id'] === 'jid1-KtlZuoiikVfFew@jetpack'); + assert.ok(addon); + assert.equal(addon['active'], true); + return { active: true, version: string(addon['version']) }; +} + +declare global { + interface Window { unlicensedControl?: boolean; chatInjection?: boolean } + const wasm: Promise<ArrayBuffer>; +} diff --git a/tsconfig.browser.json b/tsconfig.browser.json new file mode 100644 index 0000000..3f0b667 --- /dev/null +++ b/tsconfig.browser.json @@ -0,0 +1,33 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "module": "Preserve", + "moduleDetection": "legacy", + "rootDir": ".", + "outDir": "var/build/typescript", + "types": [] + }, + "files": [ + "crates/chat-crypto/browser/protocol.d.ts", + "crates/chat-server/web/app.ts" + ] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..bf78056 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,38 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. +{ + "compilerOptions": { + "target": "ES2022", + "strict": true, + "erasableSyntaxOnly": true, + "verbatimModuleSyntax": true, + "noUncheckedSideEffectImports": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "noImplicitOverride": true, + "noPropertyAccessFromIndexSignature": true, + "allowUnreachableCode": false, + "allowUnusedLabels": false, + "forceConsistentCasingInFileNames": true, + "noEmitOnError": true, + "removeComments": false, + "skipLibCheck": false, + "types": [] + } +} diff --git a/tsconfig.tests.json b/tsconfig.tests.json new file mode 100644 index 0000000..02e8f9c --- /dev/null +++ b/tsconfig.tests.json @@ -0,0 +1,38 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "lib": [ + "ES2022", + "DOM", + "DOM.Iterable" + ], + "module": "NodeNext", + "moduleResolution": "NodeNext", + "moduleDetection": "force", + "rootDir": ".", + "outDir": "var/build/typescript", + "types": [ + "node" + ] + }, + "files": [ + "crates/chat-crypto/browser/protocol.d.ts", + "crates/chat-crypto/tests/browser.ts", + "crates/chat-server/tests/browser.ts", + "crates/chat-server/tests/progress.ts" + ] +} diff --git a/tsconfig.worker.json b/tsconfig.worker.json new file mode 100644 index 0000000..dd328b0 --- /dev/null +++ b/tsconfig.worker.json @@ -0,0 +1,33 @@ +// Copyright (C) 2026 Doan Luu Duc Tai <doan@luuduct.ai> +// +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU Affero General Public License as +// published by the Free Software Foundation, either version 3 of the +// License, or (at your option) any later version. +// +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU Affero General Public License for more details. +// +// You should have received a copy of the GNU Affero General Public License +// along with this program. If not, see <https://www.gnu.org/licenses/>. +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "lib": [ + "ES2022", + "WebWorker" + ], + "module": "Preserve", + "moduleDetection": "legacy", + "rootDir": ".", + "outDir": "var/build/typescript", + "types": [] + }, + "files": [ + "crates/chat-crypto/browser/protocol.d.ts", + "crates/chat-crypto/browser/wasi.ts", + "crates/chat-server/web/worker.ts" + ] +} |
