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.

fix(power-pages): make hooks safe for nested PowerShell (#791)

Priyanshu Agrawal4cf6677de070
diff --git a/plugins/power-pages/hooks/README.md b/plugins/power-pages/hooks/README.md
new file mode 100644
index 000000000..728a5b8f9
--- /dev/null
+++ b/plugins/power-pages/hooks/README.md
@@ -0,0 +1,26 @@
+# Power Pages hooks
+
+`PreToolUse` and `UserPromptSubmit` collect skill-usage telemetry.
+`PostToolUse` runs skill validators and preserves their exit status.
+
+## Portable command quoting
+
+The shared manifest uses only `type`, `command` and `timeout`; it does not depend on host-specific fields such as `powershell`.
+The same `command` runs in POSIX shells and Windows PowerShell.
+
+A nested `-Command "..."` invocation can strip the double quotes around inline JavaScript, making PowerShell parse JavaScript such as `||` and `path.resolve(root,'hooks',...)` itself.
+This reproduces the parser failure reported in [#788](https://github.com/microsoft/power-platform-skills/issues/788), but does not identify which layer in the original sandbox loses the quotes.
+The JavaScript is single-quoted and contains no string literals or shell interpolation.
+String constants are ordinary command arguments read through Node's `process.argv`: the path module name, the relative hook filename, the missing-root diagnostic and, for telemetry, the exit event name.
+This avoids both nested double quotes and shell-specific single-quote escaping.
+Node resolves `PLUGIN_ROOT` or `CLAUDE_PLUGIN_ROOT`, so spaces and shell metacharacters in installation paths do not become shell syntax.
+
+Telemetry-only commands register an exit listener that resets Node's exit code to zero, including module-load failures and explicit telemetry exits; diagnostics remain on stderr.
+The validation command has no exit listener and retains its normal failure behavior.
+POSIX shells preserve Node's exit code; PowerShell's `-Command` reports a native nonzero exit as status 1.
+Do not add telemetry's exit listener to the validation hook.
+
+`scripts/tests/hook-commands.test.js` exercises the registered commands with isolated hook bodies and smoke-tests the installed scripts with unrelated input.
+It rejects host-specific command fields and executes `command` itself rather than selecting an override in test code.
+The existing `power-pages-script-tests` workflow discovers this test and runs it on Linux, macOS and Windows, including direct/nested Windows PowerShell 5.1 and PowerShell 7 launches.
+On a non-Windows machine with PowerShell installed, set `HOOK_TEST_POWERSHELL` to its executable to run the PowerShell cases locally.
diff --git a/plugins/power-pages/hooks/hooks.json b/plugins/power-pages/hooks/hooks.json
index 663b8621a..51dda0056 100644
--- a/plugins/power-pages/hooks/hooks.json
+++ b/plugins/power-pages/hooks/hooks.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-pretool-telemetry.js'));\"",
+ "command": "node -e 'process.on(process.argv[3],()=>{process.exitCode=0});const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!root){console.error(process.argv[4]);process.exit(0)}require(require(process.argv[1]).resolve(root,process.argv[2]))' node:path hooks/run-skill-pretool-telemetry.js exit 'PLUGIN_ROOT is not set'",
"timeout": 30
}
]
@@ -18,7 +18,7 @@
"hooks": [
{
"type": "command",
- "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-skill-posttool-validation.js'));\"",
+ "command": "node -e 'const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!root){console.error(process.argv[3]);process.exit(0)}require(require(process.argv[1]).resolve(root,process.argv[2]))' node:path hooks/run-skill-posttool-validation.js 'PLUGIN_ROOT is not set'",
"timeout": 30
}
]
@@ -29,7 +29,7 @@
"hooks": [
{
"type": "command",
- "command": "node -e \"const path=require('node:path'); const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT; if(!root){console.error('PLUGIN_ROOT is not set'); process.exit(0);} require(path.resolve(root,'hooks','run-user-prompt-telemetry.js'));\"",
+ "command": "node -e 'process.on(process.argv[3],()=>{process.exitCode=0});const root=process.env.PLUGIN_ROOT||process.env.CLAUDE_PLUGIN_ROOT;if(!root){console.error(process.argv[4]);process.exit(0)}require(require(process.argv[1]).resolve(root,process.argv[2]))' node:path hooks/run-user-prompt-telemetry.js exit 'PLUGIN_ROOT is not set'",
"timeout": 30
}
]
diff --git a/plugins/power-pages/scripts/tests/hook-commands.test.js b/plugins/power-pages/scripts/tests/hook-commands.test.js
new file mode 100644
index 000000000..185c4c2f4
--- /dev/null
+++ b/plugins/power-pages/scripts/tests/hook-commands.test.js
@@ -0,0 +1,177 @@
+const test = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const PLUGIN_ROOT = path.resolve(__dirname, '../..');
+const MANIFEST = require('../../hooks/hooks.json');
+const FILES = {
+ PreToolUse: 'run-skill-pretool-telemetry.js',
+ PostToolUse: 'run-skill-posttool-validation.js',
+ UserPromptSubmit: 'run-user-prompt-telemetry.js',
+};
+const HOOKS = Object.entries(MANIFEST.hooks).flatMap(([event, groups]) =>
+ groups.flatMap(group => group.hooks.map(hook => ({
+ ...hook, file: FILES[event], telemetry: event !== 'PostToolUse',
+ })))
+);
+const INPUT = '{"tool_input":{"skill":"example"}}';
+
+function fixture(t) {
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'power-pages hooks '));
+ t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
+ const root = path.join(directory, "plugin's files & scripts");
+ fs.mkdirSync(path.join(root, 'hooks'), { recursive: true });
+ for (const filename of Object.values(FILES)) {
+ // Replace only the installed hook body, not the manifest command. This isolates
+ // shell forwarding from PAC/network activity while proving which file ran.
+ fs.writeFileSync(path.join(root, 'hooks', filename), `
+const path = require('node:path');
+let input = '';
+process.stdin.setEncoding('utf8');
+process.stdin.on('data', chunk => { input += chunk; });
+process.stdin.on('end', () => {
+ console.log(JSON.stringify({ file: path.basename(__filename), input, cwd: process.cwd() }));
+ if (process.env.HOOK_TEST_STATUS) {
+ console.error('hook failure');
+ process.exit(Number(process.env.HOOK_TEST_STATUS));
+ }
+});
+`);
+ }
+ return { directory, root };
+}
+
+function environment(root, variable = 'PLUGIN_ROOT') {
+ return {
+ ...process.env,
+ PLUGIN_ROOT: '',
+ CLAUDE_PLUGIN_ROOT: '',
+ HOOK_TEST_STATUS: '',
+ POWER_PLATFORM_SKILLS_TELEMETRY_POWER_PAGES_OPTOUT: '1',
+ [variable]: root,
+ };
+}
+
+test('Power Pages hooks use only portable command fields and preserve registration', () => {
+ assert.deepEqual(Object.keys(MANIFEST.hooks), Object.keys(FILES));
+ assert.equal(HOOKS.length, 3);
+ for (const [event, groups] of Object.entries(MANIFEST.hooks)) {
+ assert.equal(groups.length, 1);
+ if (event !== 'UserPromptSubmit') assert.equal(groups[0].matcher, 'Skill|skill');
+ for (const hook of groups[0].hooks) {
+ assert.deepEqual(Object.keys(hook).sort(), ['command', 'timeout', 'type']);
+ assert.equal(hook.type, 'command');
+ assert.equal(hook.timeout, 30);
+ assert.ok(!hook.command.includes('"'), 'nested double quotes regress #788');
+ }
+ }
+});
+
+const shells = process.platform === 'win32' ? ['powershell.exe', 'pwsh.exe'] : [];
+if (process.platform !== 'win32' && process.env.HOOK_TEST_POWERSHELL) {
+ shells.push(process.env.HOOK_TEST_POWERSHELL);
+}
+const runners = process.platform === 'win32' ? [] : [{
+ name: 'POSIX shell',
+ binary: '/bin/sh',
+ args: command => ['-c', command],
+ failureStatus: code => code,
+}];
+for (const shell of shells) {
+ for (const nested of [false, true]) {
+ runners.push({
+ name: `${path.basename(shell)} (${nested ? 'nested' : 'direct'})`,
+ binary: shell,
+ args(command) {
+ // Model an extra -Command "..." layer that reproduces #788's parser
+ // error. Embedded " in node -e "JavaScript" exposes JS to PowerShell.
+ const script = nested
+ ? `& '${shell.replaceAll("'", "''")}' -NoLogo -NoProfile -Command "${command}"; exit (Get-Variable LASTEXITCODE -ValueOnly)`
+ : command;
+ return ['-NoLogo', '-NoProfile', '-Command', script];
+ },
+ // PowerShell -Command maps native nonzero exits to 1; POSIX preserves them.
+ failureStatus: () => 1,
+ });
+ }
+}
+
+for (const runner of runners) {
+ function launch(hook, options) {
+ return spawnSync(runner.binary, runner.args(hook.command), {
+ ...options, encoding: 'utf8', timeout: 15000,
+ });
+ }
+
+ test(`${runner.name}: commands preserve stdin, cwd, path quoting and root selection`, t => {
+ const { directory, root } = fixture(t);
+ for (const hook of HOOKS) {
+ for (const variable of ['PLUGIN_ROOT', 'CLAUDE_PLUGIN_ROOT']) {
+ const env = environment(root, variable);
+ if (variable === 'PLUGIN_ROOT') env.CLAUDE_PLUGIN_ROOT = path.join(directory, 'wrong root');
+ const result = launch(hook, { cwd: directory, env, input: INPUT });
+ assert.equal(result.status, 0, `${hook.file}: ${result.stderr}`);
+ assert.equal(result.stderr, '');
+ const output = JSON.parse(result.stdout);
+ assert.equal(output.file, hook.file);
+ assert.equal(output.input, INPUT);
+ // Windows TEMP may use RUNNER~1 while PowerShell expands it to runneradmin.
+ // Native realpath resolves 8.3 aliases so this checks directory identity.
+ assert.equal(fs.realpathSync.native(output.cwd), fs.realpathSync.native(directory));
+ }
+ }
+ });
+
+ test(`${runner.name}: telemetry failures do not block and validator failures propagate`, t => {
+ const { directory, root } = fixture(t);
+ for (const hook of HOOKS) {
+ for (const code of [1, 2]) {
+ const result = launch(hook, {
+ cwd: directory, env: { ...environment(root), HOOK_TEST_STATUS: String(code) }, input: '{}',
+ });
+ assert.equal(JSON.parse(result.stdout).file, hook.file);
+ assert.match(result.stderr, /hook failure/);
+ assert.equal(result.status, hook.telemetry ? 0 : runner.failureStatus(code), hook.file);
+ }
+ }
+ });
+
+ test(`${runner.name}: missing modules remain diagnostic and only telemetry fails open`, t => {
+ const { directory, root } = fixture(t);
+ for (const hook of HOOKS) {
+ const result = launch(hook, {
+ cwd: directory, env: environment(path.join(root, 'missing')), input: '{}',
+ });
+ assert.equal(result.stdout, '');
+ assert.match(result.stderr, /Cannot find module/);
+ assert.equal(result.status, hook.telemetry ? 0 : 1, hook.file);
+ }
+ });
+
+ test(`${runner.name}: missing plugin roots retain the existing diagnostic and no-op`, t => {
+ const { directory } = fixture(t);
+ for (const hook of HOOKS) {
+ const result = launch(hook, { cwd: directory, env: environment(''), input: '{}' });
+ assert.equal(result.status, 0, result.stderr);
+ assert.equal(result.stdout, '');
+ assert.match(result.stderr, /PLUGIN_ROOT is not set/);
+ }
+ });
+
+ test(`${runner.name}: installed hook scripts accept unrelated input without side effects`, t => {
+ const { directory } = fixture(t);
+ for (const hook of HOOKS) {
+ const result = launch(hook, {
+ cwd: directory, env: environment(PLUGIN_ROOT),
+ input: JSON.stringify({ tool_name: 'Read', tool_input: {}, prompt: 'No skill invocation' }),
+ });
+ assert.equal(result.status, 0, `${hook.file}: ${result.stderr}`);
+ assert.equal(result.stdout, '');
+ assert.equal(result.stderr, '');
+ }
+ assert.deepEqual(fs.readdirSync(directory), ["plugin's files & scripts"]);
+ });
+}