Skip to content

A plugin marketplace for GitHub Copilot and other AI agents that provides Power Platform development plugins, including reusable skills, agents, and commands for building and deploying solutions.

Enforce secure process execution in CI (#390)

Priyanshu Agrawal5ebf14d232ef
diff --git a/.github/workflows/validate-repository-metadata.yml b/.github/workflows/validate-repository-metadata.yml
index 07067911b..802f17270 100644
--- a/.github/workflows/validate-repository-metadata.yml
+++ b/.github/workflows/validate-repository-metadata.yml
@@ -2,14 +2,14 @@ name: validate-repository-metadata
on:
pull_request:
- branches:
- - main
workflow_dispatch:
jobs:
validate-repository-metadata:
name: validate-repository-metadata
runs-on: ubuntu-latest
+ env:
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: "1"
steps:
- name: checkout
uses: actions/checkout@v4
@@ -30,3 +30,9 @@ jobs:
- name: validate-telemetry-ikeys
run: node scripts/validate-telemetry-ikeys.js
+
+ - name: test-secure-process-execution-validator
+ run: node --test scripts/tests/validate-secure-process-execution.test.js
+
+ - name: validate-secure-process-execution
+ run: node scripts/validate-secure-process-execution.js
diff --git a/plugins/power-pages/AGENTS.md b/plugins/power-pages/AGENTS.md
index aec001bf2..e360b32ad 100644
--- a/plugins/power-pages/AGENTS.md
+++ b/plugins/power-pages/AGENTS.md
@@ -13,6 +13,7 @@ Read `PLUGIN_DEVELOPMENT_GUIDE.md` for UX and reliability standards when creatin
- **UUID generation** must use the shared `scripts/generate-uuid.js` — never copy it into skill-specific directories.
- **Power Pages config loading** must reuse `scripts/lib/powerpages-config.js` anywhere a script reads `.powerpages-site` table-permission or site-setting YAML. Keep that module focused on loading/parsing code-site config only; put validation or business rules in separate validator modules.
- **Script changes require tests** — Whenever you add a new script or modify an existing script, add or update `node:test` coverage under `scripts/tests/`. Prefer one `*.test.js` file per script/module being tested, and keep the test command passing: `node --test plugins/power-pages/scripts/tests/` (Node's built-in runner discovers `*.test.js` files under the given directory). Validator changes are not an exception; they must always ship with test coverage.
+- **Secure process validation** — After changing Power Pages `child_process` usage, run `node scripts/validate-secure-process-execution.js` from the repository root. Its fixture suite is `node --test scripts/tests/validate-secure-process-execution.test.js`.
- **Dataverse-backed validation** must stay opt-in for local runs only. Do not require live Dataverse connectivity in CI workflows or default test runs; gate it behind explicit local flags such as `--validate-dataverse-relationships`.
- **Azure CLI `--allow-no-subscriptions`** — this flag is only valid on `az login`. Other `az` subcommands (`az account get-access-token`, `az account show`, etc.) reject it as an unrecognized argument and exit 2, so do NOT add it to anything other than `az login`. When the user is not logged in to the Azure CLI, suggest plain `az login` first; only suggest `az login --allow-no-subscriptions` as a fallback if they don't have any associated Azure subscription, since that variant lets subscription-less accounts sign in and still mint AAD-scoped Dataverse/Power Platform tokens via subsequent `az account get-access-token` calls. Reuse the shared `getAuthToken` helper in `scripts/lib/validation-helpers.js` instead of shelling out to `az` directly.
- **Reference docs** shared across skills live in `references/` — reference via `${PLUGIN_ROOT}/references/` paths, don't duplicate.
diff --git a/plugins/power-pages/scripts/lib/detect-browser.js b/plugins/power-pages/scripts/lib/detect-browser.js
index 266201ccc..6b8461da9 100644
--- a/plugins/power-pages/scripts/lib/detect-browser.js
+++ b/plugins/power-pages/scripts/lib/detect-browser.js
@@ -4,7 +4,7 @@
// Returns a Playwright channel name ('msedge', 'chrome', 'chromium').
// Used by the Playwright MCP launcher and the axe-core audit script.
-const { execSync } = require('child_process');
+const { execFileSync } = require('child_process');
const fs = require('fs');
const path = require('path');
const os = require('os');
@@ -15,7 +15,9 @@ function exists(filePath) {
function whichExists(cmd) {
try {
- execSync(`which ${cmd}`, { stdio: 'ignore' });
+ // This helper only runs in the Linux branch below. Pass the fixed utility and
+ // candidate name separately so a future candidate cannot become shell syntax.
+ execFileSync('which', [cmd], { stdio: 'ignore', shell: false });
return true;
} catch {
return false;
diff --git a/plugins/power-pages/skills/scan-code/scripts/check-tools.js b/plugins/power-pages/skills/scan-code/scripts/check-tools.js
index 4dc1242d9..0014923e2 100644
--- a/plugins/power-pages/skills/scan-code/scripts/check-tools.js
+++ b/plugins/power-pages/skills/scan-code/scripts/check-tools.js
@@ -1,6 +1,6 @@
#!/usr/bin/env node
-const { execSync } = require('child_process');
+const { execFileSync } = require('child_process');
if (process.argv.includes('--help')) {
process.stdout.write(`check-tools.js — Detects whether opengrep and trivy are installed.
@@ -23,19 +23,34 @@ Output (stdout, JSON):
process.exit(0);
}
-function probe(cmd, parseVersion) {
+function probe(runVersion, parseVersion) {
try {
- // 60s timeout — first invocation can be slow (cold start, antivirus scan, etc.)
- const out = execSync(cmd, { encoding: 'utf8', timeout: 60000, stdio: ['ignore', 'pipe', 'pipe'] });
+ const out = runVersion();
return { available: true, version: parseVersion(out), error: null };
} catch (err) {
return { available: false, version: null, error: (err.stderr || err.message || '').toString().trim() };
}
}
+// Keep executable names at the child_process call sites. Passing an executable
+// into probe() would make future CLI/env-derived values indistinguishable from
+// this fixed two-tool allowlist to the repository security validator.
+const runOpenGrepVersion = () => execFileSync('opengrep', ['--version'], {
+ encoding: 'utf8',
+ timeout: 60000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: false,
+});
+const runTrivyVersion = () => execFileSync('trivy', ['--version'], {
+ encoding: 'utf8',
+ timeout: 60000,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ shell: false,
+});
+
const result = {
- opengrep: probe('opengrep --version', (out) => (out.match(/[\d.]+/) || [null])[0]),
- trivy: probe('trivy --version', (out) => {
+ opengrep: probe(runOpenGrepVersion, (out) => (out.match(/[\d.]+/) || [null])[0]),
+ trivy: probe(runTrivyVersion, (out) => {
const m = out.match(/Version:\s*([\d.]+)/i) || out.match(/[\d.]+/);
return m ? m[1] || m[0] : null;
}),
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/ambiguous-options.js b/scripts/tests/fixtures/secure-process-execution/fail/ambiguous-options.js
new file mode 100644
index 000000000..fb7b9a31f
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/ambiguous-options.js
@@ -0,0 +1,9 @@
+'use strict';
+
+const { spawn } = require('child_process');
+
+function launch(options) {
+ spawn('tool', [process.env.INPUT], options);
+}
+
+module.exports = { launch };
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/computed-direct-require.js b/scripts/tests/fixtures/secure-process-execution/fail/computed-direct-require.js
new file mode 100644
index 000000000..8fa1409c2
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/computed-direct-require.js
@@ -0,0 +1,3 @@
+'use strict';
+
+require('child_process')['exec'](process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/computed-member.js b/scripts/tests/fixtures/secure-process-execution/fail/computed-member.js
new file mode 100644
index 000000000..d3b34cb75
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/computed-member.js
@@ -0,0 +1,6 @@
+'use strict';
+
+const childProcess = require('child_process');
+const method = process.env.METHOD;
+
+childProcess[method]('tool', []);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/concatenated-command.js b/scripts/tests/fixtures/secure-process-execution/fail/concatenated-command.js
new file mode 100644
index 000000000..b6a60b028
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/concatenated-command.js
@@ -0,0 +1,3 @@
+import { exec as run } from 'child_process';
+
+run('pac pages upload --path ' + process.argv[2]);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/default-esm-import.mjs b/scripts/tests/fixtures/secure-process-execution/fail/default-esm-import.mjs
new file mode 100644
index 000000000..23c04b9c3
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/default-esm-import.mjs
@@ -0,0 +1,3 @@
+import childProcess from 'node:child_process';
+
+childProcess.exec(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/direct-require.js b/scripts/tests/fixtures/secure-process-execution/fail/direct-require.js
new file mode 100644
index 000000000..2adabb262
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/direct-require.js
@@ -0,0 +1,3 @@
+'use strict';
+
+require('node:child_process').exec('tool ' + process.argv[2]);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/division-after-postfix.js b/scripts/tests/fixtures/secure-process-execution/fail/division-after-postfix.js
new file mode 100644
index 000000000..eab8595f4
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/division-after-postfix.js
@@ -0,0 +1,6 @@
+'use strict';
+
+const x = 1;
+const y = 2;
+
+x++ / require('child_process').exec(process.env.COMMAND) / y;
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/duplicate-shell-property.js b/scripts/tests/fixtures/secure-process-execution/fail/duplicate-shell-property.js
new file mode 100644
index 000000000..3309e4644
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/duplicate-shell-property.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { spawn } = require('child_process');
+
+spawn('tool', [], { shell: false, shell: true });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/dynamic-executable.js b/scripts/tests/fixtures/secure-process-execution/fail/dynamic-executable.js
new file mode 100644
index 000000000..82929350a
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/dynamic-executable.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { spawnSync } = require('child_process');
+
+spawnSync(process.env.TOOL, ['--version'], { shell: false });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/dynamic-template.js b/scripts/tests/fixtures/secure-process-execution/fail/dynamic-template.js
new file mode 100644
index 000000000..590da6cad
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/dynamic-template.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { execSync: run } = require('node:child_process');
+
+run(`pac pages upload --path ${process.env.SITE_PATH}`);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/escaped-module-specifier.js b/scripts/tests/fixtures/secure-process-execution/fail/escaped-module-specifier.js
new file mode 100644
index 000000000..27cc7ec0a
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/escaped-module-specifier.js
@@ -0,0 +1,3 @@
+'use strict';
+
+require('child_\x70rocess').exec(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/escaped-shell-property.js b/scripts/tests/fixtures/secure-process-execution/fail/escaped-shell-property.js
new file mode 100644
index 000000000..b325de5ee
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/escaped-shell-property.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { spawn } = require('child_process');
+
+spawn('tool', [], { 'sh\u0065ll': true });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/even-escaped-template.js b/scripts/tests/fixtures/secure-process-execution/fail/even-escaped-template.js
new file mode 100644
index 000000000..86451f1e3
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/even-escaped-template.js
@@ -0,0 +1,6 @@
+'use strict';
+
+const { exec } = require('child_process');
+const input = process.env.INPUT;
+
+exec(`echo \\${input}`);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/indirect-shell-true.js b/scripts/tests/fixtures/secure-process-execution/fail/indirect-shell-true.js
new file mode 100644
index 000000000..cfab7483f
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/indirect-shell-true.js
@@ -0,0 +1,9 @@
+'use strict';
+
+const { execFile } = require('child_process');
+const options = {
+ encoding: 'utf8',
+ shell: true,
+};
+
+execFile('tool', [process.env.INPUT], options);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/nonconstant-command.js b/scripts/tests/fixtures/secure-process-execution/fail/nonconstant-command.js
new file mode 100644
index 000000000..eb5dca0f6
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/nonconstant-command.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const childProcess = require('child_process');
+
+childProcess.execSync(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/octal-module-specifier.js b/scripts/tests/fixtures/secure-process-execution/fail/octal-module-specifier.js
new file mode 100644
index 000000000..cde71361f
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/octal-module-specifier.js
@@ -0,0 +1 @@
+require('child\137process').exec(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/octal-shell-property.js b/scripts/tests/fixtures/secure-process-execution/fail/octal-shell-property.js
new file mode 100644
index 000000000..d4935eb3d
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/octal-shell-property.js
@@ -0,0 +1,3 @@
+const { spawn } = require('child_process');
+
+spawn('tool', [], { shell: false, 'sh\145ll': true });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/optional-call.js b/scripts/tests/fixtures/secure-process-execution/fail/optional-call.js
new file mode 100644
index 000000000..d1de3a81d
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/optional-call.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { exec } = require('child_process');
+
+exec?.(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/optional-computed-call.js b/scripts/tests/fixtures/secure-process-execution/fail/optional-computed-call.js
new file mode 100644
index 000000000..b0d6c0dd2
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/optional-computed-call.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const childProcess = require('child_process');
+
+childProcess['exec']?.(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/optional-computed-namespace.js b/scripts/tests/fixtures/secure-process-execution/fail/optional-computed-namespace.js
new file mode 100644
index 000000000..ea769a13f
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/optional-computed-namespace.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const childProcess = require('child_process');
+
+childProcess?.['exec']?.(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/optional-namespace-call.js b/scripts/tests/fixtures/secure-process-execution/fail/optional-namespace-call.js
new file mode 100644
index 000000000..e00487336
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/optional-namespace-call.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const childProcess = require('child_process');
+
+childProcess.exec?.(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/parameter-shadow.js b/scripts/tests/fixtures/secure-process-execution/fail/parameter-shadow.js
new file mode 100644
index 000000000..87119589c
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/parameter-shadow.js
@@ -0,0 +1,10 @@
+'use strict';
+
+const { exec } = require('child_process');
+const command = 'pac env who';
+
+function run(command) {
+ exec(command);
+}
+
+module.exports = { run };
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-method.js b/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-method.js
new file mode 100644
index 000000000..85139baaa
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-method.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { exec } = require('child_process');
+
+(exec)(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-namespace-method.js b/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-namespace-method.js
new file mode 100644
index 000000000..0e1dedbb2
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-namespace-method.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const childProcess = require('child_process');
+
+(childProcess.exec)(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-require.js b/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-require.js
new file mode 100644
index 000000000..3bed548a8
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/parenthesized-require.js
@@ -0,0 +1,3 @@
+'use strict';
+
+(require('child_process')).exec(process.env.COMMAND);
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/pre-fix-activation.js b/scripts/tests/fixtures/secure-process-execution/fail/pre-fix-activation.js
new file mode 100644
index 000000000..fdd51b078
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/pre-fix-activation.js
@@ -0,0 +1,12 @@
+'use strict';
+
+const { execSync } = require('child_process');
+
+function validate(checkScript, projectRoot) {
+ return execSync(`node "${checkScript}" --projectRoot "${projectRoot}"`, {
+ encoding: 'utf8',
+ timeout: 30000,
+ });
+}
+
+module.exports = { validate };
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/quoted-shell-true.js b/scripts/tests/fixtures/secure-process-execution/fail/quoted-shell-true.js
new file mode 100644
index 000000000..bd66db5ef
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/quoted-shell-true.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { spawn } = require('child_process');
+
+spawn('tool', [], { 'shell': true });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/shadowed-constant.js b/scripts/tests/fixtures/secure-process-execution/fail/shadowed-constant.js
new file mode 100644
index 000000000..9d8028b79
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/shadowed-constant.js
@@ -0,0 +1,10 @@
+'use strict';
+
+const { exec } = require('child_process');
+const command = process.env.COMMAND;
+exec(command);
+
+{
+ const command = 'pac env who';
+ void command;
+}
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/shell-true.js b/scripts/tests/fixtures/secure-process-execution/fail/shell-true.js
new file mode 100644
index 000000000..9560e3106
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/shell-true.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const childProcess = require('node:child_process');
+
+childProcess.spawn('tool', [process.argv[2]], { shell: true });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/spread-shell-options.js b/scripts/tests/fixtures/secure-process-execution/fail/spread-shell-options.js
new file mode 100644
index 000000000..781c1685b
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/spread-shell-options.js
@@ -0,0 +1,6 @@
+'use strict';
+
+const { spawn } = require('child_process');
+const inherited = { shell: true };
+
+spawn('tool', [], { ...inherited });
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/two-argument-options.js b/scripts/tests/fixtures/secure-process-execution/fail/two-argument-options.js
new file mode 100644
index 000000000..1ddabe025
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/two-argument-options.js
@@ -0,0 +1,9 @@
+'use strict';
+
+const { spawn } = require('child_process');
+
+function launch(options) {
+ spawn('tool', options);
+}
+
+module.exports = { launch };
diff --git a/scripts/tests/fixtures/secure-process-execution/fail/unsupported-syntax.js b/scripts/tests/fixtures/secure-process-execution/fail/unsupported-syntax.js
new file mode 100644
index 000000000..19d8ae25f
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/fail/unsupported-syntax.js
@@ -0,0 +1,4 @@
+@sealed
+class ToolRunner {}
+
+module.exports = ToolRunner;
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/comments-strings-regex.js b/scripts/tests/fixtures/secure-process-execution/pass/comments-strings-regex.js
new file mode 100644
index 000000000..ad11624c3
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/comments-strings-regex.js
@@ -0,0 +1,7 @@
+'use strict';
+
+const example = "execSync(`${process.env.INPUT}`)";
+const matcher = /spawn\("tool", args, \{ shell: true \}\)/;
+
+// execSync(`tool ${userInput}`);
+module.exports = { example, matcher };
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/commonjs-static-shell.js b/scripts/tests/fixtures/secure-process-execution/pass/commonjs-static-shell.js
new file mode 100644
index 000000000..bc8bdeaa8
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/commonjs-static-shell.js
@@ -0,0 +1,10 @@
+'use strict';
+
+const { execSync: run } = require('child_process');
+
+run(
+ 'pac env who',
+ {
+ encoding: 'utf8',
+ }
+);
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/control-flow-regex.js b/scripts/tests/fixtures/secure-process-execution/pass/control-flow-regex.js
new file mode 100644
index 000000000..2a611e1af
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/control-flow-regex.js
@@ -0,0 +1,6 @@
+'use strict';
+
+const ok = true;
+const value = 'example';
+
+if (ok) /require("child_process").exec(process.env.X)/.test(value);
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/esm-fixed-argv.js b/scripts/tests/fixtures/secure-process-execution/pass/esm-fixed-argv.js
new file mode 100644
index 000000000..e4bbc10d2
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/esm-fixed-argv.js
@@ -0,0 +1,8 @@
+import { execFileSync as runTool } from 'node:child_process';
+
+const userPath = process.env.USER_PATH;
+runTool(
+ 'C:\\Program Files\\Contoso\\tool.exe',
+ ['/tmp/site with spaces', 'C:\\sites\\demo & literal', userPath],
+ { shell: false }
+);
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/fixed-activation.js b/scripts/tests/fixtures/secure-process-execution/pass/fixed-activation.js
new file mode 100644
index 000000000..0c1785e69
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/fixed-activation.js
@@ -0,0 +1,13 @@
+'use strict';
+
+const { execFileSync } = require('child_process');
+
+function validate(checkScript, projectRoot) {
+ return execFileSync(process.execPath, [checkScript, '--projectRoot', projectRoot], {
+ encoding: 'utf8',
+ timeout: 30000,
+ shell: false,
+ });
+}
+
+module.exports = { validate };
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/namespace-promisify.js b/scripts/tests/fixtures/secure-process-execution/pass/namespace-promisify.js
new file mode 100644
index 000000000..b45eef6e5
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/namespace-promisify.js
@@ -0,0 +1,10 @@
+'use strict';
+
+const childProcess = require('node:child_process');
+const { promisify } = require('node:util');
+
+const run = promisify(childProcess.execFile);
+const options = { encoding: 'utf8', shell: false };
+
+run('pac', ['env', 'who'], options);
+childProcess.spawnSync(process.execPath, ['script.js', process.env.INPUT], options);
diff --git a/scripts/tests/fixtures/secure-process-execution/pass/static-template.js b/scripts/tests/fixtures/secure-process-execution/pass/static-template.js
new file mode 100644
index 000000000..d8e6ca352
--- /dev/null
+++ b/scripts/tests/fixtures/secure-process-execution/pass/static-template.js
@@ -0,0 +1,5 @@
+'use strict';
+
+const { exec } = require('child_process');
+
+exec(`pac auth who`);
diff --git a/scripts/tests/validate-secure-process-execution.test.js b/scripts/tests/validate-secure-process-execution.test.js
new file mode 100644
index 000000000..9975977b4
--- /dev/null
+++ b/scripts/tests/validate-secure-process-execution.test.js
@@ -0,0 +1,198 @@
+'use strict';
+
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('fs');
+const os = require('os');
+const path = require('path');
+const { spawnSync } = require('child_process');
+
+const {
+ AUDITED_EXCEPTIONS,
+ analyzeSource,
+ applyAuditedExceptions,
+ auditRepository,
+ listProductionJavaScript,
+ shouldScan,
+ validateExceptions,
+} = require('../validate-secure-process-execution');
+
+const REPOSITORY_ROOT = path.resolve(__dirname, '..', '..');
+const FIXTURES = path.join(__dirname, 'fixtures', 'secure-process-execution');
+const VALIDATOR = path.join(REPOSITORY_ROOT, 'scripts', 'validate-secure-process-execution.js');
+
+function fixture(group, name) {
+ const filePath = path.join(FIXTURES, group, name);
+ return {
+ path: `fixtures/${group}/${name}`,
+ source: fs.readFileSync(filePath, 'utf8'),
+ };
+}
+
+for (const name of fs.readdirSync(path.join(FIXTURES, 'pass')).sort()) {
+ test(`accepts safe fixture: ${name}`, () => {
+ const input = fixture('pass', name);
+ assert.deepEqual(analyzeSource(input.source, input.path), []);
+ });
+}
+
+const FAILING_FIXTURES = new Map([
+ ['ambiguous-options.js', 'ambiguous-shell-option'],
+ ['computed-member.js', 'ambiguous-child-process-call'],
+ ['computed-direct-require.js', 'nonconstant-shell-command'],
+ ['concatenated-command.js', 'concatenated-shell-command'],
+ ['default-esm-import.mjs', 'nonconstant-shell-command'],
+ ['direct-require.js', 'concatenated-shell-command'],
+ ['division-after-postfix.js', 'nonconstant-shell-command'],
+ ['dynamic-executable.js', 'nonconstant-executable'],
+ ['dynamic-template.js', 'dynamic-shell-command'],
+ ['duplicate-shell-property.js', 'shell-true'],
+ ['escaped-module-specifier.js', 'nonconstant-shell-command'],
+ ['escaped-shell-property.js', 'shell-true'],
+ ['even-escaped-template.js', 'dynamic-shell-command'],
+ ['indirect-shell-true.js', 'shell-true'],
+ ['nonconstant-command.js', 'nonconstant-shell-command'],
+ ['octal-module-specifier.js', 'nonconstant-shell-command'],
+ ['octal-shell-property.js', 'shell-true'],
+ ['optional-call.js', 'nonconstant-shell-command'],
+ ['optional-computed-call.js', 'nonconstant-shell-command'],
+ ['optional-computed-namespace.js', 'nonconstant-shell-command'],
+ ['optional-namespace-call.js', 'nonconstant-shell-command'],
+ ['parameter-shadow.js', 'nonconstant-shell-command'],
+ ['parenthesized-method.js', 'nonconstant-shell-command'],
+ ['parenthesized-namespace-method.js', 'nonconstant-shell-command'],
+ ['parenthesized-require.js', 'nonconstant-shell-command'],
+ ['pre-fix-activation.js', 'dynamic-shell-command'],
+ ['quoted-shell-true.js', 'shell-true'],
+ ['shadowed-constant.js', 'nonconstant-shell-command'],
+ ['shell-true.js', 'shell-true'],
+ ['spread-shell-options.js', 'ambiguous-shell-option'],
+ ['two-argument-options.js', 'ambiguous-shell-option'],
+ ['unsupported-syntax.js', 'unsupported-source-syntax'],
+]);
+
+for (const [name, expectedRule] of FAILING_FIXTURES) {
+ test(`rejects unsafe fixture: ${name}`, () => {
+ const input = fixture('fail', name);
+ const findings = analyzeSource(input.source, input.path);
+ assert.ok(
+ findings.some((item) => item.rule === expectedRule),
+ `expected ${expectedRule}; received ${JSON.stringify(findings, null, 2)}`
+ );
+ assert.ok(findings.every((item) => item.line > 0 && item.column > 0));
+ });
+}
+
+test('pre-fix activation shell command is red and argv replacement is green', () => {
+ const before = fixture('fail', 'pre-fix-activation.js');
+ const after = fixture('pass', 'fixed-activation.js');
+
+ assert.equal(analyzeSource(before.source, before.path)[0].rule, 'dynamic-shell-command');
+ assert.deepEqual(analyzeSource(after.source, after.path), []);
+});
+
+test('production path rules are explicit and exclude tests, fixtures, generated, vendor, and assets', () => {
+ const accepted = [
+ 'plugins/power-pages/hooks/post-tool.js',
+ 'plugins/power-pages/scripts/tool.js',
+ 'plugins/power-pages/scripts/lib/tool.js',
+ 'plugins/power-pages/skills/example/scripts/validate-example.js',
+ 'plugins/power-pages/skills/example/scripts/validate-example.mjs',
+ 'plugins/power-pages/scripts/tool.cjs',
+ ];
+ const rejected = [
+ 'plugins/power-pages/scripts/tests/tool.test.js',
+ 'plugins/power-pages/scripts/fixtures/tool.js',
+ 'plugins/power-pages/scripts/generated/tool.js',
+ 'plugins/power-pages/scripts/vendor/tool.js',
+ 'plugins/power-pages/skills/example/assets/tool.js',
+ 'plugins/power-pages/skills/example/references/tool.js',
+ 'plugins/power-pages/scripts/tool.json',
+ ];
+
+ for (const filePath of accepted) assert.equal(shouldScan(filePath), true, filePath);
+ for (const filePath of rejected) assert.equal(shouldScan(filePath), false, filePath);
+});
+
+test('repository walk applies the reviewed production path rules', (t) => {
+ const root = fs.mkdtempSync(path.join(os.tmpdir(), 'secure-process-paths-'));
+ t.after(() => fs.rmSync(root, { recursive: true, force: true }));
+ const files = [
+ 'plugins/power-pages/hooks/hook.js',
+ 'plugins/power-pages/scripts/tool.js',
+ 'plugins/power-pages/scripts/tests/tool.js',
+ 'plugins/power-pages/skills/demo/scripts/run.js',
+ 'plugins/power-pages/skills/demo/assets/run.js',
+ ];
+ for (const filePath of files) {
+ const absolutePath = path.join(root, filePath);
+ fs.mkdirSync(path.dirname(absolutePath), { recursive: true });
+ fs.writeFileSync(absolutePath, "'use strict';\n");
+ }
+
+ assert.deepEqual(listProductionJavaScript(root), [
+ 'plugins/power-pages/hooks/hook.js',
+ 'plugins/power-pages/scripts/tool.js',
+ 'plugins/power-pages/skills/demo/scripts/run.js',
+ ]);
+});
+
+test('audited exceptions require exact path, rule, callee, and call and fail on drift', () => {
+ const filePath = 'plugins/power-pages/scripts/legacy.js';
+ const source = [
+ "const { spawn } = require('child_process');",
+ "spawn('tool', [process.env.INPUT], { shell: true });",
+ '',
+ ].join('\n');
+ const originalFinding = analyzeSource(source, filePath)[0];
+ const exception = {
+ path: filePath,
+ rule: originalFinding.rule,
+ callee: originalFinding.callee,
+ call: originalFinding.call,
+ reason: 'Tracked legacy launch awaiting removal.',
+ };
+
+ const exact = applyAuditedExceptions([originalFinding], [exception]);
+ assert.deepEqual(exact.findings, []);
+ assert.deepEqual(exact.audited, [exception]);
+
+ const driftedFinding = analyzeSource(source.replace("'tool'", "'other-tool'"), filePath)[0];
+ const drifted = applyAuditedExceptions([driftedFinding], [exception]);
+ assert.deepEqual(
+ drifted.findings.map((item) => item.rule).sort(),
+ ['shell-true', 'stale-audited-exception']
+ );
+ assert.deepEqual(drifted.audited, []);
+});
+
+test('audited exception schema requires a review reason', () => {
+ assert.throws(
+ () => validateExceptions([{
+ path: 'plugins/power-pages/scripts/legacy.js',
+ rule: 'shell-true',
+ callee: 'spawn',
+ call: "spawn ( 'tool' , [ ] , { shell : true } )",
+ reason: '',
+ }]),
+ /reason/
+ );
+});
+
+test('repository-wide audit is clean with no audited exceptions', () => {
+ const result = auditRepository(REPOSITORY_ROOT);
+ assert.deepEqual(result.findings, []);
+ assert.deepEqual(AUDITED_EXCEPTIONS, []);
+ assert.deepEqual(result.audited, []);
+ assert.ok(result.files.length > 100, 'expected a repository-wide production scan');
+});
+
+test('CLI audit emits actionable diagnostics and succeeds for the repository', () => {
+ const result = spawnSync(process.execPath, [VALIDATOR, '--root', REPOSITORY_ROOT], {
+ encoding: 'utf8',
+ });
+
+ assert.equal(result.status, 0, result.stderr);
+ assert.doesNotMatch(result.stdout, /^AUDITED /m);
+ assert.match(result.stdout, /validation passed \(\d+ production files, 0 audited exceptions\)/);
+});
diff --git a/scripts/validate-secure-process-execution.js b/scripts/validate-secure-process-execution.js
new file mode 100644
index 000000000..8f3d023b9
--- /dev/null
+++ b/scripts/validate-secure-process-execution.js
@@ -0,0 +1,1193 @@
+#!/usr/bin/env node
+
+'use strict';
+
+/**
+ * Deterministic child_process policy for production Power Pages JavaScript.
+ *
+ * This repository intentionally has no root npm dependency graph, so CI cannot
+ * assume an installed parser. The analyzer below uses a conservative JavaScript
+ * tokenizer and balanced-token call reader instead:
+ *
+ * - CommonJS and ESM child_process imports are recognized, including aliases,
+ * namespace imports, direct require(...).method calls, simple reassignment,
+ * default-parameter aliases, and promisify(method) aliases.
+ * - Comments, strings, regular expressions, multiline calls, and templates are
+ * tokenized so text that only looks like a process launch is ignored.
+ * - exec/execSync commands must be one static string or static template literal.
+ * Concatenation, interpolation, variables, and other expressions fail closed.
+ * - execFile/spawn families require a fixed executable string or process.execPath.
+ * Their options must omit shell, set shell:false, or resolve from a local const
+ * object. shell:true and unresolved option shapes fail closed.
+ *
+ * This is not a general JavaScript parser. Unsupported lexical syntax and
+ * ambiguous child_process member/call shapes are findings rather than silently
+ * skipped. That fail-closed boundary keeps future syntax changes reviewable
+ * without adding a network dependency to CI.
+ */
+
+const fs = require('fs');
+const path = require('path');
+
+const REPOSITORY_ROOT = path.resolve(__dirname, '..');
+const POWER_PAGES_ROOT = 'plugins/power-pages';
+const CHILD_PROCESS_MODULES = new Set(['child_process', 'node:child_process']);
+const PROCESS_METHODS = new Set([
+ 'exec',
+ 'execSync',
+ 'execFile',
+ 'execFileSync',
+ 'spawn',
+ 'spawnSync',
+]);
+const SHELL_METHODS = new Set(['exec', 'execSync']);
+const ARGV_METHODS = new Set(['execFile', 'execFileSync', 'spawn', 'spawnSync']);
+
+// Production scope is intentionally narrower than "all JavaScript under the
+// plugin". Skill templates are user application source, not plugin process
+// execution code. Tests and generated/vendor trees are excluded by reviewed,
+// named path segments instead of a broad substring or file-name suppression.
+const SCAN_ROOTS = Object.freeze([
+ `${POWER_PAGES_ROOT}/hooks`,
+ `${POWER_PAGES_ROOT}/scripts`,
+ `${POWER_PAGES_ROOT}/skills`,
+]);
+const EXCLUDED_DIRECTORY_NAMES = new Set([
+ 'test',
+ 'tests',
+ 'fixture',
+ 'fixtures',
+ 'generated',
+ 'vendor',
+ '_vendor',
+ 'node_modules',
+]);
+
+// Exceptions must remain rare, exact, and removable. The current production
+// tree needs none; drift behavior stays covered by synthetic tests below.
+const AUDITED_EXCEPTIONS = Object.freeze([]);
+
+function decodeStringLiteral(raw) {
+ if (typeof raw !== 'string' || raw.length < 2) return null;
+ const quote = raw[0];
+ if ((quote !== "'" && quote !== '"') || raw[raw.length - 1] !== quote) return null;
+ let value = '';
+ for (let i = 1; i < raw.length - 1; i += 1) {
+ const char = raw[i];
+ if (char !== '\\') {
+ value += char;
+ continue;
+ }
+ i += 1;
+ const escaped = raw[i];
+ if (escaped === undefined) return null;
+ const simple = {
+ b: '\b',
+ f: '\f',
+ n: '\n',
+ r: '\r',
+ t: '\t',
+ v: '\v',
+ 0: '\0',
+ '\\': '\\',
+ "'": "'",
+ '"': '"',
+ };
+ if (Object.prototype.hasOwnProperty.call(simple, escaped)) {
+ value += simple[escaped];
+ } else if (/[0-7]/.test(escaped)) {
+ let octal = escaped;
+ while (octal.length < 3 && /[0-7]/.test(raw[i + 1] || '')) {
+ octal += raw[i + 1];
+ i += 1;
+ }
+ value += String.fromCodePoint(Number.parseInt(octal, 8));
+ } else if (escaped === 'x') {
+ const hex = raw.slice(i + 1, i + 3);
+ if (!/^[0-9A-Fa-f]{2}$/.test(hex)) return null;
+ value += String.fromCodePoint(Number.parseInt(hex, 16));
+ i += 2;
+ } else if (escaped === 'u') {
+ if (raw[i + 1] === '{') {
+ const close = raw.indexOf('}', i + 2);
+ if (close === -1) return null;
+ const hex = raw.slice(i + 2, close);
+ if (!/^[0-9A-Fa-f]{1,6}$/.test(hex)) return null;
+ value += String.fromCodePoint(Number.parseInt(hex, 16));
+ i = close;
+ } else {
+ const hex = raw.slice(i + 1, i + 5);
+ if (!/^[0-9A-Fa-f]{4}$/.test(hex)) return null;
+ value += String.fromCodePoint(Number.parseInt(hex, 16));
+ i += 4;
+ }
+ } else if (escaped === '\n') {
+ // JavaScript line continuation contributes no character.
+ } else {
+ value += escaped;
+ }
+ }
+ return value;
+}
+
+function toPosix(filePath) {
+ return filePath.replace(/\\/g, '/');
+}
+
+function isIdentifierStart(char) {
+ return /[A-Za-z_$]/.test(char);
+}
+
+function isIdentifierPart(char) {
+ return /[A-Za-z0-9_$]/.test(char);
+}
+
+function tokenize(source) {
+ const tokens = [];
+ let index = 0;
+ let line = 1;
+ let column = 1;
+
+ function advance() {
+ const char = source[index++];
+ if (char === '\n') {
+ line += 1;
+ column = 1;
+ } else {
+ column += 1;
+ }
+ return char;
+ }
+
+ function token(type, start, startLine, startColumn, extra = {}) {
+ tokens.push({
+ type,
+ raw: source.slice(start, index),
+ start,
+ end: index,
+ line: startLine,
+ column: startColumn,
+ ...extra,
+ });
+ }
+
+ function fail(message) {
+ const error = new SyntaxError(message);
+ error.line = line;
+ error.column = column;
+ throw error;
+ }
+
+ function skipQuoted(quote) {
+ advance();
+ while (index < source.length) {
+ const char = advance();
+ if (char === '\\') {
+ if (index < source.length) advance();
+ } else if (char === quote) {
+ return;
+ } else if (char === '\n' && quote !== '`') {
+ fail('unterminated string literal');
+ }
+ }
+ fail(`unterminated ${quote === '`' ? 'template' : 'string'} literal`);
+ }
+
+ function skipLineComment() {
+ advance();
+ advance();
+ while (index < source.length && source[index] !== '\n') advance();
+ }
+
+ function skipBlockComment() {
+ advance();
+ advance();
+ while (index < source.length) {
+ if (source[index] === '*' && source[index + 1] === '/') {
+ advance();
+ advance();
+ return;
+ }
+ advance();
+ }
+ fail('unterminated block comment');
+ }
+
+ function skipTemplateInterpolation() {
+ let depth = 1;
+ let previousSignificant = null;
+ while (index < source.length) {
+ const char = source[index];
+ if (char === "'" || char === '"') {
+ skipQuoted(char);
+ previousSignificant = 'value';
+ } else if (char === '`') {
+ skipTemplate();
+ previousSignificant = 'value';
+ } else if (char === '/' && source[index + 1] === '/') {
+ skipLineComment();
+ } else if (char === '/' && source[index + 1] === '*') {
+ skipBlockComment();
+ } else if (char === '/' &&
+ (previousSignificant === null || '([{:;,=!?&|'.includes(previousSignificant))) {
+ // Template expressions commonly contain regex arguments, e.g.
+ // `${value.replace(/\\/g, '\\\\')}`. Strings inside a regex are not
+ // JavaScript strings, so consume the regex before looking for `}`.
+ let inClass = false;
+ advance();
+ while (index < source.length) {
+ const regexChar = advance();
+ if (regexChar === '\\') {
+ if (index < source.length) advance();
+ } else if (regexChar === '[') {
+ inClass = true;
+ } else if (regexChar === ']') {
+ inClass = false;
+ } else if (regexChar === '/' && !inClass) {
+ while (/[A-Za-z]/.test(source[index] || '')) advance();
+ break;
+ } else if (regexChar === '\n') {
+ fail('unterminated regular expression in template interpolation');
+ }
+ }
+ previousSignificant = 'value';
+ } else {
+ advance();
+ if (char === '{') depth += 1;
+ if (char === '}') {
+ depth -= 1;
+ if (depth === 0) return;
+ }
+ if (!/\s/.test(char)) previousSignificant = char;
+ }
+ }
+ fail('unterminated template interpolation');
+ }
+
+ function skipTemplate() {
+ let dynamic = false;
+ advance();
+ while (index < source.length) {
+ const char = source[index];
+ if (char === '\\') {
+ advance();
+ if (index < source.length) advance();
+ } else if (char === '`') {
+ advance();
+ return dynamic;
+ } else if (char === '$' && source[index + 1] === '{') {
+ dynamic = true;
+ advance();
+ advance();
+ skipTemplateInterpolation();
+ } else {
+ advance();
+ }
+ }
+ fail('unterminated template literal');
+ }
+
+ function canStartRegex() {
+ const previous = tokens[tokens.length - 1];
+ if (!previous) return true;
+ if (previous.type === 'identifier' &&
+ ['return', 'case', 'throw', 'yield', 'await', 'typeof', 'instanceof',
+ 'in', 'of', 'delete', 'void', 'new'].includes(previous.raw)) {
+ return true;
+ }
+ if (previous.type === 'identifier' || previous.type === 'number' ||
+ previous.type === 'string' || previous.type === 'template' ||
+ previous.type === 'regex') {
+ return false;
+ }
+ if (previous.raw === ')') {
+ let depth = 1;
+ for (let i = tokens.length - 2; i >= 0; i -= 1) {
+ if (tokens[i].raw === ')') depth += 1;
+ if (tokens[i].raw === '(') {
+ depth -= 1;
+ if (depth === 0) {
+ return ['if', 'while', 'for', 'with', 'catch', 'switch'].includes(tokens[i - 1]?.raw);
+ }
+ }
+ }
+ }
+ return ![')', ']', '}', '++', '--'].includes(previous.raw);
+ }
+
+ function scanRegex() {
+ const start = index;
+ const startLine = line;
+ const startColumn = column;
+ let inClass = false;
+ advance();
+ while (index < source.length) {
+ const char = advance();
+ if (char === '\\') {
+ if (index < source.length) advance();
+ } else if (char === '[') {
+ inClass = true;
+ } else if (char === ']') {
+ inClass = false;
+ } else if (char === '/' && !inClass) {
+ while (/[A-Za-z]/.test(source[index] || '')) advance();
+ token('regex', start, startLine, startColumn);
+ return;
+ } else if (char === '\n') {
+ fail('unterminated regular expression literal');
+ }
+ }
+ fail('unterminated regular expression literal');
+ }
+
+ if (source.startsWith('#!')) {
+ while (index < source.length && source[index] !== '\n') advance();
+ }
+
+ while (index < source.length) {
+ const char = source[index];
+ if (/\s/.test(char)) {
+ advance();
+ continue;
+ }
+ if (char === '/' && source[index + 1] === '/') {
+ skipLineComment();
+ continue;
+ }
+ if (char === '/' && source[index + 1] === '*') {
+ skipBlockComment();
+ continue;
+ }
+
+ const start = index;
+ const startLine = line;
+ const startColumn = column;
+
+ if (char === "'" || char === '"') {
+ skipQuoted(char);
+ token('string', start, startLine, startColumn);
+ continue;
+ }
+ if (char === '`') {
+ const dynamic = skipTemplate();
+ token('template', start, startLine, startColumn, {
+ dynamic,
+ });
+ continue;
+ }
+ if (char === '/' && canStartRegex()) {
+ scanRegex();
+ continue;
+ }
+ if (isIdentifierStart(char)) {
+ advance();
+ while (isIdentifierPart(source[index] || '')) advance();
+ token('identifier', start, startLine, startColumn);
+ continue;
+ }
+ if (/[0-9]/.test(char)) {
+ advance();
+ while (/[A-Za-z0-9_.]/.test(source[index] || '')) advance();
+ token('number', start, startLine, startColumn);
+ continue;
+ }
+
+ const three = source.slice(index, index + 3);
+ const two = source.slice(index, index + 2);
+ if (['===', '!==', '>>>', '**=', '&&=', '||=', '??=', '...'].includes(three)) {
+ advance();
+ advance();
+ advance();
+ } else if ([
+ '=>', '==', '!=', '<=', '>=', '&&', '||', '??', '?.', '++', '--',
+ '+=', '-=', '*=', '/=', '%=', '**', '<<', '>>', '&=', '|=', '^=',
+ ].includes(two)) {
+ advance();
+ advance();
+ } else if ('()[]{}.,;:+-*/%!?=<>|&^~'.includes(char)) {
+ advance();
+ } else {
+ fail(`unsupported character ${JSON.stringify(char)}`);
+ }
+ token('punctuator', start, startLine, startColumn);
+ }
+
+ return tokens;
+}
+
+function matchingIndex(tokens, openIndex) {
+ const pairs = { '(': ')', '[': ']', '{': '}' };
+ const open = tokens[openIndex]?.raw;
+ const expected = pairs[open];
+ if (!expected) return -1;
+ const stack = [expected];
+ for (let i = openIndex + 1; i < tokens.length; i += 1) {
+ const raw = tokens[i].raw;
+ if (pairs[raw]) {
+ stack.push(pairs[raw]);
+ } else if (raw === stack[stack.length - 1]) {
+ stack.pop();
+ if (stack.length === 0) return i;
+ }
+ }
+ return -1;
+}
+
+function splitTopLevel(tokens, start, end, delimiter = ',') {
+ const ranges = [];
+ const stack = [];
+ let rangeStart = start;
+ const pairs = { '(': ')', '[': ']', '{': '}' };
+
+ for (let i = start; i < end; i += 1) {
+ const raw = tokens[i].raw;
+ if (pairs[raw]) {
+ stack.push(pairs[raw]);
+ } else if (raw === stack[stack.length - 1]) {
+ stack.pop();
+ } else if (raw === delimiter && stack.length === 0) {
+ ranges.push([rangeStart, i]);
+ rangeStart = i + 1;
+ }
+ }
+ ranges.push([rangeStart, end]);
+ return ranges.filter(([from, to]) => from < to);
+}
+
+function isChildProcessRequire(tokens, requireIndex) {
+ return tokens[requireIndex]?.raw === 'require' &&
+ tokens[requireIndex + 1]?.raw === '(' &&
+ tokens[requireIndex + 2]?.type === 'string' &&
+ CHILD_PROCESS_MODULES.has(decodeStringLiteral(tokens[requireIndex + 2].raw)) &&
+ tokens[requireIndex + 3]?.raw === ')';
+}
+
+function childProcessRequireExpression(tokens, start) {
+ let index = start;
+ let wrappers = 0;
+ while (tokens[index]?.raw === '(') {
+ wrappers += 1;
+ index += 1;
+ }
+ if (!isChildProcessRequire(tokens, index)) return null;
+ let end = index + 4;
+ while (wrappers > 0 && tokens[end]?.raw === ')') {
+ wrappers -= 1;
+ end += 1;
+ }
+ return wrappers === 0 ? { requireIndex: index, end } : null;
+}
+
+function parseDestructuredMethods(tokens, openIndex, closeIndex, methodBindings) {
+ for (const [start, end] of splitTopLevel(tokens, openIndex + 1, closeIndex)) {
+ const property = tokens[start]?.raw;
+ if (!PROCESS_METHODS.has(property)) continue;
+ let alias = property;
+ if (tokens[start + 1]?.raw === ':' && tokens[start + 2]?.type === 'identifier') {
+ alias = tokens[start + 2].raw;
+ } else if (tokens[start + 1]?.raw === 'as' && tokens[start + 2]?.type === 'identifier') {
+ alias = tokens[start + 2].raw;
+ }
+ methodBindings.set(alias, property);
+ }
+}
+
+function expressionEnd(tokens, start) {
+ const stack = [];
+ const pairs = { '(': ')', '[': ']', '{': '}' };
+ for (let i = start; i < tokens.length; i += 1) {
+ const raw = tokens[i].raw;
+ if (pairs[raw]) {
+ stack.push(pairs[raw]);
+ } else if (raw === stack[stack.length - 1]) {
+ stack.pop();
+ } else if (stack.length === 0 && [')', ']', '}'].includes(raw)) {
+ return i;
+ } else if (stack.length === 0 && [',', ';'].includes(raw)) {
+ return i;
+ }
+ }
+ return tokens.length;
+}
+
+function discoverBindings(tokens) {
+ const methodBindings = new Map();
+ const namespaceBindings = new Set();
+ const constBindings = new Map();
+
+ for (let i = 0; i < tokens.length; i += 1) {
+ if (tokens[i].raw === 'import') {
+ if (tokens[i + 1]?.raw === '{') {
+ const close = matchingIndex(tokens, i + 1);
+ if (close !== -1 && tokens[close + 1]?.raw === 'from' &&
+ tokens[close + 2]?.type === 'string' &&
+ CHILD_PROCESS_MODULES.has(decodeStringLiteral(tokens[close + 2].raw))) {
+ parseDestructuredMethods(tokens, i + 1, close, methodBindings);
+ }
+ } else if (tokens[i + 1]?.raw === '*' && tokens[i + 2]?.raw === 'as' &&
+ tokens[i + 3]?.type === 'identifier' &&
+ tokens[i + 4]?.raw === 'from' &&
+ tokens[i + 5]?.type === 'string' &&
+ CHILD_PROCESS_MODULES.has(decodeStringLiteral(tokens[i + 5].raw))) {
+ namespaceBindings.add(tokens[i + 3].raw);
+ } else if (tokens[i + 1]?.type === 'identifier' &&
+ tokens[i + 2]?.raw === 'from' &&
+ tokens[i + 3]?.type === 'string' &&
+ CHILD_PROCESS_MODULES.has(decodeStringLiteral(tokens[i + 3].raw))) {
+ namespaceBindings.add(tokens[i + 1].raw);
+ }
+ }
+
+ const required = childProcessRequireExpression(tokens, i);
+ if (!required) continue;
+ const equalsIndex = i - 1;
+ if (tokens[equalsIndex]?.raw !== '=') continue;
+
+ if (tokens[equalsIndex - 1]?.type === 'identifier') {
+ namespaceBindings.add(tokens[equalsIndex - 1].raw);
+ } else if (tokens[equalsIndex - 1]?.raw === '}') {
+ let open = equalsIndex - 1;
+ let depth = 1;
+ while (open > 0 && depth > 0) {
+ open -= 1;
+ if (tokens[open].raw === '}') depth += 1;
+ if (tokens[open].raw === '{') depth -= 1;
+ }
+ if (depth === 0) parseDestructuredMethods(tokens, open, equalsIndex - 1, methodBindings);
+ }
+ }
+
+ // const values are used only for local, single-expression resolution. A name
+ // declared more than once is deliberately unresolved: without a full scope
+ // tree, selecting one declaration could let a later/shadowed safe value mask
+ // an earlier unsafe call.
+ for (let i = 0; i < tokens.length - 2; i += 1) {
+ if (tokens[i].raw !== 'const' || tokens[i + 1]?.type !== 'identifier' ||
+ tokens[i + 2]?.raw !== '=') {
+ continue;
+ }
+ const end = expressionEnd(tokens, i + 3);
+ const name = tokens[i + 1].raw;
+ constBindings.set(name, constBindings.has(name) ? null : [i + 3, end]);
+ }
+
+ const shadowedNames = new Set();
+ for (let i = 0; i < tokens.length; i += 1) {
+ if (['let', 'var'].includes(tokens[i].raw) && tokens[i + 1]?.type === 'identifier') {
+ shadowedNames.add(tokens[i + 1].raw);
+ }
+ if (tokens[i].raw === 'function') {
+ let open = i + 1;
+ while (open < tokens.length && tokens[open].raw !== '(' &&
+ tokens[open].raw !== '{' && tokens[open].raw !== ';') {
+ open += 1;
+ }
+ const close = tokens[open]?.raw === '(' ? matchingIndex(tokens, open) : -1;
+ if (close !== -1) {
+ for (let j = open + 1; j < close; j += 1) {
+ if (tokens[j].type === 'identifier') shadowedNames.add(tokens[j].raw);
+ }
+ }
+ }
+ if (tokens[i].raw === 'catch' && tokens[i + 1]?.raw === '(') {
+ const close = matchingIndex(tokens, i + 1);
+ for (let j = i + 2; close !== -1 && j < close; j += 1) {
+ if (tokens[j].type === 'identifier') shadowedNames.add(tokens[j].raw);
+ }
+ }
+ if (tokens[i].type === 'identifier' && tokens[i + 1]?.raw === '=>') {
+ shadowedNames.add(tokens[i].raw);
+ }
+ if (tokens[i].raw === '(') {
+ const close = matchingIndex(tokens, i);
+ if (close !== -1 && tokens[close + 1]?.raw === '=>') {
+ for (let j = i + 1; j < close; j += 1) {
+ if (tokens[j].type === 'identifier') shadowedNames.add(tokens[j].raw);
+ }
+ }
+ }
+ }
+ for (const name of shadowedNames) {
+ if (constBindings.has(name)) constBindings.set(name, null);
+ }
+
+ // Resolve require(...).method assignments after namespace discovery.
+ for (let i = 0; i < tokens.length - 6; i += 1) {
+ const required = childProcessRequireExpression(tokens, i + 3);
+ if (tokens[i].raw !== 'const' || tokens[i + 1]?.type !== 'identifier' ||
+ tokens[i + 2]?.raw !== '=' || !required) {
+ continue;
+ }
+ if (tokens[required.end]?.raw === '.' && PROCESS_METHODS.has(tokens[required.end + 1]?.raw)) {
+ methodBindings.set(tokens[i + 1].raw, tokens[required.end + 1].raw);
+ }
+ }
+
+ // Simple aliases appear in dependency-injection fallbacks, default parameters,
+ // and promisify wrappers. Iterate because an alias may point at another alias.
+ let changed = true;
+ while (changed) {
+ changed = false;
+ for (let i = 0; i < tokens.length - 2; i += 1) {
+ if (tokens[i].type !== 'identifier' || tokens[i + 1]?.raw !== '=') continue;
+ const end = expressionEnd(tokens, i + 2);
+ const referenced = new Set();
+ for (let j = i + 2; j < end; j += 1) {
+ const method = methodBindings.get(tokens[j].raw);
+ // A method identifier followed by `(` is a call result, not another
+ // callable alias. Without this distinction, `stdout = execFileSync(...)`
+ // would taint every later variable derived from stdout as a process API.
+ if (method && tokens[j + 1]?.raw !== '(') referenced.add(method);
+ if (namespaceBindings.has(tokens[j].raw) &&
+ tokens[j + 1]?.raw === '.' &&
+ PROCESS_METHODS.has(tokens[j + 2]?.raw) &&
+ tokens[j + 3]?.raw !== '(') {
+ referenced.add(tokens[j + 2].raw);
+ }
+ }
+ if (referenced.size === 1 && !methodBindings.has(tokens[i].raw)) {
+ methodBindings.set(tokens[i].raw, [...referenced][0]);
+ changed = true;
+ }
+ }
+ }
+
+ return { methodBindings, namespaceBindings, constBindings };
+}
+
+function resolveRange(tokens, range, constBindings, seen = new Set()) {
+ let [start, end] = range;
+ while (start < end && tokens[start]?.raw === '(' && matchingIndex(tokens, start) === end - 1) {
+ start += 1;
+ end -= 1;
+ }
+ if (end - start === 1 && tokens[start]?.type === 'identifier') {
+ const name = tokens[start].raw;
+ if (seen.has(name)) return [start, end];
+ const binding = constBindings.get(name);
+ if (Array.isArray(binding)) {
+ seen.add(name);
+ return resolveRange(tokens, binding, constBindings, seen);
+ }
+ }
+ return [start, end];
+}
+
+function canonicalCall(tokens, start, end) {
+ return tokens.slice(start, end).map((item) => item.raw).join(' ');
+}
+
+function finding(filePath, call, rule, message, token = call.token) {
+ return {
+ path: filePath,
+ line: token.line,
+ column: token.column,
+ rule,
+ callee: call.method,
+ call: call.canonical,
+ message,
+ };
+}
+
+function classifyShellCommand(tokens, range, constBindings) {
+ const [start, end] = resolveRange(tokens, range, constBindings);
+ if (end - start === 1 && tokens[start].type === 'string') return 'static';
+ if (end - start === 1 && tokens[start].type === 'template') {
+ return tokens[start].dynamic ? 'dynamic-template' : 'static';
+ }
+ if (tokens.slice(start, end).some((item) => item.raw === '+')) return 'concatenation';
+ return 'nonconstant';
+}
+
+function isFixedExecutable(tokens, range, constBindings) {
+ const [start, end] = resolveRange(tokens, range, constBindings);
+ if (end - start === 1 && tokens[start].type === 'string') return true;
+ return end - start === 3 &&
+ tokens[start].raw === 'process' &&
+ tokens[start + 1].raw === '.' &&
+ tokens[start + 2].raw === 'execPath';
+}
+
+function shellProperty(tokens, range, constBindings) {
+ const [start, end] = resolveRange(tokens, range, constBindings);
+ if (tokens[start]?.raw !== '{' || matchingIndex(tokens, start) !== end - 1) {
+ return 'ambiguous';
+ }
+
+ let shell = 'absent';
+ for (const [propertyStart, propertyEnd] of splitTopLevel(tokens, start + 1, end - 1)) {
+ if (tokens[propertyStart]?.raw === '...') return 'ambiguous';
+
+ let key = null;
+ let colonIndex = propertyStart + 1;
+ const first = tokens[propertyStart];
+ if (first?.type === 'identifier') {
+ key = first.raw;
+ } else if (first?.type === 'string') {
+ key = decodeStringLiteral(first.raw);
+ } else if (first?.raw === '[') {
+ const close = matchingIndex(tokens, propertyStart);
+ if (close === propertyStart + 2 && tokens[propertyStart + 1]?.type === 'string') {
+ key = decodeStringLiteral(tokens[propertyStart + 1].raw);
+ colonIndex = close + 1;
+ } else {
+ // A computed key could evaluate to "shell".
+ return 'ambiguous';
+ }
+ }
+
+ if (['get', 'set', 'async'].includes(key) && tokens[propertyStart + 1]?.type === 'identifier') {
+ key = tokens[propertyStart + 1].raw;
+ colonIndex = propertyStart + 2;
+ }
+
+ if (key !== 'shell') {
+ continue;
+ }
+ if (tokens[colonIndex]?.raw !== ':') return 'ambiguous';
+ const value = resolveRange(tokens, [colonIndex + 1, propertyEnd], constBindings);
+ if (value[1] - value[0] === 1 && tokens[value[0]].raw === 'true') {
+ shell = 'true';
+ continue;
+ }
+ if (value[1] - value[0] === 1 && tokens[value[0]].raw === 'false') {
+ shell = 'false';
+ continue;
+ }
+ return 'ambiguous';
+ }
+ return shell;
+}
+
+function findCalls(tokens, bindings) {
+ const calls = [];
+ const { methodBindings, namespaceBindings } = bindings;
+
+ for (let i = 0; i < tokens.length; i += 1) {
+ let method = null;
+ let openIndex = -1;
+ let callStart = i;
+
+ if (methodBindings.has(tokens[i].raw) && tokens[i + 1]?.raw === '(') {
+ method = methodBindings.get(tokens[i].raw);
+ openIndex = i + 1;
+ } else if (methodBindings.has(tokens[i].raw) &&
+ tokens[i + 1]?.raw === '?.' &&
+ tokens[i + 2]?.raw === '(') {
+ method = methodBindings.get(tokens[i].raw);
+ openIndex = i + 2;
+ } else if (tokens[i].raw === '(' &&
+ methodBindings.has(tokens[i + 1]?.raw) &&
+ tokens[i + 2]?.raw === ')' &&
+ tokens[i + 3]?.raw === '(') {
+ method = methodBindings.get(tokens[i + 1].raw);
+ openIndex = i + 3;
+ } else if (namespaceBindings.has(tokens[i].raw) &&
+ ['.', '?.'].includes(tokens[i + 1]?.raw) &&
+ PROCESS_METHODS.has(tokens[i + 2]?.raw) &&
+ tokens[i + 3]?.raw === '(') {
+ method = tokens[i + 2].raw;
+ openIndex = i + 3;
+ } else if (namespaceBindings.has(tokens[i].raw) &&
+ ['.', '?.'].includes(tokens[i + 1]?.raw) &&
+ PROCESS_METHODS.has(tokens[i + 2]?.raw) &&
+ tokens[i + 3]?.raw === '?.' &&
+ tokens[i + 4]?.raw === '(') {
+ method = tokens[i + 2].raw;
+ openIndex = i + 4;
+ } else if (namespaceBindings.has(tokens[i].raw) && tokens[i + 1]?.raw === '[') {
+ const close = matchingIndex(tokens, i + 1);
+ if (close !== -1 &&
+ (tokens[close + 1]?.raw === '(' ||
+ (tokens[close + 1]?.raw === '?.' && tokens[close + 2]?.raw === '('))) {
+ const member = tokens[i + 2];
+ const memberName = member?.type === 'string' ? decodeStringLiteral(member.raw) : null;
+ if (close === i + 3 && PROCESS_METHODS.has(memberName)) {
+ method = memberName;
+ if (tokens[close + 1]?.raw === '?.' && tokens[close + 2]?.raw === '(') {
+ openIndex = close + 2;
+ } else {
+ openIndex = tokens[close + 1]?.raw === '?.' ? close + 2 : close + 1;
+ }
+ } else {
+ calls.push({
+ ambiguous: true,
+ method: 'unknown',
+ token: tokens[i],
+ canonical: canonicalCall(tokens, i, Math.min(close + 2, tokens.length)),
+ });
+ continue;
+ }
+ }
+ } else if (namespaceBindings.has(tokens[i].raw) &&
+ tokens[i + 1]?.raw === '?.' &&
+ tokens[i + 2]?.raw === '[') {
+ const close = matchingIndex(tokens, i + 2);
+ if (close !== -1 &&
+ (tokens[close + 1]?.raw === '(' ||
+ (tokens[close + 1]?.raw === '?.' && tokens[close + 2]?.raw === '('))) {
+ const member = tokens[i + 3];
+ const memberName = member?.type === 'string' ? decodeStringLiteral(member.raw) : null;
+ if (close === i + 4 && PROCESS_METHODS.has(memberName)) {
+ method = memberName;
+ openIndex = tokens[close + 1]?.raw === '?.' ? close + 2 : close + 1;
+ } else {
+ calls.push({
+ ambiguous: true,
+ method: 'unknown',
+ token: tokens[i],
+ canonical: canonicalCall(tokens, i, Math.min(close + 2, tokens.length)),
+ });
+ continue;
+ }
+ }
+ } else if (tokens[i].raw === '(' &&
+ namespaceBindings.has(tokens[i + 1]?.raw) &&
+ ['.', '?.'].includes(tokens[i + 2]?.raw) &&
+ PROCESS_METHODS.has(tokens[i + 3]?.raw) &&
+ tokens[i + 4]?.raw === ')' &&
+ tokens[i + 5]?.raw === '(') {
+ method = tokens[i + 3].raw;
+ openIndex = i + 5;
+ } else if (childProcessRequireExpression(tokens, i)) {
+ const required = childProcessRequireExpression(tokens, i);
+ if (['.', '?.'].includes(tokens[required.end]?.raw) &&
+ PROCESS_METHODS.has(tokens[required.end + 1]?.raw)) {
+ method = tokens[required.end + 1].raw;
+ if (tokens[required.end + 2]?.raw === '?.' && tokens[required.end + 3]?.raw === '(') {
+ openIndex = required.end + 3;
+ } else if (tokens[required.end + 2]?.raw === '(') {
+ openIndex = required.end + 2;
+ }
+ } else if (tokens[required.end]?.raw === '[' ||
+ (tokens[required.end]?.raw === '?.' && tokens[required.end + 1]?.raw === '[')) {
+ const bracket = tokens[required.end]?.raw === '[' ? required.end : required.end + 1;
+ const close = matchingIndex(tokens, bracket);
+ if (close !== -1 && tokens[close + 1]?.raw === '(') {
+ const member = tokens[bracket + 1];
+ const memberName = member?.type === 'string' ? decodeStringLiteral(member.raw) : null;
+ if (close === bracket + 2 && PROCESS_METHODS.has(memberName)) {
+ method = memberName;
+ openIndex = close + 1;
+ } else {
+ calls.push({
+ ambiguous: true,
+ method: 'unknown',
+ token: tokens[i],
+ canonical: canonicalCall(tokens, i, Math.min(close + 2, tokens.length)),
+ });
+ continue;
+ }
+ }
+ }
+ }
+
+ if (!method) continue;
+ const closeIndex = matchingIndex(tokens, openIndex);
+ if (closeIndex === -1) {
+ calls.push({
+ ambiguous: true,
+ method,
+ token: tokens[i],
+ canonical: canonicalCall(tokens, callStart, tokens.length),
+ });
+ continue;
+ }
+ calls.push({
+ method,
+ token: tokens[i],
+ args: splitTopLevel(tokens, openIndex + 1, closeIndex),
+ canonical: canonicalCall(tokens, callStart, closeIndex + 1),
+ });
+ i = closeIndex;
+ }
+ return calls;
+}
+
+function analyzeSource(source, filePath = '<source>') {
+ let tokens;
+ try {
+ tokens = tokenize(source);
+ } catch (error) {
+ return [{
+ path: filePath,
+ line: error.line || 1,
+ column: error.column || 1,
+ rule: 'unsupported-source-syntax',
+ callee: 'unknown',
+ call: '',
+ message: `Source cannot be analyzed safely: ${error.message}.`,
+ }];
+ }
+
+ const bindings = discoverBindings(tokens);
+ const calls = findCalls(tokens, bindings);
+ const findings = [];
+
+ for (const call of calls) {
+ if (call.ambiguous) {
+ findings.push(finding(
+ filePath,
+ call,
+ 'ambiguous-child-process-call',
+ 'Child process call shape is ambiguous; use a direct named method with a fixed executable and argv array.'
+ ));
+ continue;
+ }
+ if (call.args.length === 0) {
+ findings.push(finding(
+ filePath,
+ call,
+ 'ambiguous-child-process-call',
+ `${call.method} requires an explicit command or executable.`
+ ));
+ continue;
+ }
+
+ if (SHELL_METHODS.has(call.method)) {
+ const commandType = classifyShellCommand(tokens, call.args[0], bindings.constBindings);
+ if (commandType === 'dynamic-template') {
+ findings.push(finding(
+ filePath,
+ call,
+ 'dynamic-shell-command',
+ `${call.method} command uses template interpolation; use execFile/spawn with a fixed executable and argv array.`
+ ));
+ } else if (commandType === 'concatenation') {
+ findings.push(finding(
+ filePath,
+ call,
+ 'concatenated-shell-command',
+ `${call.method} command uses string concatenation; use execFile/spawn with a fixed executable and argv array.`
+ ));
+ } else if (commandType !== 'static') {
+ findings.push(finding(
+ filePath,
+ call,
+ 'nonconstant-shell-command',
+ `${call.method} command is not a static literal; non-constant data must be passed as argv, never shell syntax.`
+ ));
+ }
+ continue;
+ }
+
+ if (!ARGV_METHODS.has(call.method)) continue;
+ if (!isFixedExecutable(tokens, call.args[0], bindings.constBindings)) {
+ findings.push(finding(
+ filePath,
+ call,
+ 'nonconstant-executable',
+ `${call.method} executable is not a fixed literal or process.execPath.`
+ ));
+ }
+
+ let optionsRange = null;
+ if (call.args.length >= 3) {
+ optionsRange = call.args[2];
+ } else if (call.args.length === 2) {
+ const resolved = resolveRange(tokens, call.args[1], bindings.constBindings);
+ if (tokens[resolved[0]]?.raw === '{') {
+ optionsRange = call.args[1];
+ } else if (tokens[resolved[0]]?.raw !== '[') {
+ findings.push(finding(
+ filePath,
+ call,
+ 'ambiguous-shell-option',
+ `${call.method} second argument could be an options object; pass an argv array and explicit shell:false options.`
+ ));
+ }
+ }
+
+ if (optionsRange) {
+ const shell = shellProperty(tokens, optionsRange, bindings.constBindings);
+ if (shell === 'true') {
+ findings.push(finding(
+ filePath,
+ call,
+ 'shell-true',
+ `${call.method} enables shell:true; pass arguments directly with shell:false.`
+ ));
+ } else if (shell === 'ambiguous') {
+ findings.push(finding(
+ filePath,
+ call,
+ 'ambiguous-shell-option',
+ `${call.method} options cannot be proven to keep shell execution disabled.`
+ ));
+ }
+ }
+ }
+
+ return findings;
+}
+
+function shouldScan(relativePath) {
+ const normalized = toPosix(relativePath);
+ if (!/\.(?:cjs|js|mjs)$/.test(normalized)) return false;
+ const segments = normalized.split('/');
+ if (segments.some((segment) => EXCLUDED_DIRECTORY_NAMES.has(segment))) return false;
+ if (normalized.startsWith(`${POWER_PAGES_ROOT}/hooks/`)) return true;
+ if (normalized.startsWith(`${POWER_PAGES_ROOT}/scripts/`)) return true;
+ return normalized.startsWith(`${POWER_PAGES_ROOT}/skills/`) &&
+ normalized.includes('/scripts/');
+}
+
+function walkJavaScript(root, relativeDirectory, results) {
+ const absoluteDirectory = path.join(root, relativeDirectory);
+ if (!fs.existsSync(absoluteDirectory)) return;
+ for (const entry of fs.readdirSync(absoluteDirectory, { withFileTypes: true })) {
+ const relativePath = toPosix(path.join(relativeDirectory, entry.name));
+ if (entry.isDirectory()) {
+ if (!EXCLUDED_DIRECTORY_NAMES.has(entry.name)) {
+ walkJavaScript(root, relativePath, results);
+ }
+ } else if (entry.isFile() && shouldScan(relativePath)) {
+ results.push(relativePath);
+ }
+ }
+}
+
+function listProductionJavaScript(root) {
+ const files = [];
+ for (const scanRoot of SCAN_ROOTS) walkJavaScript(root, scanRoot, files);
+ return files.sort();
+}
+
+function validateExceptions(exceptions) {
+ for (const exception of exceptions) {
+ for (const field of ['path', 'rule', 'callee', 'call', 'reason']) {
+ if (typeof exception[field] !== 'string' || exception[field].trim() === '') {
+ throw new Error(`Audited exception is missing required field '${field}'.`);
+ }
+ }
+ }
+}
+
+function applyAuditedExceptions(findings, exceptions = AUDITED_EXCEPTIONS) {
+ validateExceptions(exceptions);
+ const matches = new Map(exceptions.map((exception) => [exception, 0]));
+ const remaining = [];
+
+ for (const item of findings) {
+ const exception = exceptions.find((candidate) =>
+ candidate.path === item.path &&
+ candidate.rule === item.rule &&
+ candidate.callee === item.callee &&
+ candidate.call === item.call
+ );
+ if (exception) {
+ matches.set(exception, matches.get(exception) + 1);
+ } else {
+ remaining.push(item);
+ }
+ }
+
+ const audited = [];
+ for (const exception of exceptions) {
+ const count = matches.get(exception);
+ if (count === 1) {
+ audited.push(exception);
+ } else {
+ remaining.push({
+ path: exception.path,
+ line: 1,
+ column: 1,
+ rule: 'stale-audited-exception',
+ callee: exception.callee,
+ call: exception.call,
+ message: count === 0
+ ? `Audited exception no longer matches exactly: ${exception.reason}`
+ : `Audited exception matched ${count} calls instead of one: ${exception.reason}`,
+ });
+ }
+ }
+
+ return { findings: remaining, audited };
+}
+
+function auditRepository(root = REPOSITORY_ROOT, exceptions = AUDITED_EXCEPTIONS) {
+ const rawFindings = [];
+ const files = listProductionJavaScript(root);
+ for (const relativePath of files) {
+ const source = fs.readFileSync(path.join(root, relativePath), 'utf8');
+ rawFindings.push(...analyzeSource(source, relativePath));
+ }
+ const result = applyAuditedExceptions(rawFindings, exceptions);
+ return { ...result, files };
+}
+
+function parseCli(argv) {
+ let root = REPOSITORY_ROOT;
+ for (let i = 0; i < argv.length; i += 1) {
+ if (argv[i] === '--root') {
+ if (!argv[i + 1]) throw new Error('--root requires a path');
+ root = path.resolve(argv[i + 1]);
+ i += 1;
+ } else if (argv[i] === '--help') {
+ return { help: true, root };
+ } else {
+ throw new Error(`Unknown argument: ${argv[i]}`);
+ }
+ }
+ return { help: false, root };
+}
+
+function runCli(argv = process.argv.slice(2)) {
+ let options;
+ try {
+ options = parseCli(argv);
+ } catch (error) {
+ process.stderr.write(`${error.message}\n`);
+ return 2;
+ }
+
+ if (options.help) {
+ process.stdout.write(
+ 'Usage: node scripts/validate-secure-process-execution.js [--root <repository>]\n' +
+ 'Audits production Power Pages hooks, shared scripts, and skill scripts.\n'
+ );
+ return 0;
+ }
+
+ const result = auditRepository(options.root);
+ for (const exception of result.audited) {
+ process.stdout.write(
+ `AUDITED ${exception.path} [${exception.rule}]: ${exception.reason}\n`
+ );
+ }
+
+ if (result.findings.length > 0) {
+ process.stderr.write('Secure process execution validation failed:\n');
+ for (const item of result.findings) {
+ process.stderr.write(
+ `${item.path}:${item.line}:${item.column} [${item.rule}] ${item.message}\n`
+ );
+ }
+ return 1;
+ }
+
+ process.stdout.write(
+ `Secure process execution validation passed (${result.files.length} production files, ` +
+ `${result.audited.length} audited exception${result.audited.length === 1 ? '' : 's'}).\n`
+ );
+ return 0;
+}
+
+if (require.main === module) {
+ process.exitCode = runCli();
+}
+
+module.exports = {
+ AUDITED_EXCEPTIONS,
+ EXCLUDED_DIRECTORY_NAMES,
+ SCAN_ROOTS,
+ analyzeSource,
+ applyAuditedExceptions,
+ auditRepository,
+ canonicalCall,
+ listProductionJavaScript,
+ runCli,
+ shouldScan,
+ tokenize,
+ validateExceptions,
+};