diff --git a/.github/workflows/npm-pack.yml b/.github/workflows/npm-pack.yml new file mode 100644 index 0000000..8fc5b29 --- /dev/null +++ b/.github/workflows/npm-pack.yml @@ -0,0 +1,47 @@ +name: npm pack (dry run) + +# Builds the six npm packages with placeholder engines and runs `npm pack` on each, exactly the code +# path release.yml publishes with. Nothing is published, no secrets, read-only token. The file list +# of every tarball is uploaded as an artifact. The real engines are checked in the release run. +on: + pull_request: + paths: + - "clients/node/**" + - ".github/workflows/npm-pack.yml" + - ".github/workflows/release.yml" + workflow_dispatch: + +permissions: + contents: read + +jobs: + pack: + runs-on: ubuntu-latest + defaults: + run: + working-directory: clients/node + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: "24" + cache: npm + cache-dependency-path: clients/node/package-lock.json + - run: npm ci + - run: node npm/fake-engines.mjs "$RUNNER_TEMP/engines" + - run: node npm/build.mjs --engines "$RUNNER_TEMP/engines" --out npm/dist + - run: node npm/publish.mjs --out npm/dist --dry-run --pack-dir npm/packed + - name: Every tarball has what it should (and no source, tests or scripts) + run: | + set -e + cat npm/packed/*.files.txt + for f in npm/packed/*.files.txt; do + if grep -qE '^(src|test|npm|scripts)/' "$f"; then echo "unexpected files in $f"; exit 1; fi + done + test "$(ls npm/packed/*.tgz | wc -l)" -eq 6 + grep -q '^dist/index.js$' npm/packed/sqlguardllm-0*.files.txt + grep -q '^engine/sqlguardllm-engine$' npm/packed/sqlguardllm-engine-linux-x64-*.files.txt + - uses: actions/upload-artifact@v4 + with: + name: npm-pack-files + path: clients/node/npm/packed/*.files.txt diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 53fa603..8685398 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -123,9 +123,13 @@ jobs: path: dist/ - uses: pypa/gh-action-pypi-publish@release/v1 + # The five engine packages first, the client last (it lists them as optionalDependencies). + # Every engine comes from the archives of this same run: checksums and the signed provenance + # attestation are verified before anything is unpacked. A version already on npm is skipped, so + # a failed run can simply be re-run. npm: - name: Publish the Node.js client to npm - needs: [build, engines] + name: Publish the Node.js client and engine packages to npm + needs: [build, engines, attest] runs-on: ubuntu-latest environment: name: npm @@ -143,16 +147,34 @@ jobs: with: node-version: "24" registry-url: "https://registry.npmjs.org" + - uses: actions/download-artifact@v4 + with: + name: engine-release + path: engine-release/ + - name: Verify the engine archives (attestation, then checksums) and unpack them + working-directory: . + env: + GH_TOKEN: ${{ github.token }} + VERSION: ${{ needs.build.outputs.version }} + run: | + set -e + for f in engine-release/*; do + gh attestation verify "$f" --repo "$GITHUB_REPOSITORY" + done + python3 scripts/fetch-engine.py "$VERSION" --base-url engine-release --no-attestation --out engines - run: npm ci - - name: Publish (prepublishOnly runs typecheck, build and tests) + - name: Build the platform packages and the digests + run: node npm/build.mjs --engines ../../engines --out npm/dist + - name: Dry run, the same code path as publishing (npm pack, nothing is published) + run: node npm/publish.mjs --out npm/dist --dry-run --pack-dir npm/packed + - uses: actions/upload-artifact@v4 + with: + name: npm-pack-files + path: clients/node/npm/packed/*.files.txt + - name: Publish (platform packages first, sqlguardllm last; prepublishOnly runs typecheck, build and tests) env: - VERSION: ${{ needs.build.outputs.npm_version }} TAG: ${{ needs.build.outputs.npm_tag }} - run: | - if npm view "sqlguardllm@$VERSION" version >/dev/null 2>&1; then - echo "sqlguardllm@$VERSION is already on npm; nothing to do"; exit 0 - fi - npm publish --tag "$TAG" + run: node npm/publish.mjs --out npm/dist --tag "$TAG" nuget: name: Publish the .NET client to NuGet diff --git a/CHANGELOG.md b/CHANGELOG.md index 848cefb..cb2bc5a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,9 @@ All notable changes to sqlguardllm are documented here. The format follows [Keep ## [Unreleased] +### Added +- npm: the release now publishes the five `sqlguardllm-engine-` packages and then `sqlguardllm` with the embedded engine in its `optionalDependencies`, all with `npm publish --provenance` (#75). The engines are the attested archives of the same run. `clients/node/npm/publish.mjs --dry-run` runs `npm pack` on all six; the new `npm pack (dry run)` workflow runs it on pull requests and uploads the file lists. The one-time owner steps (Trusted Publisher on each new package) are in CONTRIBUTING.md. + ## [0.5.0a4] - 2026-11-27 Security release: upgrade if you use `dialect="duckdb"` with hidden or masked columns. It also brings the embedded-engine groundwork (engine protocol, standalone binaries, npm and NuGet engine packages), the opt-in audit log and the LLM red team. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 46ef15c..fd7c4c2 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -82,5 +82,16 @@ Maintainers only. Every release goes to PyPI, npm and NuGet together, with one v 2. Move the `Unreleased` notes in `CHANGELOG.md` under `## [0.6.0a1] - YYYY-MM-DD`. 3. Merge to `main`, then tag: `git tag -a v0.6.0a1 -m "sqlguardllm 0.6.0a1" && git push origin v0.6.0a1`. -The `Release` workflow checks that tag, versions and changelog agree, runs the tests, and publishes to PyPI, npm and NuGet with Trusted Publishing (no tokens). npm gets the dist-tag from the version: before 1.0 every release is `latest`; from 1.0 on, prereleases get `alpha`, `beta` or `rc` and final releases `latest`. If npm holds a release for approval (staged publishing), approve it at npmjs.com → Staged Packages. +The `Release` workflow checks that tag, versions and changelog agree, runs the tests, and publishes to PyPI, npm and NuGet with Trusted Publishing (no tokens). npm gets the dist-tag from the version: before 1.0 every release is `latest`; from 1.0 on, prereleases get `alpha`, `beta` or `rc` and final releases `latest`. npm publishes six packages per release: `sqlguardllm-engine-{linux-x64,linux-arm64,macos-arm64,macos-x64,windows-x64}` first, then `sqlguardllm` last (its `optionalDependencies` are merged in at publish time and never committed). The engines are the archives of that same run, attested and re-verified (attestation, then SHA-256) before they are unpacked; each package is published with `npm publish --provenance`, and one already on npm is skipped, so a failed release can be re-run. `clients/node/npm/publish.mjs --dry-run` does `npm pack` on all six without publishing; the `npm pack (dry run)` workflow runs it on every pull request (with placeholder engines) and uploads the file list of every tarball, and the release runs it with the real engines just before publishing. + +**Before the first tag that publishes the engine packages (owner, once).** npm Trusted Publishing is configured per package, on npmjs.com, and as far as I could establish it needs the package to exist: I found no "pending publisher" for a name that does not exist yet (PyPI has one, npm does not, as far as I know; check npm's current docs, this may have changed). So the five `sqlguardllm-engine-*` names need a one-time bootstrap: + +1. Log in with an account that can publish to the `sqlguardllm-engine-*` names (`npm login`, 2FA on). +2. For each of the five names, publish a minimal placeholder by hand, for example `0.0.0` with `--tag bootstrap` (a folder with only a `package.json` that has the name, `"version": "0.0.0"`, `"license": "Apache-2.0"`, and `publishConfig.access: public`; `npm publish --access public --tag bootstrap`). This does not touch `latest`. It has no provenance; real releases do. +3. On npmjs.com, open each of the five packages and the existing `sqlguardllm` → Settings → Trusted Publisher → GitHub Actions: organization or user `jmmana`, repository `sqlguardllm`, workflow filename `release.yml`, environment `npm`. +4. Make sure the GitHub environment `npm` exists in the repository settings. Then tag as above. + +The alternative is a short-lived granular access token stored as a secret in the `npm` environment for the first release only, which this workflow does not use and which is worse than the one-time manual placeholder. After the first release, delete any such token. + +If npm holds a release for approval (staged publishing), approve it at npmjs.com → Staged Packages. diff --git a/clients/node/README.md b/clients/node/README.md index 7ea1b45..25a9a84 100644 --- a/clients/node/README.md +++ b/clients/node/README.md @@ -1,8 +1,8 @@ # sqlguardllm (Node.js client) -Official TypeScript client for the [sqlguardllm](https://github.com/jmmana/sqlguardllm) SQL firewall. The engine runs in `sqlguardllm serve` (one engine, many clients); this package is a thin, typed HTTP client with **zero runtime dependencies** (global `fetch`: Node 18+, Deno, Bun, edge runtimes). ESM and CJS. +Official TypeScript client for the [sqlguardllm](https://github.com/jmmana/sqlguardllm) SQL firewall. It runs the embedded engine as a child process (local mode) or talks to `sqlguardllm serve` (remote mode, a thin, typed HTTP client) with **zero runtime dependencies** (global `fetch`: Node 18+, Deno, Bun, edge runtimes). ESM and CJS. -> **Today this package needs a running `sqlguardllm serve`.** An embedded engine, so that `npm install sqlguardllm` works with no Python and no server, is planned in [#85](https://github.com/jmmana/sqlguardllm/issues/85). +> `npm install sqlguardllm` also installs the engine for your platform (an optional dependency), so [local mode](#local-mode) needs no Python and no server. On a platform without an engine package, use the remote mode with a running `sqlguardllm serve`. ```sh npm install sqlguardllm @@ -56,7 +56,7 @@ Row-filter values (tenant, user id) must come from your authenticated session, n The engine binary ships as one npm package per platform, `sqlguardllm-engine-` (`linux-x64`, `linux-arm64`, `macos-arm64`, `macos-x64`, `windows-x64`), declared as `optionalDependencies` with `os`/`cpu` so npm installs only yours. There is no `postinstall` and no download: it works offline, with `--ignore-scripts` and from a lockfile. `resolveEngine()` recomputes the SHA-256 of the engine folder and compares it with the value built into `sqlguardllm`; on any difference, or if the package is missing, it throws `SqlGuardError` (`engine_digest_mismatch`, `engine_not_found`) and nothing is started. On other platforms (including musl Linux such as Alpine) it throws `unsupported_platform`, and the message points to the remote mode (`sqlguardllm serve` and `new SqlGuard({ baseUrl })`). -Maintainers: `python scripts/fetch-engine.py --out engines`, then `npm run build:engines`, which writes the platform packages to `npm/dist/` and the digests to `src/engine-digests.json`. Publish the platform packages first and `sqlguardllm` last, with `npm/dist/optional-dependencies.json` merged into its `optionalDependencies`. +Maintainers: the release workflow does this (see CONTRIBUTING.md, Releasing). By hand: `python scripts/fetch-engine.py --out engines`, then `npm run build:engines` (platform packages in `npm/dist/`, digests in `src/engine-digests.json`), then `node npm/publish.mjs --out npm/dist --dry-run` to `npm pack` all six packages without publishing. ## Local mode diff --git a/clients/node/npm/fake-engines.mjs b/clients/node/npm/fake-engines.mjs new file mode 100644 index 0000000..fd6ac32 --- /dev/null +++ b/clients/node/npm/fake-engines.mjs @@ -0,0 +1,19 @@ +#!/usr/bin/env node +// Placeholder engines for the pull-request dry run (no real binaries, no Python): +// node npm/fake-engines.mjs +// Writes //sqlguardllm-engine-/ in the layout scripts/fetch-engine.py unpacks, +// so npm/build.mjs and npm/publish.mjs --dry-run can be exercised on every PR. They are never published. +import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const platforms = JSON.parse(readFileSync(join(here, "platforms.json"), "utf8")); +const target = resolve(process.argv[2] ?? "engines"); +for (const [key, p] of Object.entries(platforms)) { + const folder = join(target, key, `sqlguardllm-engine-${key}`); + mkdirSync(join(folder, "_internal"), { recursive: true }); + writeFileSync(join(folder, p.executable), `placeholder engine for ${key}\n`); + chmodSync(join(folder, p.executable), 0o755); + writeFileSync(join(folder, "_internal", "lib.bin"), "placeholder\n"); +} diff --git a/clients/node/npm/publish.mjs b/clients/node/npm/publish.mjs new file mode 100644 index 0000000..4da8bb8 --- /dev/null +++ b/clients/node/npm/publish.mjs @@ -0,0 +1,82 @@ +#!/usr/bin/env node +// Publish (or dry-run) the npm packages built by npm/build.mjs, in the only safe order: +// the five platform packages first, the main package last. +// +// node npm/publish.mjs --out npm/dist --dry-run [--pack-dir DIR] # npm pack only, publishes nothing +// node npm/publish.mjs --out npm/dist --tag latest # npm publish --provenance (CI only) +// +// A version that is already on the registry is skipped, so re-running a half-finished release is safe. +// The main package gets `optionalDependencies` (optional-dependencies.json) for the publish only: +// package.json is restored afterwards and the change is never committed. The main package is built +// (npm run build) after build.mjs wrote src/engine-digests.json, so the digests are in its dist. +// Node.js standard library only. +import { execFileSync } from "node:child_process"; +import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = dirname(fileURLToPath(import.meta.url)); +const root = resolve(here, ".."); +const platforms = JSON.parse(readFileSync(join(here, "platforms.json"), "utf8")); +const npm = process.platform === "win32" ? "npm.cmd" : "npm"; + +/** Merge optionalDependencies into a package.json object (pure, tested). */ +export function withOptionalDependencies(pkg, optional) { + return { ...pkg, optionalDependencies: { ...(pkg.optionalDependencies ?? {}), ...optional } }; +} + +function onRegistry(name, version) { + try { + execFileSync(npm, ["view", `${name}@${version}`, "version"], { stdio: "pipe" }); + return true; + } catch { + return false; // E404: not published yet + } +} + +function packOrPublish(cwd, name, version, mode, tag, packDir) { + if (mode === "dry-run") { + const out = execFileSync(npm, ["pack", "--json", "--pack-destination", packDir], { cwd, encoding: "utf8" }); + const [info] = JSON.parse(out); + console.log(`${name}@${version}: ${info.files.length} files, ${info.size} bytes packed`); + writeFileSync(join(packDir, `${info.filename}.files.txt`), info.files.map((f) => f.path).join("\n") + "\n"); + return; + } + if (onRegistry(name, version)) { + console.log(`${name}@${version} is already on npm; skipping`); + return; + } + execFileSync(npm, ["publish", "--provenance", "--access", "public", "--tag", tag], { cwd, stdio: "inherit" }); +} + +function run(argv) { + const opt = (name, fallback) => (argv.includes(name) ? argv[argv.indexOf(name) + 1] : fallback); + const out = resolve(opt("--out", join(here, "dist"))); + const mode = argv.includes("--dry-run") ? "dry-run" : "publish"; + const tag = opt("--tag", ""); + if (mode === "publish" && !tag) throw new Error("--tag is required to publish"); + const packDir = resolve(opt("--pack-dir", join(out, "..", "packed"))); + const pkgPath = join(root, "package.json"); + const original = readFileSync(pkgPath, "utf8"); + const pkg = JSON.parse(original); + if (mode === "dry-run") { + rmSync(packDir, { recursive: true, force: true }); + mkdirSync(packDir, { recursive: true }); + } + for (const key of Object.keys(platforms)) { + const dir = join(out, key); + const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")); + if (manifest.version !== pkg.version) throw new Error(`${manifest.name} is ${manifest.version}, expected ${pkg.version}; rebuild`); + packOrPublish(dir, manifest.name, manifest.version, mode, tag, packDir); + } + const optional = JSON.parse(readFileSync(join(out, "optional-dependencies.json"), "utf8")); + try { + writeFileSync(pkgPath, JSON.stringify(withOptionalDependencies(pkg, optional), null, 2) + "\n"); + execFileSync(npm, ["run", "build"], { cwd: root, stdio: "inherit" }); // engine-digests.json into dist + packOrPublish(root, pkg.name, pkg.version, mode, tag, packDir); + } finally { + writeFileSync(pkgPath, original); + } +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) run(process.argv.slice(2)); diff --git a/clients/node/test/engine.test.ts b/clients/node/test/engine.test.ts index 9a6b687..02897ab 100644 --- a/clients/node/test/engine.test.ts +++ b/clients/node/test/engine.test.ts @@ -102,3 +102,13 @@ describe("resolveEngine", () => { expect(e?.message).toContain("remote mode"); }); }); + +describe("publish script", () => { + it("merges optionalDependencies without touching the rest", async () => { + // @ts-expect-error plain ESM script without types + const { withOptionalDependencies } = await import("../npm/publish.mjs"); + const merged = withOptionalDependencies({ name: "x", version: "1.0.0" }, mainOptionalDependencies("1.0.0")); + expect(merged.name).toBe("x"); + expect(Object.keys(merged.optionalDependencies)).toHaveLength(Object.keys(platforms).length); + }); +}); diff --git a/docs/es/guide-node.md b/docs/es/guide-node.md index 325b032..b7b3137 100644 --- a/docs/es/guide-node.md +++ b/docs/es/guide-node.md @@ -4,8 +4,8 @@ El paquete de npm `sqlguardllm` es un cliente pequeño y sin dependencias. El motor se ejecuta en `sqlguardllm serve`, un servidor HTTP junto a tu aplicación, así que Node.js recibe exactamente las mismas respuestas que Python. Necesitas Node.js 18 o posterior, y Python 3.10 o posterior para el servidor. -!!! note "Hoy el cliente necesita un servidor en marcha" - Un motor embebido, para que `npm install sqlguardllm` funcione sin Python y sin servidor, está previsto en [#85](https://github.com/jmmana/sqlguardllm/issues/85). +!!! note "Modo local o modo remoto" + `npm install sqlguardllm` también instala el motor de tu plataforma (linux x64/arm64, macOS x64/arm64, Windows x64), así que `await SqlGuard.local({ policyPath: "policy.json" })` ejecuta el guard sin Python y sin servidor (consulta el [README del paquete](https://github.com/jmmana/sqlguardllm/tree/main/clients/node#local-mode)). Esta guía usa el modo remoto, más abajo. Si tu plataforma no tiene paquete de motor (por ejemplo Alpine/musl), o usas Deno, un navegador o un entorno edge, usa el modo remoto con un servidor en marcha. ## 1. Escribe una política diff --git a/docs/guide-node.md b/docs/guide-node.md index 4e02195..87ec304 100644 --- a/docs/guide-node.md +++ b/docs/guide-node.md @@ -4,8 +4,8 @@ The npm package `sqlguardllm` is a small client with no dependencies. The engine runs in `sqlguardllm serve`, an HTTP server next to your application, so Node.js gets exactly the same answers as Python. You need Node.js 18 or later, and Python 3.10 or later for the server. -!!! note "Today the client needs a running server" - An embedded engine, so that `npm install sqlguardllm` works with no Python and no server, is planned in [#85](https://github.com/jmmana/sqlguardllm/issues/85). +!!! note "Local mode or remote mode" + `npm install sqlguardllm` also installs the engine for your platform (linux x64/arm64, macOS x64/arm64, Windows x64), so `await SqlGuard.local({ policyPath: "policy.json" })` runs the guard with no Python and no server (see the [package README](https://github.com/jmmana/sqlguardllm/tree/main/clients/node#local-mode)). This guide uses the remote mode below. If your platform has no engine package (for example Alpine/musl), or you run on Deno, a browser or an edge runtime, use the remote mode with a running server. ## 1. Write a policy