diff --git a/.changeset/feat-browser-standalone-executable.md b/.changeset/feat-browser-standalone-executable.md new file mode 100644 index 00000000..df436139 --- /dev/null +++ b/.changeset/feat-browser-standalone-executable.md @@ -0,0 +1,5 @@ +--- +"turno-browser": patch +--- + +turno-browser now also comes as a standalone executable for machines without Node or npm: one file per platform (macOS on Apple silicon and Intel, Linux x64, and an experimental Windows x64) on each GitHub release, with `SHA256SUMS` and build provenance attestations. The executable is both programs: `turno-browser `, and `turno-browser mcp` for the MCP server. In it, `turno-browser setup` and `init` give the agent the executable itself (`/turno-browser mcp --identity `), and `status` and `doctor` recognize that entry in an agent's config. See [Install without Node](https://turno.wimo.dev/docs/browser/get-started#install-without-node). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 563f1aa9..f4ea7e90 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -13,6 +13,9 @@ name: release # with Harden-Runner blocking every host outside its allow list (as in tag). # Trusted publishing stages each version; a maintainer approves it on npmjs.com. # tag creates the git tags and GitHub releases of what was published. +# standalone after a turno-browser release, the standalone executables (standalone.yml), +# built from the tarball that was published and uploaded to its GitHub release. It +# runs after npm has the version, so a failure here never holds back the npm release. on: push: branches: [main] @@ -173,6 +176,8 @@ jobs: runs-on: ubuntu-latest permissions: contents: write # create tags and releases + outputs: + browser-version: ${{ steps.tag.outputs.browser-version }} steps: - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 with: @@ -186,6 +191,7 @@ jobs: name: release path: release - name: Tag and release what was published + id: tag env: GH_TOKEN: ${{ github.token }} REPO: ${{ github.repository }} @@ -201,4 +207,20 @@ jobs: gh api "repos/$REPO/git/refs" -f "ref=refs/tags/$name@$version" -f "sha=$SHA" gh release create "$name@$version" --repo "$REPO" --verify-tag "${flags[@]}" \ --title "$name $version" --notes-file "${name}-${version}.notes.md" "${name}-${version}.cdx.json" + if [ "$name" = turno-browser ]; then echo "browser-version=$version" >> "$GITHUB_OUTPUT"; fi done + + standalone: + name: standalone executables + needs: tag + if: needs.tag.outputs.browser-version != '' + permissions: + contents: write # upload the archives to the turno-browser release + id-token: write # sign their attestations + attestations: write # store their attestations + # A local reusable workflow already comes from the commit of this run; the newer "$/" form + # means the same and is not yet understood by every workflow linter. + uses: ./.github/workflows/standalone.yml # zizmor: ignore[self-repository] + with: + version: ${{ needs.tag.outputs.browser-version }} + release-artifact: release diff --git a/.github/workflows/standalone.yml b/.github/workflows/standalone.yml new file mode 100644 index 00000000..22fb2db0 --- /dev/null +++ b/.github/workflows/standalone.yml @@ -0,0 +1,203 @@ +name: standalone + +# The standalone turno-browser executables: one file per platform for machines without Node or +# npm (scripts/standalone-build.mjs). Three jobs, so the one that can write never runs project code: +# build on macOS (the macOS executables are signed ad hoc there), every target from the +# same packed package and the pinned Node.js; uploads the archives and SHA256SUMS +# as an artifact. No id-token, no secrets. +# smoke on each platform: the executable answers --version and an MCP initialize +# (scripts/standalone-smoke.mjs). Windows is experimental and may fail. +# release attests the archives and uploads them with SHA256SUMS to the GitHub release +# turno-browser@. Skipped in a dry run, which keeps them in the run's artifact. +# Signing: the macOS executables are signed ad hoc and the Windows one is not signed, so +# Gatekeeper and SmartScreen warn on a browser download (the docs say what to do). Developer ID +# signing and notarization, or Authenticode, would sign each executable in the build job before +# it is zipped, with the certificates as secrets; there are none yet. +# Callers: release.yml after it publishes turno-browser (with the tarball it published); a +# maintainer, for a version already on npm (workflow_dispatch); a pull request that changes the +# build, as a dry run from the checkout. +on: + workflow_call: + inputs: + version: + description: turno-browser version + required: true + type: string + release-artifact: + description: artifact of the calling run with the packed tarballs (built from them, not from npm) + required: false + type: string + default: "" + workflow_dispatch: + inputs: + version: + description: turno-browser version on npm with a GitHub release (turno-browser@) + required: true + type: string + dry-run: + description: keep the archives in this run's artifacts instead of uploading them to the release + required: false + type: boolean + default: true + pull_request: + paths: + - .github/workflows/standalone.yml + - scripts/standalone-* + - scripts/local-registry.mjs + +permissions: {} + +concurrency: + group: standalone-${{ github.event_name }}-${{ github.ref }}-${{ inputs.version }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +jobs: + build: + name: build + runs-on: macos-15 + timeout-minutes: 30 + permissions: + contents: read # check out the code + outputs: + version: ${{ steps.version.outputs.version }} + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + - id: pin + name: Pinned Node.js release (a SEA blob only loads in the release that wrote it) + run: echo "node=$(jq -r .version scripts/standalone-node.json)" >> "$GITHUB_OUTPUT" + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: ${{ steps.pin.outputs.node }} + - id: version + name: Version + env: + VERSION: ${{ inputs.version }} + run: | + if [ -z "$VERSION" ]; then VERSION=$(jq -r .version packages/browser/package.json); fi + echo "version=$VERSION" >> "$GITHUB_OUTPUT" + # A pull request: the packages of this checkout, packed as a release packs them. + - if: github.event_name == 'pull_request' + uses: pnpm/action-setup@73e46992e05b19abd31f2f3c20e0e7370d762115 # v6.1.1 + - if: github.event_name == 'pull_request' + name: Pack turno-core and turno-browser from the checkout + run: | + pnpm install --frozen-lockfile + mkdir -p "$RUNNER_TEMP/tarballs" + for dir in core browser; do (cd "packages/$dir" && pnpm pack --pack-destination "$RUNNER_TEMP/tarballs"); done + # The release: the tarballs it published. + - if: inputs.release-artifact != '' + uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: ${{ inputs.release-artifact }} + path: ${{ runner.temp }}/tarballs + - name: Build the executables + env: + FROM: ${{ (github.event_name == 'pull_request' || inputs.release-artifact != '') && format('{0}/tarballs', runner.temp) || inputs.version }} + run: node scripts/standalone-build.mjs --from "$FROM" --out standalone + - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 + with: + name: standalone + path: standalone/ + if-no-files-found: error + retention-days: 7 + + smoke: + name: smoke (${{ matrix.target }}) + needs: build + strategy: + fail-fast: false + matrix: + include: + - { target: darwin-arm64, os: macos-15 } + - { target: darwin-x64, os: macos-15-intel } + - { target: linux-x64, os: ubuntu-latest } + # Experimental until turno-browser supports Windows. + - { target: win-x64, os: windows-latest, experimental: true } + runs-on: ${{ matrix.os }} + continue-on-error: ${{ matrix.experimental == true }} + timeout-minutes: 15 + permissions: + contents: read # check out the smoke script + steps: + - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + if: runner.os == 'Linux' + with: + egress-policy: block + allowed-endpoints: > + github.com:443 + api.github.com:443 + objects.githubusercontent.com:443 + release-assets.githubusercontent.com:443 + nodejs.org:443 + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + sparse-checkout: scripts/standalone-smoke.mjs + sparse-checkout-cone-mode: false + - uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0 + with: + node-version: 24 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: standalone + path: standalone + - name: Check the archive against SHA256SUMS and unpack it + shell: bash + env: + TARGET: ${{ matrix.target }} + run: | + cd standalone + grep " turno-browser-$TARGET.zip\$" SHA256SUMS > one.sum + if command -v sha256sum >/dev/null; then sha256sum -c one.sum; else shasum -a 256 -c one.sum; fi + mkdir unpacked + if [ "$RUNNER_OS" = Windows ]; then 7z x -bd -ounpacked "turno-browser-$TARGET.zip"; else unzip -q -d unpacked "turno-browser-$TARGET.zip"; fi + ls -l unpacked + - name: --version and an MCP initialize + shell: bash + env: + VERSION: ${{ needs.build.outputs.version }} + run: | + exe=standalone/unpacked/turno-browser + if [ "$RUNNER_OS" = Windows ]; then exe="$exe.exe"; fi + node scripts/standalone-smoke.mjs "$exe" "$VERSION" + + release: + name: upload to the release + needs: [build, smoke] + if: github.event_name != 'pull_request' && !inputs.dry-run + runs-on: ubuntu-latest + timeout-minutes: 15 + permissions: + contents: write # upload the archives to the release + id-token: write # sign the attestations + attestations: write # store the attestations + steps: + # Block mode: the release upload (api.github.com, uploads.github.com) and the attestation + # signing (token.actions.githubusercontent.com and Sigstore), as in release.yml's publish job. + - uses: step-security/harden-runner@1d88384fd173af6ecb012dfd0264a306b711241a # v2.22.4 + with: + egress-policy: block + allowed-endpoints: > + api.github.com:443 + github.com:443 + uploads.github.com:443 + token.actions.githubusercontent.com:443 + fulcio.sigstore.dev:443 + rekor.sigstore.dev:443 + tuf-repo-cdn.sigstore.dev:443 + - uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2 + with: + name: standalone + path: standalone + - uses: actions/attest-build-provenance@4d101475d8b20a2381f78447822ac1eab6504dd8 # v4.2.2 + with: + subject-path: standalone/*.zip + - name: Upload to turno-browser@${{ needs.build.outputs.version }} + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + VERSION: ${{ needs.build.outputs.version }} + working-directory: standalone + run: gh release upload "turno-browser@$VERSION" turno-browser-*.zip SHA256SUMS --repo "$REPO" --clobber diff --git a/apps/docs/content/docs/browser/get-started.mdx b/apps/docs/content/docs/browser/get-started.mdx index 8cf0ccd0..cfb244fc 100644 --- a/apps/docs/content/docs/browser/get-started.mdx +++ b/apps/docs/content/docs/browser/get-started.mdx @@ -3,7 +3,7 @@ title: "Get started" description: "Install turno-browser and let turno-browser init set it up: an identity, a sign-in by hand and your agent." --- -turno-browser works on its own: you do not need turno to use it. It needs Node 22.11 or newer and a Chromium-based browser on the machine: Google Chrome, or Microsoft Edge, Brave or Chromium ([Choosing the browser](/docs/browser/identities#choosing-the-browser)). It downloads no browser unless you ask: on a machine with none, and no admin password to install one, `turno-browser install-browser` puts Chrome for Testing in your user cache. +turno-browser works on its own: you do not need turno to use it. It needs Node 22.11 or newer (or the [standalone executable](#install-without-node), which needs no Node) and a Chromium-based browser on the machine: Google Chrome, or Microsoft Edge, Brave or Chromium ([Choosing the browser](/docs/browser/identities#choosing-the-browser)). It downloads no browser unless you ask: on a machine with none, and no admin password to install one, `turno-browser install-browser` puts Chrome for Testing in your user cache. ## Install @@ -13,6 +13,72 @@ npm install --global turno-browser This installs two commands: `turno-browser`, which manages identities, and `turno-browser-mcp`, the MCP server an agent runs for one identity. +## Install without Node + +On a machine without Node or npm, use the standalone executable: one file that holds turno-browser and the Node.js runtime it needs. It still drives the Chrome, Edge or Brave installed on the machine, or the Chrome for Testing that `turno-browser install-browser` puts in your user cache. The GitHub release of each turno-browser version, tagged `turno-browser@` on the [releases page](https://github.com/wimo-dev/turno/releases), has one archive per platform and a `SHA256SUMS` file: + +| Platform | Archive | +|---|---| +| macOS, Apple silicon | `turno-browser-darwin-arm64.zip` | +| macOS, Intel | `turno-browser-darwin-x64.zip` | +| Linux, x64 | `turno-browser-linux-x64.zip` | +| Windows, x64 (experimental) | `turno-browser-win-x64.zip` | + +Windows is experimental: turno-browser does not support Windows yet, so that executable is published for testing and may not work. + +Each archive holds the executable (`turno-browser`, or `turno-browser.exe`) and its license files. The one executable is both programs: `turno-browser ` is the CLI, and `turno-browser mcp` is the MCP server that `turno-browser-mcp` is in the npm package. + +```sh +version=0.9.0 # the version you want +platform=darwin-arm64 +base="https://github.com/wimo-dev/turno/releases/download/turno-browser%40$version" +curl -fLO "$base/turno-browser-$platform.zip" +curl -fLO "$base/SHA256SUMS" +``` + +### Check the download + +Compare the archive with `SHA256SUMS`: + +```sh +shasum -a 256 -c SHA256SUMS --ignore-missing # macOS +sha256sum -c SHA256SUMS --ignore-missing # Linux +``` + +On Windows, `Get-FileHash .\turno-browser-win-x64.zip -Algorithm SHA256` in PowerShell prints the hash to compare with the line in `SHA256SUMS`. + +Each archive also has a build provenance attestation: a signed record that the release workflow of this repository built it. With the [GitHub CLI](https://cli.github.com): + +```sh +gh attestation verify turno-browser-darwin-arm64.zip --repo wimo-dev/turno +``` + +### Put it in place + +Unzip the archive and move the executable to a folder you keep, for example `~/.local/bin` (add that folder to your `PATH` to type just `turno-browser`): + +```sh +unzip turno-browser-darwin-arm64.zip turno-browser +mkdir -p ~/.local/bin && mv turno-browser ~/.local/bin/ +~/.local/bin/turno-browser --version +``` + +`turno-browser setup` and `init` give the agent this executable by its full path (`/turno-browser mcp --identity `), so after moving it, run `setup` again. To update, replace the file with the one from a newer release; the identities stay. + +**macOS.** The executable is not signed with an Apple Developer ID yet, so Gatekeeper refuses to open a copy that a browser downloaded. A file fetched with `curl`, as above, is not marked and runs as it is. For a browser download, remove the mark in Terminal: + +```sh +xattr -d com.apple.quarantine ~/.local/bin/turno-browser +``` + +or, after the first refusal, open System Settings, Privacy & Security, and click Open Anyway next to the message about `turno-browser` (on macOS 14 and older, Control-click the file in Finder and choose Open). + +**Windows.** The executable is not Authenticode-signed yet, so SmartScreen may warn that it is unrecognized: choose More info, then Run anyway. In PowerShell, `Unblock-File .\turno-browser.exe` removes the downloaded-from-the-internet mark before the first run. + +### Where it keeps its data + +The same places as the npm package, so the standalone executable and an npm install share the identities: profiles and settings under `~/.local/share/turno/browser/` (or `$XDG_DATA_HOME/turno/browser/`), and Chrome for Testing, when you install it, in the Playwright cache (`~/Library/Caches/ms-playwright` on macOS, `~/.cache/ms-playwright` on Linux, or `PLAYWRIGHT_BROWSERS_PATH`). The executable itself writes nothing next to itself. + ## Set it up ```sh diff --git a/packages/browser/README.md b/packages/browser/README.md index 557ebee1..01993d5a 100644 --- a/packages/browser/README.md +++ b/packages/browser/README.md @@ -18,6 +18,12 @@ turno-browser init identity to your agent. Each step is also a command of its own: `turno-browser add`, `login` and `setup`. +No Node on the machine? Each [GitHub release](https://github.com/wimo-dev/turno/releases) of +turno-browser also has a standalone executable for macOS (Apple silicon and Intel) and Linux, with +`SHA256SUMS` and build provenance attestations; a Windows one is experimental. +[Install without Node](https://turno.wimo.dev/docs/browser/get-started#install-without-node) has +the steps. + The docs are at [turno.wimo.dev/docs/browser](https://turno.wimo.dev/docs/browser), starting with [Get started](https://turno.wimo.dev/docs/browser/get-started). diff --git a/packages/browser/src/agent-mcp.ts b/packages/browser/src/agent-mcp.ts index 71697c06..b7dbb65e 100644 --- a/packages/browser/src/agent-mcp.ts +++ b/packages/browser/src/agent-mcp.ts @@ -205,11 +205,13 @@ export function findEntry(agent: McpAgent, id: string, env: NodeJS.ProcessEnv): } /** - * True when the entry runs turno-browser-mcp (by name, or this package's bin/mcp.js) or turno. - * A server merely named `browser-` (browser-use, say) is someone else's. + * True when the entry runs turno-browser-mcp (by name, or this package's bin/mcp.js), the + * standalone turno-browser executable with `mcp`, or turno. A server merely named + * `browser-` (browser-use, say) is someone else's. */ export function isTurnoEntry(e: McpEntry): boolean { const words = [e.command ?? "", ...(e.args ?? [])]; + if (/^turno-browser(\.exe)?$/i.test(e.command?.split(/[\\/]/).pop() ?? "") && e.args?.[0] === "mcp") return true; return words.some( (w) => basename(w) === "turno-browser-mcp" || basename(w) === "turno" || /turno-browser[\\/].*bin[\\/]mcp\.js$/.test(w), diff --git a/packages/browser/src/cli/init.ts b/packages/browser/src/cli/init.ts index f5e85892..0ff71fd4 100644 --- a/packages/browser/src/cli/init.ts +++ b/packages/browser/src/cli/init.ts @@ -327,8 +327,8 @@ export async function init(c: Ctx, args: string[], io: Io, run: RunCommand = run let exit: number = Exit.ok; if (agent === "none") say(`Skipped. ${b} setup --identity ${id} prints it later.`); else { - const { command, onPath } = mcpCommand(io.env); - const cfg = setupConfig(agent, id, command); + const { command, args: lead, onPath } = mcpCommand(io.env); + const cfg = setupConfig(agent, id, command, lead); if (!onPath) cfg.notes.push("turno-browser-mcp is not on the PATH here, so this names it by its full path."); const info = agent === "json" ? undefined : AGENTS[agent]; const register = info?.add?.(cfg.server, command, cfg.args) ?? null; diff --git a/packages/browser/src/cli/setup.ts b/packages/browser/src/cli/setup.ts index 9d89cae2..0ffe4dc9 100644 --- a/packages/browser/src/cli/setup.ts +++ b/packages/browser/src/cli/setup.ts @@ -1,3 +1,4 @@ +import { isSea } from "node:sea"; import { fileURLToPath } from "node:url"; import { type FlagSpec, @@ -70,18 +71,22 @@ function json(v: unknown): string { } /** - * The command an agent runs: `turno-browser-mcp` when it is on the PATH, else this install's - * full path (a `pnpm add` or a local checkout puts it nowhere on the PATH). + * The command an agent runs, and the arguments that go before the identity's. The standalone + * executable (a Node.js single executable application, with this package inside it) runs + * itself as ` mcp`. Otherwise `turno-browser-mcp` when it is on the PATH, else this + * install's full path (a `pnpm add` or a local checkout puts it nowhere on the PATH); `onPath` + * is false only then. */ -export function mcpCommand(env: NodeJS.ProcessEnv): { command: string; onPath: boolean } { - if (findOnPath("turno-browser-mcp", env)) return { command: "turno-browser-mcp", onPath: true }; - return { command: fileURLToPath(new URL("../bin/mcp.js", import.meta.url)), onPath: false }; +export function mcpCommand(env: NodeJS.ProcessEnv): { command: string; args: string[]; onPath: boolean } { + if (isSea()) return { command: process.execPath, args: ["mcp"], onPath: true }; + if (findOnPath("turno-browser-mcp", env)) return { command: "turno-browser-mcp", args: [], onPath: true }; + return { command: fileURLToPath(new URL("../bin/mcp.js", import.meta.url)), args: [], onPath: false }; } -/** The config of `agent` for identity `id`, run as `command`. */ -export function setupConfig(agent: SetupAgent, id: string, command: string): SetupConfig { +/** The config of `agent` for identity `id`, run as `command` with `lead` before `--identity`. */ +export function setupConfig(agent: SetupAgent, id: string, command: string, lead: readonly string[] = []): SetupConfig { const server = serverName(id); - const args = ["--identity", id]; + const args = [...lead, "--identity", id]; const base = { agent, identity: id, server, command, args }; const stdio = { command, args }; switch (agent) { @@ -210,8 +215,8 @@ export function setup(c: Ctx, args: string[], io: Io): number { if (!agent) return fail(`setup needs an agent: ${b} setup <${SETUP_AGENTS.join("|")}> [--identity ]`); if (!(SETUP_AGENTS as readonly string[]).includes(agent)) return fail(unknownAgent(agent)); const id = pickIdentity(c, str(p, "identity"), io); - const { command, onPath } = mcpCommand(io.env); - const cfg = setupConfig(agent as SetupAgent, id, command); + const { command, args: lead, onPath } = mcpCommand(io.env); + const cfg = setupConfig(agent as SetupAgent, id, command, lead); if (!onPath) cfg.notes.push("turno-browser-mcp is not on the PATH here, so this names it by its full path."); if (bool(p, "json")) { emit(io, p, SETUP_JSON, cfg); diff --git a/packages/browser/test/cli/standalone.test.ts b/packages/browser/test/cli/standalone.test.ts new file mode 100644 index 00000000..43c2b244 --- /dev/null +++ b/packages/browser/test/cli/standalone.test.ts @@ -0,0 +1,38 @@ +import { afterEach, describe, expect, it, vi } from "vitest"; + +/** + * The standalone executable (scripts/standalone-build.mjs) is a Node.js single executable + * application: the package's own files live inside it, so an agent's config must run the + * executable itself with `mcp`, never a script path. + */ + +vi.mock("node:sea", () => ({ isSea: () => true })); + +afterEach(() => vi.restoreAllMocks()); + +describe("the standalone executable", () => { + it("is what setup gives an agent, with mcp before the identity", async () => { + const { mcpCommand, setupConfig } = await import("../../src/cli/setup.js"); + const run = mcpCommand({ PATH: "" }); + expect(run).toEqual({ command: process.execPath, args: ["mcp"], onPath: true }); + const cfg = setupConfig("json", "work", run.command, run.args); + expect(cfg.args).toEqual(["mcp", "--identity", "work"]); + expect(JSON.parse(cfg.config!)).toEqual({ + mcpServers: { "browser-work": { command: process.execPath, args: ["mcp", "--identity", "work"] } }, + }); + }); + + it("counts as turno-browser in an agent's config", async () => { + const { isTurnoEntry } = await import("../../src/agent-mcp.js"); + const entry = (command: string, args: string[]) => ({ + agent: "claude-code" as const, + server: "browser-work", + file: "~/.claude.json", + command, + args, + }); + expect(isTurnoEntry(entry("/opt/tools/turno-browser", ["mcp", "--identity", "work"]))).toBe(true); + expect(isTurnoEntry(entry("C:\\Tools\\turno-browser.exe", ["mcp", "--identity", "work"]))).toBe(true); + expect(isTurnoEntry(entry("/opt/tools/turno-browser", ["list"]))).toBe(false); + }); +}); diff --git a/scripts/standalone-build.mjs b/scripts/standalone-build.mjs new file mode 100644 index 00000000..098e574b --- /dev/null +++ b/scripts/standalone-build.mjs @@ -0,0 +1,231 @@ +#!/usr/bin/env node +// Builds the standalone turno-browser executables: one file per platform that runs without Node +// or npm installed. Each is a Node.js single executable application (SEA) whose assets are the +// npm package of turno-browser, installed with its shrinkwrap, served from a read-only virtual +// file system inside the executable (useVfs, Node.js 26.9 or newer). +// node scripts/standalone-build.mjs --from --out [--targets a,b] +// --from takes a published version (installed from registry.npmjs.org, so the executable holds +// exactly what npm users get) or a folder of packed workspace tarballs (served by +// scripts/local-registry.mjs, for a pull request). Targets: darwin-arm64, darwin-x64, linux-x64, +// win-x64 (default: all). Every target is built on the host running this script with the Node.js +// release pinned in standalone-node.json, whose archives are checked against their SHA-256 +// before use. The macOS executables are stripped of local symbols and signed ad hoc (Apple +// Silicon runs no unsigned code), so those two targets need a macOS host. +// Writes /turno-browser-.zip (the executable, its license files and Node.js's) +// and /SHA256SUMS. +import { execFileSync, spawn } from "node:child_process"; +import { createHash } from "node:crypto"; +import { + copyFileSync, + createWriteStream, + existsSync, + mkdirSync, + readFileSync, + readdirSync, + rmSync, + statSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { basename, dirname, join, relative, resolve, sep } from "node:path"; +import { pipeline } from "node:stream/promises"; +import { fileURLToPath } from "node:url"; +import { parseArgs } from "node:util"; +import { ZipEntry, ZipFile, createZipArchive } from "node:zlib"; + +const here = dirname(fileURLToPath(import.meta.url)); +const pin = JSON.parse(readFileSync(join(here, "standalone-node.json"), "utf8")); +// Fixed entry times, so the same inputs give the same archives. +const MODIFIED = new Date("2000-01-01T00:00:00Z"); + +const { values } = parseArgs({ + options: { + from: { type: "string" }, + out: { type: "string" }, + targets: { type: "string", default: Object.keys(pin.targets).join(",") }, + }, +}); +if (!values.from || !values.out) { + console.error("usage: node scripts/standalone-build.mjs --from --out [--targets a,b]"); + process.exit(2); +} +const targets = values.targets.split(",").filter(Boolean); +for (const t of targets) if (!pin.targets[t]) fail(`unknown target ${t} (${Object.keys(pin.targets).join(", ")})`); +// A SEA blob only loads in the Node.js release that wrote it. +if (process.version !== `v${pin.version}`) fail(`run this with Node.js ${pin.version} (this is ${process.version})`); +if (process.platform !== "darwin" && targets.some((t) => t.startsWith("darwin"))) + fail("the macOS targets need a macOS host: their executables are signed with codesign"); + +const out = resolve(values.out); +const work = join(tmpdir(), `turno-standalone-${process.pid}`); +rmSync(work, { recursive: true, force: true }); +mkdirSync(out, { recursive: true }); +mkdirSync(work, { recursive: true }); +try { + const stage = await stagePackage(values.from, join(work, "stage")); + const version = JSON.parse(readFileSync(join(stage, "node_modules/turno-browser/package.json"), "utf8")).version; + console.log(`turno-browser ${version}, Node.js ${pin.version}`); + const payload = join(work, "payload.zip"); + await writePayload(stage, payload); + const files = []; + for (const target of targets) files.push(await buildTarget(target, stage, payload, version)); + writeFileSync(join(out, "SHA256SUMS"), files.map((f) => `${sha256(readFileSync(f))} ${basename(f)}\n`).join("")); + for (const f of [...files, join(out, "SHA256SUMS")]) console.log(`${basename(f)} ${statSync(f).size} bytes`); +} finally { + rmSync(work, { recursive: true, force: true }); +} + +function fail(message) { + console.error(`standalone-build: ${message}`); + process.exit(1); +} + +function sha256(data) { + return createHash("sha256").update(data).digest("hex"); +} + +function run(command, args, options = {}) { + execFileSync(command, args, { stdio: ["ignore", "inherit", "inherit"], ...options }); +} + +/** npm installs turno-browser into `dir` as a user's install would: its shrinkwrap, no scripts, no dev deps. */ +async function stagePackage(from, dir) { + mkdirSync(dir, { recursive: true }); + writeFileSync(join(dir, "package.json"), '{ "private": true }\n'); + const npm = ["install", "--omit=dev", "--ignore-scripts", "--no-audit", "--no-fund", "--no-package-lock"]; + if (!existsSync(from)) { + run("npm", [...npm, `turno-browser@${from}`], { cwd: dir }); + return dir; + } + // Packed workspace tarballs: turno-core may not be on npm yet, so a local registry serves them. + const folder = resolve(from); + const tarball = readdirSync(folder).find((n) => /^turno-browser-\d.*\.tgz$/.test(n)); + if (!tarball) fail(`no turno-browser-.tgz in ${folder}`); + const registry = spawn(process.execPath, [join(here, "local-registry.mjs"), folder], { + stdio: ["ignore", "pipe", "inherit"], + }); + try { + const url = await new Promise((ok, ko) => { + registry.stdout.once("data", (d) => ok(String(d).trim())); + registry.once("exit", (code) => ko(new Error(`the local registry exited (${code})`))); + }); + run("npm", [...npm, "--registry", url, join(folder, tarball)], { cwd: dir }); + } finally { + registry.kill(); + } + return dir; +} + +/** Every regular file under `dir`, as paths relative to it with forward slashes. */ +function walk(dir, base = dir) { + const found = []; + for (const entry of readdirSync(dir, { withFileTypes: true })) { + const path = join(dir, entry.name); + if (entry.isDirectory()) found.push(...walk(path, base)); + else if (entry.isFile()) found.push(relative(base, path).split(sep).join("/")); + } + return found.sort(); +} + +async function writeZip(file, entries) { + await pipeline(createZipArchive(entries), createWriteStream(file)); +} + +/** + * The virtual file system: the launcher at the root and node_modules next to it. Entries are + * stored, not deflated: the executable starts faster, and the release archive compresses them. + * The .bin links and npm's own bookkeeping are left out. + */ +async function writePayload(stage, file) { + const names = walk(join(stage, "node_modules")) + .filter((n) => !n.startsWith(".") && !n.includes("/.bin/") && !n.endsWith("/.package-lock.json")) + .map((n) => `node_modules/${n}`); + const entries = []; + for (const name of names) { + const data = readFileSync(join(stage, name)); + entries.push(await ZipEntry.create(name, data, { method: "store", modified: MODIFIED })); + } + await writeZip(file, entries); + console.log(`payload: ${names.length} files`); +} + +/** The pinned Node.js archive for `target`, downloaded once and checked against its SHA-256. */ +async function nodeArchive(target) { + const { archive, sha256: want } = pin.targets[target]; + const cache = join(tmpdir(), "turno-standalone-node"); + mkdirSync(cache, { recursive: true }); + const file = join(cache, archive); + if (!existsSync(file) || sha256(readFileSync(file)) !== want) { + const url = `https://nodejs.org/dist/v${pin.version}/${archive}`; + const res = await fetch(url); + if (!res.ok) fail(`${url}: HTTP ${res.status}`); + writeFileSync(file, Buffer.from(await res.arrayBuffer())); + } + const got = sha256(readFileSync(file)); + if (got !== want) fail(`${archive}: SHA-256 ${got}, expected ${want}`); + return file; +} + +/** The node executable and LICENSE of the archive, extracted into `dir`. */ +async function extractNode(target, dir) { + const archive = await nodeArchive(target); + const top = basename(archive).replace(/\.(tar\.gz|zip)$/, ""); + const exe = target.startsWith("win") ? "node.exe" : "node"; + mkdirSync(dir, { recursive: true }); + if (archive.endsWith(".zip")) { + const zip = await ZipFile.open(archive); + try { + for (const [name, to] of [ + [`${top}/${exe}`, exe], + [`${top}/LICENSE`, "LICENSE"], + ]) { + const entry = await zip.get(name); + if (!entry) fail(`${archive} has no ${name}`); + writeFileSync(join(dir, to), await entry.content()); + } + } finally { + await zip.close(); + } + } else { + run("tar", ["-xzf", archive, "-C", dir, "--strip-components", "1", `${top}/bin/node`, `${top}/LICENSE`]); + copyFileSync(join(dir, "bin", "node"), join(dir, exe)); + } + return { exe: join(dir, exe), license: join(dir, "LICENSE") }; +} + +/** Builds one target and packs it as /turno-browser-.zip. */ +async function buildTarget(target, stage, payload, version) { + const dir = join(work, target); + const node = await extractNode(target, join(dir, "node")); + const windows = target.startsWith("win"); + const darwin = target.startsWith("darwin"); + if (darwin) run("strip", ["-x", node.exe]); + const name = windows ? "turno-browser.exe" : "turno-browser"; + const exe = join(dir, name); + const config = join(dir, "sea-config.json"); + writeFileSync( + config, + JSON.stringify({ + main: join(here, "standalone-launcher.mjs"), + mainFormat: "module", + executable: node.exe, + output: exe, + useVfs: true, + vfsArchive: payload, + disableExperimentalSEAWarning: true, + }), + ); + run(process.execPath, ["--build-sea", config]); + if (darwin) run("codesign", ["--force", "--sign", "-", exe]); + const pkg = join(stage, "node_modules/turno-browser"); + const zip = join(out, `turno-browser-${target}.zip`); + const entries = [ + await ZipEntry.create(name, readFileSync(exe), { mode: 0o755, modified: MODIFIED }), + await ZipEntry.create("LICENSE", readFileSync(join(pkg, "LICENSE")), { modified: MODIFIED }), + await ZipEntry.create("NOTICE", readFileSync(join(pkg, "NOTICE")), { modified: MODIFIED }), + await ZipEntry.create("LICENSE.node.txt", readFileSync(node.license), { modified: MODIFIED }), + ]; + await writeZip(zip, entries); + console.log(`${target}: turno-browser ${version}, ${statSync(exe).size} bytes unpacked`); + return zip; +} diff --git a/scripts/standalone-launcher.mjs b/scripts/standalone-launcher.mjs new file mode 100644 index 00000000..fbb67625 --- /dev/null +++ b/scripts/standalone-launcher.mjs @@ -0,0 +1,100 @@ +// The entry of the standalone turno-browser executable (scripts/standalone-build.mjs). The +// executable is a Node.js single executable application whose assets are the npm package of +// turno-browser with its dependencies, mounted read-only as a virtual file system next to this +// file. One executable serves both programs of the package: +// turno-browser ... the CLI (dist/cli/main.js) +// turno-browser mcp [flags] ... the MCP server (dist/bin/mcp.js), also when the +// executable is named turno-browser-mcp +// The package runs some of its own scripts as `process.execPath