diff --git a/desktop-shell/tauri-skeleton/RELEASE.md b/desktop-shell/tauri-skeleton/RELEASE.md index f3349db0..d5c70f86 100644 --- a/desktop-shell/tauri-skeleton/RELEASE.md +++ b/desktop-shell/tauri-skeleton/RELEASE.md @@ -81,6 +81,13 @@ of `python-3.11.9-embed-amd64.zip`; the pinned SHA-256 is still enforced. Set `SHADOWBROKER_BACKEND_PYTHON` only when the production backend interpreter is outside the normal `backend/venv` location. +Only git-tracked backend files (plus the installed `backend/node_modules`) +are staged, so local leftovers such as old venvs, `graphify-out/` or caches +never ship. Rust builds (the desktop shell, `privacy_core`, the browser wasm) +run with `--remap-path-prefix` for the home folder and the checkout, and +`scripts/build-privacy.cjs check` fails the build if the staged backend, +`companion-www` or the shell binary still names either path. + When an installed runtime layout changes, the desktop updater removes legacy virtualenv directories and their marker after copying the new bundle. The operator's `.env`, `data/`, and unrelated runtime files remain preserved. diff --git a/desktop-shell/tauri-skeleton/build.ps1 b/desktop-shell/tauri-skeleton/build.ps1 index 9811cb6a..8219c77b 100644 --- a/desktop-shell/tauri-skeleton/build.ps1 +++ b/desktop-shell/tauri-skeleton/build.ps1 @@ -16,6 +16,7 @@ $iconsScript = Join-Path $scriptDir "scripts\generate-icons.cjs" $exportScript = Join-Path $scriptDir "scripts\build-frontend-export.cjs" $backendRuntimeScript = Join-Path $scriptDir "scripts\build-backend-runtime.cjs" $manifestScript = Join-Path $scriptDir "scripts\write-release-manifest.cjs" +$privacyScript = Join-Path $scriptDir "scriptsuild-privacy.cjs" $localUpdaterKey = Join-Path $repoRoot "release-secrets\shadowbroker-updater.key" $localUpdaterKeyPassword = Join-Path $repoRoot "release-secrets\shadowbroker-updater.key.pass" @@ -156,10 +157,15 @@ try { } Write-Host "" - cargo tauri build + # Nothing that ships may name this machine (home folder, checkout path). + Invoke-External -Command @("node", $privacyScript, "check", $companionDir, $backendRuntimeDir) + + # Remaps build paths out of the Rust binary. + & node $privacyScript run cargo tauri build if ($LASTEXITCODE -ne 0) { throw "cargo tauri build failed." } + Invoke-External -Command @("node", $privacyScript, "check", (Join-Path $srcTauriDir "target elease\shadowbroker-tauri-shell.exe")) $bundleDir = Join-Path $srcTauriDir "target\release\bundle" if (Test-Path $bundleDir) { diff --git a/desktop-shell/tauri-skeleton/build.sh b/desktop-shell/tauri-skeleton/build.sh index cb277fb1..9d24599a 100644 --- a/desktop-shell/tauri-skeleton/build.sh +++ b/desktop-shell/tauri-skeleton/build.sh @@ -44,6 +44,7 @@ ICON_SCRIPT="$SCRIPT_DIR/scripts/generate-icons.cjs" EXPORT_SCRIPT="$SCRIPT_DIR/scripts/build-frontend-export.cjs" BACKEND_RUNTIME_SCRIPT="$SCRIPT_DIR/scripts/build-backend-runtime.cjs" MANIFEST_SCRIPT="$SCRIPT_DIR/scripts/write-release-manifest.cjs" +PRIVACY_SCRIPT="$SCRIPT_DIR/scripts/build-privacy.cjs" LOCAL_UPDATER_KEY="$REPO_ROOT/release-secrets/shadowbroker-updater.key" LOCAL_UPDATER_KEY_PASSWORD="$REPO_ROOT/release-secrets/shadowbroker-updater.key.pass" CLEAN=0 @@ -150,7 +151,12 @@ else fi echo "" -cargo tauri build +# Nothing that ships may name this machine (home folder, checkout path). +node "$PRIVACY_SCRIPT" check "$SCRIPT_DIR/src-tauri/companion-www" "$SCRIPT_DIR/src-tauri/backend-runtime" + +# Remaps build paths out of the Rust binary. +node "$PRIVACY_SCRIPT" run cargo tauri build +node "$PRIVACY_SCRIPT" check "$SCRIPT_DIR/src-tauri/target/release/shadowbroker-tauri-shell" BUNDLE_DIR="$SCRIPT_DIR/src-tauri/target/release/bundle" if [ -d "$BUNDLE_DIR" ]; then diff --git a/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.cjs b/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.cjs index 17bb0f59..7e3a0cc3 100644 --- a/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.cjs +++ b/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.cjs @@ -5,6 +5,7 @@ const fs = require('node:fs'); const os = require('node:os'); const path = require('node:path'); const { spawnSync } = require('node:child_process'); +const { assertNoBuildMachinePaths, buildMachinePaths, remapRustEnv } = require('./build-privacy.cjs'); const scriptDir = __dirname; const tauriDir = path.resolve(scriptDir, '..'); @@ -37,6 +38,7 @@ const excludedNames = new Set([ 'backend.egg-info', 'build', 'data', + 'graphify-out', 'tests', 'timemachine', ]); @@ -79,15 +81,40 @@ function backendPythonPath() { return path.join(backendDir, venvDir, 'bin', 'python3'); } +let trackedBackendCache = null; + +// Only files committed to git ship, plus the installed node_modules the AIS +// proxy needs. Local leftovers (old venvs, caches, notes, graphs) never do. +function trackedBackendPaths() { + if (trackedBackendCache) return trackedBackendCache; + const result = spawnSync('git', ['ls-files', '-z'], { cwd: backendDir, encoding: 'utf8' }); + if (result.error || result.status !== 0) { + throw new Error('Desktop packaging needs a git checkout to know which backend files ship.'); + } + const tracked = new Set(); + for (const file of result.stdout.split('\0').filter(Boolean)) { + const parts = file.split('/'); + for (let index = 1; index <= parts.length; index += 1) { + tracked.add(parts.slice(0, index).join(path.sep)); + } + } + trackedBackendCache = tracked; + return tracked; +} + function shouldCopyBackendPath( srcPath, platform = process.platform, venvDirName = selectedVenvDirName(), + tracked = trackedBackendPaths(), ) { const relativePath = path.relative(backendDir, srcPath); if (!relativePath) return true; const parts = relativePath.split(path.sep); + if (parts[0] !== 'node_modules' && !tracked.has(relativePath)) { + return false; + } if ( platform === 'win32' && (parts[0] === venvDirName || conventionalVenvNames.has(parts[0])) @@ -165,17 +192,16 @@ function privacyCoreArtifactPath() { } function ensurePrivacyCoreArtifact() { + // Always (re)build: cargo skips the work when nothing changed, and an older + // library may have been built without the path remapping. const artifact = privacyCoreArtifactPath(); - if (fs.existsSync(artifact)) { - return artifact; - } - console.log('privacy-core release library missing; building it for desktop packaging...'); + console.log('Building privacy-core release library for desktop packaging...'); const result = spawnSync( 'cargo', ['build', '--release', '--manifest-path', path.join(privacyCoreDir, 'Cargo.toml')], { cwd: repoRoot, - env: process.env, + env: remapRustEnv(), stdio: 'inherit', }, ); @@ -344,27 +370,17 @@ function walkFiles(root) { return files; } -function assertPortableWindowsBundle(root, buildInfo) { - const forbiddenPaths = [repoRoot, backendDir, buildInfo.prefix, buildInfo.base_prefix] - .filter(Boolean) - .map((value) => path.resolve(value).toLowerCase()); - +// Every staged file, binaries and large files included, must be free of the +// build machine's home folder, checkout and Python paths. +function assertPortableBundle(root, buildInfo) { for (const filePath of walkFiles(root)) { const leaf = path.basename(filePath).toLowerCase(); if (leaf === 'pyvenv.cfg' || /\.(?:egg-link|pth)$/i.test(leaf)) { throw new Error(`Non-portable virtualenv metadata was staged: ${filePath}`); } - - const stat = fs.statSync(filePath); - if (stat.size > 2 * 1024 * 1024) continue; - const bytes = fs.readFileSync(filePath); - if (bytes.includes(0)) continue; - const text = bytes.toString('utf8').toLowerCase(); - const leakedPath = forbiddenPaths.find((value) => text.includes(value)); - if (leakedPath) { - throw new Error(`Build-machine path leaked into staged runtime: ${filePath}`); - } } + const extra = buildInfo ? [backendDir, buildInfo.prefix, buildInfo.base_prefix] : [backendDir]; + assertNoBuildMachinePaths([root], buildMachinePaths(extra)); } function verifyRelocatableWindowsRuntime() { @@ -418,8 +434,8 @@ async function stageBackendRuntime() { stageReleaseAttestation(); stageStartScripts(); + assertPortableBundle(outputDir, buildInfo); if (process.platform === 'win32') { - assertPortableWindowsBundle(outputDir, buildInfo); verifyRelocatableWindowsRuntime(); } } @@ -499,7 +515,9 @@ if (require.main === module) { } module.exports = { - assertPortableWindowsBundle, + assertPortableBundle, + // Older name, kept for callers. + assertPortableWindowsBundle: assertPortableBundle, configureEmbeddedPythonPath, shouldCopyBackendPath, shouldCopySitePackagePath, diff --git a/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.test.cjs b/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.test.cjs index 150cc96a..1b6d73fc 100644 --- a/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.test.cjs +++ b/desktop-shell/tauri-skeleton/scripts/build-backend-runtime.test.cjs @@ -106,3 +106,58 @@ test('bundle validation rejects pyvenv.cfg and developer home paths', () => { fs.rmSync(temp, { recursive: true, force: true }); } }); + +test('only git-tracked backend files and node_modules are staged', () => { + const tracked = new Set(['services', path.join('services', 'config.py'), 'main.py']); + const copies = (rel) => + shouldCopyBackendPath(path.join(backendDir, rel), 'linux', 'venv', tracked); + + assert.equal(copies('main.py'), true); + assert.equal(copies(path.join('services', 'config.py')), true); + assert.equal(copies(path.join('node_modules', 'ws', 'index.js')), true); + // Local leftovers that are not in git never ship. + assert.equal(copies(path.join('graphify-out', 'graph.json')), false); + assert.equal(copies(path.join('venv-nov13', 'pyvenv.cfg')), false); + assert.equal(copies(path.join('services', 'ais_cache.json')), false); + assert.equal(copies('notes.md'), false); +}); + +test('graphify output is never staged even if it were tracked', () => { + const tracked = new Set(['graphify-out', path.join('graphify-out', 'graph.json')]); + assert.equal( + shouldCopyBackendPath(path.join(backendDir, 'graphify-out', 'graph.json'), 'linux', 'venv', tracked), + false, + ); +}); + +test('the leak check also finds escaped, binary and large-file paths', () => { + const { findBuildMachinePaths, buildMachinePaths } = require('./build-privacy.cjs'); + const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'sb-privacy-scan-test-')); + const home = path.win32.join('C:', 'Users', 'developer'); + const needles = buildMachinePaths([], path.win32.join('D:', 'src', 'Shadowbroker'), home); + const write = (name, data) => fs.writeFileSync(path.join(temp, name), data); + try { + write('clean.txt', 'nothing here\n'); + write('json.json', JSON.stringify({ path: path.win32.join(home, 'Shadowbroker', 'main.py') })); + write('slash.js', 'x("c:/users/developer/.cargo/registry/src/lib.rs")'); + write('binary.dll', Buffer.concat([Buffer.from([0, 1, 2]), Buffer.from(path.win32.join(home, 'lib.rs'))])); + write('wide.exe', Buffer.from(path.win32.join(home, 'tool'), 'utf16le')); + write('big.bin', Buffer.concat([Buffer.alloc(3 * 1024 * 1024), Buffer.from(home)])); + + const leaks = findBuildMachinePaths([temp], needles).map((file) => path.basename(file)).sort(); + assert.deepEqual(leaks, ['big.bin', 'binary.dll', 'json.json', 'slash.js', 'wide.exe']); + } finally { + fs.rmSync(temp, { recursive: true, force: true }); + } +}); + +test('Rust builds remap the home folder and checkout out of binaries', () => { + const { remapRustEnv } = require('./build-privacy.cjs'); + const env = remapRustEnv({ RUSTFLAGS: '-C target-cpu=native' }, '/home/dev/Shadowbroker', '/home/dev'); + const flags = env.CARGO_ENCODED_RUSTFLAGS.split('\x1f'); + assert.equal(env.RUSTFLAGS, undefined); + assert.deepEqual(flags.slice(0, 2), ['-C', 'target-cpu=native']); + assert.ok(flags.includes(`--remap-path-prefix=${path.resolve('/home/dev')}=~`)); + // The checkout is inside home, so its remap must come last to win. + assert.equal(flags.at(-1), `--remap-path-prefix=${path.resolve('/home/dev/Shadowbroker')}=shadowbroker`); +}); diff --git a/desktop-shell/tauri-skeleton/scripts/build-privacy.cjs b/desktop-shell/tauri-skeleton/scripts/build-privacy.cjs new file mode 100644 index 00000000..6c45820d --- /dev/null +++ b/desktop-shell/tauri-skeleton/scripts/build-privacy.cjs @@ -0,0 +1,128 @@ +#!/usr/bin/env node +// Keep the build machine out of release files. +// +// node build-privacy.cjs run run a cargo build with path remapping +// node build-privacy.cjs check fail if a file names a build-machine path +// +// Rust embeds the source path of every panic location, including crates under +// ~/.cargo and the toolchain under ~/.rustup. Remapping turns those into +// "~/..." and "shadowbroker/..." so a binary never carries a home folder or +// user name. The check backs that up for everything that ships. + +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const { spawnSync } = require('node:child_process'); + +const repoRoot = path.resolve(__dirname, '..', '..', '..'); + +function existingRustFlags(env) { + if (env.CARGO_ENCODED_RUSTFLAGS) { + return env.CARGO_ENCODED_RUSTFLAGS.split('\x1f').filter(Boolean); + } + if (env.RUSTFLAGS) { + return env.RUSTFLAGS.split(/\s+/).filter(Boolean); + } + return []; +} + +function remapRustEnv(env = process.env, root = repoRoot, home = os.homedir()) { + // rustc applies the last matching remap, so the repo (inside home) goes last. + const remaps = []; + for (const [from, to] of [ + [env.CARGO_HOME, '~/.cargo'], + [env.RUSTUP_HOME, '~/.rustup'], + [home, '~'], + [root, 'shadowbroker'], + ]) { + if (from) remaps.push(`--remap-path-prefix=${path.resolve(from)}=${to}`); + } + const flags = [...existingRustFlags(env), ...remaps]; + const next = { ...env, CARGO_ENCODED_RUSTFLAGS: flags.join('\x1f') }; + delete next.RUSTFLAGS; + return next; +} + +function buildMachinePaths(extra = [], root = repoRoot, home = os.homedir()) { + const values = new Set(); + for (const value of [home, root, ...extra]) { + if (!value) continue; + // Keep Windows paths as they are when checking on another OS. + const absolute = path.isAbsolute(value) || path.win32.isAbsolute(value); + const resolved = (absolute ? path.normalize(value) : path.resolve(value)).toLowerCase(); + if (resolved.length < 4) continue; + values.add(resolved); + values.add(resolved.replace(/\\/g, '/')); + values.add(resolved.replace(/\\/g, '\\\\')); + } + return [...values]; +} + +function walkFiles(target) { + const stat = fs.statSync(target); + if (!stat.isDirectory()) return [target]; + const files = []; + for (const entry of fs.readdirSync(target, { withFileTypes: true })) { + files.push(...walkFiles(path.join(target, entry.name))); + } + return files; +} + +function findBuildMachinePaths(targets, needles = buildMachinePaths()) { + // Search raw bytes too (binaries), plus UTF-16 for Windows wide strings. + const patterns = needles.flatMap((needle) => [needle, needle.split('').join('\0')]); + const leaks = []; + for (const target of targets) { + for (const file of walkFiles(target)) { + const text = fs.readFileSync(file).toString('latin1').toLowerCase(); + if (patterns.some((pattern) => text.includes(pattern))) { + leaks.push(file); + } + } + } + return leaks; +} + +function assertNoBuildMachinePaths(targets, needles) { + const leaks = findBuildMachinePaths(targets, needles); + if (leaks.length) { + throw new Error( + `Build-machine path leaked into release files:\n ${leaks.slice(0, 20).join('\n ')}` + + (leaks.length > 20 ? `\n ...and ${leaks.length - 20} more` : ''), + ); + } +} + +function main(argv) { + const [mode, ...rest] = argv; + if (mode === 'run' && rest.length) { + const result = spawnSync(rest[0], rest.slice(1), { + env: remapRustEnv(), + stdio: 'inherit', + }); + return result.error ? 1 : (result.status ?? 1); + } + if (mode === 'check' && rest.length) { + try { + assertNoBuildMachinePaths(rest.map((value) => path.resolve(value))); + } catch (error) { + console.error(error.message); + return 1; + } + console.log(`No build-machine paths in ${rest.length} location(s).`); + return 0; + } + console.error('Usage: build-privacy.cjs run | check '); + return 2; +} + +if (require.main === module) { + process.exitCode = main(process.argv.slice(2)); +} + +module.exports = { + assertNoBuildMachinePaths, + buildMachinePaths, + findBuildMachinePaths, + remapRustEnv, +}; diff --git a/frontend/scripts/build-privacy-core-wasm.cjs b/frontend/scripts/build-privacy-core-wasm.cjs index a1edf25a..fcb738b0 100644 --- a/frontend/scripts/build-privacy-core-wasm.cjs +++ b/frontend/scripts/build-privacy-core-wasm.cjs @@ -6,6 +6,10 @@ const frontendDir = path.resolve(__dirname, '..'); const repoRoot = path.resolve(frontendDir, '..'); const privacyCoreManifest = path.join(repoRoot, 'privacy-core', 'Cargo.toml'); const outDir = path.join(frontendDir, 'src', 'mesh', 'privacyCoreWasm'); +// Strips build-machine paths (home folder, checkout) out of the shipped wasm. +const { assertNoBuildMachinePaths, remapRustEnv } = require( + path.join(repoRoot, 'desktop-shell', 'tauri-skeleton', 'scripts', 'build-privacy.cjs'), +); const wasmPath = path.join( repoRoot, 'privacy-core', @@ -18,6 +22,7 @@ const wasmPath = path.join( function run(bin, args) { execFileSync(bin, args, { cwd: repoRoot, + env: remapRustEnv(), stdio: 'inherit', }); } @@ -27,3 +32,4 @@ fs.mkdirSync(outDir, { recursive: true }); run('rustup', ['target', 'add', 'wasm32-unknown-unknown']); run('cargo', ['build', '--target', 'wasm32-unknown-unknown', '--release', '--manifest-path', privacyCoreManifest]); run('wasm-bindgen', ['--target', 'web', '--out-dir', outDir, wasmPath]); +assertNoBuildMachinePaths([outDir]); diff --git a/frontend/src/mesh/privacyCoreWasm/privacy_core.d.ts b/frontend/src/mesh/privacyCoreWasm/privacy_core.d.ts index 2d9015a0..b6390306 100644 --- a/frontend/src/mesh/privacyCoreWasm/privacy_core.d.ts +++ b/frontend/src/mesh/privacyCoreWasm/privacy_core.d.ts @@ -29,9 +29,11 @@ export interface InitOutput { readonly privacy_core_decrypt_group_message: (a: number, b: bigint, c: number, d: number) => void; readonly privacy_core_dm_decrypt: (a: bigint, b: number, c: number, d: number, e: number) => bigint; readonly privacy_core_dm_encrypt: (a: bigint, b: number, c: number, d: number, e: number) => bigint; + readonly privacy_core_dm_session_fingerprint: (a: bigint, b: number, c: number) => bigint; readonly privacy_core_dm_session_welcome: (a: bigint, b: number, c: number) => bigint; readonly privacy_core_encrypt_group_message: (a: number, b: bigint, c: number, d: number) => void; readonly privacy_core_export_dm_state: (a: number, b: number) => bigint; + readonly privacy_core_export_dm_state_with_identities: (a: number, b: number, c: number, d: number) => bigint; readonly privacy_core_export_gate_state: (a: number, b: number, c: number, d: number, e: number, f: number) => bigint; readonly privacy_core_export_key_package: (a: number, b: bigint) => void; readonly privacy_core_export_public_bundle: (a: number, b: bigint) => void; diff --git a/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm b/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm index c079fbce..8ad2973a 100644 Binary files a/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm and b/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm differ diff --git a/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm.d.ts b/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm.d.ts index d2c23893..b3f59d6b 100644 --- a/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm.d.ts +++ b/frontend/src/mesh/privacyCoreWasm/privacy_core_bg.wasm.d.ts @@ -11,9 +11,11 @@ export const privacy_core_create_identity: () => bigint; export const privacy_core_decrypt_group_message: (a: number, b: bigint, c: number, d: number) => void; export const privacy_core_dm_decrypt: (a: bigint, b: number, c: number, d: number, e: number) => bigint; export const privacy_core_dm_encrypt: (a: bigint, b: number, c: number, d: number, e: number) => bigint; +export const privacy_core_dm_session_fingerprint: (a: bigint, b: number, c: number) => bigint; export const privacy_core_dm_session_welcome: (a: bigint, b: number, c: number) => bigint; export const privacy_core_encrypt_group_message: (a: number, b: bigint, c: number, d: number) => void; export const privacy_core_export_dm_state: (a: number, b: number) => bigint; +export const privacy_core_export_dm_state_with_identities: (a: number, b: number, c: number, d: number) => bigint; export const privacy_core_export_gate_state: (a: number, b: number, c: number, d: number, e: number, f: number) => bigint; export const privacy_core_export_key_package: (a: number, b: bigint) => void; export const privacy_core_export_public_bundle: (a: number, b: bigint) => void;