diff --git a/.github/workflows/npm-package-release.yml b/.github/workflows/npm-package-release.yml new file mode 100644 index 0000000..97e933e --- /dev/null +++ b/.github/workflows/npm-package-release.yml @@ -0,0 +1,174 @@ +name: npm-package-release + +on: + push: + tags: + - 'v[0-9]*' + pull_request: + branches: [main] + workflow_dispatch: + +permissions: + contents: read + +jobs: + clean-install: + name: npm clean install / ${{ matrix.os }} + runs-on: ${{ matrix.os }} + timeout-minutes: 25 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest, macos-latest] + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + version: 12 + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: pnpm + - run: pnpm install --frozen-lockfile --ignore-scripts + - name: Compile and test npm tarball, gateway, MCP, and local Admin UI + run: pnpm run test:package + - run: pnpm run test:portable + - run: pnpm run test:portable:server + - run: pnpm run test:cli + - run: pnpm run test:extensions + - name: Linux policy and integration acceptance + if: runner.os == 'Linux' + run: pnpm run test:policy && pnpm run test:integration && pnpm run test:sources + shell: bash + + full-tests: + name: npm release full regression / Linux + runs-on: ubuntu-latest + timeout-minutes: 25 + steps: + - uses: actions/checkout@v4 + - uses: pnpm/action-setup@v4 + with: + version: 12 + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: pnpm + - run: pnpm install --frozen-lockfile --ignore-scripts + - name: Install workstation-specific test prerequisites + # Full suite tests real chezmoi target resolution and fish syntax. + # CI-only tools; no npm runtime dependency or modified assertions. + shell: bash + run: | + set -euo pipefail + sudo apt-get update -qq + sudo apt-get install -y --no-install-recommends fish + # Ubuntu's runner apt repositories do not provide chezmoi. + # Fetch one immutable upstream release and verify its published digest. + curl --fail --location --silent --show-error --retry 2 \ + https://github.com/twpayne/chezmoi/releases/download/v2.74.1/chezmoi_2.74.1_linux_amd64.tar.gz \ + -o "$RUNNER_TEMP/chezmoi.tar.gz" + printf '%s %s\n' \ + ae01c66b1a6dbf563667c63fbbd9986b3cfa3c98dd266ddee732f63e8af2e9d1 \ + "$RUNNER_TEMP/chezmoi.tar.gz" | sha256sum --check + tar -xzf "$RUNNER_TEMP/chezmoi.tar.gz" -C "$RUNNER_TEMP" chezmoi + chmod 755 "$RUNNER_TEMP/chezmoi" + echo "$RUNNER_TEMP" >> "$GITHUB_PATH" + "$RUNNER_TEMP/chezmoi" --version + fish --version + - run: pnpm run build + - name: Full existing regression suite + run: pnpm run test:all + - name: Native tool schema inventory + run: node scripts/sync-tool-counts.mjs --check-manifest profiles/native-tool-counts.json + + tarball: + name: Verified npm tarball + needs: [clean-install, full-tests] + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + - uses: pnpm/action-setup@v4 + with: + version: 12 + - uses: actions/setup-node@v4 + with: + node-version: '24' + cache: pnpm + - run: pnpm install --frozen-lockfile --ignore-scripts + - name: Verify release tag and protected main ancestry + if: startsWith(github.ref, 'refs/tags/') + shell: bash + run: | + node -e 'const p=require("./package.json");if(process.env.GITHUB_REF_NAME!=="v"+p.version){throw Error("Tag and package.json version mismatch")}' + git fetch origin main + git merge-base --is-ancestor HEAD origin/main + - name: Generate prebuilt package + run: npm pack + - name: Record tarball SHA-256 + shell: bash + run: sha256sum bridge-dev-*.tgz + - uses: actions/upload-artifact@v4 + with: + name: npm-tarball + path: bridge-dev-*.tgz + if-no-files-found: error + retention-days: 14 + + publish: + name: npm trusted publish (explicit opt-in only) + needs: tarball + # Existing npm package: trusted publisher registered in npm settings. + # Avoid setup-node registry-url here: an empty _authToken can suppress OIDC. + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && vars.NPM_PUBLISH_ENABLED == 'true' && vars.NPM_TRUSTED_PUBLISH_READY == 'true' && vars.NPM_BOOTSTRAP_ENABLED != 'true' + runs-on: ubuntu-latest + environment: npm-release + timeout-minutes: 10 + permissions: + contents: read + id-token: write + steps: + - uses: actions/setup-node@v4 + with: + node-version: '24' + - uses: actions/download-artifact@v4 + with: + name: npm-tarball + - name: Require npm trusted-publishing CLI version + shell: bash + run: | + node -e 'const [a,b,c]=require("child_process").execFileSync("npm",["--version"],{encoding:"utf8"}).trim().split(".").map(Number);if(a<11||(a===11&&(b<5||(b===5&&c<1))))throw Error("npm 11.5.1+ required for OIDC publishing")' + - name: Publish verified tarball using OIDC with provenance + shell: bash + run: npm publish ./bridge-dev-*.tgz --access public --provenance + + bootstrap-publish: + name: npm first release (explicit one-time credential opt-in) + needs: tarball + # npm requires the package to exist before a trusted publisher can be + # registered. Only the initial release uses a reviewed temporary npm token. + if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') && vars.NPM_PUBLISH_ENABLED == 'true' && vars.NPM_BOOTSTRAP_ENABLED == 'true' && vars.NPM_TRUSTED_PUBLISH_READY != 'true' + runs-on: ubuntu-latest + environment: npm-release + timeout-minutes: 10 + permissions: + contents: read + id-token: write + steps: + - uses: actions/setup-node@v4 + with: + node-version: '24' + registry-url: 'https://registry.npmjs.org' + - uses: actions/download-artifact@v4 + with: + name: npm-tarball + - name: First package publication with provenance + shell: bash + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + run: | + test -n "$NODE_AUTH_TOKEN" || { echo "Missing NPM_TOKEN secret for one-time initial publication" >&2; exit 1; } + npm publish ./bridge-dev-*.tgz --access public --provenance diff --git a/.github/workflows/portable-platforms.yml b/.github/workflows/portable-platforms.yml index 227891c..405b17f 100644 --- a/.github/workflows/portable-platforms.yml +++ b/.github/workflows/portable-platforms.yml @@ -31,6 +31,8 @@ jobs: - run: pnpm run test:portable:server - run: pnpm run test:trial - run: pnpm run test:cli + - name: Packed npm installation (isolated prefix) + run: pnpm run test:package - run: node scripts/test-install-portable.mjs - run: pnpm run test:extensions sources: diff --git a/README.md b/README.md index 21eeca9..8f7af58 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,22 @@ Requires **Node.js 22+ and npm**. No Git checkout, global TypeScript or pnpm installation is required. The standard portable install needs no administrator permissions, background service, or host-root controller. +**npm package (after its first verified registry release):** + +```sh +npm install -g bridge-dev +bridge-dev setup +bridge-dev start +``` + +The tarball contains the prebuilt CLI, gateway and Admin UI; no Git checkout, +TypeScript toolchain or postinstall script is needed on the consumer machine. +Until publication, the same tarball is validated with `pnpm run test:package`. +An npm installation does not enable a service or grant root access. Existing +managed Linux installations keep their verified GitHub updater and signed lease +workflow. [Package details](docs/INSTALL.md#npm-package) ยท +[Release procedure](docs/RELEASING.md). + **Linux / macOS / Termux** ```sh diff --git a/docs/INSTALL.md b/docs/INSTALL.md index cbb7daa..69a1a73 100644 --- a/docs/INSTALL.md +++ b/docs/INSTALL.md @@ -24,6 +24,53 @@ modes and update requirements. +## npm package + +BridgeDev is packaged as a precompiled npm CLI: its tarball contains `dist/`, +`public/ui/`, reviewed portable profiles, required runtime scripts, and the +license and installation documentation. npm installs the production Node.js +dependencies automatically. No TypeScript build, pnpm, Git checkout, service or +root controller is required on the consumer machine. + +After a registry release is explicitly published, the installation is: + +~~~sh +npm install -g bridge-dev +bridge-dev setup +bridge-dev start +~~~ + +**Publication is a separate operator action.** Until the registry package is +published, create and inspect a local tarball instead: + +~~~sh +pnpm install --frozen-lockfile --ignore-scripts +npm run test:package +npm pack +# In a disposable prefix, inspect and install the generated .tgz before use. +~~~ + +`npm run test:package` builds and checks the tarball in a temporary local +installation, verifies CLI/help and portable setup, and rejects excluded files. +The global npm command must not replace the launcher for an existing managed +BridgeDev installation. Its signed host-controller lease, systemd cutover and +rollback remain governed by the [separate managed update procedure](PERSISTENT_SERVICE.md). +For an **explicit initial** Linux service setup from an npm-installed CLI, +`bridge-dev service install --start` stages the *GitHub CI-verified release* +corresponding to the npm package's `vX.Y.Z` tag; it does not seed the unverified +npm files into an operator-privileged service. This advanced operation requires +the `gh` CLI authenticated for the release-artifact API, an already-published +tag and green main-branch CI. It does not create YOLO authorization or Funnel +exposure. Existing managed installations use their own operator CLI for +verified service updates; a standalone npm CLI only reports npm update guidance. + +`bridge-dev --version` reports the packaged version. `bridge-dev doctor` +identifies the installation source. For npm installs, `bridge-dev update --check` +reports the manual update command `npm install -g bridge-dev@latest` and does +not invoke GitHub deployment or npm itself; the managed Linux updater is +unchanged. A standalone npm gateway must never inherit a different, managed +gateway's operator-signed YOLO authorization. See [release instructions](RELEASING.md). + ## One-command portable installation Requirements: **Node.js 22+ and npm**. The shell installer also needs `curl` and `tar`. Windows PowerShell requires `Invoke-WebRequest` and `Expand-Archive`. diff --git a/docs/RELEASING.md b/docs/RELEASING.md new file mode 100644 index 0000000..481e57e --- /dev/null +++ b/docs/RELEASING.md @@ -0,0 +1,102 @@ +# BridgeDev npm release procedure + +The npm tarball is a precompiled JavaScript CLI and gateway, not a system installer. +Node.js >=22 is required on the consumer machine. It includes the Admin UI, +reviewed metadata profiles, and the lease verification / service acceptance +helpers needed by the code. npm resolves the five production JavaScript packages; +there are no required native Node addons, postinstall scripts, persistent +services, host-root grants, credential copies, or automatically started servers. + +## Package name and ownership + +The intended public name is `bridge-dev` (version 2.0.0 is the current source +baseline). On 2026-11-17, `npm view bridge-dev` returned E404, **not proof of +permanent name reservation**. Before first publication, independently check +`npm view bridge-dev` from the operator's terminal, then register/login to +[npmjs.com](https://www.npmjs.com/). If another account owns the name, use +`@kmanisk/bridge-dev` with `--access public`, update `package.json`, +all hardcoded npm commands and package tests, and inspect the changed tarball. +Never publish an unreviewed third-party package under the intended name. + +## Local preflight (no publication) + +From a clean feature branch: + +```sh +pnpm install --frozen-lockfile --ignore-scripts +pnpm run test:package +pnpm test +pnpm run test:policy +pnpm run test:portable +pnpm run test:cli +pnpm run test:extensions +pnpm run test:integration +pnpm run test:all +node scripts/sync-tool-counts.mjs --check-manifest profiles/native-tool-counts.json +git diff --check +npm pack --dry-run +``` + +The packaged test creates a disposable npm installation with its own HOME, +configuration, workspace, ports and tokens; it starts an isolated gateway, +checks an authenticated MCP session and local Admin UI, and removes fixtures. +It must not attach to a running managed service or inherit its signed YOLO +lease. Inspect the tarball file list and source diff before approving a release. + +## npm publishing (operator-only setup) + +1. Create or sign in to npm, enable account-level two-factor authentication, + configure recovery factors and confirm the package name is available. +2. Configure a protected GitHub Actions environment named `npm-release`, + with a required operator reviewer before publishing. +3. **First publication:** npm requires a package to exist before its trusted + publisher can be configured. Create a short-lived npm publication token + with appropriate publish privileges and save it as a GitHub Actions + repository secret `NPM_TOKEN`. For a one-time, independently approved + release, set repository variables `NPM_BOOTSTRAP_ENABLED=true` and + `NPM_PUBLISH_ENABLED=true`; leave `NPM_TRUSTED_PUBLISH_READY` unset. + The tag workflow then publishes its *verified tarball* using that token + with provenance from CI, not from the developer's laptop. +4. Immediately after the first release, **revoke the bootstrap token** and + set `NPM_BOOTSTRAP_ENABLED=false`. In the npm package's Trusted Publisher + settings, register GitHub Actions owner `kmanisk`, repository `bridge-dev`, + workflow filename `npm-package-release.yml`, allowing release + publication. Set `NPM_TRUSTED_PUBLISH_READY=true` only after validating + the link. Keep `NPM_PUBLISH_ENABLED=false` until the next release + is independently approved. +5. Subsequent releases use **tokenless GitHub OIDC** with `id-token: write`, + Node.js 24, npm CLI 11.5.1+, and provenance. The OIDC job deliberately + avoids a `setup-node` `registry-url` option because an empty .npmrc + auth token may suppress the trusted-publisher exchange. Do not install + an npm token for these releases. +6. Review the version bump in `package.json` and `pnpm-lock.yaml` as + applicable; merge via the protected `main` pull request and CI. + Confirm the exact merged main commit and package version locally. + Create a signed or annotated `vX.Y.Z` tag on that exact commit and push + it **only after explicit publication approval**. This document does + not authorize creating a tag or publishing automatically. +7. The tag workflow runs Linux, Windows and macOS clean-install tests, + full Linux regression, a tag/version and main ancestry check, and + uploads the verified .tgz artifact. Publishing occurs only if + `NPM_PUBLISH_ENABLED=true` *and* the corresponding one-time bootstrap + or trusted-publisher flag is set. Manual `workflow_dispatch` only verifies. +8. From a fresh terminal inspect `npm view bridge-dev version dist.integrity` + and provenance, then `npm install -g bridge-dev`, + `bridge-dev --version`, `bridge-dev doctor` and an explicit portable + gateway smoke test. Never paste private credentials into logs. + +## Upgrade, recovery and rollback + +- npm installation: `npm install -g bridge-dev@latest` executed manually as + the owner; no background updates. For a known good version use + `npm install -g bridge-dev@X.Y.Z`. +- A verified managed Linux service is **not** upgraded by npm. It uses + `bridge-dev update`, its GitHub CI artifact, shadow tests, controlled + systemd cutover, preserved operator-signed lease and rollback. +- GitHub-source portable installer: rerun the reviewed `install.sh` or + `install.ps1`; its previous built app is retained separately. +- npm versions are immutable: do **not** overwrite a published version. + For an incorrect release, use `npm deprecate bridge-dev@X.Y.Z + "Reason; use X.Y.Z+1"` and publish a new patch version through a new, + reviewed tag. Follow npm policy for rare unpublish emergencies. +- Never update a running production gateway merely to test npm packaging. diff --git a/package.json b/package.json index a8f0597..9ced61d 100644 --- a/package.json +++ b/package.json @@ -12,12 +12,35 @@ }, "author": "kmanisk (based on MIT-licensed chatgpt-local-coder by hoangcoderr)", "type": "module", + "engines": { + "node": ">=22" + }, + "files": [ + "dist/", + "public/ui/", + "profiles/", + "scripts/lease-activation.mjs", + "scripts/lease-activation.d.mts", + "scripts/deploy-acceptance/", + "scripts/shadow-release-acceptance.mjs", + "scripts/policygate-operator.mjs", + "platform/windows-provider-cleanup.ps1", + "docs/INSTALL.md", + "docs/RELEASING.md", + "docs/POLICY_GATEWAY.md", + "docs/PERSISTENT_SERVICE.md", + "docs/HOST_CONTROLLER.md", + "docs/MCP_INTEGRATIONS.md", + "docs/ADMIN_AUTH.md" + ], "main": "dist/index.js", "bin": { "bridge-dev": "dist/cli.js" }, "scripts": { "build": "tsc", + "prepack": "npm run build", + "test:package": "npm run build && node scripts/test-install-source.mjs && node scripts/test-npm-package.mjs", "test": "tsc && node scripts/isolated-tests.mjs scripts/test-patch.mjs scripts/test-tools.mjs scripts/test-checkpoints.mjs scripts/test-mcp-upstream.mjs scripts/test-mcp-oauth.mjs scripts/test-activity-log.mjs scripts/test-project-memory.mjs scripts/test-tool-profile.mjs scripts/test-shell-persist.mjs scripts/test-phase1-safe-edit.mjs scripts/test-phase2-chezmoi.mjs scripts/test-system-enhancements.mjs scripts/test-policy-gateway.mjs", "test:all": "node scripts/run-all-tests.mjs", "test:integration": "tsc && node scripts/isolated-tests.mjs scripts/test-mcp-bridge-integration.mjs scripts/test-extension-interfaces.mjs scripts/test-managed-session-http.mjs scripts/test-output-schemas.mjs scripts/test-deploy-acceptance.mjs", diff --git a/scripts/mock-host-controller-gateway.mjs b/scripts/mock-host-controller-gateway.mjs index 850adaf..bda7e19 100644 --- a/scripts/mock-host-controller-gateway.mjs +++ b/scripts/mock-host-controller-gateway.mjs @@ -3,6 +3,7 @@ import {mock} from 'node:test'; if(!process.env.BRIDGEDEV_TEST_ROOT)throw Error('Isolated HTTP fixture only'); mock.module('../dist/lib/host-controller.js',{namedExports:{ hostControllerAvailable:()=>true, + verifiedManagedGatewayIdentity:()=>true, executeHostCommand:async(command,cwd,timeout,approvalId)=>({exit_code:0,stdout:'UNPRIVILEGED_ROUTING_FIXTURE',stderr:'',cwd,timed_out:false,job_id:'fixture-routing-only',job_status:'SUCCESS',fixture_command:command,fixture_approval:approvalId||null}), controllerCall:async()=>{throw Error('Real host controller prohibited in fixture');} }}); diff --git a/scripts/test-install-source.mjs b/scripts/test-install-source.mjs new file mode 100644 index 0000000..d6dda0b --- /dev/null +++ b/scripts/test-install-source.mjs @@ -0,0 +1,61 @@ +#!/usr/bin/env node +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { detectInstallSource, updateInstructions } from "../dist/lib/install-source.js"; + +const temp = fs.mkdtempSync(path.join(os.tmpdir(), "bridge-dev-install-kind-")); +try { + const src = path.join(temp, "source"); + const installed = path.join(temp, "node_modules", "bridge-dev"); + const scoped = path.join(temp, "node_modules", "@kmanisk", "bridge-dev"); + const portable = path.join(temp, "portable", "app"); + const release = path.join(temp, "releases", "abc"); + for (const dir of [src, installed, scoped, portable, release]) fs.mkdirSync(dir, {recursive:true}); + fs.mkdirSync(path.join(portable,"scripts")); + fs.writeFileSync(path.join(portable,"scripts","install-portable.mjs"),""); + fs.writeFileSync(path.join(release,"DEPLOYED_COMMIT"),"a".repeat(40)+"\n"); + + assert.equal(detectInstallSource(src),"source"); + assert.equal(detectInstallSource(installed),"npm"); + assert.equal(detectInstallSource(scoped),"npm"); + assert.equal(detectInstallSource(portable),"portable-installer"); + assert.equal(detectInstallSource(release),"managed"); + assert.match(updateInstructions("npm"),/^npm install -g bridge-dev@latest/); + assert.match(updateInstructions("managed"),/bridge-dev update/); + assert.match(updateInstructions("portable-installer"),/install\.sh/); + if (process.platform === "linux" && !process.env.BRIDGEDEV_TEST_ROOT) { + // Synthetic active-release identity; never access the real operator or lease. + const manager = path.join(temp,"managed-service"); + const sha = "b".repeat(40); + const active = path.join(manager,"releases",sha); + const lib = path.join(active,"dist","lib"); + fs.mkdirSync(lib,{recursive:true}); + fs.mkdirSync(path.join(manager,"service")); + fs.copyFileSync(path.join(process.cwd(),"dist","lib","host-controller.js"), + path.join(lib,"host-controller.js")); + fs.writeFileSync(path.join(active,"package.json"),'{"type":"module"}'); + fs.writeFileSync(path.join(active,"DEPLOYED_COMMIT"),sha+"\n"); + fs.symlinkSync(path.join("releases",sha),path.join(manager,"current")); + fs.writeFileSync(path.join(manager,"service","config.json"), + JSON.stringify({root:manager,current:sha}),{mode:0o600}); + const previous = process.env.BRIDGEDEV_SERVICE_ROOT; + try { + process.env.BRIDGEDEV_SERVICE_ROOT=manager; + const {verifiedManagedGatewayIdentity} = await import( + new URL("file://"+path.join(lib,"host-controller.js"))); + assert.equal(verifiedManagedGatewayIdentity(),true); + fs.writeFileSync(path.join(manager,"service","config.json"), + JSON.stringify({root:manager,current:"c".repeat(40)}),{mode:0o600}); + assert.equal(verifiedManagedGatewayIdentity(),false, + "Mismatched release must fail closed"); + } finally { + if (previous === undefined) delete process.env.BRIDGEDEV_SERVICE_ROOT; + else process.env.BRIDGEDEV_SERVICE_ROOT=previous; + } + } + console.log("Install-source identification and managed release isolation PASS"); +} finally { + fs.rmSync(temp,{recursive:true,force:true}); +} diff --git a/scripts/test-npm-package.mjs b/scripts/test-npm-package.mjs new file mode 100644 index 0000000..a52476d --- /dev/null +++ b/scripts/test-npm-package.mjs @@ -0,0 +1,257 @@ +#!/usr/bin/env node +// Verify the publishable npm tarball in an isolated, disposable prefix. +// No global installation, service manipulation, root access, or npm publish. +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { spawn, spawnSync } from "node:child_process"; +import { fileURLToPath } from "node:url"; +import net from "node:net"; +import { randomBytes } from "node:crypto"; + +const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const pkg = JSON.parse(fs.readFileSync(path.join(root, "package.json"), "utf8")); +const npm = process.platform === "win32" ? "npm.cmd" : "npm"; +const scratch = fs.mkdtempSync(path.join(os.tmpdir(), "bridge-dev-npm-pack-")); +const prefix = path.join(scratch, "install"); +const home = path.join(scratch, "home"); +const cache = path.join(scratch, "npm-cache"); +const config = path.join(scratch, "config"); +const workspace = path.join(scratch, "workspace"); +for (const dir of [prefix, home, cache, config, workspace]) fs.mkdirSync(dir, { recursive: true }); + +const env = { ...process.env }; +for (const key of Object.keys(env)) { + if (/^(MCP_TOKEN|ADMIN_TOKEN|POLICYGATE_|BRIDGEDEV_|LOCAL_CODER_|NODE_OPTIONS|NODE_PATH|MCP_UPSTREAM_CONFIG|PORT$|ADMIN_PORT$|HOST$|DOTENV_CONFIG_PATH$)/.test(key)) delete env[key]; +} +Object.assign(env, { + HOME: home, + USERPROFILE: home, + XDG_DATA_HOME: path.join(scratch, "data"), + XDG_CONFIG_HOME: config, + XDG_CACHE_HOME: path.join(scratch, "cache"), + WORKSPACE_PATH: workspace, + BRIDGEDEV_SERVICE_ROOT: path.join(scratch, "service"), + BRIDGEDEV_STATE_DIR: path.join(scratch, "state"), + BRIDGEDEV_RUNTIME_MODE: "portable", + DOTENV_CONFIG_PATH: path.join(config, "bridge-dev", ".env"), + npm_config_cache: cache, + npm_config_audit: "false", + npm_config_fund: "false", + npm_config_update_notifier: "false", +}); + +function run(command, args, cwd, timeout = 180_000) { + const result = spawnSync(command, args, { + cwd, env, encoding: "utf8", + shell: process.platform === "win32", + timeout, maxBuffer: 8 * 1024 * 1024, + }); + if (result.error || result.status !== 0) { + // Do not dump CLI output: it can contain sensitive data on unexpected failures. + throw new Error(`${path.basename(command)} ${args[0]} failed: ${result.error?.message || `exit ${result.status}`}`); + } + return result.stdout; +} + +try { + assert.equal(pkg.name, "bridge-dev"); + assert.equal(pkg.bin?.["bridge-dev"], "dist/cli.js"); + assert.equal(pkg.scripts?.prepack, "npm run build"); + + const raw = run(npm, [ + "pack", "--json", "--pack-destination", scratch, + ], root); + const packed = JSON.parse(raw); + // npm versions emit either an array or a package-name-keyed record. + const info = Array.isArray(packed) ? packed[0] : packed?.[pkg.name]; + assert.ok(info && typeof info === "object", "Invalid npm pack metadata"); + assert.equal(info.name, "bridge-dev"); + assert.equal(info.version, pkg.version); + const names = info.files.map(file => file.path); + const required = [ + "dist/cli.js", + "dist/index.js", + "dist/admin/server.js", + "public/ui/index.html", + "public/ui/app.js", + "profiles/marketplace.v1.json", + "profiles/policy.example.json", + "scripts/lease-activation.mjs", + "scripts/deploy-acceptance/portable-client.mjs", + "scripts/shadow-release-acceptance.mjs", + "platform/windows-provider-cleanup.ps1", + "docs/INSTALL.md", + "docs/RELEASING.md", + "README.md", + "LICENSE", + "package.json", + ]; + for (const filename of required) { + assert.ok(names.includes(filename), `Missing published file: ${filename}`); + } + for (const filename of names) { + assert.doesNotMatch(filename, /(^|\/)(src|node_modules|\.git|\.env|\.npmrc|\.research|\.tools|coverage|test-output|\.policygate-dev\.audit\.jsonl)(\/|$)/); + assert.doesNotMatch(filename, /^scripts\/test-/); + assert.doesNotMatch(filename, /(^|\/)(?:id_rsa|id_ed25519|.*\.(?:pem|key|p12|pfx)|private-credentials\.json)(?:$|\/)/i); + } + assert.ok(info.size < 8 * 1024 * 1024, "Tarball unexpectedly large"); + + const tarball = path.join(scratch, info.filename); + assert.ok(fs.statSync(tarball).size > 0); + run(npm, [ + "install", "--prefix", prefix, "--ignore-scripts", + "--no-audit", "--no-fund", "--prefer-offline", tarball, + ], scratch); + const installed = path.join(prefix, "node_modules", pkg.name); + const cli = path.join(installed, "dist", "cli.js"); + assert.ok(fs.existsSync(cli)); + assert.ok(fs.existsSync(path.join(installed, "public", "ui", "index.html"))); + assert.ok(fs.existsSync(path.join(installed, "scripts", "lease-activation.mjs"))); + // Scan the exact npm package content, not production state or dependencies. + for (const filename of names) { + if (!/\.(?:js|mjs|json|md|txt|css|html|ts)$/i.test(filename)) continue; + const file = path.join(installed, ...filename.split("/")); + const stat = fs.statSync(file); + if (stat.size > 3 * 1024 * 1024) throw Error("Oversized text file in package"); + const body = fs.readFileSync(file,"utf8"); + assert.doesNotMatch(body, /-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----/); + assert.doesNotMatch(body, /(?:^|\n)\s*(?:MCP_TOKEN|ADMIN_TOKEN)\s*=\s*["\u0027]?[A-Za-z0-9._-]{32,}/); + } + const bin = path.join(prefix, "node_modules", ".bin", + process.platform === "win32" ? "bridge-dev.cmd" : "bridge-dev"); + assert.ok(fs.existsSync(bin), "npm did not install the bridge-dev command"); + if (process.platform !== "win32") assert.ok(fs.statSync(bin).mode & 0o111, "Installed command is not executable"); + assert.match(run(bin, ["help"], scratch), /BridgeDev/i); + assert.equal(run(bin, ["--version"], scratch).trim(), pkg.version); + const outer = JSON.parse(run(process.execPath, [cli, "setup", "--json"], scratch)); + assert.equal(outer.ok, true); + const setup = Array.isArray(outer.output) && typeof outer.output[0] === "string" + ? JSON.parse(outer.output[0]) : outer; + assert.equal(setup.ok, true); + assert.equal(setup.runtime, "portable"); + assert.equal(setup.mode, "portable"); + assert.ok(setup.config.tokens_configured); + + function readCommandJson(args, allowWarning = false) { + const result = spawnSync(process.execPath, [cli, ...args], { + cwd: scratch, env, encoding: "utf8", timeout: 20_000, maxBuffer: 2 * 1024 * 1024, + }); + assert.ok([0, ...(allowWarning ? [1] : [])].includes(result.status), + `CLI ${args[0]} exit ${result.status}`); + const outer = JSON.parse(result.stdout); + return Array.isArray(outer.output) && typeof outer.output[0] === "string" + ? JSON.parse(outer.output[0]) : outer; + } + const update = readCommandJson(["update", "--check", "--json"]); + assert.equal(update.update_method, "npm"); + assert.match(update.command, /npm install -g bridge-dev@latest/); + const diagnostics = readCommandJson(["doctor", "--json"], true); + const installCheck = diagnostics.checks?.find(row => row.label === "Installation"); + assert.ok(installCheck?.detail?.startsWith("npm;"), "Doctor must identify npm install"); + const modeCheck = diagnostics.checks?.find(row => row.label === "Security mode"); + assert.match(modeCheck?.detail || "", /^STANDARD/, "npm CLI must not inherit managed YOLO"); + + async function freePort() { + const server = net.createServer(); + await new Promise((resolve,reject) => { + server.once("error", reject); + server.listen(0,"127.0.0.1",resolve); + }); + const addr = server.address(); + await new Promise(resolve => server.close(resolve)); + assert.ok(addr && typeof addr === "object"); + return addr.port; + } + const [port, adminPort] = [await freePort(), await freePort()]; + assert.notEqual(port, adminPort); + const mcpToken = randomBytes(32).toString("hex"); + const adminToken = randomBytes(32).toString("hex"); + const serverEnv = { + ...env, PORT:String(port), ADMIN_PORT:String(adminPort), HOST:"127.0.0.1", + MCP_TOKEN:mcpToken, ADMIN_TOKEN:adminToken, CHATGPT_TOOL_PROFILE:"slim", + }; + const child = spawn(process.execPath,[cli,"start"],{ + cwd:scratch,env:serverEnv,stdio:["ignore","pipe","pipe"], + }); + let outputBytes = 0; + child.stdout.on("data",chunk => { outputBytes += chunk.length; }); + child.stderr.on("data",chunk => { outputBytes += chunk.length; }); + try { + let health; + for (let attempt=0; attempt<75 && !health; attempt++) { + if (child.exitCode !== null) throw Error("Installed CLI gateway exited prematurely"); + try { + const res = await fetch(`http://127.0.0.1:${port}/health`, { + headers:{Authorization:`Bearer ${mcpToken}`}, + signal:AbortSignal.timeout(650), + }); + if (res.ok) health = await res.json(); + } catch {} + if (!health) await new Promise(resolve=>setTimeout(resolve,150)); + } + assert.equal(health?.status,"ok","Installed CLI gateway did not become ready"); + assert.equal(health?.runtimeMode,"portable"); + assert.equal(health?.fullMachineAccess,false); + assert.equal((await fetch(`http://127.0.0.1:${port}/health`)).status,401); + const admin = await fetch(`http://127.0.0.1:${adminPort}/ui/`); + assert.equal(admin.status,200,"Admin UI must load from npm tarball"); + assert.match(await admin.text(),/BridgeDev/i); + const response = await fetch(`http://127.0.0.1:${port}/mcp`, { + method:"POST", + headers:{Authorization:`Bearer ${mcpToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}, + body:JSON.stringify({jsonrpc:"2.0",id:1,method:"initialize",params:{ + protocolVersion:"2025-03-26",capabilities:{},clientInfo:{name:"npm-smoke",version:"1"}, + }}), + signal:AbortSignal.timeout(7000), + }); + assert.equal(response.status,200,"Installed npm package MCP initialization"); + const sessionId = response.headers.get("mcp-session-id"); + assert.ok(sessionId,"Installed MCP client must receive a session ID"); + assert.match(await response.text(),/serverInfo|bridge-dev/i); + const mcpHeaders = { + Authorization:`Bearer ${mcpToken}`, + "Content-Type":"application/json", + Accept:"application/json, text/event-stream", + "Mcp-Session-Id":sessionId, + "Mcp-Protocol-Version":"2025-03-26", + }; + const notification = await fetch(`http://127.0.0.1:${port}/mcp`, { + method:"POST",headers:mcpHeaders, + body:JSON.stringify({jsonrpc:"2.0",method:"notifications/initialized"}), + signal:AbortSignal.timeout(7000), + }); + assert.ok(notification.ok,"Installed MCP initialized notification"); + const discovered = await fetch(`http://127.0.0.1:${port}/mcp`, { + method:"POST",headers:mcpHeaders, + body:JSON.stringify({jsonrpc:"2.0",id:2,method:"tools/list",params:{}}), + signal:AbortSignal.timeout(7000), + }); + assert.equal(discovered.status,200,"Installed npm package MCP tool discovery"); + const inventory = await discovered.json(); + assert.ok(Array.isArray(inventory.result?.tools),"Installed MCP tool list must be an array"); + assert.ok(inventory.result.tools.some(tool => tool.name === "system_context"), + "Installed MCP gateway must expose its native tools"); + assert.ok(outputBytes < 200_000,"Gateway produced excessive startup output"); + } finally { + if (child.exitCode === null) { + child.kill(); + await Promise.race([ + new Promise(resolve=>child.once("exit",resolve)), + new Promise(resolve=>setTimeout(resolve,2500)), + ]); + if (child.exitCode === null) child.kill("SIGKILL"); + } + } + + console.log(JSON.stringify({ + result: "PASS", name: info.name, version: info.version, + tarball_bytes: info.size, unpacked_bytes: info.unpackedSize, + file_count: names.length, installed_cli: "PASS", isolated_setup: "PASS", + install_type: "npm", doctor:"PASS", update_check:"PASS", + gateway_start:"PASS", mcp_initialization:"PASS", admin_ui:"PASS", + })); +} finally { + fs.rmSync(scratch, { recursive: true, force: true }); +} diff --git a/src/cli.ts b/src/cli.ts index a61ac2d..43da579 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -35,8 +35,9 @@ import path from "node:path"; import { randomBytes } from "node:crypto"; import { formatMcpEndpoint, inspectLocalMode, resolveProjectDirectory, validateProjectName, verifyAuditProof } from "./lib/cli-security.js"; import { platformCapabilities, getRuntimeMode, portableStateDir, portableWorkspace, portableWorkspaceRoots } from "./lib/runtime.js"; +import { detectInstallSource, updateInstructions } from "./lib/install-source.js"; -const VERSION = "2.0.0"; +const VERSION = runtimeVersion().version; // Fallback dotenv loading if environment variables are not populated const envCandidates = [ @@ -140,6 +141,11 @@ function fetchHealth(port = 3000): Promise { } function getActiveMode(): { mode: string; detail: string } { + // A separately installed npm binary cannot claim the managed gateway's + // signed YOLO lease. Its own policy gate enforces the same boundary. + if (getRuntimeMode() === "portable" && detectInstallSource() === "npm") { + return { mode: "STANDARD", detail: "npm portable runtime; managed host lease not inherited" }; + } if (hostControllerAvailable()) { const libDir = fs.existsSync("/var/lib/local-coder-policygate") ? "/var/lib/local-coder-policygate" @@ -225,6 +231,8 @@ async function cmdStatus(json = false,verbose = false) { console.log(JSON.stringify({ ok: true, version: VERSION, + install_source: detectInstallSource(), + update_command: updateInstructions(detectInstallSource()), platform: process.platform, runtime: health?.runtimeMode || (unit ? "managed" : getRuntimeMode()), service: { @@ -260,6 +268,7 @@ async function cmdStatus(json = false,verbose = false) { } console.log(`BridgeDev v${VERSION}`); + console.log(`Install : ${detectInstallSource()} (${updateInstructions(detectInstallSource())})`); console.log(`Runtime : ${health?.runtimeMode || (unit ? "managed system service" : getRuntimeMode())} on ${process.platform}`); console.log(`Service : ${service.installed ? service.unit + " " + service.state + " (PID: " + service.pid + ")" : unit ? serviceStatus + ` (PID: ${pid}, systemd: ${unit})` : health ? "foreground server reachable" : "not detected"}`); console.log(`Status : ${health ? "connected" : "offline"}${health ? ` (Profile: ${profile}, Active Sessions: ${sessions})` : ""}`); @@ -750,7 +759,8 @@ async function cmdDoctor(json = false,verbose = false) { const checks: Array<{ label: string; status: "OK" | "UNVERIFIED" | "INFO"; detail: string }> = []; const add = (label: string, status: "OK" | "UNVERIFIED" | "INFO", detail: string) => checks.push({ label, status, detail }); const nodeMajor = Number.parseInt(process.versions.node.split(".")[0] || "0", 10); - add("Node runtime", nodeMajor >= 20 ? "OK" : "UNVERIFIED", process.version); + add("Node runtime", nodeMajor >= 22 ? "OK" : "UNVERIFIED", process.version); + add("Installation", "INFO", `${detectInstallSource()}; updates: ${updateInstructions(detectInstallSource())}`); if (getRuntimeMode() === "portable") { add("Persistent service", service.installed && service.active ? "OK" : "INFO", service.installed ? service.unit + " " + service.state : "not installed; foreground runtime"); if (service.installed) { @@ -948,10 +958,20 @@ function cmdLogin(args: string[] = []) { async function cmdUpdate(args: string[], json: boolean,verbose=false): Promise { - if (process.platform !== "linux") throw Error("UPDATE_SERVICE_UNSUPPORTED: managed Linux service required"); if (args.some(x => !["--check", "--no-wait", "--standard-window"].includes(x)) || (args.includes("--check") && args.includes("--no-wait"))) throw Error("Usage: bridge-dev update [--check | --no-wait | --standard-window]"); + const installSource = detectInstallSource(); + if (installSource === "npm" || installSource === "portable-installer") { + const method = installSource === "npm" ? "npm" : "portable-installer"; + const instruction = updateInstructions(installSource); + const result = {ok:true,installed_via:method,update_method:method,command:instruction, + updated:false,checked:args.includes("--check")}; + if (json) console.log(JSON.stringify(result)); + else console.log(`BridgeDev ${method} installation: ${instruction}. No update performed.`); + return; + } + if (process.platform !== "linux") throw Error("UPDATE_SERVICE_UNSUPPORTED: managed Linux service required"); const status=await userServiceStatus(); if (!status.installed) throw Error("UPDATE_SERVICE_NOT_INSTALLED: use bridge-dev service install"); // Resolve main once; the existing updater independently validates exact SHA, @@ -1109,7 +1129,7 @@ function cmdHelp() { console.log(" doctor Run comprehensive diagnostics on environment health"); console.log(" access Display secure connection instructions (interactive only)"); console.log(" dashboard Open locally paired Admin dashboard (Linux local terminal only)"); - console.log(" update [--check] One-command verified main update; temporarily STANDARD, then local YOLO reconfirmation"); + console.log(" update [--check] Show correct npm/portable update command, or verify managed Linux release"); console.log(" update notices Shown during interactive use; cached six hours, never auto-applied"); console.log(" token status Inspect protected token configuration, without values"); console.log(" token rotate admin Rotate Admin token with 0600 backup (--restart optional)"); @@ -1140,6 +1160,7 @@ function cmdHelp() { console.log(" --json Output machine-readable JSON"); console.log(" --verbose Show full diagnostic details (default output is brief)"); console.log(" CLI event log "+cliLogFile()); + console.log(" --version, -v Show installed package version"); console.log(" help, --help, -h Show this help menu\n"); console.log("Security Modes:"); console.log(" STANDARD : Approved workspace files, Git, ordinary shell; no blanket sudo."); @@ -1154,6 +1175,7 @@ async function main() { // interval, update, sudo, token disclosure, or machine-readable noise. const interactive = (args[0] || "status").toLowerCase(); if (!json && process.stderr.isTTY && + !["npm", "portable-installer"].includes(detectInstallSource()) && process.env.BRIDGEDEV_UPDATE_NOTICE !== "off" && ["status","doctor"].includes(interactive)) { try { @@ -1247,6 +1269,11 @@ async function main() { } break; } + case "version": + case "--version": + case "-v": + console.log(VERSION); + break; case "help": case "--help": case "-h": diff --git a/src/lib/host-controller.ts b/src/lib/host-controller.ts index e413fbe..8567c9e 100644 --- a/src/lib/host-controller.ts +++ b/src/lib/host-controller.ts @@ -1,8 +1,35 @@ import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; import { spawn } from "node:child_process"; import { randomUUID } from "node:crypto"; const CONTROLLER="/usr/local/bin/bridge-dev-controller"; + +/** Only the installed, immutable, currently selected managed release may + * inherit a host lease. A second/npm/foreground gateway must remain STANDARD, + * even when the operator has authorized the production service for YOLO. */ +export function verifiedManagedGatewayIdentity(): boolean { + if (process.platform !== "linux" || process.env.BRIDGEDEV_TEST_ROOT) return false; + const root = process.env.BRIDGEDEV_SERVICE_ROOT; + if (!root || !path.isAbsolute(root)) return false; + try { + const ownRoot = fs.realpathSync.native(path.resolve( + path.dirname(fileURLToPath(import.meta.url)), "../..")); + const releaseSha = fs.readFileSync(path.join(ownRoot,"DEPLOYED_COMMIT"),"utf8").trim(); + if (!/^[a-f0-9]{40}$/.test(releaseSha)) return false; + const rootReal = fs.realpathSync.native(root); + const expected = fs.realpathSync.native(path.join(rootReal,"releases",releaseSha)); + if (expected !== ownRoot || fs.realpathSync.native(path.join(rootReal,"current")) !== ownRoot) return false; + const configFile = path.join(rootReal,"service","config.json"); + const stat = fs.lstatSync(configFile); + if (!stat.isFile() || stat.isSymbolicLink() || + stat.uid !== process.getuid?.() || (stat.mode & 0o077)) return false; + const config = JSON.parse(fs.readFileSync(configFile,"utf8")); + return config.root === rootReal && config.current === releaseSha; + } catch { return false; } +} + export function hostControllerAvailable():boolean { // Isolated suites can only reduce privilege; they never contact an installed helper. return !process.env.BRIDGEDEV_TEST_ROOT&&process.platform==="linux"&&fs.existsSync(CONTROLLER); diff --git a/src/lib/install-source.ts b/src/lib/install-source.ts new file mode 100644 index 0000000..6c6452b --- /dev/null +++ b/src/lib/install-source.ts @@ -0,0 +1,42 @@ +import fs from "node:fs"; +import path from "node:path"; +import { sourceRoot } from "./service-config.js"; + +export type InstallSource = "managed" | "npm" | "portable-installer" | "source"; + +/** Classify the invoked executable's own package root, not the cwd or a + * different BridgeDev service on the machine. This is deliberately read-only. */ +export function detectInstallSource(root: string = sourceRoot): InstallSource { + const dir = path.resolve(root); + try { + if (/^[a-f0-9]{40}\s*$/.test(fs.readFileSync(path.join(dir, "DEPLOYED_COMMIT"), "utf8"))) { + return "managed"; + } + } catch {} + const parent = path.dirname(dir); + if (path.basename(dir) === "bridge-dev" && path.basename(parent) === "node_modules") { + return "npm"; + } + if (path.basename(dir) === "bridge-dev" && + path.basename(parent) !== "node_modules" && + path.basename(path.dirname(parent)) === "node_modules" && + path.basename(parent).startsWith("@")) { + return "npm"; + } + // The user-scoped GitHub installer builds into /app. + if (path.basename(dir) === "app" && + fs.existsSync(path.join(dir, "scripts", "install-portable.mjs"))) { + return "portable-installer"; + } + return "source"; +} + +export function updateInstructions(source: InstallSource, packageName = "bridge-dev"): string { + if (source === "npm") { + return `npm install -g ${packageName}@latest (run as your normal user; restart an existing foreground process separately)`; + } + if (source === "portable-installer") { + return "re-run the reviewed install.sh / install.ps1; stop an existing foreground gateway first"; + } + return "bridge-dev update (verified GitHub release; local operator only)"; +} diff --git a/src/lib/policy-gateway.ts b/src/lib/policy-gateway.ts index 2fba886..fb0b8a8 100644 --- a/src/lib/policy-gateway.ts +++ b/src/lib/policy-gateway.ts @@ -5,7 +5,7 @@ import path from "node:path"; import os from "node:os"; import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual, verify } from "node:crypto"; import { requestIdentity } from "./request-identity.js"; -import {hostControllerAvailable} from "./host-controller.js"; +import {hostControllerAvailable,verifiedManagedGatewayIdentity} from "./host-controller.js"; import {readLeaseActivation,verifyLeaseActivation,isActiveLease} from "../../scripts/lease-activation.mjs"; import { fileURLToPath } from "node:url"; import { assertRegistryComplete, classifyTool, type ToolClass } from "./tool-classification.js"; @@ -153,7 +153,8 @@ export class PolicyGate { return digester.digest("hex"); } getActiveProfile(): "strict" | "standard" | "dangerous" { - const controllerAvailable = hostControllerAvailable(); + const controllerAvailable = hostControllerAvailable() && + (getRuntimeMode() !== "portable" || verifiedManagedGatewayIdentity()); const activationFile = process.env.POLICYGATE_YOLO_ACTIVATION_FILE || (controllerAvailable ? "/var/lib/bridge-dev-operator/active-lease.json" : undefined); // Keep the gateway's implicit key/lease selection identical to the CLI's // installed-controller priority. Independent env overrides take precedence. diff --git a/src/lib/service-manager.ts b/src/lib/service-manager.ts index 8d49328..f8acea7 100644 --- a/src/lib/service-manager.ts +++ b/src/lib/service-manager.ts @@ -7,6 +7,7 @@ import { spawn } from "node:child_process"; import { randomUUID, createHash } from "node:crypto"; import { pathToFileURL } from "node:url"; import { atomicJson } from "./atomic-store.js"; +import { detectInstallSource } from "./install-source.js"; import {runShadowAcceptance} from "./shadow-update.js"; import {snapshotUpdateLease,assertSameUpdateLease,assertLocalUpdateCgroup,type UpdateLeaseSnapshot} from "./update-lease.js"; import { HashAudit, verifyAuditFile } from "./hash-audit.js"; @@ -18,6 +19,7 @@ import { serviceStatus, serviceRoot, sourceRoot, + runtimeVersion, privateEnvironment, systemctl, operatorEnvironment, @@ -149,9 +151,17 @@ export async function installService(options: { throw Error("SERVICE_UNSUPPORTED: Linux systemd user manager required"); const root = path.resolve(options.root || serviceRoot()), existing = await readServiceConfig(root); + // A prebuilt npm distribution has no Git checkout or operator-seeded SHA. + // On explicit first service install, stage the CI-verified GitHub artifact + // for the published npm version's tag, never rebuild npm files as a lease- + // capable service or silently enable the host controller. const seeded = existing ? { commit: existing.current } - : await seedLocalRelease(root, options.source || sourceRoot); + : options.source + ? await seedLocalRelease(root, options.source) + : detectInstallSource() === "npm" + ? await stageVerifiedGithubRelease("v" + runtimeVersion().version, root) + : await seedLocalRelease(root, sourceRoot); const c = existing || (await makeServiceConfig({