Non-invasive MCP accelerator plugin for Google Antigravity (CLI/Desktop/IDE): cuts LLM turns (-34%), token quota (-31%), and upload traffic (-40%) without affecting native UI or diffs.
TypeScript ai-agentai-codingantigravityantigravity-cliantigravity-ideantigravity-pluginscoding-agentcontext-optimizationdeveloper-productivitydeveloper-toolsgeminigoogle-antigravitylatency-optimizationmcpmcp-pluginmcp-servermodel-context-protocolperformanceplugintoken-optimization
fix(install.ps1): isolate piped remote install from CWD, harden manifest/repo checks, and verify pwsh + PowerShell 5.1
wathing-wind1e15876ab52b
diff --git a/install.ps1 b/install.ps1index e1b4776..1222c90 100644--- a/install.ps1+++ b/install.ps1@@ -29,6 +29,7 @@ $__agyFastState = @{ ExitCode = 0 }param([string[]]$InputArgs = @(),[string]$ScriptRoot = "",+ [bool]$IsFile = $false,[hashtable]$State)@@ -36,7 +37,7 @@ $__agyFastState = @{ ExitCode = 0 }$defaultRepo = "https://github.com/INK-Q/agy-fast.git"if (-not (Get-Command node -ErrorAction SilentlyContinue)) {- Write-Error "Node.js >= 20 is required. Install Node.js first: https://nodejs.org/"+ Write-Error "Node.js >= 20 is required. Install Node.js first: https://nodejs.org/" -ErrorAction Continue$State.ExitCode = 1return}@@ -52,7 +53,7 @@ $__agyFastState = @{ ExitCode = 0 }$nodeMajor = 0if ($nodeCheckExit -ne 0 -or -not [int]::TryParse($nodeMajorRaw, [ref]$nodeMajor) -or $nodeMajor -lt 20) {$nodeVer = (& node -v 2>$null | Out-String).Trim()- Write-Error "Node.js >= 20 is required (found $nodeVer)."+ Write-Error "Node.js >= 20 is required (found $nodeVer)." -ErrorAction Continue$State.ExitCode = 1return}@@ -95,48 +96,97 @@ $__agyFastState = @{ ExitCode = 0 }}}- # In `irm ... | iex`, $ScriptRoot is empty. Never infer a local plugin from the- # current workspace in that case, and verify plugin identity before running local scripts\install.mjs.- if (-not [string]::IsNullOrEmpty($ScriptRoot)) {- $localManifest = Join-Path $ScriptRoot "plugin.json"- $localInstaller = Join-Path $ScriptRoot "scripts\install.mjs"- if ((Test-Path -LiteralPath $localManifest) -and (Test-Path -LiteralPath $localInstaller)) {- $isAgyFast = $false- try {- $manifestObj = Get-Content -LiteralPath $localManifest -Raw -Encoding UTF8 | ConvertFrom-Json- if ($null -ne $manifestObj -and [string]$manifestObj.name -eq "agy-fast") {- $isAgyFast = $true- }- } catch {- $isAgyFast = $false+ function Test-LocalAgyFastRepo {+ param(+ [string]$Candidate+ )+ if ([string]::IsNullOrWhiteSpace($Candidate)) {+ return $false+ }+ $manifestPath = Join-Path $Candidate "plugin.json"+ $installerPath = Join-Path (Join-Path $Candidate "scripts") "install.mjs"+ if (-not (Test-Path -LiteralPath $manifestPath -PathType Leaf) -or -not (Test-Path -LiteralPath $installerPath -PathType Leaf)) {+ return $false+ }+ try {+ $rawManifest = Get-Content -LiteralPath $manifestPath -Raw -Encoding UTF8 -ErrorAction Stop+ if ([string]::IsNullOrWhiteSpace($rawManifest)) {+ return $false+ }+ $trimmedManifest = $rawManifest.TrimStart([char]0xFEFF).TrimStart()+ if (-not $trimmedManifest.StartsWith("{")) {+ return $false}- if ($isAgyFast) {- Invoke-NodeInstaller -InstallerPath $localInstaller -ForwardArgs $forwardArgs -RunState $State- return+ $manifest = ConvertFrom-Json -InputObject $trimmedManifest -ErrorAction Stop+ if (-not ($manifest -is [pscustomobject])) {+ return $false}+ foreach ($prop in $manifest.PSObject.Properties) {+ if (($prop.Name -ceq "name") -and ($prop.Value -is [string]) -and ($prop.Value -ceq "agy-fast")) {+ return $true+ }+ }+ return $false+ } catch {+ return $false}}- $homeDir = if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {- $env:USERPROFILE- } elseif (-not [string]::IsNullOrWhiteSpace($HOME)) {- $HOME+ # Never fall back to CWD when invoked via `irm ... | iex` ($IsFile is $false).+ # Only trust a local scripts/install.mjs when running an explicit install.ps1 file+ # whose sibling plugin.json strictly identifies name === "agy-fast".+ if ($IsFile -and -not [string]::IsNullOrWhiteSpace($ScriptRoot) -and (Test-LocalAgyFastRepo -Candidate $ScriptRoot)) {+ $localInstaller = Join-Path (Join-Path $ScriptRoot "scripts") "install.mjs"+ Invoke-NodeInstaller -InstallerPath $localInstaller -ForwardArgs $forwardArgs -RunState $State+ return+ }++ $isWin = ($PSVersionTable.PSVersion.Major -lt 6) -or $IsWindows+ $userHome = if ($isWin) {+ if (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {+ $env:USERPROFILE+ } elseif ((-not [string]::IsNullOrWhiteSpace($env:HOMEDRIVE)) -and (-not [string]::IsNullOrWhiteSpace($env:HOMEPATH))) {+ ($env:HOMEDRIVE + $env:HOMEPATH).Trim()+ } elseif (-not [string]::IsNullOrWhiteSpace($env:HOME)) {+ $env:HOME+ } else {+ [Environment]::GetFolderPath('UserProfile')+ }+ } else {+ if (-not [string]::IsNullOrWhiteSpace($env:HOME)) {+ $env:HOME+ } elseif (-not [string]::IsNullOrWhiteSpace($HOME)) {+ $HOME+ } elseif (-not [string]::IsNullOrWhiteSpace($env:USERPROFILE)) {+ $env:USERPROFILE+ } else {+ [Environment]::GetFolderPath('UserProfile')+ }+ }+ $defaultTarget = if (-not [string]::IsNullOrWhiteSpace($userHome)) {+ Join-Path $userHome (Join-Path ".gemini" (Join-Path "config" (Join-Path "plugins" "agy-fast")))} else {""}- if ($hasSubcmd -and ($InputArgs[0] -ne "install") -and (-not [string]::IsNullOrWhiteSpace($homeDir))) {- $defaultTarget = Join-Path $homeDir ".gemini\config\plugins\agy-fast"- $installedInstaller = Join-Path $defaultTarget "scripts\install.mjs"- if (Test-Path -LiteralPath $installedInstaller) {- Invoke-NodeInstaller -InstallerPath $installedInstaller -ForwardArgs $forwardArgs -RunState $State- return- }+ $installedInstaller = if (-not [string]::IsNullOrWhiteSpace($defaultTarget)) {+ Join-Path (Join-Path $defaultTarget "scripts") "install.mjs"+ } else {+ ""+ }+ if ($hasSubcmd -and ($InputArgs[0] -ne "install") -and (-not [string]::IsNullOrEmpty($installedInstaller)) -and (Test-Path -LiteralPath $installedInstaller -PathType Leaf)) {+ Invoke-NodeInstaller -InstallerPath $installedInstaller -ForwardArgs $forwardArgs -RunState $State+ return}- $repoUrl = if ($env:AGY_FAST_REPO) { $env:AGY_FAST_REPO } else { $defaultRepo }+ $repoUrl = if (-not [string]::IsNullOrWhiteSpace($env:AGY_FAST_REPO)) { $env:AGY_FAST_REPO.Trim() } else { $defaultRepo }+ if ($repoUrl.StartsWith("-")) {+ Write-Error "Invalid AGY_FAST_REPO value: repository URL must not start with '-'." -ErrorAction Continue+ $State.ExitCode = 1+ return+ }if (-not (Get-Command git -ErrorAction SilentlyContinue)) {- Write-Error "git is required for remote installation."+ Write-Error "git is required for remote installation." -ErrorAction Continue$State.ExitCode = 1return}@@ -147,25 +197,25 @@ $__agyFastState = @{ ExitCode = 0 }$savedEap = $ErrorActionPreference$ErrorActionPreference = "Continue"try {- & git clone --depth 1 $repoUrl $tmpClone+ & git clone --depth 1 -- $repoUrl $tmpClone$gitExit = $LASTEXITCODE} finally {$ErrorActionPreference = $savedEap}if ($gitExit -ne 0) {- Write-Error "git clone failed with exit code $gitExit."+ Write-Error "git clone failed with exit code $gitExit." -ErrorAction Continue$State.ExitCode = $gitExitreturn}- $clonedInstaller = Join-Path $tmpClone "scripts\install.mjs"+ $clonedInstaller = Join-Path (Join-Path $tmpClone "scripts") "install.mjs"Invoke-NodeInstaller -InstallerPath $clonedInstaller -ForwardArgs $forwardArgs -RunState $State} finally {- if (Test-Path $tmpClone) {- Remove-Item -Path $tmpClone -Recurse -Force -ErrorAction SilentlyContinue+ if (Test-Path -LiteralPath $tmpClone) {+ Remove-Item -LiteralPath $tmpClone -Recurse -Force -ErrorAction SilentlyContinue}}-} -InputArgs $__agyFastRawArgs -ScriptRoot $__agyFastScriptRoot -State $__agyFastState+} -InputArgs $__agyFastRawArgs -ScriptRoot $__agyFastScriptRoot -IsFile $__agyFastIsFile -State $__agyFastState$__agyFastFinalExit = $__agyFastState.ExitCode$__agyFastWasFile = $__agyFastIsFilediff --git a/test/installer.test.ts b/test/installer.test.tsindex 6e535e9..fb9b412 100644--- a/test/installer.test.ts+++ b/test/installer.test.ts@@ -1,5 +1,5 @@import assert from "node:assert/strict";-import { execFileSync, spawn } from "node:child_process";+import { execFileSync, spawn, spawnSync } from "node:child_process";import { promises as fs } from "node:fs";import os from "node:os";import path from "node:path";@@ -243,7 +243,205 @@ describe("installer", () => {assert.match(ps1, /"mcp-config"/);assert.doesNotMatch(ps1, /Get-Location/);assert.match(ps1, /ConvertFrom-Json/);- assert.match(ps1, /\$manifestObj\.name\s+-eq\s+"agy-fast"/);+ assert.match(ps1, /Test-LocalAgyFastRepo/);+ });++ it("isolates install.ps1 piped remote execution from CWD, hardens manifest/repo checks, and verifies behavior on pwsh & PowerShell 5.1", async () => {+ const ps1 = await fs.readFile(INSTALL_PS1, "utf8");+ // Must never fall back to CWD when invoked via piped `irm ... | iex`+ assert.doesNotMatch(ps1, /Get-Location/);+ assert.match(ps1, /if\s*\(\s*\$IsFile\s+-and\s+-not\s+\[string\]::IsNullOrWhiteSpace\(\$ScriptRoot\)\s+-and\s+\(Test-LocalAgyFastRepo\s+-Candidate\s+\$ScriptRoot\)\s*\)/);+ // Strict JSON object/string/case-sensitive manifest validation (key + value, no array coercion/unwrapping)+ assert.match(ps1, /ConvertFrom-Json\s+-InputObject\s+\$trimmedManifest/);+ assert.match(ps1, /\$manifest\s+-is\s+\[pscustomobject\]/);+ assert.match(ps1, /\$prop\.Name\s+-ceq\s+"name"/);+ assert.match(ps1, /\$prop\.Value\s+-is\s+\[string\]/);+ assert.match(ps1, /\$prop\.Value\s+-ceq\s+"agy-fast"/);+ // Platform-aware home resolution (with Windows HOMEDRIVE+HOMEPATH fallback), LiteralPath cleanup, and git option-injection guard+ assert.doesNotMatch(ps1, /Join-Path\s+\$env:USERPROFILE\b/);+ assert.match(ps1, /\$isWin\s*=\s*\(\$PSVersionTable\.PSVersion\.Major\s+-lt\s+6\)\s+-or\s+\$IsWindows/);+ assert.match(ps1, /\$env:HOMEDRIVE/);+ assert.match(ps1, /\$env:HOMEPATH/);+ assert.match(ps1, /Test-Path\s+-LiteralPath\s+\$tmpClone/);+ assert.match(ps1, /Remove-Item\s+-LiteralPath\s+\$tmpClone/);+ assert.match(ps1, /& git clone --depth 1 -- \$repoUrl \$tmpClone/);++ // Validate AST syntax AND real behavioral execution across every installed PowerShell engine+ // (on Windows CI, both pwsh 7 AND Windows PowerShell 5.1 are exercised — no early `break`).+ const psCandidates = process.platform === "win32" ? ["pwsh", "powershell.exe"] : ["pwsh"];+ const availableBins: string[] = [];+ for (const bin of psCandidates) {+ const parseRes = spawnSync(+ bin,+ [+ "-NoProfile",+ "-NonInteractive",+ "-Command",+ "$t = $null; $e = $null; [void][System.Management.Automation.Language.Parser]::ParseFile($env:AGY_TEST_PS1_PATH, [ref]$t, [ref]$e); if ($e.Count -gt 0) { $e | ForEach-Object { [Console]::Error.WriteLine($_.Message) }; exit 1 }",+ ],+ { env: { ...process.env, AGY_TEST_PS1_PATH: INSTALL_PS1 }, encoding: "utf8" },+ );+ if ((parseRes.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT") continue;+ assert.equal(parseRes.error, undefined, `${bin} spawn failed: ${String(parseRes.error)}`);+ assert.equal(parseRes.status, 0, `${bin} failed to parse install.ps1: ${parseRes.stderr}`);+ availableBins.push(bin);+ }++ if (process.platform === "win32") {+ assert.ok(+ availableBins.includes("powershell.exe"),+ "Expected Windows PowerShell 5.1 (powershell.exe) to be exercised on Windows",+ );+ }++ if (availableBins.length === 0) return;++ const psSandbox = await fs.mkdtemp(path.join(os.tmpdir(), "agy-fast-ps1-safety-"));+ try {+ const project = path.join(psSandbox, "decoy-workspace");+ const binDir = path.join(psSandbox, "bin");+ const localRepo = path.join(psSandbox, "local-repo");+ const psHome = path.join(psSandbox, "home");+ await fs.mkdir(path.join(project, "scripts"), { recursive: true });+ await fs.mkdir(binDir, { recursive: true });+ await fs.mkdir(path.join(localRepo, "scripts"), { recursive: true });+ await fs.mkdir(psHome, { recursive: true });++ // Decoy workspace pretends to be agy-fast+ await fs.writeFile(path.join(project, "plugin.json"), JSON.stringify({ name: "agy-fast" }), "utf8");+ await fs.writeFile(+ path.join(project, "scripts", "install.mjs"),+ 'console.log("DECOY_EXECUTED");\n',+ "utf8",+ );++ // Stub git binary that proves remote clone path was selected without hitting network+ if (process.platform === "win32") {+ await fs.writeFile(+ path.join(binDir, "git.cmd"),+ "@echo off\r\necho REMOTE_CLONE_ATTEMPT 1>&2\r\nexit /b 19\r\n",+ "utf8",+ );+ } else {+ const fakeGit = path.join(binDir, "git");+ await fs.writeFile(fakeGit, "#!/bin/sh\necho REMOTE_CLONE_ATTEMPT >&2\nexit 19\n", "utf8");+ await fs.chmod(fakeGit, 0o755);+ }++ const buildPsEnv = (extra: Record<string, string | undefined> = {}): NodeJS.ProcessEnv => {+ const env: NodeJS.ProcessEnv = { ...process.env };+ let origPath = "";+ for (const k of Object.keys(env)) {+ if (k.toLowerCase() === "path") {+ origPath = origPath || env[k] || "";+ delete env[k];+ }+ }+ const nodeDir = path.dirname(process.execPath);+ env.PATH = `${binDir}${path.delimiter}${nodeDir}${origPath ? `${path.delimiter}${origPath}` : ""}`;+ env.HOME = psHome;+ env.USERPROFILE = psHome;+ delete env.AGY_FAST_REPO;+ for (const [k, v] of Object.entries(extra)) {+ if (v === undefined) delete env[k];+ else env[k] = v;+ }+ return env;+ };++ await fs.copyFile(INSTALL_PS1, path.join(localRepo, "install.ps1"));+ await fs.writeFile(+ path.join(localRepo, "scripts", "install.mjs"),+ 'console.log("LOCAL_INSTALLER", process.argv.slice(2).join(" "));\n',+ "utf8",+ );++ for (const bin of availableBins) {+ const baseFlags =+ process.platform === "win32"+ ? ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass"]+ : ["-NoProfile", "-NonInteractive"];++ // 1. Piped `irm | iex` inside decoy CWD must NEVER execute decoy scripts/install.mjs+ const pipedRes = spawnSync(+ bin,+ [+ ...baseFlags,+ "-Command",+ "$src = Get-Content -LiteralPath $env:AGY_TEST_PS1_PATH -Raw; Invoke-Expression $src",+ ],+ {+ cwd: project,+ env: buildPsEnv({ AGY_TEST_PS1_PATH: INSTALL_PS1 }),+ encoding: "utf8",+ },+ );+ const pipedCombined = `${pipedRes.stdout}\n${pipedRes.stderr}`;+ assert.doesNotMatch(pipedCombined, /DECOY_EXECUTED/, `${bin}: piped iex executed CWD decoy`);+ assert.match(pipedCombined, /REMOTE_CLONE_ATTEMPT/, `${bin}: piped iex did not reach remote clone`);++ // 2. Explicit local file invocation from another CWD executes sibling scripts/install.mjs+ await fs.writeFile(+ path.join(localRepo, "plugin.json"),+ JSON.stringify({ name: "agy-fast" }),+ "utf8",+ );+ const localRes = spawnSync(+ bin,+ [...baseFlags, "-File", path.join(localRepo, "install.ps1"), "doctor"],+ {+ cwd: project,+ env: buildPsEnv(),+ encoding: "utf8",+ },+ );+ assert.equal(localRes.status, 0, `${bin}: local install.ps1 failed: ${localRes.stderr}`);+ assert.match(localRes.stdout, /LOCAL_INSTALLER doctor/);+ assert.doesNotMatch(`${localRes.stdout}\n${localRes.stderr}`, /REMOTE_CLONE_ATTEMPT/);++ // 3. Foreign / array-coercion / single-element-array / key-or-value case-mismatch manifests reject local execution+ const invalidManifests = [+ JSON.stringify({ name: "other" }),+ JSON.stringify({ name: ["agy-fast", "evil"] }),+ JSON.stringify([{ name: "agy-fast" }]),+ JSON.stringify({ name: "AGY-FAST" }),+ JSON.stringify({ Name: "agy-fast" }),+ ];+ for (const badJson of invalidManifests) {+ await fs.writeFile(path.join(localRepo, "plugin.json"), badJson, "utf8");+ const badRes = spawnSync(+ bin,+ [...baseFlags, "-File", path.join(localRepo, "install.ps1")],+ {+ cwd: project,+ env: buildPsEnv(),+ encoding: "utf8",+ },+ );+ const badCombined = `${badRes.stdout}\n${badRes.stderr}`;+ assert.equal(badRes.status, 19, `${bin}: expected stub git exit 19 for ${badJson}, got ${badRes.status}: ${badCombined}`);+ assert.match(badCombined, /REMOTE_CLONE_ATTEMPT/, `${bin}: expected remote clone for ${badJson}`);+ assert.doesNotMatch(badCombined, /LOCAL_INSTALLER/, `${bin}: executed local installer for ${badJson}`);+ }++ // 4. Rejects dash-prefixed AGY_FAST_REPO before invoking git+ const dashRepoRes = spawnSync(+ bin,+ [...baseFlags, "-File", path.join(localRepo, "install.ps1")],+ {+ cwd: project,+ env: buildPsEnv({ AGY_FAST_REPO: "--upload-pack=evil" }),+ encoding: "utf8",+ },+ );+ const dashCombined = `${dashRepoRes.stdout}\n${dashRepoRes.stderr}`;+ assert.equal(dashRepoRes.status, 1, `${bin}: expected exit 1 for dash-prefixed repo`);+ assert.match(dashCombined, /must not start with '-'/);+ assert.doesNotMatch(dashCombined, /REMOTE_CLONE_ATTEMPT/);+ }+ } finally {+ await fs.rm(psSandbox, { recursive: true, force: true });+ }});it("protects source repo across symlink/case variants, rejects ancestors and non-plugin dirs, and handles empty/symlink targets safely", async () => {