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.
JavaScript claude-code-pluginclaude-code-skillscode-appsgithub-copilot-pluginpower-appspower-pagespower-platform
Harden marketplace installer command execution (#737)
amitjoshi438478cfdf838aa
diff --git a/.github/workflows/validate-repository-metadata.yml b/.github/workflows/validate-repository-metadata.ymlindex e2a6e3b68..e091600fb 100644--- a/.github/workflows/validate-repository-metadata.yml+++ b/.github/workflows/validate-repository-metadata.yml@@ -27,9 +27,6 @@ jobs:- name: test-legacy-compatibility-validatorrun: node --test scripts/tests/validate-legacy-compatibility.test.js- - name: test-installer-arguments- run: node --test scripts/tests/install.test.js-- name: validate-legacy-compatibilityrun: node scripts/validate-legacy-compatibility.js@@ -84,3 +81,21 @@ jobs:- name: validate-plugin-copiesrun: node scripts/validate-plugin-copies.js++ test-installer:+ name: test-installer (${{ matrix.os }})+ runs-on: ${{ matrix.os }}+ strategy:+ matrix:+ os: [ubuntu-latest, windows-latest]+ steps:+ - name: checkout+ uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1++ - name: setup-node+ uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0+ with:+ node-version: 20++ - name: test-installer+ run: node --test scripts/tests/install.test.jsdiff --git a/AGENTS.md b/AGENTS.mdindex 4284fcef5..cdbaa2962 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -90,7 +90,8 @@ No root-level build, lint, or test commands exist. Build/test tooling lives insi## CI**Only two workflows run on every PR** — `validate-keyword-case` and `validate-repository-metadata`.-Both are repo-wide and enforce metadata/marketplace rules, not behavior.+Both are repo-wide and enforce metadata/marketplace rules. `validate-repository-metadata` also+runs standalone installer regression tests on Linux and Windows.**Every test workflow is path-filtered** — to a single plugin (`power-pages` → `plugins/power-pages/**`;`model-apps` → `plugins/model-apps/**` + `evals/model-apps/**` + the `shared/` sources it bundles;diff --git a/README.md b/README.mdindex 7da25a579..2e9b6d602 100644--- a/README.md+++ b/README.md@@ -31,6 +31,11 @@ The installer automatically:- Registers the plugin marketplace and installs all listed plugins except `dataverse`- Enables auto-update so plugins stay current+The installer validates plugin names in local and downloaded marketplace manifests before+installation. Names must follow the Open Plugins format: 1–64 lowercase ASCII letters or+digits, with single dots or hyphens allowed between alphanumeric endpoints. CLI arguments+are passed directly to executables; Windows batch launchers accept only shell-inert arguments.+To also install the [Dataverse](#dataverse-external) plugin, pass `--include-dataverse`:```powershelldiff --git a/scripts/install.js b/scripts/install.jsindex faaa5772c..2b86296b7 100644--- a/scripts/install.js+++ b/scripts/install.js@@ -15,7 +15,7 @@* -h, --help Show this help*/-const { execSync } = require("child_process");+const { execFileSync } = require("child_process");const fs = require("fs");const path = require("path");const os = require("os");@@ -87,24 +87,84 @@ function selectPlugins(pluginNames, includedOptIn) {}// ── Helpers ───────────────────────────────────────────────────-function hasCommand(cmd) {- try {- const which = process.platform === "win32" ? "where" : "which";- execSync(`${which} ${cmd}`, { stdio: "pipe" });- return true;- } catch {- return false;+function envValue(name) {+ if (process.platform !== "win32") return process.env[name];+ // Match Node's case-insensitive environment lookup, including duplicate PATH spellings.+ const key = Object.keys(process.env).filter((k) => k.toUpperCase() === name.toUpperCase()).sort()[0];+ return key === undefined ? undefined : process.env[key];+}++function isFullyQualifiedPath(file) {+ // Windows considers \tools absolute, but it still depends on the current drive.+ // A longer root identifies a drive-qualified or UNC path instead.+ return path.isAbsolute(file) && (process.platform !== "win32" || path.parse(file).root.length > 1);+}++function resolveCommand(cmd) {+ if (typeof cmd !== "string" || /^[a-z0-9-]+$/.exec(cmd)?.[0] !== cmd) {+ throw new Error("Invalid command name");}+ const win = process.platform === "win32";+ const paths = String(envValue("PATH") || "").split(win ? ";" : ":");+ const extensions = win+ ? String(envValue("PATHEXT") || ".COM;.EXE;.BAT;.CMD").split(";")+ .map((ext) => ext.trim().toLowerCase()).filter((ext) => /^\.(?:com|exe|bat|cmd)$/.test(ext))+ : [""];+ for (const entry of paths) {+ // On POSIX, whitespace and quotes are literal directory-name characters.+ const dir = win ? entry.trim().replace(/^"(.*)"$/, "$1") : entry;+ // Skip implicit working-directory lookup and relative PATH entries.+ if (!isFullyQualifiedPath(dir)) continue;+ for (const ext of extensions) {+ const file = path.join(dir, cmd + ext);+ try {+ if (!fs.statSync(file).isFile()) continue;+ if (!win) fs.accessSync(file, fs.constants.X_OK);+ return file;+ } catch (err) {+ if (!["ENOENT", "ENOTDIR", "EACCES", "EPERM"].includes(err.code)) throw err;+ }+ }+ }+ return null;}-function run(cmd, opts = {}) {+function hasCommand(cmd) {+ return resolveCommand(cmd) !== null;+}++function run(cmd, args = [], opts = {}) {try {- const output = execSync(cmd, {+ let file = resolveCommand(cmd);+ if (!file) throw new Error(`${cmd} was not found on PATH`);+ let argv = args;+ const options = {stdio: "pipe",timeout: 120_000,cwd: opts.cwd,- shell: true,- });+ shell: false,+ windowsHide: true,+ };+ if (process.platform === "win32" && /\.(?:cmd|bat)$/i.test(file)) {+ // Node cannot execute Windows batch shims directly. cmd.exe parses the /c line+ // and the shim's %* again, so only inert argument tokens may cross this boundary.+ // The installer is also downloaded/piped alone: it cannot require a repo-local runner.+ // See: https://nodejs.org/api/child_process.html#spawning-bat-and-cmd-files-on-windows+ if (/["%!\u0000-\u001f\u007f]/.test(file)+ || !args.every((arg) => typeof arg === "string" && /^[A-Za-z0-9_./:@=-]+$/.exec(arg)?.[0] === arg)) {+ throw new Error(`Cannot safely pass the executable path or arguments to ${cmd}'s Windows batch launcher`);+ }+ const comspec = envValue("ComSpec");+ const systemRoot = envValue("SystemRoot") || "C:\\Windows";+ const shell = comspec && isFullyQualifiedPath(comspec) && path.basename(comspec).toLowerCase() === "cmd.exe"+ ? comspec : path.join(systemRoot, "System32", "cmd.exe");+ if (!isFullyQualifiedPath(shell)) throw new Error("Windows command interpreter path must be fully qualified");+ argv = ["/d", "/s", "/v:off", "/c", `""${file}" ${args.join(" ")}"`];+ file = shell;+ options.windowsVerbatimArguments = true;+ options.env = { ...process.env, NoDefaultCurrentDirectoryInExePath: "1" };+ }+ const output = execFileSync(file, argv, options);return { ok: true, output: output.toString().trim() };} catch (err) {const stderr = err.stderr ? err.stderr.toString().trim() : err.message;@@ -133,13 +193,31 @@ function httpsGet(url) {});}+function isValidPluginName(name) {+ // Use the Open Plugins grammar shared with the repository validator. Compare the+ // whole match because JavaScript's $ anchor also accepts a trailing newline.+ const match = typeof name === "string" && /^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$/.exec(name);+ return Boolean(match && match[0] === name && !name.includes("--") && !name.includes(".."));+}+function parseMarketplaceManifest(raw) {const manifest = JSON.parse(raw);+ if (!manifest || typeof manifest !== "object" || Array.isArray(manifest)) {+ throw new Error("marketplace manifest must be an object");+ }if (manifest.name !== MARKETPLACE_NAME) {throw new Error(`manifest name is '${manifest.name || "(missing)"}', expected '${MARKETPLACE_NAME}'`);}+ if (!Array.isArray(manifest.plugins)) {+ throw new Error("marketplace plugins must be an array");+ }+ for (const [index, plugin] of manifest.plugins.entries()) {+ if (!plugin || typeof plugin !== "object" || Array.isArray(plugin) || !isValidPluginName(plugin.name)) {+ throw new Error(`plugins[${index}].name does not follow Open Plugins name constraints`);+ }+ }return manifest;}@@ -189,6 +267,7 @@ async function loadMarketplace() {return parseMarketplaceManifest(fs.readFileSync(filePath, "utf8"));} catch (err) {errors.push(`${filePath}: ${err.message}`);+ warn(`Ignoring invalid marketplace manifest: ${filePath}: ${err.message}`);}}}@@ -213,7 +292,7 @@ function installClaude(plugins) {// 1. Register marketplace via CLI (CLI clones the repo automatically)info("Registering marketplace...");- const addResult = run(`claude plugin marketplace add "${REPO}"`);+ const addResult = run("claude", ["plugin", "marketplace", "add", REPO]);if (addResult.ok) {ok("Marketplace registered");} else if (addResult.output.includes("already")) {@@ -225,7 +304,7 @@ function installClaude(plugins) {// 2. Update marketplaceinfo("Updating marketplace...");- const updateResult = run(`claude plugin marketplace update "${MARKETPLACE_NAME}"`);+ const updateResult = run("claude", ["plugin", "marketplace", "update", MARKETPLACE_NAME]);if (updateResult.ok) {ok("Marketplace updated");} else {@@ -239,9 +318,7 @@ function installClaude(plugins) {// 4. Install each plugin via CLIfor (const plugin of plugins) {info(`Installing ${plugin}...`);- const installResult = run(- `claude plugin install "${plugin}@${MARKETPLACE_NAME}" --scope user`- );+ const installResult = run("claude", ["plugin", "install", `${plugin}@${MARKETPLACE_NAME}`, "--scope", "user"]);if (installResult.ok) {ok(`${plugin} installed`);} else if (installResult.output.includes("already installed")) {@@ -253,7 +330,7 @@ function installClaude(plugins) {// 5. Verify installationinfo("Verifying installation...");- const listResult = run("claude plugin list");+ const listResult = run("claude", ["plugin", "list"]);if (listResult.ok) {const installed = plugins.filter((p) => listResult.output.includes(p));if (installed.length > 0) {@@ -270,7 +347,7 @@ function installCopilot(plugins) {// 1. Register marketplace via CLI (CLI clones the repo automatically)info("Registering marketplace...");- const addResult = run(`copilot plugin marketplace add "${REPO}"`);+ const addResult = run("copilot", ["plugin", "marketplace", "add", REPO]);if (addResult.ok) {ok("Marketplace registered");} else if (addResult.output.includes("already")) {@@ -287,7 +364,7 @@ function installCopilot(plugins) {// 3. Install each plugin via CLIfor (const plugin of plugins) {info(`Installing ${plugin}...`);- const installResult = run(`copilot plugin install "${plugin}@${MARKETPLACE_NAME}"`);+ const installResult = run("copilot", ["plugin", "install", `${plugin}@${MARKETPLACE_NAME}`]);if (installResult.ok) {ok(`${plugin} installed`);} else if (installResult.output.includes("already installed")) {@@ -299,7 +376,7 @@ function installCopilot(plugins) {// 4. Verify installationinfo("Verifying installation...");- const listResult = run("copilot plugin list");+ const listResult = run("copilot", ["plugin", "list"]);if (listResult.ok) {const installed = plugins.filter((p) => listResult.output.includes(p));if (installed.length > 0) {@@ -330,12 +407,12 @@ async function main() {const tools = [];if (hasCommand("claude")) {- const ver = run("claude --version");+ const ver = run("claude", ["--version"]);tools.push("claude");ok(`Claude Code ${ver.ok ? ver.output : "(version unknown)"}`);}if (hasCommand("copilot")) {- const ver = run("copilot --version");+ const ver = run("copilot", ["--version"]);tools.push("copilot");ok(`GitHub Copilot CLI ${ver.ok ? ver.output : "(version unknown)"}`);}@@ -353,7 +430,7 @@ async function main() {header("Power Platform CLI (pac)");if (hasCommand("pac")) {- const ver = run("pac help");+ const ver = run("pac", ["help"]);const versionMatch = ver.ok && ver.output.match(/Version:\s*(.+)/i);ok(`PAC CLI ${versionMatch ? versionMatch[1].trim() : "(installed)"}`);@@ -376,9 +453,7 @@ async function main() {} else if (latestVersion) {info(`Newer version available: ${latestVersion} (installed: ${localVersion || "unknown"})`);info("Updating PAC CLI...");- const updateResult = run(- "dotnet tool update --global Microsoft.PowerApps.CLI.Tool"- );+ const updateResult = run("dotnet", ["tool", "update", "--global", "Microsoft.PowerApps.CLI.Tool"]);if (updateResult.ok) {ok(`Updated to ${latestVersion}`);} else {@@ -391,9 +466,7 @@ async function main() {if (hasCommand("dotnet")) {info("Installing PAC CLI via dotnet tool...");- const installResult = run(- "dotnet tool install --global Microsoft.PowerApps.CLI.Tool"- );+ const installResult = run("dotnet", ["tool", "install", "--global", "Microsoft.PowerApps.CLI.Tool"]);if (installResult.ok) {ok("PAC CLI installed");info("You may need to restart your terminal for the 'pac' command to be available.");@@ -417,7 +490,7 @@ async function main() {header("Azure CLI (az)");if (hasCommand("az")) {- const ver = run("az version -o tsv");+ const ver = run("az", ["version", "-o", "tsv"]);const versionLine = ver.ok && ver.output.split("\n")[0];const azVersion = versionLine ? versionLine.split("\t")[0] : null;ok(`Azure CLI ${azVersion || "(installed)"}`);@@ -427,9 +500,8 @@ async function main() {let installed = false;if (process.platform === "win32" && hasCommand("winget")) {info("Installing Azure CLI via winget...");- const installResult = run(- "winget install -e --id Microsoft.AzureCLI --accept-source-agreements --accept-package-agreements"- );+ const installResult = run("winget", ["install", "-e", "--id", "Microsoft.AzureCLI",+ "--accept-source-agreements", "--accept-package-agreements"]);if (installResult.ok) {ok("Azure CLI installed");info("You may need to restart your terminal for the 'az' command to be available.");@@ -439,7 +511,7 @@ async function main() {}} else if (process.platform === "darwin" && hasCommand("brew")) {info("Installing Azure CLI via Homebrew...");- const installResult = run("brew install azure-cli");+ const installResult = run("brew", ["install", "azure-cli"]);if (installResult.ok) {ok("Azure CLI installed");installed = true;@@ -509,4 +581,7 @@ if (require.main === module || module.id === "[stdin]") {});}-module.exports = { parseArgs, selectPlugins, OPT_IN_PLUGINS };+module.exports = {+ parseArgs, selectPlugins, OPT_IN_PLUGINS, isValidPluginName, parseMarketplaceManifest,+ loadMarketplace, resolveCommand, run, installClaude, installCopilot, main,+};diff --git a/scripts/tests/install.test.js b/scripts/tests/install.test.jsindex 0363494bd..8a47b2a70 100644--- a/scripts/tests/install.test.js+++ b/scripts/tests/install.test.js@@ -1,13 +1,108 @@-// Covers the installer's argument handling and plugin selection. Importing install.js-// must not start an install, so a regression in its entry-point guard shows up here as a-// test run that tries to register marketplaces instead of passing quietly.+// Importing install.js must not start an install. Process and network boundaries are+// mocked below so malformed marketplace fixtures can never run a CLI or fetch real data.const test = require('node:test');const assert = require('node:assert');+const fs = require('node:fs');+const os = require('node:os');+const path = require('node:path');+const vm = require('node:vm');+const { EventEmitter } = require('node:events');+const { execFileSync } = require('node:child_process');-const { parseArgs, selectPlugins, OPT_IN_PLUGINS } = require('../install.js');+const {+ parseArgs, selectPlugins, OPT_IN_PLUGINS, isValidPluginName, parseMarketplaceManifest,+} = require('../install.js');const MARKETPLACE = ['power-pages', 'model-apps', 'dataverse', 'power-automate'];+const SOURCE = fs.readFileSync(path.join(__dirname, '..', 'install.js'), 'utf8');+const RAW_ROOT = 'https://raw.githubusercontent.com/microsoft/power-platform-skills/main/';+const INJECTION_NAMES = [+ 'power-pages$(echo REVIEW_ONLY)',+ 'power-pages`echo REVIEW_ONLY`',+ 'power-pages" & echo REVIEW_ONLY & rem "',+ 'power-pages;echo REVIEW_ONLY',+ 'power-pages|echo REVIEW_ONLY',+ '%COMSPEC%',+ '!PATH!',+ 'power-pages\n',+ 'power-pages\r\n',+ 'power-pages\u0000',+];++function manifest(names = MARKETPLACE) {+ return { name: 'power-platform-skills', plugins: names.map((name) => ({ name })) };+}++function loadInstaller({+ platform = 'linux',+ env = platform === 'win32' ? { Path: 'C:\\tools', SystemRoot: 'C:\\Windows' } : { PATH: '/tools' },+ files = {},+ commands = [],+ remote = {},+ execute = () => Buffer.from('power-pages model-apps dataverse power-automate'),+ argv,+} = {}) {+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const root = platform === 'win32' ? 'C:\\project' : '/project';+ const file = paths.join(root, 'scripts', 'install.js');+ const calls = [];+ const requests = [];+ const messages = [];+ const writes = [];+ const module = { id: 'installer-test', exports: {} };+ const requireMock = (name) => {+ if (name === 'path') return paths;+ if (name === 'os') return { homedir: () => paths.join(root, 'home') };+ if (name === 'fs') return {+ constants: fs.constants,+ existsSync: (target) => Object.hasOwn(files, target),+ readFileSync: (target) => {+ if (Object.hasOwn(files, target)) return files[target];+ throw Object.assign(new Error('not found'), { code: 'ENOENT' });+ },+ writeFileSync: (...args) => writes.push(args),+ statSync: (target) => {+ if (commands.includes(target)) return { isFile: () => true };+ throw Object.assign(new Error('not found'), { code: 'ENOENT' });+ },+ accessSync: () => {},+ };+ if (name === 'child_process') return {+ execSync: () => assert.fail('The installer must not use execSync'),+ execFileSync: (file, args, options) => {+ assert.equal(options.shell, false);+ calls.push({ file, args: Array.from(args), options });+ return execute(file, args, options);+ },+ };+ if (name === 'https') return {+ get: (url, options, callback) => {+ requests.push(url);+ const res = new EventEmitter();+ res.statusCode = Object.hasOwn(remote, url) ? 200 : 404;+ callback(res);+ queueMicrotask(() => {+ res.emit('data', remote[url]);+ res.emit('end');+ });+ return new EventEmitter();+ },+ };+ throw new Error(`Unexpected require: ${name}`);+ };+ vm.runInNewContext(SOURCE, {+ require: requireMock, module,+ process: {+ platform, env, version: process.version, stdout: { isTTY: false },+ cwd: () => root,+ argv: argv || ['node', file],+ exit: (code) => assert.fail(`Unexpected exit ${code}`),+ },+ console: { log: (...args) => messages.push(args.join(' ')) },+ }, { filename: 'install.js' });+ return { installer: module.exports, calls, requests, messages, writes };+}test('dataverse is opt-in through --include-dataverse', () => {assert.equal(OPT_IN_PLUGINS.dataverse, '--include-dataverse');@@ -34,3 +129,362 @@ test('an unknown or misspelled argument fails instead of silently skipping a pluassert.throws(() => parseArgs(['--include-dataverze']), /Unknown argument '--include-dataverze'/);assert.throws(() => parseArgs(['dataverse']), /Unknown argument/);});++test('plugin-name validation accepts the Open Plugins grammar, including its length boundaries', () => {+ for (const name of ['a', '0', 'plugin.v2', 'plugin-2', 'a'.repeat(64), ...MARKETPLACE]) {+ assert.equal(isValidPluginName(name), true, name);+ }+ for (const name of [+ '', 'a'.repeat(65), '-plugin', 'plugin-', '.plugin', 'plugin.', 'plugin--name',+ 'plugin..name', 'Uppercase', 'plugin_name', 'plugin/name', 'plugin name', 'plügïn',+ ...INJECTION_NAMES, null, 42, {}, [], true,+ ]) {+ assert.equal(isValidPluginName(name), false, JSON.stringify(name));+ }+});++test('marketplace validation rejects every malformed entry, including opt-in and later entries', () => {+ for (const plugins of [undefined, null, {}, 'plugins']) {+ assert.throws(() => parseMarketplaceManifest(JSON.stringify({ name: 'power-platform-skills', plugins })),+ /plugins must be an array/);+ }+ for (const entry of [null, 'dataverse', [], {}, { name: 1 }, ...INJECTION_NAMES.map((name) => ({ name }))]) {+ assert.throws(() => parseMarketplaceManifest(JSON.stringify({+ name: 'power-platform-skills', plugins: [{ name: 'power-pages' }, entry],+ })), /plugins\[1\].name/);+ }+ for (const raw of ['null', '[]', '"marketplace"', '42']) {+ assert.throws(() => parseMarketplaceManifest(raw), /manifest must be an object/);+ }+ assert.throws(() => parseMarketplaceManifest('{"name":"different","plugins":[]}'), /expected 'power-platform-skills'/);+ assert.throws(() => parseMarketplaceManifest('{invalid'), SyntaxError);+ assert.deepEqual(parseMarketplaceManifest(JSON.stringify(manifest([]))), manifest([]));+});++test('local and remote plugin source formats and committed manifests remain supported', () => {+ for (const source of [+ './plugins/power-pages',+ { source: 'github', repo: 'contoso/plugins', path: 'plugins/widget' },+ { source: 'git-subdir', url: 'contoso/plugins', path: 'plugins/widget' },+ ]) {+ const value = { name: 'power-platform-skills', plugins: [{ name: 'widget', source }] };+ assert.deepEqual(parseMarketplaceManifest(JSON.stringify(value)), value);+ }+ for (const file of ['marketplace.json', path.join('.claude-plugin', 'marketplace.json')]) {+ const value = parseMarketplaceManifest(fs.readFileSync(path.join(__dirname, '..', '..', file), 'utf8'));+ assert.ok(value.plugins.some((plugin) => plugin.name === 'dataverse'));+ }+});++for (const platform of ['linux', 'win32']) {+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const root = platform === 'win32' ? 'C:\\project' : '/project';+ for (const relative of ['marketplace.json', paths.join('.plugin', 'marketplace.json'), paths.join('.claude-plugin', 'marketplace.json')]) {+ test(`${platform}: local ${relative} validates names before returning a marketplace`, async () => {+ const file = paths.join(root, relative);+ const valid = loadInstaller({ platform, files: { [file]: JSON.stringify(manifest()) } });+ assert.deepEqual(JSON.parse(JSON.stringify(await valid.installer.loadMarketplace())), manifest());+ assert.deepEqual(valid.requests, []);+ for (const name of INJECTION_NAMES) {+ const bad = loadInstaller({ platform, files: { [file]: JSON.stringify(manifest([name])) } });+ await assert.rejects(bad.installer.loadMarketplace(), /plugins\[0\].name/);+ assert.deepEqual(bad.calls, []);+ assert.ok(bad.messages.some((message) => message.includes('Ignoring invalid marketplace manifest')));+ }+ });+ }+}++for (const relative of ['marketplace.json', '.plugin/marketplace.json', '.claude-plugin/marketplace.json']) {+ test(`downloaded ${relative} validates names before returning a marketplace`, async () => {+ const url = RAW_ROOT + relative;+ const valid = loadInstaller({ remote: { [url]: JSON.stringify(manifest()) } });+ assert.deepEqual(JSON.parse(JSON.stringify(await valid.installer.loadMarketplace())), manifest());+ for (const name of INJECTION_NAMES) {+ const bad = loadInstaller({ remote: { [url]: JSON.stringify(manifest([name])) } });+ await assert.rejects(bad.installer.loadMarketplace(), /plugins\[0\].name/);+ assert.deepEqual(bad.calls, []);+ }+ });+}++test('invalid local manifests are reported and never returned instead of a valid fallback', async () => {+ const fixture = loadInstaller({+ files: { '/project/marketplace.json': JSON.stringify(manifest([INJECTION_NAMES[0]])) },+ remote: { [RAW_ROOT + 'marketplace.json']: JSON.stringify(manifest()) },+ });+ assert.deepEqual(JSON.parse(JSON.stringify(await fixture.installer.loadMarketplace())), manifest());+ assert.ok(fixture.messages.some((message) => message.includes('Ignoring invalid marketplace manifest')));+ assert.deepEqual(fixture.calls, []);+});++test('CLI resolution skips relative PATH entries and honors PATH and supported PATHEXT order', () => {+ const linux = loadInstaller({ env: { PATH: ':.:tools:/first:/second' }, commands: ['/second/copilot', '/first/copilot'] });+ assert.equal(linux.installer.resolveCommand('copilot'), '/first/copilot');+ const windows = loadInstaller({+ platform: 'win32',+ env: { Path: 'C:\\ignored', PATH: '.;tools;;"C:\\first";C:\\second', PATHEXT: '.JS;.CMD;.EXE' },+ commands: ['C:\\first\\copilot.js', 'C:\\first\\copilot.cmd', 'C:\\first\\copilot.exe', 'C:\\second\\copilot.exe'],+ });+ assert.equal(windows.installer.resolveCommand('copilot'), 'C:\\first\\copilot.cmd');+ assert.equal(windows.installer.resolveCommand('missing'), null);+ for (const name of ['copilot & echo REVIEW_ONLY', 'copilot\n', '../copilot', '', null]) {+ assert.throws(() => windows.installer.resolveCommand(name), /Invalid command name/);+ }+});++test('POSIX CLI resolution preserves whitespace and quotes in PATH entries literally', () => {+ for (const entry of [' /tmp/tools', '"/tmp/tools"']) {+ const fixture = loadInstaller({+ env: { PATH: `${entry}:/trusted` }, commands: ['/tmp/tools/copilot', '/trusted/copilot'],+ });+ assert.equal(fixture.installer.resolveCommand('copilot'), '/trusted/copilot', JSON.stringify(entry));+ }+ const trailingSpace = loadInstaller({+ env: { PATH: '/tmp/tools :/trusted' },+ commands: ['/tmp/tools/copilot', '/tmp/tools /copilot', '/trusted/copilot'],+ });+ assert.equal(trailingSpace.installer.resolveCommand('copilot'), '/tmp/tools /copilot');+ const missingLiteral = loadInstaller({+ env: { PATH: '/tmp/tools :/trusted' }, commands: ['/tmp/tools/copilot', '/trusted/copilot'],+ });+ assert.equal(missingLiteral.installer.resolveCommand('copilot'), '/trusted/copilot');+});++test('Windows CLI resolution skips current-drive-relative paths but accepts drive and UNC roots', () => {+ for (const entry of ['\\tools', '/tools', 'C:tools', 'C:', '\\\\server', '\\', '/']) {+ const fixture = loadInstaller({+ platform: 'win32', env: { Path: `${entry};C:\\trusted` },+ commands: [path.win32.join(entry, 'copilot.exe'), 'C:\\trusted\\copilot.exe'],+ });+ assert.equal(fixture.installer.resolveCommand('copilot'), 'C:\\trusted\\copilot.exe', entry);+ }+ for (const entry of ['C:\\tools', 'C:/tools', '\\\\server\\share\\tools', '//server/share/tools']) {+ const file = path.win32.join(entry, 'copilot.exe');+ const fixture = loadInstaller({ platform: 'win32', env: { Path: entry }, commands: [file] });+ assert.equal(fixture.installer.resolveCommand('copilot'), file);+ }+});++test('native CLI calls preserve argv and process options without shell interpretation', () => {+ for (const platform of ['linux', 'win32']) {+ const file = platform === 'win32' ? 'C:\\tools\\copilot.exe' : '/tools/copilot';+ const fixture = loadInstaller({ platform, commands: [file], execute: () => Buffer.from(' output \n') });+ const args = ['plugin', 'install', 'power-pages@power-platform-skills', ...INJECTION_NAMES];+ const result = fixture.installer.run('copilot', args, { cwd: 'working-directory' });+ assert.equal(result.ok, true);+ assert.equal(result.output, 'output');+ assert.equal(fixture.calls[0].file, file);+ assert.deepEqual(fixture.calls[0].args, args);+ assert.equal(fixture.calls[0].options.cwd, 'working-directory');+ assert.equal(fixture.calls[0].options.timeout, 120_000);+ assert.equal(fixture.calls[0].options.windowsVerbatimArguments, undefined);+ }+});++test('process failures, stderr and missing commands retain actionable error output', () => {+ const failure = loadInstaller({+ commands: ['/tools/copilot'],+ execute: () => { throw Object.assign(new Error('launch failed'), { stderr: Buffer.from('CLI error\n') }); },+ });+ assert.equal(failure.installer.run('copilot', ['--version']).output, 'CLI error');+ assert.equal(failure.installer.run('copilot', ['--version']).ok, false);+ assert.match(failure.installer.run('missing', []).output, /not found on PATH/);+});++test('Windows batch launchers use an absolute cmd.exe and only checked inert arguments', () => {+ for (const extension of ['cmd', 'bat']) {+ const file = `C:\\Program Files\\CLI\\copilot.${extension}`;+ const fixture = loadInstaller({+ platform: 'win32', commands: [file],+ env: { Path: 'C:\\Program Files\\CLI', ComSpec: 'cmd.exe', SystemRoot: 'C:\\Windows' },+ });+ assert.equal(fixture.installer.run('copilot', ['plugin', 'install', 'widget.v2@power-platform-skills']).ok, true);+ const call = fixture.calls[0];+ assert.equal(call.file, 'C:\\Windows\\System32\\cmd.exe');+ assert.deepEqual(call.args, ['/d', '/s', '/v:off', '/c',+ `""${file}" plugin install widget.v2@power-platform-skills"`]);+ assert.equal(call.options.windowsVerbatimArguments, true);+ assert.equal(call.options.env.NoDefaultCurrentDirectoryInExePath, '1');+ for (const arg of [...INJECTION_NAMES, 'a&b', 'a^b', '(echo)', 'a>b', 'a<b', 'two words', '', 'x\t', 42]) {+ assert.equal(fixture.installer.run('copilot', [arg]).ok, false, JSON.stringify(arg));+ }+ assert.equal(fixture.calls.length, 1, 'unsafe arguments fail before spawning');+ }+});++test('Windows batch launchers reject paths containing expansion, quotes or control characters', () => {+ for (const dir of ['C:\\100%\\bin', 'C:\\wow!\\bin', 'C:\\a"\\bin', 'C:\\line\nbreak\\bin']) {+ const fixture = loadInstaller({+ platform: 'win32', env: { Path: dir }, commands: [path.win32.join(dir, 'copilot.cmd')],+ });+ assert.equal(fixture.installer.run('copilot', ['--version']).ok, false, JSON.stringify(dir));+ assert.deepEqual(fixture.calls, []);+ }+});++test('Windows batch launchers ignore current-drive-relative ComSpec and reject an unqualified fallback', () => {+ for (const ComSpec of ['\\cmd.exe', '/cmd.exe', 'C:cmd.exe', 'cmd.exe']) {+ const fixture = loadInstaller({+ platform: 'win32', env: { Path: 'C:\\tools', ComSpec, SystemRoot: 'C:\\Windows' },+ commands: ['C:\\tools\\copilot.cmd'],+ });+ const result = fixture.installer.run('copilot', ['--version']);+ assert.equal(result.ok, true, result.output);+ assert.equal(fixture.calls[0].file, 'C:\\Windows\\System32\\cmd.exe', ComSpec);+ }+ for (const SystemRoot of ['\\Windows', '/Windows', 'C:Windows', 'Windows']) {+ const fixture = loadInstaller({+ platform: 'win32', env: { Path: 'C:\\tools', ComSpec: '\\cmd.exe', SystemRoot },+ commands: ['C:\\tools\\copilot.cmd'],+ });+ const result = fixture.installer.run('copilot', ['--version']);+ assert.equal(result.ok, false, SystemRoot);+ assert.match(result.output, /fully qualified/);+ assert.deepEqual(fixture.calls, []);+ }+});++test('Windows batch launchers accept fully qualified drive and UNC interpreter paths', () => {+ for (const ComSpec of ['D:\\Windows\\System32\\cmd.exe', '\\\\server\\share\\cmd.exe']) {+ const fixture = loadInstaller({+ platform: 'win32', env: { Path: 'C:\\tools', ComSpec, SystemRoot: '\\Windows' },+ commands: ['C:\\tools\\copilot.cmd'],+ });+ const result = fixture.installer.run('copilot', ['--version']);+ assert.equal(result.ok, true, result.output);+ assert.equal(fixture.calls[0].file, ComSpec);+ }+ const fixture = loadInstaller({+ platform: 'win32', env: { Path: 'C:\\tools', SystemRoot: '\\\\server\\share\\Windows' },+ commands: ['C:\\tools\\copilot.cmd'],+ });+ assert.equal(fixture.installer.run('copilot', ['--version']).ok, true);+ assert.equal(fixture.calls[0].file, '\\\\server\\share\\Windows\\System32\\cmd.exe');+});++test('both plugin installers pass the original CLI flags and identifiers as separate arguments', () => {+ const fixture = loadInstaller({ commands: ['/tools/claude', '/tools/copilot'] });+ fixture.installer.installClaude(MARKETPLACE);+ fixture.installer.installCopilot(MARKETPLACE);+ assert.deepEqual(fixture.calls.filter((call) => call.args[1] === 'install').map(({ file, args }) => ({ file, args })), [+ ...MARKETPLACE.map((name) => ({ file: '/tools/claude', args: ['plugin', 'install', `${name}@power-platform-skills`, '--scope', 'user'] })),+ ...MARKETPLACE.map((name) => ({ file: '/tools/copilot', args: ['plugin', 'install', `${name}@power-platform-skills`] })),+ ]);+ assert.deepEqual(fixture.calls.filter((call) => call.args[1] === 'marketplace').map((call) => call.args), [+ ['plugin', 'marketplace', 'add', 'microsoft/power-platform-skills'],+ ['plugin', 'marketplace', 'update', 'power-platform-skills'],+ ['plugin', 'marketplace', 'add', 'microsoft/power-platform-skills'],+ ]);+});++test('main preserves default and opt-in selection for clone, downloaded and piped launch modes', async () => {+ for (const platform of ['linux', 'win32']) {+ const paths = platform === 'win32' ? path.win32 : path.posix;+ const root = platform === 'win32' ? 'C:\\project' : '/project';+ const cliDir = platform === 'win32' ? 'C:\\tools' : '/tools';+ const extension = platform === 'win32' ? '.cmd' : '';+ for (const script of [paths.join(root, 'scripts', 'install.js'), paths.join(root, 'install.js'), '-', undefined]) {+ for (const includeDataverse of [false, true]) {+ if (script === undefined && includeDataverse) continue;+ const argv = script === undefined ? ['node'] : ['node', script];+ if (includeDataverse) argv.push('--include-dataverse');+ const fixture = loadInstaller({+ platform, argv,+ files: { [paths.join(root, 'marketplace.json')]: JSON.stringify(manifest()) },+ commands: ['claude', 'copilot', 'pac', 'az'].map((cli) => paths.join(cliDir, cli + extension)),+ });+ await fixture.installer.main();+ const calls = fixture.calls.filter((call) => platform === 'win32'+ ? call.args[4].includes(' plugin install ') : call.args[1] === 'install');+ const expected = includeDataverse ? MARKETPLACE : MARKETPLACE.filter((name) => name !== 'dataverse');+ assert.equal(calls.length, expected.length * 2);+ for (const name of expected) {+ assert.equal(calls.filter((call) => call.args.join(' ').includes(`${name}@power-platform-skills`)).length, 2);+ }+ assert.deepEqual(fixture.requests, [], 'local installs do not need another repository file or network request');+ if (!includeDataverse) assert.ok(fixture.messages.some((line) => line.includes('Skipping dataverse')));+ }+ }+ }+});++test('main never installs a plugin from an invalid local or downloaded marketplace', async () => {+ for (const local of [true, false]) {+ for (const name of INJECTION_NAMES) {+ const raw = JSON.stringify(manifest(['power-pages', name]));+ const fixture = loadInstaller({+ commands: ['/tools/claude', '/tools/copilot', '/tools/pac', '/tools/az'],+ files: local ? { '/project/marketplace.json': raw } : {},+ remote: local ? {} : { [RAW_ROOT + 'marketplace.json']: raw },+ });+ await assert.rejects(fixture.installer.main(), /plugins\[1\].name/);+ assert.equal(fixture.calls.some((call) => call.args[0] === 'plugin'), false);+ assert.deepEqual(fixture.writes, []);+ }+ }+});++test('prerequisite install and update commands retain their separate arguments', async () => {+ const cases = [+ { platform: 'linux', commands: ['copilot', 'dotnet', 'az'], expected: ['tool', 'install', '--global', 'Microsoft.PowerApps.CLI.Tool'] },+ { platform: 'linux', commands: ['copilot', 'dotnet', 'pac', 'az'], expected: ['tool', 'update', '--global', 'Microsoft.PowerApps.CLI.Tool'] },+ { platform: 'darwin', commands: ['copilot', 'pac', 'brew'], expected: ['install', 'azure-cli'] },+ { platform: 'win32', commands: ['copilot', 'pac', 'winget'], expected: ['install', '-e', '--id', 'Microsoft.AzureCLI',+ '--accept-source-agreements', '--accept-package-agreements'] },+ ];+ for (const scenario of cases) {+ const win = scenario.platform === 'win32';+ const paths = win ? path.win32 : path.posix;+ const root = win ? 'C:\\project' : '/project';+ const fixture = loadInstaller({+ platform: scenario.platform,+ commands: scenario.commands.map((cli) => paths.join(win ? 'C:\\tools' : '/tools', cli + (win ? '.exe' : ''))),+ files: { [paths.join(root, 'marketplace.json')]: JSON.stringify(manifest()) },+ remote: { 'https://api.nuget.org/v3-flatcontainer/microsoft.powerapps.cli.tool/index.json': '{"versions":["2.0.0"]}' },+ });+ await fixture.installer.main();+ assert.ok(fixture.calls.some((call) => JSON.stringify(call.args) === JSON.stringify(scenario.expected)));+ }+});++test('the single-file installer works when piped into Node, with or without an explicit stdin argument', () => {+ for (const args of [['-', '--help'], []]) {+ const input = args.length ? SOURCE : SOURCE.replace(/^(#![^\n]*\n)/,+ "$1process.argv.push('-', '--help');\n");+ const output = execFileSync(process.execPath, args, { input, encoding: 'utf8', timeout: 30_000, shell: false });+ assert.match(output, /Usage: node install.js/);+ assert.doesNotMatch(output, /Checking prerequisites/);+ }+});++test('a real native executable receives metacharacters as data, not shell syntax', () => {+ const fixture = loadInstaller({+ platform: process.platform,+ env: { ...process.env, PATH: path.dirname(process.execPath), Path: path.dirname(process.execPath) },+ commands: [process.execPath], execute: execFileSync,+ });+ const values = ['$(echo REVIEW_ONLY)', 'x" & echo REVIEW_ONLY & rem "', '%PATH%', '!PATH!'];+ const result = fixture.installer.run('node', ['-e', 'process.stdout.write(JSON.stringify(process.argv.slice(1)))', '--', ...values]);+ assert.equal(result.ok, true, result.output);+ assert.deepEqual(JSON.parse(result.output), values);+});++test('real Windows batch launchers forward plugin argv unchanged from a path containing spaces and &', {+ skip: process.platform !== 'win32',+}, (t) => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'installer shim & path-'));+ t.after(() => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 5, retryDelay: 100 }));+ const script = path.join(dir, 'argv.js');+ const shim = path.join(dir, 'copilot.cmd');+ fs.writeFileSync(script, 'process.stdout.write(JSON.stringify(process.argv.slice(2)));\n');+ fs.writeFileSync(shim, `@echo off\r\n"${process.execPath}" "${script}" %*\r\n`);+ const fixture = loadInstaller({+ platform: 'win32', env: { ...process.env, PATH: dir, Path: dir },+ commands: [shim], execute: execFileSync,+ });+ const args = ['plugin', 'install', 'widget.v2@power-platform-skills', '--scope', 'user'];+ const result = fixture.installer.run('copilot', args);+ assert.equal(result.ok, true, result.output);+ assert.deepEqual(JSON.parse(result.output), args);+});diff --git a/scripts/validate-plugin-names.js b/scripts/validate-plugin-names.jsindex b5cf08513..a17d1bc9a 100644--- a/scripts/validate-plugin-names.js+++ b/scripts/validate-plugin-names.js@@ -6,16 +6,16 @@const fs = require('fs');const path = require('path');+const { isValidPluginName } = require('./install.js');const ROOT = path.resolve(__dirname, '..');-const OPEN_PLUGIN_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9.-]{0,62}[a-z0-9])?$/;function validateName(name, source) {if (typeof name !== 'string') {return `${source}: plugin name must be a string`;}- if (OPEN_PLUGIN_NAME_PATTERN.test(name) && !name.includes('--') && !name.includes('..')) {+ if (isValidPluginName(name)) {return null;}return `${source}: '${name}' does not follow Open Plugins name constraints`;