Open-source AI browser agent for Chrome and Firefox (monorepo) ðŸ§
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
fix: reject unsafe unpacked build outputs
Barack Sokullu8508450e75ce
diff --git a/package.json b/package.jsonindex babf83c30..4d8277d1f 100644--- a/package.json+++ b/package.json@@ -5,13 +5,14 @@"private": true,"type": "module","scripts": {- "test": "npm run test:runtime-lifecycle && npm run test:provider-limits && npm run test:toolbar-guard && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",+ "test": "npm run test:runtime-lifecycle && npm run test:provider-limits && npm run test:toolbar-guard && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:build-unpacked && node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security","test:provider-limits": "node test/provider-model-limits.mjs","test:security": "node test/security/injection-corpus.mjs","test:toolbar-guard": "node test/rich-text-toolbar-guard.mjs","test:pdf-read": "node test/pdf-read.mjs","test:pdf-selection": "node test/pdf-selection.mjs","test:pdf-mime-handler": "node test/pdf-mime-handler-e2e.mjs",+ "test:build-unpacked": "node --test test/build-unpacked.mjs","test:injection-bench": "node test/llm/run-scenarios.mjs --category prompt-injection","test:safety-report": "node test/llm/safety-report.mjs","test:fixtures": "node test/fixtures/run.mjs",diff --git a/scripts/build-unpacked.mjs b/scripts/build-unpacked.mjsindex 82b09e98b..51bce87a3 100644--- a/scripts/build-unpacked.mjs+++ b/scripts/build-unpacked.mjs@@ -22,7 +22,7 @@* test. Never publish these directories to stores; use `npm run build:zip`.*/-import { cpSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs';+import { cpSync, existsSync, mkdirSync, readFileSync, realpathSync, rmSync } from 'node:fs';import { fileURLToPath } from 'node:url';import path from 'node:path';@@ -36,6 +36,8 @@ export const DEV_BUILD_SOURCE_DIRS = {firefox: 'src/firefox',};+const DEV_BUILD_PROTECTED_DIRS = ['.git', 'src', 'scripts'];+/*** Resolve which browsers to build and where they land.* Pure helper so tests and CLIs share one source of truth.@@ -55,6 +57,81 @@ export function resolveBuildPlan({ browser = 'all', outDir = 'build' } = {}) {}));}+function pathContains(parent, candidate) {+ const relative = path.relative(parent, candidate);+ return relative === ''+ || (!path.isAbsolute(relative) && relative !== '..' && !relative.startsWith(`..${path.sep}`));+}++function pathsOverlap(left, right) {+ return pathContains(left, right) || pathContains(right, left);+}++// Resolve symlinks in the existing portion of a path. This catches an output+// parent that aliases src/ even when the final build directory does not exist.+function resolveExistingPath(absPath) {+ let existing = path.resolve(absPath);+ const missing = [];+ while (!existsSync(existing)) {+ const parent = path.dirname(existing);+ if (parent === existing) break;+ missing.unshift(path.basename(existing));+ existing = parent;+ }+ const resolvedParent = existsSync(existing) ? realpathSync(existing) : existing;+ return path.resolve(resolvedParent, ...missing);+}++/**+ * Resolve and validate the complete plan before any destination is removed.+ * Outputs must not contain the repository, overlap either browser source, or+ * enter repository metadata/build-script directories.+ */+export function assertSafeBuildPlan(plan, rootDir = root) {+ const rootPath = resolveExistingPath(rootDir);+ const sourcePaths = Object.entries(DEV_BUILD_SOURCE_DIRS).map(([name, sourceDir]) => ({+ label: `${name} source`,+ path: resolveExistingPath(path.resolve(rootPath, sourceDir)),+ }));+ const protectedPaths = DEV_BUILD_PROTECTED_DIRS.map((protectedDir) => ({+ label: `protected repository directory ${protectedDir}`,+ path: resolveExistingPath(path.resolve(rootPath, protectedDir)),+ }));+ const resolvedPlan = plan.map((step) => ({+ ...step,+ sourcePath: path.resolve(rootPath, step.sourceDir),+ outputPath: path.resolve(rootPath, step.outDir),+ outputSafetyPath: resolveExistingPath(path.resolve(rootPath, step.outDir)),+ }));++ for (const step of resolvedPlan) {+ if (pathContains(step.outputSafetyPath, rootPath)) {+ throw new Error(+ `unsafe output directory for ${step.browser}: ${step.outputPath} contains repository root ${rootPath}`,+ );+ }+ for (const protectedPath of [...sourcePaths, ...protectedPaths]) {+ if (pathsOverlap(step.outputSafetyPath, protectedPath.path)) {+ throw new Error(+ `unsafe output directory for ${step.browser}: ${step.outputPath} overlaps ${protectedPath.label} ${protectedPath.path}`,+ );+ }+ }+ }++ for (let i = 0; i < resolvedPlan.length; i += 1) {+ for (let j = i + 1; j < resolvedPlan.length; j += 1) {+ if (pathsOverlap(resolvedPlan[i].outputSafetyPath, resolvedPlan[j].outputSafetyPath)) {+ throw new Error(+ `unsafe output directories overlap: ${resolvedPlan[i].outputPath} and ${resolvedPlan[j].outputPath}`,+ );+ }+ }+ }++ return resolvedPlan;+}+/** Read + parse JSON, throwing a path-annotated error. */export function readJsonFile(absPath) {try {@@ -113,43 +190,55 @@ function parseArgs(argv) {return args;}-function runCli() {- const args = parseArgs(process.argv.slice(2));- const { version } = assertDevBuildInputs(root);- const plan = resolveBuildPlan({ browser: args.browser, outDir: args.outDir });+export function buildUnpacked({+ browser = 'all',+ outDir = 'build',+ dryRun = false,+ clean = false,+ rootDir = root,+ log = console.log,+} = {}) {+ const { version } = assertDevBuildInputs(rootDir);+ const plan = assertSafeBuildPlan(resolveBuildPlan({ browser, outDir }), rootDir);- if (args.clean && !args.dryRun) {+ if (clean && !dryRun) {for (const step of plan) {- rmSync(path.resolve(root, step.outDir), { recursive: true, force: true });+ rmSync(step.outputPath, { recursive: true, force: true });}}for (const step of plan) {- const from = path.resolve(root, step.sourceDir);- const to = path.resolve(root, step.outDir);+ const from = step.sourcePath;+ const to = step.outputPath;if (!existsSync(from)) throw new Error(`missing source directory: ${from}`);- if (args.dryRun) {- console.log(`[dry-run] ${step.browser}: ${step.sourceDir}/ -> ${step.outDir}/ (v${version})`);+ if (dryRun) {+ log(`[dry-run] ${step.browser}: ${step.sourceDir}/ -> ${step.outDir}/ (v${version})`);continue;}mkdirSync(path.dirname(to), { recursive: true });rmSync(to, { recursive: true, force: true });cpSync(from, to, { recursive: true });- console.log(`built ${step.browser} v${version}: ${step.sourceDir}/ -> ${step.outDir}/`);+ log(`built ${step.browser} v${version}: ${step.sourceDir}/ -> ${step.outDir}/`);}- if (!args.dryRun) {- console.log('Load paths:');+ if (!dryRun) {+ log('Load paths:');for (const step of plan) {if (step.browser === 'chrome') {- console.log(` Chrome: chrome://extensions/ -> Load unpacked -> ${step.outDir}/`);+ log(` Chrome: chrome://extensions/ -> Load unpacked -> ${step.outDir}/`);} else {- console.log(+ log(` Firefox: about:debugging#/runtime/this-firefox -> Load Temporary Add-on -> ${step.outDir}/manifest.json`,);}}}++ return { version, plan };+}++function runCli() {+ buildUnpacked(parseArgs(process.argv.slice(2)));}const invokedAsCli =diff --git a/test/build-unpacked.mjs b/test/build-unpacked.mjsnew file mode 100644index 000000000..34302a23c--- /dev/null+++ b/test/build-unpacked.mjs@@ -0,0 +1,87 @@+import { strict as assert } from 'node:assert';+import {+ existsSync,+ mkdirSync,+ mkdtempSync,+ readFileSync,+ rmSync,+ symlinkSync,+ writeFileSync,+} from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import test from 'node:test';++import {+ assertSafeBuildPlan,+ buildUnpacked,+ resolveBuildPlan,+} from '../scripts/build-unpacked.mjs';++function makeFixture(t) {+ const root = mkdtempSync(path.join(tmpdir(), 'webbrain-build-unpacked-'));+ t.after(() => rmSync(root, { recursive: true, force: true }));+ for (const browser of ['chrome', 'firefox']) {+ const source = path.join(root, 'src', browser);+ mkdirSync(source, { recursive: true });+ writeFileSync(path.join(source, 'manifest.json'), JSON.stringify({ version: '1.2.3' }));+ writeFileSync(path.join(source, 'source-marker.txt'), browser);+ }+ mkdirSync(path.join(root, '.git'), { recursive: true });+ mkdirSync(path.join(root, 'scripts'), { recursive: true });+ writeFileSync(path.join(root, 'package.json'), JSON.stringify({ version: '1.2.3' }));+ return root;+}++test('buildUnpacked rejects a destination equal to a source before deleting it', (t) => {+ const root = makeFixture(t);+ const marker = path.join(root, 'src', 'chrome', 'source-marker.txt');++ assert.throws(+ () => buildUnpacked({ browser: 'chrome', outDir: 'src', rootDir: root, log() {} }),+ /unsafe output directory.*overlaps chrome source/,+ );+ assert.equal(readFileSync(marker, 'utf8'), 'chrome');+});++test('build-plan safety rejects ancestors or descendants of sources and protected directories', (t) => {+ const root = makeFixture(t);+ for (const outDir of ['src/chrome/dev', 'src/firefox/dev', 'src/build', '.git/dev', 'scripts/dev']) {+ assert.throws(+ () => assertSafeBuildPlan(resolveBuildPlan({ browser: 'chrome', outDir }), root),+ /unsafe output directory/,+ outDir,+ );+ }+ assert.throws(+ () => assertSafeBuildPlan([{+ browser: 'chrome',+ sourceDir: 'src/chrome',+ outDir: 'src',+ }], root),+ /unsafe output directory.*overlaps chrome source/,+ );+});++test('build-plan safety resolves an existing symlinked parent before comparison', (t) => {+ const root = makeFixture(t);+ const alias = path.join(root, 'source-alias');+ symlinkSync(path.join(root, 'src'), alias, process.platform === 'win32' ? 'junction' : 'dir');++ assert.throws(+ () => assertSafeBuildPlan(resolveBuildPlan({ browser: 'chrome', outDir: 'source-alias' }), root),+ /unsafe output directory.*overlaps chrome source/,+ );+});++test('buildUnpacked still copies safe Chrome and Firefox output directories', (t) => {+ const root = makeFixture(t);+ const { plan } = buildUnpacked({ rootDir: root, log() {} });++ assert.equal(plan.length, 2);+ for (const browser of ['chrome', 'firefox']) {+ const marker = path.join(root, 'build', browser, 'source-marker.txt');+ assert.equal(existsSync(marker), true);+ assert.equal(readFileSync(marker, 'utf8'), browser);+ }+});