From e6aeb746d9ef8d450a9d2d73a12de27fbd63718e Mon Sep 17 00:00:00 2001 From: jdalton Date: Tue, 24 Nov 2026 11:53:33 -0500 Subject: [PATCH] feat(release): build, verify and stage native CLI release candidates --- .claude/skills/bump-cdxgen/SKILL.md | 7 +- .claude/skills/bump-node-sea/SKILL.md | 2 +- .claude/skills/bump-socket/SKILL.md | 2 +- .../bump-socket/references/release-lanes.md | 5 +- .claude/skills/bump-synp/SKILL.md | 5 +- .claude/skills/bump-uv/SKILL.md | 2 +- .config/release-tools.json | 13 + .config/rollup.base.config.mjs | 16 +- .config/rollup.cdxgen-sea.config.mjs | 10 +- .config/rollup.dist.config.mjs | 118 ++-- .config/rollup.sea.config.mjs | 9 + .config/tsconfig.scripts.json | 1 + .gitattributes | 2 + .../actions/repo/upload-artifact/action.yml | 4 +- .../scripts/download-release-artifacts.mts | 136 ++++ .github/scripts/smoke-test-tarball.mts | 70 ++ .github/scripts/smoke-test-tarball.sh | 61 -- .github/scripts/verify-release.mts | 137 ++++ .github/workflows/ci.yml | 540 +-------------- .github/workflows/e2e-tests.yml | 119 +--- .github/workflows/publish-npm.yml | 654 +++++++----------- .github/workflows/release-github.yml | 13 + .gitignore | 18 +- .husky/pre-commit | 1 + .pnpmrc | 14 - package.json | 14 +- pnpm-lock.yaml | 502 ++++++++++++-- scripts/build-package-matrix.mts | 124 +++- scripts/ci/check-bin-eol.sh | 13 + scripts/ci/upload-artifact.mjs | 36 +- scripts/{test => lib}/apple-signing.mts | 0 scripts/release/approve-npm.mts | 73 +- scripts/release/native-launcher.cjs | 57 ++ scripts/release/native-packages.mts | 148 ++++ scripts/release/packages.mts | 31 +- scripts/release/registry.mts | 4 +- scripts/setup/firewall.sh | 74 ++ scripts/setup/release-tools.sh | 72 ++ scripts/test/native.mts | 22 +- src/commands/manifest/scripts/run.mts | 20 +- .../cmd-optimize-pnpm-versions.test.mts | 17 +- src/sea/README.md | 25 +- src/sea/bootstrap.mts | 74 +- src/sea/build-sea.mts | 79 +-- src/sea/build/smoke-test.mts | 107 +++ src/sea/pnpm-lock.mts | 23 + src/sea/rollup-provenance.mjs | 7 +- src/sea/vfs-digest.mts | 29 + src/utils/pnpm.mts | 32 +- test/lib/native/cli-harness.mts | 14 +- test/native-launcher.test.mts | 109 +++ test/native/commands/cli.native.test.mts | 2 +- test/native/commands/tui.native.test.mts | 2 +- test/package-matrix.test.mts | 166 +++-- test/release-approve-npm.test.mts | 66 +- test/release-artifact-download.test.mts | 115 ++- test/release-availability.test.mts | 11 +- test/release-registry.test.mts | 16 +- test/release-workflow.test.mts | 63 +- test/setup-uv.test.mts | 2 +- test/unit/scripts/test/apple-signing.test.mts | 2 +- test/unit/sea/build-sea.test.mts | 42 +- test/upload-artifact.test.mts | 9 +- 63 files changed, 2555 insertions(+), 1606 deletions(-) create mode 100644 .config/release-tools.json create mode 100644 .github/scripts/download-release-artifacts.mts create mode 100644 .github/scripts/smoke-test-tarball.mts delete mode 100755 .github/scripts/smoke-test-tarball.sh create mode 100644 .github/scripts/verify-release.mts delete mode 100644 .pnpmrc create mode 100644 scripts/ci/check-bin-eol.sh rename scripts/{test => lib}/apple-signing.mts (100%) create mode 100644 scripts/release/native-launcher.cjs create mode 100644 scripts/release/native-packages.mts create mode 100644 scripts/setup/firewall.sh create mode 100644 scripts/setup/release-tools.sh create mode 100644 src/sea/build/smoke-test.mts create mode 100644 src/sea/vfs-digest.mts create mode 100644 test/native-launcher.test.mts diff --git a/.claude/skills/bump-cdxgen/SKILL.md b/.claude/skills/bump-cdxgen/SKILL.md index f17a5c9cc1..6b3d3243ca 100644 --- a/.claude/skills/bump-cdxgen/SKILL.md +++ b/.claude/skills/bump-cdxgen/SKILL.md @@ -9,8 +9,9 @@ user-invocable: true Take the exact released version as `$ARGUMENTS`; ask if missing. Read [the VFS and provenance reference](references/vfs-provenance.md), update the exact dev dependency and lockfile with -`pnpm add -D --save-exact "@cyclonedx/cdxgen@$ARGUMENTS"`, then rebuild the -macOS arm64 SEA prototype with `pnpm build:sea -- --prototype`. +`pnpm add -D --save-exact "@cyclonedx/cdxgen@$ARGUMENTS"`, then run +`pnpm build:sea` to rebuild the SEA for the local OS and architecture. +Run this check on macOS arm64 to include the cdxgen payload. Check the new dependency graph and update package-version-specific provenance, license text, and notices where required. Keep the cdxgen capability unavailable @@ -21,7 +22,7 @@ unavailable: ```sh pnpm run test:unit \ test/unit/sea/build-sea.test.mts test/unit/sea/runtime.test.mts -pnpm build:sea -- --prototype +pnpm build:sea ``` Create one signed conventional commit and a PR against `v1.x`. diff --git a/.claude/skills/bump-node-sea/SKILL.md b/.claude/skills/bump-node-sea/SKILL.md index c59957cb94..a404e379a4 100644 --- a/.claude/skills/bump-node-sea/SKILL.md +++ b/.claude/skills/bump-node-sea/SKILL.md @@ -15,7 +15,7 @@ supported SEA target and exposes the SEA/VFS APIs the builder uses. Build the native prototype first. It updates the README marker from the new pin: ```sh -pnpm build:sea -- --prototype +pnpm build:sea ``` Then run the Node pin and SEA builder tests: diff --git a/.claude/skills/bump-socket/SKILL.md b/.claude/skills/bump-socket/SKILL.md index b21b79c4da..dcb649293a 100644 --- a/.claude/skills/bump-socket/SKILL.md +++ b/.claude/skills/bump-socket/SKILL.md @@ -16,7 +16,7 @@ dry run for the requested lane: gh workflow run publish-npm.yml --ref v1.x \ -f mode=release-pr -f dry-run=true -f release-major=1 -# Native 2.1 prerelease: socket only +# Native 2.1 prerelease: socket launcher and five platform packages gh workflow run publish-npm.yml --ref v1.x \ -f mode=release-pr -f dry-run=true -f release-major=2 ``` diff --git a/.claude/skills/bump-socket/references/release-lanes.md b/.claude/skills/bump-socket/references/release-lanes.md index 29399da466..e7a09d286e 100644 --- a/.claude/skills/bump-socket/references/release-lanes.md +++ b/.claude/skills/bump-socket/references/release-lanes.md @@ -6,7 +6,7 @@ first; publishing is a separate dispatch after that PR is merged. | Lane | Release line | npm packages | npm dist-tag | | --- | --- | --- | --- | | Stable | v1.x | `socket`, `@socketsecurity/cli`, `@socketsecurity/cli-with-sentry` | `latest` | -| Native prerelease | 2.1.0 RCs | `socket` only | `rc-2.1.0` | +| Native prerelease | 2.1.0 RCs | `socket` launcher and five exact-version platform packages | `rc-2.1.0` | The package list is enforced by `scripts/release/packages.mts`. The build matrix is defined in `scripts/build-package-matrix.mts`. Prerelease versions @@ -22,5 +22,6 @@ preparation PR. After the merged version PR, the separate `mode=publish` workflow builds and tests package tarballs. Stable releases stage all three packages; RC releases -stage only `socket`. A human approves each npm stage ID locally. Approval and +stage the five platform packages and the `socket` launcher. Approve the platform +stages first, then the launcher. Approval and GitHub release creation are not part of the bump skill. diff --git a/.claude/skills/bump-synp/SKILL.md b/.claude/skills/bump-synp/SKILL.md index f910447aeb..5883932b2c 100644 --- a/.claude/skills/bump-synp/SKILL.md +++ b/.claude/skills/bump-synp/SKILL.md @@ -9,7 +9,8 @@ user-invocable: true Take the exact released version as `$ARGUMENTS`; ask if missing. Read [the VFS and notice reference](references/vfs-notices.md), update the exact dev dependency and lockfile with `pnpm add -D --save-exact "synp@$ARGUMENTS"`, then -rebuild the macOS arm64 SEA prototype with `pnpm build:sea -- --prototype`. +run `pnpm build:sea` to rebuild the SEA for the local OS and architecture. +Run this check on macOS arm64 to include the synp payload. Keep the Yarn Classic capability unavailable while source provenance or notice obligations remain unresolved. Run the SEA builder and runtime tests, then @@ -18,7 +19,7 @@ inspect the manifest and confirm the capability remains unavailable: ```sh pnpm run test:unit \ test/unit/sea/build-sea.test.mts test/unit/sea/runtime.test.mts -pnpm build:sea -- --prototype +pnpm build:sea ``` Create one signed conventional commit and a PR against `v1.x`. diff --git a/.claude/skills/bump-uv/SKILL.md b/.claude/skills/bump-uv/SKILL.md index dbf9d43e66..c0aa5d2bc3 100644 --- a/.claude/skills/bump-uv/SKILL.md +++ b/.claude/skills/bump-uv/SKILL.md @@ -20,7 +20,7 @@ target: ```sh pnpm run test:unit \ test/unit/sea/build-sea.test.mts test/unit/sea/runtime.test.mts -pnpm build:sea -- --prototype +pnpm build:sea ``` Confirm the adjacent `build/sea/*.manifest.json` reports the new uv version diff --git a/.config/release-tools.json b/.config/release-tools.json new file mode 100644 index 0000000000..e0cb1013ac --- /dev/null +++ b/.config/release-tools.json @@ -0,0 +1,13 @@ +{ + "npm": { + "version": "12.2.3", + "integrity": "sha512-ovmNRRe76Jvcp1E6iOePQ6H9Zr4XMOrqgfaeGNhtRvP3XSl2Lo/a9C1N5/jRlLLrsqCem/omgGdZHpZ5a6yn1Q==" + }, + "pnpm": { + "darwin-arm64": "52bb314bf0d48928fc15126ccce42aa199275e29018bef112a04ae8acdcaaf14", + "linux-arm64": "dd03f7616625ff8f13d952f641f0864a2300d73d0a751a682737615bd9f9a7a2", + "linux-x64": "b515e29f2ac1adc0fbe63173414a6682827baff24f17e7ad3476821bdef236ac", + "win32-arm64": "d38e823fad07b42edbba6206c56dcb3b5bcf1a6e18a6ba7cd0602490c02fb186", + "win32-x64": "1a954bdc1b15ff036294279391d01a09407b7d46ff972a59d81f23becce96c1c" + } +} diff --git a/.config/rollup.base.config.mjs b/.config/rollup.base.config.mjs index ec426e353b..34deb2eccb 100644 --- a/.config/rollup.base.config.mjs +++ b/.config/rollup.base.config.mjs @@ -34,6 +34,9 @@ const { INLINED_SOCKET_CLI_VERSION_HASH, NODE_MODULES, ROLLUP_EXTERNAL_SUFFIX, + SOCKET_CLI_LEGACY_PACKAGE_NAME, + SOCKET_CLI_PACKAGE_NAME, + SOCKET_CLI_SENTRY_PACKAGE_NAME, UTF8, VITEST, } = constants @@ -47,6 +50,17 @@ const builtinAliases = builtinModules.reduce((o, n) => { return o }, {}) +// The previous variant can still be named in package.json while Rollup runs. +export function getBuildPackageName() { + if (constants.ENV[INLINED_SOCKET_CLI_LEGACY_BUILD]) { + return SOCKET_CLI_LEGACY_PACKAGE_NAME + } + if (constants.ENV[INLINED_SOCKET_CLI_SENTRY_BUILD]) { + return SOCKET_CLI_SENTRY_PACKAGE_NAME + } + return SOCKET_CLI_PACKAGE_NAME +} + let _rootPkgJson function getRootPkgJsonSync() { if (_rootPkgJson === undefined) { @@ -205,7 +219,7 @@ export default function baseConfig(extendConfig = {}) { ], [ INLINED_SOCKET_CLI_NAME, - () => JSON.stringify(getRootPkgJsonSync().name), + () => JSON.stringify(getBuildPackageName()), ], [ INLINED_SOCKET_CLI_PUBLISHED_BUILD, diff --git a/.config/rollup.cdxgen-sea.config.mjs b/.config/rollup.cdxgen-sea.config.mjs index 9d540efbb6..0e3b16c79e 100644 --- a/.config/rollup.cdxgen-sea.config.mjs +++ b/.config/rollup.cdxgen-sea.config.mjs @@ -9,7 +9,7 @@ import commonjsPlugin from '@rollup/plugin-commonjs' import jsonPlugin from '@rollup/plugin-json' import { nodeResolve } from '@rollup/plugin-node-resolve' -import { parsePnpmLock } from '../src/sea/pnpm-lock.mts' +import { readPnpmLock } from '../src/sea/pnpm-lock.mts' const root = path.resolve( path.dirname(url.fileURLToPath(import.meta.url)), @@ -146,10 +146,10 @@ function thirdPartyNoticePlugin() { const packages = new Map() const sourceModules = new Map() const unmappedModuleCount = { count: 0 } - const lock = parsePnpmLock( - await fs.readFile(path.join(root, 'pnpm-lock.yaml'), 'utf8'), - await fs.readFile(path.join(root, 'pnpm-workspace.yaml'), 'utf8'), - ) + const lock = await readPnpmLock(root) + if (!lock || typeof lock.packages !== 'object' || !lock.packages) { + throw new Error('pnpm-lock.yaml does not contain a packages graph') + } const lockPackages = lock.packages const patchedDependencies = lock.patchedDependencies ?? {} for (const id of this.getModuleIds()) { diff --git a/.config/rollup.dist.config.mjs b/.config/rollup.dist.config.mjs index d6f402a6df..d3d44cfb96 100644 --- a/.config/rollup.dist.config.mjs +++ b/.config/rollup.dist.config.mjs @@ -10,6 +10,7 @@ import jsonPlugin from '@rollup/plugin-json' import { nodeResolve } from '@rollup/plugin-node-resolve' import fastGlob from 'fast-glob' import trash from 'trash' + import constants from '../scripts/constants.js' import { isDirEmptySync } from '../scripts/lib/fs.js' import { hasKeys } from '../scripts/lib/objects.js' @@ -17,7 +18,7 @@ import { readPackageJson } from '../scripts/lib/packages.js' import { normalizePath } from '../scripts/lib/path.js' import { escapeRegExp } from '../scripts/lib/regexps.js' import { naturalCompare } from '../scripts/lib/sorts.js' -import { fetchPackageManifest, spawnAsync } from '../scripts/lib/spawn.js' +import { spawnAsync } from '../scripts/lib/spawn.js' import socketModifyPlugin from '../scripts/rollup/socket-modify-plugin.js' import { getPackageName, @@ -28,7 +29,10 @@ import { includedModulesInventoryPlugin, writeCopiedPackageInventory, } from '../src/sea/rollup-provenance.mjs' -import baseConfig, { EXTERNAL_PACKAGES } from './rollup.base.config.mjs' +import baseConfig, { + EXTERNAL_PACKAGES, + getBuildPackageName, +} from './rollup.base.config.mjs' const { CONSTANTS, @@ -47,16 +51,13 @@ const { SLASH_NODE_MODULES_SLASH, SOCKET_CLI_BIN_NAME, SOCKET_CLI_BIN_NAME_ALIAS, - SOCKET_CLI_LEGACY_PACKAGE_NAME, SOCKET_CLI_NPM_BIN_NAME, SOCKET_CLI_NPX_BIN_NAME, - SOCKET_CLI_PACKAGE_NAME, SOCKET_CLI_PNPM_BIN_NAME, SOCKET_CLI_SENTRY_BIN_NAME, SOCKET_CLI_SENTRY_BIN_NAME_ALIAS, SOCKET_CLI_SENTRY_NPM_BIN_NAME, SOCKET_CLI_SENTRY_NPX_BIN_NAME, - SOCKET_CLI_SENTRY_PACKAGE_NAME, SOCKET_CLI_SENTRY_PNPM_BIN_NAME, SOCKET_CLI_SENTRY_YARN_BIN_NAME, SOCKET_CLI_YARN_BIN_NAME, @@ -65,7 +66,7 @@ const { const BLESSED = 'blessed' const BLESSED_CONTRIB = 'blessed-contrib' const FLAGS = 'flags' -const LICENSE_MD = 'LICENSE.md' +const LICENSE_MD = `LICENSE.md` const SENTRY_NODE = '@sentry/node' const SEA_BUILD_ENV = 'SOCKET_SEA_BUILD' const SOCKET_DESCRIPTION = 'CLI for Socket.dev' @@ -84,10 +85,7 @@ function newBareBlessedRequireRegExp() { function relativeBlessedPath(filepath) { return ( normalizePath( - path.relative( - path.dirname(path.resolve(filepath)), - constants.blessedPath, - ), + path.relative(path.dirname(filepath), constants.blessedPath), ) || '.' ) } @@ -262,44 +260,33 @@ function blessedContribInventoryPlugin(filepath) { }) } -async function copyPackage(pkgName, options) { - const { strict = true } = { __proto__: null, ...options } +async function copyPackage(pkgName) { const nmPath = path.join(constants.rootPath, NODE_MODULES) const pkgDestPath = path.join(constants.externalPath, pkgName) const pkgNmPath = path.join(nmPath, pkgName) // Copy entire package folder over to dist with dereference to follow symlinks. await fs.cp(pkgNmPath, pkgDestPath, { recursive: true, dereference: true }) - if (strict) { - // Add 'use strict' directive to js files. - const jsFiles = await fastGlob.glob(['**/*.js'], { - absolute: true, - cwd: pkgDestPath, - ignore: [NODE_MODULES_GLOB_RECURSIVE], - }) - await Promise.all( - jsFiles.map(async p => { - const content = await fs.readFile(p, 'utf8') - // Start by trimming the hashbang. - const hashbang = /^#!.*(?:\r?\n)*/.exec(content)?.[0] ?? '' - let trimmed = content.slice(hashbang.length).trimStart() - // Then, trim "use strict" directive. - const useStrict = - /^(['"])use strict\1;?(?:\r?\n)*/.exec(trimmed)?.[0] ?? '' - trimmed = trimmed.slice(useStrict.length).trimStart() - // Add back hashbang and add "use strict" directive. - const modded = `${hashbang.trim()}${hashbang ? os.EOL : ''}${useStrict.trim() || "'use strict'"}${os.EOL}${os.EOL}${trimmed}` - await fs.writeFile(p, modded, 'utf8') - }), - ) - } -} - -let _sentryManifest -async function getSentryManifest() { - if (_sentryManifest === undefined) { - _sentryManifest = await fetchPackageManifest(`${SENTRY_NODE}@latest`) - } - return _sentryManifest + // Add 'use strict' directive to js files. + const jsFiles = await fastGlob.glob(['**/*.js'], { + absolute: true, + cwd: pkgDestPath, + ignore: [NODE_MODULES_GLOB_RECURSIVE], + }) + await Promise.all( + jsFiles.map(async p => { + const content = await fs.readFile(p, 'utf8') + // Start by trimming the hashbang. + const hashbang = /^#!.*(?:\r?\n)*/.exec(content)?.[0] ?? '' + let trimmed = content.slice(hashbang.length).trimStart() + // Then, trim "use strict" directive. + const useStrict = + /^(['"])use strict\1;?(?:\r?\n)*/.exec(trimmed)?.[0] ?? '' + trimmed = trimmed.slice(useStrict.length).trimStart() + // Add back hashbang and add "use strict" directive. + const modded = `${hashbang.trim()}${hashbang ? os.EOL : ''}${useStrict.trim() || "'use strict'"}${os.EOL}${os.EOL}${trimmed}` + await fs.writeFile(p, modded, 'utf8') + }), + ) } async function updatePackageJson() { @@ -310,22 +297,23 @@ async function updatePackageJson() { const bin = resetBin(editablePkgJson.content.bin) const dependencies = resetDependencies(editablePkgJson.content.dependencies) editablePkgJson.update({ - name: SOCKET_CLI_PACKAGE_NAME, + name: getBuildPackageName(), description: SOCKET_DESCRIPTION, bin, dependencies: hasKeys(dependencies) ? dependencies : undefined, }) if (constants.ENV[INLINED_SOCKET_CLI_LEGACY_BUILD]) { editablePkgJson.update({ - name: SOCKET_CLI_LEGACY_PACKAGE_NAME, bin: { [SOCKET_CLI_BIN_NAME_ALIAS]: bin[SOCKET_CLI_BIN_NAME], ...bin, }, }) } else if (constants.ENV[INLINED_SOCKET_CLI_SENTRY_BUILD]) { + const sentry = await readPackageJson( + path.join(constants.rootPath, NODE_MODULES, SENTRY_NODE), + ) editablePkgJson.update({ - name: SOCKET_CLI_SENTRY_PACKAGE_NAME, description: SOCKET_DESCRIPTION_WITH_SENTRY, bin: { [SOCKET_CLI_SENTRY_BIN_NAME_ALIAS]: bin[SOCKET_CLI_BIN_NAME], @@ -337,7 +325,7 @@ async function updatePackageJson() { }, dependencies: { ...dependencies, - [SENTRY_NODE]: (await getSentryManifest()).version, + [SENTRY_NODE]: sentry.version, }, }) } @@ -349,22 +337,18 @@ async function updatePackageLockFile() { if (!existsSync(rootPackageLockPath)) { return } - try { - await spawnAsync( - 'pnpm', - [ - 'install', - '--frozen-lockfile=false', - '--config.confirmModulesPurge=false', - ], - { - cwd: constants.rootPath, - stdio: 'inherit', - }, - ) - } catch (e) { - console.warn('Failed to update pnpm lockfile:', e?.message) - } + await spawnAsync( + 'pnpm', + [ + 'install', + '--frozen-lockfile=false', + '--config.confirmModulesPurge=false', + ], + { + cwd: constants.rootPath, + stdio: 'inherit', + }, + ) } async function removeEmptyDirs(thePath) { @@ -505,14 +489,6 @@ export default async () => { switch (id) { case constantsSrcPath: return CONSTANTS - case normalizePath(path.join(srcPath, 'constants/runtime.mts')): - return 'runtime-constants' - case normalizePath(path.join(utilsSrcPath, 'env.mts')): - return 'env-helpers' - case normalizePath(path.join(utilsSrcPath, 'spawn-sync.mts')): - return 'spawn-sync' - case normalizePath(path.join(utilsSrcPath, 'spinner.mts')): - return 'spinner' case flagsSrcPath: return FLAGS case shadowNpmBinSrcPath: diff --git a/.config/rollup.sea.config.mjs b/.config/rollup.sea.config.mjs index b22fe8e32c..f1886a7e81 100644 --- a/.config/rollup.sea.config.mjs +++ b/.config/rollup.sea.config.mjs @@ -9,6 +9,7 @@ import url from 'node:url' import { babel as babelPlugin } from '@rollup/plugin-babel' import commonjsPlugin from '@rollup/plugin-commonjs' import { nodeResolve } from '@rollup/plugin-node-resolve' +import replacePlugin from '@rollup/plugin-replace' const __dirname = path.dirname(url.fileURLToPath(import.meta.url)) const rootDir = path.join(__dirname, '..') @@ -37,6 +38,14 @@ export default { configFile: path.join(__dirname, 'babel.config.js'), extensions: ['.mjs', '.js', '.ts', '.mts'], }), + replacePlugin({ + preventAssignment: true, + values: { + INLINED_SEA_SMOKE_TEST: JSON.stringify( + JSON.parse(process.env.SEA_SMOKE_TEST || 'null'), + ), + }, + }), commonjsPlugin(), ], } diff --git a/.config/tsconfig.scripts.json b/.config/tsconfig.scripts.json index 486698d283..068e31a818 100644 --- a/.config/tsconfig.scripts.json +++ b/.config/tsconfig.scripts.json @@ -16,6 +16,7 @@ "../scripts/*.mts", "../scripts/lib/**/*.mts", "../scripts/setup/**/*.mts", + "../scripts/release/packages.mts", "../scripts/refresh/**/*.mts", "../scripts/test/**/*.mts", "../src/sea/version.mts" diff --git a/.gitattributes b/.gitattributes index be352a6324..766d940230 100644 --- a/.gitattributes +++ b/.gitattributes @@ -3,3 +3,5 @@ # Generated terminal image baselines are reviewed through the screenshot report. test/snapshots/termless/**/*.svg binary linguist-generated=true test/snapshots/termless/**/*.png binary linguist-generated=true + +# pnpm rejects CRLF shebangs when packing the CLI from a Windows checkout. diff --git a/.github/actions/repo/upload-artifact/action.yml b/.github/actions/repo/upload-artifact/action.yml index 280875f7fb..f5b185f90e 100644 --- a/.github/actions/repo/upload-artifact/action.yml +++ b/.github/actions/repo/upload-artifact/action.yml @@ -1,11 +1,11 @@ name: Upload verified release tarballs -description: Upload the three verified tarballs using the Actions artifact service. +description: Upload verified release tarballs using the Actions artifact service. inputs: name: description: Artifact name default: npm-release-tarballs path: - description: Directory containing exactly three verified tarballs + description: Directory containing the verified release tarballs required: true outputs: artifact-id: diff --git a/.github/scripts/download-release-artifacts.mts b/.github/scripts/download-release-artifacts.mts new file mode 100644 index 0000000000..a300945e89 --- /dev/null +++ b/.github/scripts/download-release-artifacts.mts @@ -0,0 +1,136 @@ +import { execFile, spawn } from 'node:child_process' +import { createHash } from 'node:crypto' +import { createReadStream, createWriteStream } from 'node:fs' +import { mkdir, mkdtemp, readFile, rm } from 'node:fs/promises' +import path from 'node:path' +import { pipeline } from 'node:stream/promises' +import { setTimeout } from 'node:timers/promises' +import { promisify } from 'node:util' + +const execute = promisify(execFile) +const maxBytes = 512 * 1024 * 1024 + +function required(name: string): string { + const value = process.env[name] + if (!value) { + throw new Error(`Missing ${name}.`) + } + return value +} + +async function streamFile(command: string, args: string[], file: string, exclusive = false) { + const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] }) + let errorText = '' + child.stderr.setEncoding('utf8').on('data', chunk => { errorText += chunk }) + const done = new Promise((resolve, reject) => { + child.once('error', reject) + child.once('close', code => { + if (code === 0) { + resolve() + } else { + reject(new Error(`${command} exited with ${code}: ${errorText}`)) + } + }) + }) + let bytes = 0 + try { + await Promise.all([done, pipeline(child.stdout, async function* (chunks) { + for await (const chunk of chunks) { + bytes += chunk.length + if (exclusive && bytes > maxBytes) { + throw new Error('Oversized release tarball.') + } + yield chunk + } + }, createWriteStream(file, { flags: exclusive ? 'wx' : 'w' }))]) + } finally { + child.kill() + } + return bytes +} + +async function fetchArtifact(endpoint: string, file: string) { + for (let attempt = 1; ; attempt++) { + try { + await streamFile('bash', ['-c', 'exec gh api "$1"', 'gh', endpoint], file) + return + } catch (error) { + if (!(error instanceof Error) || !error.message.includes('HTTP 404') || attempt === 6) { + throw error + } + await setTimeout(5000) + } + } +} + +async function download(name: string, receipt: unknown, expected: string[], scratch: string, destination: string) { + const match = typeof receipt === 'string' && /^([1-9]\d*):([a-f0-9]{64})$/u.exec(receipt) + if (!match) { + throw new Error(`Missing or invalid upload receipt for ${name}.`) + } + const endpoint = `repos/${required('GITHUB_REPOSITORY')}/actions/artifacts/${match[1]}` + const metadataFile = path.join(scratch, 'artifact.json') + await fetchArtifact(endpoint, metadataFile) + const metadata = JSON.parse(await readFile(metadataFile, 'utf8')) + if (String(metadata.workflow_run?.id) !== required('GITHUB_RUN_ID') || + !new RegExp(`^${name}-[1-9][0-9]*$`, 'u').test(metadata.name) || metadata.expired !== false) { + throw new Error(`Artifact metadata does not match the release run for ${name}.`) + } + const archive = path.join(scratch, 'artifact.zip') + await fetchArtifact(endpoint + '/zip', archive) + const hash = createHash('sha256') + for await (const chunk of createReadStream(archive)) { + hash.update(chunk) + } + if (hash.digest('hex') !== match[2]) { + throw new Error(`Artifact digest does not match the verified upload for ${name}.`) + } + + const { stdout } = await execute('unzip', ['-Z', '-l', archive], { env: { ...process.env, LC_ALL: 'C' } }) + const entries = stdout.trimEnd().split(/\r?\n/u).slice(2, -1) + const remaining = new Set(expected) + for (const entry of entries) { + // zipinfo's long listing includes the Unix file type and unpacked size. + const fields = /^-\S*\s+\S+\s+\S+\s+(\d+)\s+\S+\s+\d+\s+\S+\s+\S+\s+\S+\s+([^\s]+)$/u.exec(entry) + const filename = fields?.[2] + const size = Number(fields?.[1]) + if (!filename || !remaining.delete(filename) || !(size > 0 && size <= maxBytes)) { + throw new Error(`Invalid tarball entry in ${name}.`) + } + const written = await streamFile('unzip', ['-p', archive, filename], path.join(destination, filename), true) + if (written !== size) { + throw new Error(`Invalid tarball size in ${name}.`) + } + } + if (remaining.size) { + throw new Error(`Missing release tarballs in ${name}.`) + } +} + +const version = required('VERSION') +if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version)) { + throw new Error('Invalid release version.') +} +const packages = version.includes('-') ? ['socket'] : ['socket', 'socketsecurity-cli', 'socketsecurity-cli-with-sentry'] +const releases = [{ name: 'npm-release-tarballs', receipt: required('ROOT_RECEIPT'), files: packages.map(pkg => `${pkg}-${version}.tgz`) }] +if (process.env['NATIVE_RECEIPTS'] !== undefined) { + const receipts = JSON.parse(process.env['NATIVE_RECEIPTS']) + const targets = version.includes('-') ? ['darwin-arm64', 'linux-arm64', 'linux-x64', 'win32-arm64', 'win32-x64'] : [] + if (!receipts || typeof receipts !== 'object' || Array.isArray(receipts) || + Object.keys(receipts).length !== targets.length || !targets.every(target => Object.hasOwn(receipts, target))) { + throw new Error('Platform upload receipts do not match the release track.') + } + for (const target of targets) { + releases.push({ name: `native-${target}`, receipt: receipts[target], files: [`socketsecurity-socket-cli-${target}-${version}.tgz`] }) + } +} +const destination = required('DIST_DIRECTORY') +await mkdir(destination, { recursive: true }) +const scratch = await mkdtemp(path.join(required('RUNNER_TEMP'), 'release-')) +try { + for (const release of releases) { + await download(release.name, release.receipt, release.files, scratch, destination) + } +} finally { + await rm(scratch, { recursive: true, force: true }) +} diff --git a/.github/scripts/smoke-test-tarball.mts b/.github/scripts/smoke-test-tarball.mts new file mode 100644 index 0000000000..1e016cf8a0 --- /dev/null +++ b/.github/scripts/smoke-test-tarball.mts @@ -0,0 +1,70 @@ +import { execFileSync } from 'node:child_process' +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { join } from 'node:path' + +const { PKG, VERSION, TARGET, RUNNER_TEMP } = process.env +if (!PKG || !VERSION || !RUNNER_TEMP) { + throw new Error('PKG, VERSION, and RUNNER_TEMP are required.') +} +const consumer = mkdtempSync(join(RUNNER_TEMP, 'socket-consumer-')) +try { + writeFileSync( + join(consumer, 'package.json'), + JSON.stringify({ name: 'socket-cli-smoke', private: true }), + ) + if (TARGET) { + writeFileSync( + join(consumer, 'pnpm-workspace.yaml'), + `overrides:\n "@socketsecurity/socket-cli-${TARGET}@${VERSION}": "file:../platform/socketsecurity-socket-cli-${TARGET}-${VERSION}.tgz"\n`, + ) + } + const tarball = join( + RUNNER_TEMP, + TARGET ? 'launcher' : 'dist', + PKG.replace(/^@/u, '').replace('/', '-') + '-' + VERSION + '.tgz', + ) + // Git Bash runs both the Unix shims and the pnpm-generated Windows shell shims. + execFileSync( + 'bash', + [ + '-c', + 'exec pnpm add --ignore-scripts "$@"', + 'pnpm', + ...(TARGET ? ['--offline'] : []), + tarball, + ], + { cwd: consumer, stdio: 'inherit' }, + ) + const manifest = JSON.parse( + readFileSync(join(consumer, 'node_modules', PKG, 'package.json'), 'utf8'), + ) + const main = PKG.split('/').pop()! + if ( + manifest.name !== PKG || + manifest.version !== VERSION || + !Object.hasOwn(manifest.bin ?? {}, main) + ) { + throw new Error( + `Installed manifest does not match ${PKG}@${VERSION} or lacks its main executable.`, + ) + } + for (const bin of Object.keys(manifest.bin)) { + const executable = './node_modules/.bin/' + bin + if (TARGET && bin === main) { + execFileSync('bash', ['-c', 'exec "$1" --help', 'smoke', executable], { + cwd: consumer, + stdio: 'inherit', + }) + } + const reported = execFileSync( + 'bash', + ['-c', 'exec "$1" --version', 'smoke', executable], + { cwd: consumer, encoding: 'utf8' }, + ).trimEnd() + if (bin === main && reported !== VERSION) { + throw new Error(`${bin} reported ${reported}; expected ${VERSION}.`) + } + } +} finally { + rmSync(consumer, { recursive: true, force: true }) +} diff --git a/.github/scripts/smoke-test-tarball.sh b/.github/scripts/smoke-test-tarball.sh deleted file mode 100755 index 47ec49afea..0000000000 --- a/.github/scripts/smoke-test-tarball.sh +++ /dev/null @@ -1,61 +0,0 @@ -#!/usr/bin/env bash -# -# Install a freshly packed tarball into a throwaway consumer and run every -# executable its manifest declares. A tarball can build green, pack green, and -# still be unusable — a missing `files` entry, a bin pointing at a path that -# was never built, a broken shebang. This is the gate that catches that, and -# it runs on dry runs too, so the failure lands before any release marker -# exists rather than after. -# -# Inputs (environment): -# PKG the package name to install and probe, e.g. socket -# RUNNER_TEMP GitHub Actions temp dir; the tarball lives in $RUNNER_TEMP/dist -set -euo pipefail - -if [ -z "${PKG:-}" ]; then - echo "PKG is required (the package name to smoke test)." >&2 - exit 1 -fi - -dist_dir="${RUNNER_TEMP:-/tmp}/dist" -# The tarball name npm derives from the package name: scope separator dropped, -# leading @ removed (@socketsecurity/cli -> socketsecurity-cli). -slug="$(printf '%s' "$PKG" | sed 's|^@||; s|/|-|')" -tarball="$(ls -t "$dist_dir/$slug"-*.tgz 2>/dev/null | head -1)" -if [ -z "$tarball" ]; then - echo "No packed tarball for $PKG in $dist_dir." >&2 - echo "Wanted: $dist_dir/$slug-.tgz" >&2 - ls -la "$dist_dir" >&2 || true - exit 1 -fi - -consumer="$(mktemp -d)" -trap 'rm -rf "$consumer"' EXIT -printf '%s\n' '{"name":"socket-cli-smoke","private":true}' > "$consumer/package.json" - -echo "Installing $(basename "$tarball") into a throwaway consumer" -npm install --ignore-scripts --no-audit --no-fund --prefix "$consumer" "$tarball" - -installed="$consumer/node_modules/$PKG" -if [ ! -d "$installed" ]; then - echo "$PKG did not install into the consumer." >&2 - exit 1 -fi - -bins="$(node -p "Object.keys(require('$installed/package.json').bin ?? {}).join(' ')")" -if [ -z "$bins" ]; then - echo "$PKG declares no bin entries; nothing to probe." >&2 - exit 1 -fi - -for bin in $bins; do - bin_path="$consumer/node_modules/.bin/$bin" - if [ ! -x "$bin_path" ]; then - echo "Declared executable '$bin' is missing or not executable at $bin_path." >&2 - exit 1 - fi - echo "Running $bin --version" - "$bin_path" --version -done - -echo "$PKG installs and every declared executable runs." diff --git a/.github/scripts/verify-release.mts b/.github/scripts/verify-release.mts new file mode 100644 index 0000000000..4f96e7223e --- /dev/null +++ b/.github/scripts/verify-release.mts @@ -0,0 +1,137 @@ +import { execFileSync } from 'node:child_process' +import { appendFileSync, readFileSync, writeFileSync } from 'node:fs' +import { basename, join } from 'node:path' + +const [command, ...args] = process.argv.slice(2) + +function required(name: string): string { + const value = process.env[name] + if (!value) { + throw new Error(`Missing ${name}`) + } + return value +} + +function recordStage() { + const output = readFileSync(args[0]!, 'utf8') + const start = output.search(/^(?:\{(?=\s*")|\[(?=\s*\{))/mu) + const value = JSON.parse(start < 0 ? output : output.slice(start)) + const rows: unknown[] = Array.isArray(value) + ? value + : Object.values(value ?? {}) + const matches = rows.filter( + (row): row is { name: string; version: string; stageId: string } => + row !== null && + typeof row === 'object' && + 'name' in row && + 'version' in row && + 'stageId' in row && + typeof row.name === 'string' && + typeof row.version === 'string' && + typeof row.stageId === 'string' && + /^[a-f\d]{8}-[a-f\d]{4}-[1-8][a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/iu.test( + row.stageId, + ), + ) + if (matches.length !== 1) + {throw new Error('Expected one npm stage ID in pnpm JSON output.')} + const stage = matches[0]! + const artifactName = `${stage.name.replace(/^@/u, '').replace('/', '-')}-${stage.version}.tgz` + if (basename(args[2]!) !== artifactName) + {throw new Error('Stage identity does not match the verified tarball.')} + appendFileSync( + args[1]!, + `- ${stage.name}@${stage.version} — stage ID: \`${stage.stageId}\`\n`, + ) + process.stdout.write(`Stage ID: ${stage.stageId}\n`) +} + +switch (command) { + case 'stage-output': + recordStage() + break + case 'tarball-count': { + const expected = required('VERSION').includes('-') ? 6 : 3 + if (Number(args[0]) !== expected) { + throw new Error( + `Expected ${expected} verified tarballs, found ${args[0]}.`, + ) + } + console.log(expected) + break + } + case 'first-release': { + const missing = [] + for (const target of [ + 'darwin-arm64', + 'linux-arm64', + 'linux-x64', + 'win32-arm64', + 'win32-x64', + ]) { + const name = `@socketsecurity/socket-cli-${target}` + const status = execFileSync( + 'curl', + [ + '--retry', + '3', + '--silent', + '--show-error', + '--output', + '/dev/null', + '--write-out', + '%{http_code}', + `https://registry.npmjs.org/@socketsecurity%2fsocket-cli-${target}`, + ], + { encoding: 'utf8' }, + ) + if (status === '404') { + missing.push(name) + } else if (status !== '200') { + throw new Error(`Registry lookup for ${name} returned ${status}`) + } + } + writeFileSync( + join(required('RUNNER_TEMP'), 'first-native-packages'), + missing.join('\n'), + ) + if (missing.length && required('BOOTSTRAP_AVAILABLE') !== 'true') { + throw new Error( + `Set NPM_FIRST_STAGE_TOKEN to stage ${missing.join(', ')}.`, + ) + } + break + } + case 'commit': { + const sha = execFileSync( + 'git', + ['rev-parse', '--verify', 'HEAD^{commit}'], + { encoding: 'utf8' }, + ).trim() + const verified = execFileSync( + 'gh', + [ + 'api', + `repos/${required('REPOSITORY')}/commits/${sha}`, + '--jq', + '.commit.verification.verified', + ], + { encoding: 'utf8' }, + ).trim() + if (verified !== 'true') { + throw new Error( + `Release commit ${sha} is not GitHub-verified; npm staging stopped.`, + ) + } + break + } + case 'latest-branch': + if (required('REF') !== 'refs/heads/v1.x') { + throw new Error( + 'Refusing to publish the latest dist-tag outside refs/heads/v1.x.', + ) + } + break + default: + throw new Error(`Unknown release check: ${command}`) +} diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index a253fcb95f..77863b8a45 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -42,6 +42,9 @@ jobs: git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" git checkout -q --detach FETCH_HEAD + - name: Check CLI executable line endings + run: bash scripts/ci/check-bin-eol.sh + - name: Install zizmor shell: bash run: | # zizmor: ignore[github-env] @@ -94,171 +97,16 @@ jobs: } fi - - name: Install pnpm + - name: Install release toolchain shell: bash - run: | # zizmor: ignore[github-env] - PNPM_VERSION="12.21.0" - PNPM_DIR="${RUNNER_TEMP:-/tmp}/pnpm-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="pnpm-linux-x64.tar.gz" ; EXPECTED_SHA256="84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Linux-aarch64) ASSET="pnpm-linux-arm64.tar.gz" ; EXPECTED_SHA256="6c5913a48c93b3a556b71c3bd9bf12c6bf9fbfbbbd2dcbd1d52a85c539751b9e" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-x86_64) ASSET="pnpm-darwin-x64.tar.gz" ; EXPECTED_SHA256="415c05ae4262c89b8f24ca58c693be5d969856ae909c086aa06996951fca30ea" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-arm64) ASSET="pnpm-darwin-arm64.tar.gz" ; EXPECTED_SHA256="5c4d73018e00dd602531ce714625594fb693cbe110e6719df2b043b0ae62ab1a" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="pnpm-win32-x64.zip" ; EXPECTED_SHA256="4fb64bb37e46c788309e0fd4ea93beb512546fdc7348121194fb704fbb72c09c" ; PNPM_BIN="$PNPM_DIR/pnpm.exe" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - PNPM_ARCHIVE="$PNPM_DIR/$ASSET" - if [ ! -x "$PNPM_BIN" ]; then - mkdir -p "$PNPM_DIR" - curl -fsSL -o "$PNPM_ARCHIVE" "https://github.com/pnpm/pnpm/releases/download/v${PNPM_VERSION}/${ASSET}" - ACTUAL_SHA256="$( (sha256sum "$PNPM_ARCHIVE" 2>/dev/null || shasum -a 256 "$PNPM_ARCHIVE") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET}!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$PNPM_ARCHIVE" - exit 1 - fi - if [[ "$ASSET" == *.zip ]]; then unzip -q "$PNPM_ARCHIVE" -d "$PNPM_DIR"; else tar -xzf "$PNPM_ARCHIVE" -C "$PNPM_DIR"; fi - chmod +x "$PNPM_BIN" - fi - echo "$PNPM_DIR" >> "${GITHUB_PATH:-/dev/null}" - - - name: Install Node.js - shell: bash - env: - NODE_VERSION: 26.13.0 - run: pnpm run ci:setup-node + run: bash scripts/setup/release-tools.sh - - name: Install latest npm - shell: bash - env: - NPM_VERSION: 12.2.3 - run: | - npm install --global "npm@$NPM_VERSION" --ignore-scripts --no-audit --no-fund - test "$(npm --version)" = "$NPM_VERSION" - - - name: Download sfw + - name: Set up Socket Firewall shell: bash env: GH_TOKEN: ${{ github.token }} SOCKET_API_KEY: ${{ secrets.SOCKET_API_TOKEN_FOR_CLI_AND_SFW }} # zizmor: ignore[secrets-outside-env] - run: | # zizmor: ignore[github-env] - # Pinned version + per-platform checksum pairs. Bumping a tool - # requires updating the matching version AND every platform's - # SHA256 in the same commit, otherwise the download / verify - # steps will diverge. - SFW_FREE_VERSION="1.16.0" - SFW_ENTERPRISE_VERSION="1.16.0" - SFW_DIR="${RUNNER_TEMP:-/tmp}/sfw-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - USE_ENTERPRISE=false - [ -n "$SOCKET_API_KEY" ] && USE_ENTERPRISE=true - if [ "$USE_ENTERPRISE" = "true" ]; then - REPO="SocketDev/firewall-release" - SFW_VERSION="$SFW_ENTERPRISE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9c5e77a2c08683c3cca7c5fba9d380c7acca7ed6ea71c0d3919b2a723bea34b3" ;; - Linux-aarch64) ASSET="sfw-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="945708d9907f4702d91d341647576aae667ad0c411cd9c02a4f56b130512695c" ;; - Darwin-x86_64) ASSET="sfw-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9b6faa3c4cb5d2cbbea7bad5c7a47a4a9f179a8a75f1ce2993ac0c50e5e040cf" ;; - Darwin-arm64) ASSET="sfw-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="16fbe362a24af30b75938667e7bff00ed79df24e17a8e2d0abf3ae53d5739e92" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="e8ecd768aebabc365d91306e0b5ef8b66c16b4816496934ff4998cda60590e3c" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - else - REPO="SocketDev/sfw-free" - SFW_VERSION="$SFW_FREE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-free-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="1f24d2628aeb3995f1f2651509e37641c7c41d07749ac68594ecb5bb2dd44d8a" ;; - Linux-aarch64) ASSET="sfw-free-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="474cdb684e42d33d4b697dedd7d90c159d71380be0e53c496f0e7097c3617a6c" ;; - Darwin-x86_64) ASSET="sfw-free-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="b574931bc2b3c36a9bf07ac07b9c07894f8cd314efc91bc5e4fe1c371b56adca" ;; - Darwin-arm64) ASSET="sfw-free-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="29df049df2ef705a8ce726c6c41fe73a6034f6b1cd0d87f3f15a780d074b6d83" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-free-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="fafcb65a0349ff21af4feeda170f669053efa68acb55e1b935f7ed1b2ac93ca7" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - fi - if [ ! -x "$SFW_BIN" ]; then - mkdir -p "$SFW_DIR" - DOWNLOAD_URL="$(gh api "repos/${REPO}/releases/tags/v${SFW_VERSION}" \ - --jq ".assets[] | select(.name == \"$ASSET\") | .browser_download_url")" - if [ -z "$DOWNLOAD_URL" ]; then - echo "Asset ${ASSET} not found in ${REPO}@v${SFW_VERSION}" >&2 - exit 1 - fi - curl -fsSL -o "$SFW_BIN" "$DOWNLOAD_URL" - ACTUAL_SHA256="$( (sha256sum "$SFW_BIN" 2>/dev/null || shasum -a 256 "$SFW_BIN") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET} (${REPO}@v${SFW_VERSION})!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$SFW_BIN" - exit 1 - fi - chmod +x "$SFW_BIN" - fi - echo "SFW_BIN=$SFW_BIN" >> "${GITHUB_ENV:-/dev/null}" - echo "SFW_IS_ENTERPRISE=$USE_ENTERPRISE" >> "${GITHUB_ENV:-/dev/null}" - if [ "$USE_ENTERPRISE" = "true" ]; then - echo "SOCKET_API_KEY=$SOCKET_API_KEY" >> "${GITHUB_ENV:-/dev/null}" - fi - - - name: Create sfw shims - shell: bash - run: | # zizmor: ignore[github-env] - SHIM_DIR="${RUNNER_TEMP:-/tmp}/sfw-shim" - rm -rf "$SHIM_DIR" - mkdir -p "$SHIM_DIR" - IS_WINDOWS=false - [[ "$OSTYPE" == msys* || "$OSTYPE" == cygwin* ]] && IS_WINDOWS=true - msys_to_win_path() { - if $IS_WINDOWS && [[ "$1" =~ ^/([a-zA-Z])/(.*) ]]; then - echo "${BASH_REMATCH[1]^^}:\\${BASH_REMATCH[2]//\//\\}" - else - echo "$1" - fi - } - strip_shim_dir() { echo "$PATH" | tr ':' '\n' | grep -vxF "$SHIM_DIR" | paste -sd: -; } - CLEAN_PATH="$(strip_shim_dir)" - # Wrapper mode ecosystems (sfw-free): - # JavaScript/TypeScript: npm, yarn, pnpm - # Python: pip, uv - # Rust: cargo - # https://github.com/SocketDev/sfw-free?tab=readme-ov-file#supported-package-managers - # - # Additional wrapper mode ecosystems (sfw-enterprise): - # Ruby: gem, bundler - # .NET: nuget - # Go: go (Linux only) - # https://github.com/SocketDev/firewall-release/wiki#support-matrix - SSL_WORKAROUND="" - SHIM_CMDS="npm yarn pnpm pip uv cargo" - if [ "$SFW_IS_ENTERPRISE" = "true" ]; then - SHIM_CMDS="npm yarn pnpm pip uv cargo gem bundler nuget" - # Go wrapper mode is only supported on Linux. - [[ "$OSTYPE" == linux* ]] && SHIM_CMDS="$SHIM_CMDS go" - else - SSL_WORKAROUND='export GIT_SSL_NO_VERIFY=true # Workaround: sfw-free does not yet set GIT_SSL_CAINFO.' - fi - for CMD in $SHIM_CMDS; do - REAL="$(PATH="$CLEAN_PATH" command -v "$CMD" 2>/dev/null || true)" - [ -z "$REAL" ] && continue - if $IS_WINDOWS && [ -f "${REAL}.exe" ]; then REAL="${REAL}.exe"; fi - REAL="$(msys_to_win_path "$REAL")" - SHIM_LINES=('#!/bin/bash' "export PATH=\"\$(echo \"\$PATH\" | tr ':' '\n' | grep -vxF '${SHIM_DIR}' | paste -sd: -)\"") - [ -n "$SSL_WORKAROUND" ] && SHIM_LINES+=("$SSL_WORKAROUND") - SHIM_LINES+=("exec \"${SFW_BIN}\" \"${REAL}\" \"\$@\"") - printf '%s\n' "${SHIM_LINES[@]}" > "$SHIM_DIR/$CMD" - chmod +x "$SHIM_DIR/$CMD" - if $IS_WINDOWS; then - printf '@echo off\r\nset "PATH=;%%PATH%%;"\r\nset "PATH=%%PATH:;%s;=;%%"\r\nset "PATH=%%PATH:~1,-1%%"\r\n"%s" "%s" %%*\r\n' \ - "$SHIM_DIR" "$SFW_BIN" "$REAL" > "$SHIM_DIR/$CMD.cmd" - fi - done - echo "$SHIM_DIR" >> "${GITHUB_PATH:-/dev/null}" - echo "SFW_SHIM_DIR=$SHIM_DIR" >> "${GITHUB_ENV:-/dev/null}" + run: bash scripts/setup/firewall.sh - name: Install dependencies run: pnpm install --loglevel error @@ -292,171 +140,16 @@ jobs: git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" git checkout -q --detach FETCH_HEAD - - name: Install pnpm - shell: bash - run: | # zizmor: ignore[github-env] - PNPM_VERSION="12.21.0" - PNPM_DIR="${RUNNER_TEMP:-/tmp}/pnpm-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="pnpm-linux-x64.tar.gz" ; EXPECTED_SHA256="84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Linux-aarch64) ASSET="pnpm-linux-arm64.tar.gz" ; EXPECTED_SHA256="6c5913a48c93b3a556b71c3bd9bf12c6bf9fbfbbbd2dcbd1d52a85c539751b9e" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-x86_64) ASSET="pnpm-darwin-x64.tar.gz" ; EXPECTED_SHA256="415c05ae4262c89b8f24ca58c693be5d969856ae909c086aa06996951fca30ea" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-arm64) ASSET="pnpm-darwin-arm64.tar.gz" ; EXPECTED_SHA256="5c4d73018e00dd602531ce714625594fb693cbe110e6719df2b043b0ae62ab1a" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="pnpm-win32-x64.zip" ; EXPECTED_SHA256="4fb64bb37e46c788309e0fd4ea93beb512546fdc7348121194fb704fbb72c09c" ; PNPM_BIN="$PNPM_DIR/pnpm.exe" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - PNPM_ARCHIVE="$PNPM_DIR/$ASSET" - if [ ! -x "$PNPM_BIN" ]; then - mkdir -p "$PNPM_DIR" - curl -fsSL -o "$PNPM_ARCHIVE" "https://github.com/pnpm/pnpm/releases/download/v${PNPM_VERSION}/${ASSET}" - ACTUAL_SHA256="$( (sha256sum "$PNPM_ARCHIVE" 2>/dev/null || shasum -a 256 "$PNPM_ARCHIVE") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET}!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$PNPM_ARCHIVE" - exit 1 - fi - if [[ "$ASSET" == *.zip ]]; then unzip -q "$PNPM_ARCHIVE" -d "$PNPM_DIR"; else tar -xzf "$PNPM_ARCHIVE" -C "$PNPM_DIR"; fi - chmod +x "$PNPM_BIN" - fi - echo "$PNPM_DIR" >> "${GITHUB_PATH:-/dev/null}" - - - name: Install Node.js + - name: Install release toolchain shell: bash - env: - NODE_VERSION: 26.13.0 - run: pnpm run ci:setup-node - - - name: Install latest npm - shell: bash - env: - NPM_VERSION: 12.2.3 - run: | - npm install --global "npm@$NPM_VERSION" --ignore-scripts --no-audit --no-fund - test "$(npm --version)" = "$NPM_VERSION" + run: bash scripts/setup/release-tools.sh - - name: Download sfw + - name: Set up Socket Firewall shell: bash env: GH_TOKEN: ${{ github.token }} SOCKET_API_KEY: ${{ secrets.SOCKET_API_TOKEN_FOR_CLI_AND_SFW }} # zizmor: ignore[secrets-outside-env] - run: | # zizmor: ignore[github-env] - # Pinned version + per-platform checksum pairs. Bumping a tool - # requires updating the matching version AND every platform's - # SHA256 in the same commit, otherwise the download / verify - # steps will diverge. - SFW_FREE_VERSION="1.16.0" - SFW_ENTERPRISE_VERSION="1.16.0" - SFW_DIR="${RUNNER_TEMP:-/tmp}/sfw-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - USE_ENTERPRISE=false - [ -n "$SOCKET_API_KEY" ] && USE_ENTERPRISE=true - if [ "$USE_ENTERPRISE" = "true" ]; then - REPO="SocketDev/firewall-release" - SFW_VERSION="$SFW_ENTERPRISE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9c5e77a2c08683c3cca7c5fba9d380c7acca7ed6ea71c0d3919b2a723bea34b3" ;; - Linux-aarch64) ASSET="sfw-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="945708d9907f4702d91d341647576aae667ad0c411cd9c02a4f56b130512695c" ;; - Darwin-x86_64) ASSET="sfw-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9b6faa3c4cb5d2cbbea7bad5c7a47a4a9f179a8a75f1ce2993ac0c50e5e040cf" ;; - Darwin-arm64) ASSET="sfw-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="16fbe362a24af30b75938667e7bff00ed79df24e17a8e2d0abf3ae53d5739e92" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="e8ecd768aebabc365d91306e0b5ef8b66c16b4816496934ff4998cda60590e3c" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - else - REPO="SocketDev/sfw-free" - SFW_VERSION="$SFW_FREE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-free-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="1f24d2628aeb3995f1f2651509e37641c7c41d07749ac68594ecb5bb2dd44d8a" ;; - Linux-aarch64) ASSET="sfw-free-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="474cdb684e42d33d4b697dedd7d90c159d71380be0e53c496f0e7097c3617a6c" ;; - Darwin-x86_64) ASSET="sfw-free-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="b574931bc2b3c36a9bf07ac07b9c07894f8cd314efc91bc5e4fe1c371b56adca" ;; - Darwin-arm64) ASSET="sfw-free-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="29df049df2ef705a8ce726c6c41fe73a6034f6b1cd0d87f3f15a780d074b6d83" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-free-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="fafcb65a0349ff21af4feeda170f669053efa68acb55e1b935f7ed1b2ac93ca7" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - fi - if [ ! -x "$SFW_BIN" ]; then - mkdir -p "$SFW_DIR" - DOWNLOAD_URL="$(gh api "repos/${REPO}/releases/tags/v${SFW_VERSION}" \ - --jq ".assets[] | select(.name == \"$ASSET\") | .browser_download_url")" - if [ -z "$DOWNLOAD_URL" ]; then - echo "Asset ${ASSET} not found in ${REPO}@v${SFW_VERSION}" >&2 - exit 1 - fi - curl -fsSL -o "$SFW_BIN" "$DOWNLOAD_URL" - ACTUAL_SHA256="$( (sha256sum "$SFW_BIN" 2>/dev/null || shasum -a 256 "$SFW_BIN") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET} (${REPO}@v${SFW_VERSION})!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$SFW_BIN" - exit 1 - fi - chmod +x "$SFW_BIN" - fi - echo "SFW_BIN=$SFW_BIN" >> "${GITHUB_ENV:-/dev/null}" - echo "SFW_IS_ENTERPRISE=$USE_ENTERPRISE" >> "${GITHUB_ENV:-/dev/null}" - if [ "$USE_ENTERPRISE" = "true" ]; then - echo "SOCKET_API_KEY=$SOCKET_API_KEY" >> "${GITHUB_ENV:-/dev/null}" - fi - - - name: Create sfw shims - shell: bash - run: | # zizmor: ignore[github-env] - SHIM_DIR="${RUNNER_TEMP:-/tmp}/sfw-shim" - rm -rf "$SHIM_DIR" - mkdir -p "$SHIM_DIR" - IS_WINDOWS=false - [[ "$OSTYPE" == msys* || "$OSTYPE" == cygwin* ]] && IS_WINDOWS=true - msys_to_win_path() { - if $IS_WINDOWS && [[ "$1" =~ ^/([a-zA-Z])/(.*) ]]; then - echo "${BASH_REMATCH[1]^^}:\\${BASH_REMATCH[2]//\//\\}" - else - echo "$1" - fi - } - strip_shim_dir() { echo "$PATH" | tr ':' '\n' | grep -vxF "$SHIM_DIR" | paste -sd: -; } - CLEAN_PATH="$(strip_shim_dir)" - # Wrapper mode ecosystems (sfw-free): - # JavaScript/TypeScript: npm, yarn, pnpm - # Python: pip, uv - # Rust: cargo - # https://github.com/SocketDev/sfw-free?tab=readme-ov-file#supported-package-managers - # - # Additional wrapper mode ecosystems (sfw-enterprise): - # Ruby: gem, bundler - # .NET: nuget - # Go: go (Linux only) - # https://github.com/SocketDev/firewall-release/wiki#support-matrix - SSL_WORKAROUND="" - SHIM_CMDS="npm yarn pnpm pip uv cargo" - if [ "$SFW_IS_ENTERPRISE" = "true" ]; then - SHIM_CMDS="npm yarn pnpm pip uv cargo gem bundler nuget" - # Go wrapper mode is only supported on Linux. - [[ "$OSTYPE" == linux* ]] && SHIM_CMDS="$SHIM_CMDS go" - else - SSL_WORKAROUND='export GIT_SSL_NO_VERIFY=true # Workaround: sfw-free does not yet set GIT_SSL_CAINFO.' - fi - for CMD in $SHIM_CMDS; do - REAL="$(PATH="$CLEAN_PATH" command -v "$CMD" 2>/dev/null || true)" - [ -z "$REAL" ] && continue - if $IS_WINDOWS && [ -f "${REAL}.exe" ]; then REAL="${REAL}.exe"; fi - REAL="$(msys_to_win_path "$REAL")" - SHIM_LINES=('#!/bin/bash' "export PATH=\"\$(echo \"\$PATH\" | tr ':' '\n' | grep -vxF '${SHIM_DIR}' | paste -sd: -)\"") - [ -n "$SSL_WORKAROUND" ] && SHIM_LINES+=("$SSL_WORKAROUND") - SHIM_LINES+=("exec \"${SFW_BIN}\" \"${REAL}\" \"\$@\"") - printf '%s\n' "${SHIM_LINES[@]}" > "$SHIM_DIR/$CMD" - chmod +x "$SHIM_DIR/$CMD" - if $IS_WINDOWS; then - printf '@echo off\r\nset "PATH=;%%PATH%%;"\r\nset "PATH=%%PATH:;%s;=;%%"\r\nset "PATH=%%PATH:~1,-1%%"\r\n"%s" "%s" %%*\r\n' \ - "$SHIM_DIR" "$SFW_BIN" "$REAL" > "$SHIM_DIR/$CMD.cmd" - fi - done - echo "$SHIM_DIR" >> "${GITHUB_PATH:-/dev/null}" - echo "SFW_SHIM_DIR=$SHIM_DIR" >> "${GITHUB_ENV:-/dev/null}" + run: bash scripts/setup/firewall.sh - name: Install dependencies run: pnpm install --loglevel error @@ -512,44 +205,12 @@ jobs: git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" git checkout -q --detach FETCH_HEAD - - name: Install pnpm - shell: bash - run: | # zizmor: ignore[github-env] - PNPM_VERSION="12.21.0" - PNPM_DIR="${RUNNER_TEMP:-/tmp}/pnpm-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="pnpm-linux-x64.tar.gz" ; EXPECTED_SHA256="84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Linux-aarch64) ASSET="pnpm-linux-arm64.tar.gz" ; EXPECTED_SHA256="6c5913a48c93b3a556b71c3bd9bf12c6bf9fbfbbbd2dcbd1d52a85c539751b9e" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-x86_64) ASSET="pnpm-darwin-x64.tar.gz" ; EXPECTED_SHA256="415c05ae4262c89b8f24ca58c693be5d969856ae909c086aa06996951fca30ea" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-arm64) ASSET="pnpm-darwin-arm64.tar.gz" ; EXPECTED_SHA256="5c4d73018e00dd602531ce714625594fb693cbe110e6719df2b043b0ae62ab1a" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="pnpm-win32-x64.zip" ; EXPECTED_SHA256="4fb64bb37e46c788309e0fd4ea93beb512546fdc7348121194fb704fbb72c09c" ; PNPM_BIN="$PNPM_DIR/pnpm.exe" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - PNPM_ARCHIVE="$PNPM_DIR/$ASSET" - if [ ! -x "$PNPM_BIN" ]; then - mkdir -p "$PNPM_DIR" - curl -fsSL -o "$PNPM_ARCHIVE" "https://github.com/pnpm/pnpm/releases/download/v${PNPM_VERSION}/${ASSET}" - ACTUAL_SHA256="$( (sha256sum "$PNPM_ARCHIVE" 2>/dev/null || shasum -a 256 "$PNPM_ARCHIVE") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET}!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$PNPM_ARCHIVE" - exit 1 - fi - if [[ "$ASSET" == *.zip ]]; then unzip -q "$PNPM_ARCHIVE" -d "$PNPM_DIR"; else tar -xzf "$PNPM_ARCHIVE" -C "$PNPM_DIR"; fi - chmod +x "$PNPM_BIN" - fi - echo "$PNPM_DIR" >> "${GITHUB_PATH:-/dev/null}" - - name: Install Node.js • Linux if: runner.os == 'Linux' shell: bash env: NODE_VERSION: ${{ matrix.node-version }} - run: pnpm run ci:setup-node + run: node scripts/setup/node.mts --version "$NODE_VERSION" - name: Install Node.js • Windows if: runner.os == 'Windows' @@ -587,133 +248,16 @@ jobs: Expand-Archive $archivePath $tools (Join-Path $tools "node-v$nodeVersion-win-x64") | Add-Content $env:GITHUB_PATH - - name: Install latest npm + - name: Install pinned package managers shell: bash - env: - NPM_VERSION: 12.2.3 - run: | - npm install --global "npm@$NPM_VERSION" --ignore-scripts --no-audit --no-fund - test "$(npm --version)" = "$NPM_VERSION" + run: bash scripts/setup/release-tools.sh --keep-node - - name: Download sfw + - name: Set up Socket Firewall shell: bash env: GH_TOKEN: ${{ github.token }} SOCKET_API_KEY: ${{ secrets.SOCKET_API_TOKEN_FOR_CLI_AND_SFW }} # zizmor: ignore[secrets-outside-env] - run: | # zizmor: ignore[github-env] - # Pinned version + per-platform checksum pairs. Bumping a tool - # requires updating the matching version AND every platform's - # SHA256 in the same commit, otherwise the download / verify - # steps will diverge. - SFW_FREE_VERSION="1.16.0" - SFW_ENTERPRISE_VERSION="1.16.0" - SFW_DIR="${RUNNER_TEMP:-/tmp}/sfw-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - USE_ENTERPRISE=false - [ -n "$SOCKET_API_KEY" ] && USE_ENTERPRISE=true - if [ "$USE_ENTERPRISE" = "true" ]; then - REPO="SocketDev/firewall-release" - SFW_VERSION="$SFW_ENTERPRISE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9c5e77a2c08683c3cca7c5fba9d380c7acca7ed6ea71c0d3919b2a723bea34b3" ;; - Linux-aarch64) ASSET="sfw-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="945708d9907f4702d91d341647576aae667ad0c411cd9c02a4f56b130512695c" ;; - Darwin-x86_64) ASSET="sfw-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9b6faa3c4cb5d2cbbea7bad5c7a47a4a9f179a8a75f1ce2993ac0c50e5e040cf" ;; - Darwin-arm64) ASSET="sfw-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="16fbe362a24af30b75938667e7bff00ed79df24e17a8e2d0abf3ae53d5739e92" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="e8ecd768aebabc365d91306e0b5ef8b66c16b4816496934ff4998cda60590e3c" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - else - REPO="SocketDev/sfw-free" - SFW_VERSION="$SFW_FREE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-free-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="1f24d2628aeb3995f1f2651509e37641c7c41d07749ac68594ecb5bb2dd44d8a" ;; - Linux-aarch64) ASSET="sfw-free-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="474cdb684e42d33d4b697dedd7d90c159d71380be0e53c496f0e7097c3617a6c" ;; - Darwin-x86_64) ASSET="sfw-free-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="b574931bc2b3c36a9bf07ac07b9c07894f8cd314efc91bc5e4fe1c371b56adca" ;; - Darwin-arm64) ASSET="sfw-free-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="29df049df2ef705a8ce726c6c41fe73a6034f6b1cd0d87f3f15a780d074b6d83" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-free-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="fafcb65a0349ff21af4feeda170f669053efa68acb55e1b935f7ed1b2ac93ca7" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - fi - if [ ! -x "$SFW_BIN" ]; then - mkdir -p "$SFW_DIR" - DOWNLOAD_URL="$(gh api "repos/${REPO}/releases/tags/v${SFW_VERSION}" \ - --jq ".assets[] | select(.name == \"$ASSET\") | .browser_download_url")" - if [ -z "$DOWNLOAD_URL" ]; then - echo "Asset ${ASSET} not found in ${REPO}@v${SFW_VERSION}" >&2 - exit 1 - fi - curl -fsSL -o "$SFW_BIN" "$DOWNLOAD_URL" - ACTUAL_SHA256="$( (sha256sum "$SFW_BIN" 2>/dev/null || shasum -a 256 "$SFW_BIN") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET} (${REPO}@v${SFW_VERSION})!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$SFW_BIN" - exit 1 - fi - chmod +x "$SFW_BIN" - fi - echo "SFW_BIN=$SFW_BIN" >> "${GITHUB_ENV:-/dev/null}" - echo "SFW_IS_ENTERPRISE=$USE_ENTERPRISE" >> "${GITHUB_ENV:-/dev/null}" - if [ "$USE_ENTERPRISE" = "true" ]; then - echo "SOCKET_API_KEY=$SOCKET_API_KEY" >> "${GITHUB_ENV:-/dev/null}" - fi - - - name: Create sfw shims - shell: bash - run: | # zizmor: ignore[github-env] - SHIM_DIR="${RUNNER_TEMP:-/tmp}/sfw-shim" - rm -rf "$SHIM_DIR" - mkdir -p "$SHIM_DIR" - IS_WINDOWS=false - [[ "$OSTYPE" == msys* || "$OSTYPE" == cygwin* ]] && IS_WINDOWS=true - msys_to_win_path() { - if $IS_WINDOWS && [[ "$1" =~ ^/([a-zA-Z])/(.*) ]]; then - echo "${BASH_REMATCH[1]^^}:\\${BASH_REMATCH[2]//\//\\}" - else - echo "$1" - fi - } - strip_shim_dir() { echo "$PATH" | tr ':' '\n' | grep -vxF "$SHIM_DIR" | paste -sd: -; } - CLEAN_PATH="$(strip_shim_dir)" - # Wrapper mode ecosystems (sfw-free): - # JavaScript/TypeScript: npm, yarn, pnpm - # Python: pip, uv - # Rust: cargo - # https://github.com/SocketDev/sfw-free?tab=readme-ov-file#supported-package-managers - # - # Additional wrapper mode ecosystems (sfw-enterprise): - # Ruby: gem, bundler - # .NET: nuget - # Go: go (Linux only) - # https://github.com/SocketDev/firewall-release/wiki#support-matrix - SSL_WORKAROUND="" - SHIM_CMDS="npm yarn pnpm pip uv cargo" - if [ "$SFW_IS_ENTERPRISE" = "true" ]; then - SHIM_CMDS="npm yarn pnpm pip uv cargo gem bundler nuget" - # Go wrapper mode is only supported on Linux. - [[ "$OSTYPE" == linux* ]] && SHIM_CMDS="$SHIM_CMDS go" - else - SSL_WORKAROUND='export GIT_SSL_NO_VERIFY=true # Workaround: sfw-free does not yet set GIT_SSL_CAINFO.' - fi - for CMD in $SHIM_CMDS; do - REAL="$(PATH="$CLEAN_PATH" command -v "$CMD" 2>/dev/null || true)" - [ -z "$REAL" ] && continue - if $IS_WINDOWS && [ -f "${REAL}.exe" ]; then REAL="${REAL}.exe"; fi - REAL="$(msys_to_win_path "$REAL")" - SHIM_LINES=('#!/bin/bash' "export PATH=\"\$(echo \"\$PATH\" | tr ':' '\n' | grep -vxF '${SHIM_DIR}' | paste -sd: -)\"") - [ -n "$SSL_WORKAROUND" ] && SHIM_LINES+=("$SSL_WORKAROUND") - SHIM_LINES+=("exec \"${SFW_BIN}\" \"${REAL}\" \"\$@\"") - printf '%s\n' "${SHIM_LINES[@]}" > "$SHIM_DIR/$CMD" - chmod +x "$SHIM_DIR/$CMD" - if $IS_WINDOWS; then - printf '@echo off\r\nset "PATH=;%%PATH%%;"\r\nset "PATH=%%PATH:;%s;=;%%"\r\nset "PATH=%%PATH:~1,-1%%"\r\n"%s" "%s" %%*\r\n' \ - "$SHIM_DIR" "$SFW_BIN" "$REAL" > "$SHIM_DIR/$CMD.cmd" - fi - done - echo "$SHIM_DIR" >> "${GITHUB_PATH:-/dev/null}" - echo "SFW_SHIM_DIR=$SHIM_DIR" >> "${GITHUB_ENV:-/dev/null}" + run: bash scripts/setup/firewall.sh - name: Install dependencies • Bash if: matrix.shell == 'bash' @@ -833,51 +377,9 @@ jobs: git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" git checkout -q --detach FETCH_HEAD - - name: Install Node.js 26.13.0 (checksum verified) + - name: Install release toolchain shell: bash - run: | - set -euo pipefail - version=26.13.0 - base="https://nodejs.org/dist/v${version}" - if [[ "$RUNNER_OS" == Windows ]]; then - archive="node-v${version}-win-x64.zip" - curl -fsSLO "$base/$archive" - curl -fsSLO "$base/SHASUMS256.txt" - grep " $archive$" SHASUMS256.txt | sha256sum -c - - mkdir -p "$RUNNER_TEMP/node" - unzip -q "$archive" -d "$RUNNER_TEMP/node" - cygpath -w "$RUNNER_TEMP/node/node-v${version}-win-x64" >> "$GITHUB_PATH" - else - if [[ "$RUNNER_OS" == macOS ]]; then platform=darwin-arm64; else platform=linux-x64; fi - archive="node-v${version}-${platform}.tar.xz" - curl -fsSLO "$base/$archive" - curl -fsSLO "$base/SHASUMS256.txt" - grep " $archive$" SHASUMS256.txt | shasum -a 256 -c - - mkdir -p "$RUNNER_TEMP/node" - tar -xJf "$archive" -C "$RUNNER_TEMP/node" --strip-components=1 - echo "$RUNNER_TEMP/node/bin" >> "$GITHUB_PATH" - fi - if [[ "$RUNNER_OS" == Windows ]]; then "$RUNNER_TEMP/node/node-v${version}-win-x64/node.exe" -e 'if(process.versions.node!=="26.13.0")process.exit(1)'; else "$RUNNER_TEMP/node/bin/node" -e 'if(process.versions.node!=="26.13.0")process.exit(1)'; fi - - - name: Install pinned pnpm - shell: bash - run: | - set -euo pipefail - version=12.21.0 - case "$RUNNER_OS/$RUNNER_ARCH" in - Linux/X64) asset=pnpm-linux-x64.tar.gz; sha=84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410 ;; - macOS/ARM64) asset=pnpm-darwin-arm64.tar.gz; sha=5c4d73018e00dd602531ce714625594fb693cbe110e6719df2b043b0ae62ab1a ;; - Windows/X64) asset=pnpm-win32-x64.zip; sha=4fb64bb37e46c788309e0fd4ea93beb512546fdc7348121194fb704fbb72c09c ;; - *) echo "Unsupported runner: $RUNNER_OS/$RUNNER_ARCH" >&2; exit 1 ;; - esac - dir="$RUNNER_TEMP/pnpm-bin" - mkdir -p "$dir" - curl -fsSL "https://github.com/pnpm/pnpm/releases/download/v${version}/${asset}" -o "$dir/$asset" - actual=$( (sha256sum "$dir/$asset" 2>/dev/null || shasum -a 256 "$dir/$asset") | cut -d' ' -f1 | tr -d '\134') - [[ "$actual" == "$sha" ]] || { echo "pnpm checksum mismatch" >&2; exit 1; } - if [[ "$asset" == *.zip ]]; then unzip -q "$dir/$asset" -d "$dir"; else tar -xzf "$dir/$asset" -C "$dir"; chmod +x "$dir/pnpm"; fi - if [[ "$RUNNER_OS" == Windows ]]; then dir=$(cygpath -w "$dir"); fi - echo "$dir" >> "$GITHUB_PATH" + run: bash scripts/setup/release-tools.sh - name: Install dependencies run: pnpm install --frozen-lockfile @@ -925,10 +427,10 @@ jobs: shell: bash run: dotnet --list-sdks | awk -F. '$1 >= 8 { found=1 } END { exit !found }' - - name: Build prototype native executable + - name: Build and check the native executable env: NODE_OPTIONS: ${{ matrix.target == 'darwin-arm64' && '--max-old-space-size=4096' || '' }} - run: pnpm build:sea --prototype + run: pnpm build:sea - name: Save pinned SEA download cache if: success() && steps.sea-download-cache.outputs.cache-hit != 'true' && github.repository == 'SocketDev/socket-cli' && (github.event_name == 'push' || github.event_name == 'workflow_dispatch') && (github.ref == 'refs/heads/v1.x' || github.ref == 'refs/heads/feat/v1x-node27-sea-vfs-socket' || startsWith(github.ref, 'refs/heads/test/native-terminal-validation-')) @@ -952,7 +454,7 @@ jobs: export SOCKET_CLI_NATIVE_TEST_ARTIFACTS rm -rf "$SOCKET_CLI_NATIVE_TEST_ARTIFACTS" mkdir -p "$SOCKET_CLI_NATIVE_TEST_ARTIFACTS" - if pnpm test:native test/native/commands/cli.native.test.mts test/native/commands/cli-behavior.native.test.mts test/native/commands/tui.native.test.mts; then result=0; else result=$?; fi + if pnpm test:sea test/native/commands/cli.native.test.mts test/native/commands/cli-behavior.native.test.mts test/native/commands/tui.native.test.mts; then result=0; else result=$?; fi if [[ $result == 0 ]]; then status=passed; else status=failed; fi export TEST_STATUS="$status" TEST_EXIT_CODE="$result" TEST_PLATFORM="$RUNNER_OS/$RUNNER_ARCH" node -e 'const fs=require("node:fs"); let receipt={}; try { receipt=JSON.parse(fs.readFileSync(process.env.SOCKET_CLI_NATIVE_TEST_ARTIFACTS+"/signing-receipt.json","utf8")); } catch {} process.stdout.write(JSON.stringify({status:process.env.TEST_STATUS,exitCode:Number(process.env.TEST_EXIT_CODE),platform:process.env.TEST_PLATFORM,sourceCommit:process.env.GITHUB_SHA||"unknown",signingMode:receipt.mode||"unknown",sourceSha256:receipt.sourceSha256,binarySha256:receipt.stagedSha256})+"\n")' > "$SOCKET_CLI_NATIVE_TEST_ARTIFACTS/test-result.json" diff --git a/.github/workflows/e2e-tests.yml b/.github/workflows/e2e-tests.yml index 772766acf1..93adf97044 100644 --- a/.github/workflows/e2e-tests.yml +++ b/.github/workflows/e2e-tests.yml @@ -40,133 +40,24 @@ jobs: git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" git checkout -q --detach FETCH_HEAD - - name: Install pnpm - shell: bash - run: | # zizmor: ignore[github-env] - PNPM_VERSION="12.21.0" - PNPM_DIR="${RUNNER_TEMP:-/tmp}/pnpm-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="pnpm-linux-x64.tar.gz" ; EXPECTED_SHA256="84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Linux-aarch64) ASSET="pnpm-linux-arm64.tar.gz" ; EXPECTED_SHA256="6c5913a48c93b3a556b71c3bd9bf12c6bf9fbfbbbd2dcbd1d52a85c539751b9e" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-x86_64) ASSET="pnpm-darwin-x64.tar.gz" ; EXPECTED_SHA256="415c05ae4262c89b8f24ca58c693be5d969856ae909c086aa06996951fca30ea" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - Darwin-arm64) ASSET="pnpm-darwin-arm64.tar.gz" ; EXPECTED_SHA256="5c4d73018e00dd602531ce714625594fb693cbe110e6719df2b043b0ae62ab1a" ; PNPM_BIN="$PNPM_DIR/pnpm" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="pnpm-win32-x64.zip" ; EXPECTED_SHA256="4fb64bb37e46c788309e0fd4ea93beb512546fdc7348121194fb704fbb72c09c" ; PNPM_BIN="$PNPM_DIR/pnpm.exe" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - PNPM_ARCHIVE="$PNPM_DIR/$ASSET" - if [ ! -x "$PNPM_BIN" ]; then - mkdir -p "$PNPM_DIR" - curl -fsSL -o "$PNPM_ARCHIVE" "https://github.com/pnpm/pnpm/releases/download/v${PNPM_VERSION}/${ASSET}" - ACTUAL_SHA256="$( (sha256sum "$PNPM_ARCHIVE" 2>/dev/null || shasum -a 256 "$PNPM_ARCHIVE") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET}!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$PNPM_ARCHIVE" - exit 1 - fi - if [[ "$ASSET" == *.zip ]]; then unzip -q "$PNPM_ARCHIVE" -d "$PNPM_DIR"; else tar -xzf "$PNPM_ARCHIVE" -C "$PNPM_DIR"; fi - chmod +x "$PNPM_BIN" - fi - echo "$PNPM_DIR" >> "${GITHUB_PATH:-/dev/null}" - - name: Install Node.js shell: bash env: NODE_VERSION: ${{ matrix.node-version }} - run: pnpm run ci:setup-node + run: node scripts/setup/node.mts --version "$NODE_VERSION" - - name: Install latest npm + - name: Install pinned package managers shell: bash - env: - NPM_VERSION: 12.2.3 - run: | - npm install --global "npm@$NPM_VERSION" --ignore-scripts --no-audit --no-fund - test "$(npm --version)" = "$NPM_VERSION" + run: bash scripts/setup/release-tools.sh --keep-node - name: Install uv run: pnpm run ci:setup-uv - - name: Download sfw-free + - name: Set up Socket Firewall shell: bash env: GH_TOKEN: ${{ github.token }} - run: | # zizmor: ignore[github-env] - # Pinned version + per-platform checksum pair. Bumping sfw-free - # requires updating SFW_FREE_VERSION AND every platform's - # SHA256 in the same commit, otherwise the download / verify - # steps will diverge. - SFW_FREE_VERSION="1.16.0" - SFW_DIR="${RUNNER_TEMP:-/tmp}/sfw-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-free-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="1f24d2628aeb3995f1f2651509e37641c7c41d07749ac68594ecb5bb2dd44d8a" ;; - Linux-aarch64) ASSET="sfw-free-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="474cdb684e42d33d4b697dedd7d90c159d71380be0e53c496f0e7097c3617a6c" ;; - Darwin-x86_64) ASSET="sfw-free-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="b574931bc2b3c36a9bf07ac07b9c07894f8cd314efc91bc5e4fe1c371b56adca" ;; - Darwin-arm64) ASSET="sfw-free-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="29df049df2ef705a8ce726c6c41fe73a6034f6b1cd0d87f3f15a780d074b6d83" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-free-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="fafcb65a0349ff21af4feeda170f669053efa68acb55e1b935f7ed1b2ac93ca7" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - if [ ! -x "$SFW_BIN" ]; then - mkdir -p "$SFW_DIR" - DOWNLOAD_URL="$(gh api "repos/SocketDev/sfw-free/releases/tags/v${SFW_FREE_VERSION}" \ - --jq ".assets[] | select(.name == \"$ASSET\") | .browser_download_url")" - if [ -z "$DOWNLOAD_URL" ]; then - echo "Asset ${ASSET} not found in SocketDev/sfw-free@v${SFW_FREE_VERSION}" >&2 - exit 1 - fi - curl -fsSL -o "$SFW_BIN" "$DOWNLOAD_URL" - ACTUAL_SHA256="$( (sha256sum "$SFW_BIN" 2>/dev/null || shasum -a 256 "$SFW_BIN") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET} (SocketDev/sfw-free@v${SFW_FREE_VERSION})!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$SFW_BIN" - exit 1 - fi - chmod +x "$SFW_BIN" - fi - echo "SFW_BIN=$SFW_BIN" >> "${GITHUB_ENV:-/dev/null}" - - - name: Create sfw shims - shell: bash - run: | # zizmor: ignore[github-env] - SHIM_DIR="${RUNNER_TEMP:-/tmp}/sfw-shim" - rm -rf "$SHIM_DIR" - mkdir -p "$SHIM_DIR" - IS_WINDOWS=false - [[ "$OSTYPE" == msys* || "$OSTYPE" == cygwin* ]] && IS_WINDOWS=true - msys_to_win_path() { - if $IS_WINDOWS && [[ "$1" =~ ^/([a-zA-Z])/(.*) ]]; then - echo "${BASH_REMATCH[1]^^}:\\${BASH_REMATCH[2]//\//\\}" - else - echo "$1" - fi - } - strip_shim_dir() { echo "$PATH" | tr ':' '\n' | grep -vxF "$SHIM_DIR" | paste -sd: -; } - CLEAN_PATH="$(strip_shim_dir)" - # https://docs.socket.dev/docs/socket-firewall-free#what-ecosystems-and-package-managers-are-supported - for CMD in npm yarn pnpm pip uv cargo; do - REAL="$(PATH="$CLEAN_PATH" command -v "$CMD" 2>/dev/null || true)" - [ -z "$REAL" ] && continue - REAL="$(msys_to_win_path "$REAL")" - printf '%s\n' \ - '#!/bin/bash' \ - "export PATH=\"\$(echo \"\$PATH\" | tr ':' '\n' | grep -vxF '${SHIM_DIR}' | paste -sd: -)\"" \ - 'export GIT_SSL_NO_VERIFY=true # Workaround: sfw-free does not yet set GIT_SSL_CAINFO.' \ - "exec \"${SFW_BIN}\" \"${REAL}\" \"\$@\"" \ - > "$SHIM_DIR/$CMD" - chmod +x "$SHIM_DIR/$CMD" - if $IS_WINDOWS; then - printf '@echo off\r\nset "PATH=;%%PATH%%;"\r\nset "PATH=%%PATH:;%s;=;%%"\r\nset "PATH=%%PATH:~1,-1%%"\r\n"%s" "%s" %%*\r\n' \ - "$SHIM_DIR" "$SFW_BIN" "$REAL" > "$SHIM_DIR/$CMD.cmd" - fi - done - echo "$SHIM_DIR" >> "${GITHUB_PATH:-/dev/null}" - echo "SFW_SHIM_DIR=$SHIM_DIR" >> "${GITHUB_ENV:-/dev/null}" + run: bash scripts/setup/firewall.sh - name: Install dependencies run: pnpm install --loglevel error diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index a6867b12d3..6480a9f066 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -1,7 +1,7 @@ name: Publish to npm registry # Release process for v1.x and the configured Socket prerelease. Stable v1.x -# publishes all three packages; the 2.1.0-rc track publishes only `socket`. +# publishes all three packages; the 2.1.0-rc track stages the native launcher and five platform packages. # # 1. Between releases nobody touches the version. package.json keeps the # last released number and user-facing notes accrue under the @@ -61,7 +61,7 @@ on: default: '' type: string release-major: - description: 'release-pr only. Select the release line (2 selects the configured Socket prerelease track).' + description: 'Select the release line for a release PR or publish dry run. Choose 2 to exercise native RC packaging.' required: false default: '1' type: choice @@ -85,8 +85,8 @@ jobs: # Build, pack, and prove every variant WITHOUT any publish credential: this # job binds no environment and mints no OIDC token, so nothing it runs — # install scripts and build tooling — can reach a token. - # It hands the publish job three verified tarballs; those exact bytes are - # what ship, so what was tested is what publishes. + # Stable builds upload all three tarballs here. For an RC, this job uploads + # the launcher and each native host uploads its tested platform package. verify: name: Verify and pack if: ${{ inputs.mode == 'publish' }} @@ -97,11 +97,10 @@ jobs: contents: read outputs: - artifact-id: ${{ steps.upload.outputs.artifact-id }} - artifact-digest: ${{ steps.upload.outputs.artifact-digest }} + receipt: ${{ steps.upload.outputs.artifact-id }}:${{ steps.upload.outputs.artifact-digest }} sha: ${{ steps.release-meta.outputs.sha }} version: ${{ steps.release-meta.outputs.version }} - dist-tag: ${{ steps.release-policy.outputs.dist-tag }} + dist-tag: ${{ steps.release-meta.outputs.dist-tag }} steps: # npm trusted publishing authorizes on repository + workflow filename + @@ -160,46 +159,13 @@ jobs: REPOSITORY: ${{ github.repository }} run: | set -euo pipefail - SHA="$(git rev-parse --verify 'HEAD^{commit}')" - VERIFIED="$(gh api "repos/${REPOSITORY}/commits/${SHA}" --jq '.commit.verification.verified')" - if [ "$VERIFIED" != true ]; then - echo "::error::Release commit ${SHA} is not GitHub-verified; npm staging stopped." >&2 - exit 1 - fi + gh api "repos/$REPOSITORY/contents/.github/scripts/verify-release.mts?ref=$GITHUB_WORKFLOW_SHA" -H 'Accept: application/vnd.github.raw+json' > "$RUNNER_TEMP/verify-release.mts" + node "$RUNNER_TEMP/verify-release.mts" commit - - &install-pnpm - name: Install pnpm + - &release-tools + name: Install release toolchain shell: bash - run: | # zizmor: ignore[github-env] - # pnpm 12 is required for `pnpm stage publish` (the staged upload - # the per-package trusted-publisher grants allow) and ships tar.gz - # release assets (a `pnpm` binary + its dist/ tree). The job only - # runs ubuntu-latest, so only the Linux assets are pinned. - PNPM_VERSION="12.21.0" - PNPM_DIR="${RUNNER_TEMP:-/tmp}/pnpm-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="pnpm-linux-x64.tar.gz" ; EXPECTED_SHA256="84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410" ;; - Linux-aarch64) ASSET="pnpm-linux-arm64.tar.gz" ; EXPECTED_SHA256="6c5913a48c93b3a556b71c3bd9bf12c6bf9fbfbbbd2dcbd1d52a85c539751b9e" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - PNPM_BIN="$PNPM_DIR/pnpm" - if [ ! -x "$PNPM_BIN" ]; then - mkdir -p "$PNPM_DIR" - curl -fsSL -o "$PNPM_DIR/$ASSET" "https://github.com/pnpm/pnpm/releases/download/v${PNPM_VERSION}/${ASSET}" - ACTUAL_SHA256="$( (sha256sum "$PNPM_DIR/$ASSET" 2>/dev/null || shasum -a 256 "$PNPM_DIR/$ASSET") | cut -d' ' -f1)" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET}!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$PNPM_DIR/$ASSET" - exit 1 - fi - tar -xzf "$PNPM_DIR/$ASSET" -C "$PNPM_DIR" - chmod +x "$PNPM_BIN" - fi - echo "$PNPM_DIR" >> "${GITHUB_PATH:-/dev/null}" + run: bash scripts/setup/release-tools.sh # Prove the pinned pnpm owns `stage` BEFORE anything else runs — from a # neutral cwd so the packageManager delegation cannot swap it out. Runs @@ -208,339 +174,232 @@ jobs: - name: Verify the stage command resolves working-directory: ${{ runner.temp }} run: | - "${RUNNER_TEMP}/pnpm-bin/pnpm" --version - "${RUNNER_TEMP}/pnpm-bin/pnpm" stage --help > /dev/null + pnpm --version + pnpm stage --help > /dev/null echo "pnpm stage resolves via the pinned binary." - - &install-node - name: Install Node.js - shell: bash - env: - NODE_VERSION: 26.13.0 - run: pnpm run ci:setup-node - - - name: Install latest npm - shell: bash - env: - NPM_VERSION: 12.2.3 - run: | - npm install --global "npm@$NPM_VERSION" --ignore-scripts --no-audit --no-fund - test "$(npm --version)" = "$NPM_VERSION" - - - &download-sfw - name: Download sfw + - &setup-firewall + name: Set up Socket Firewall shell: bash env: GH_TOKEN: ${{ github.token }} SOCKET_API_KEY: ${{ secrets.SOCKET_API_TOKEN_FOR_CLI_AND_SFW }} # zizmor: ignore[secrets-outside-env] - run: | # zizmor: ignore[github-env] - # Pinned version + per-platform checksum pairs. Bumping a tool - # requires updating the matching version AND every platform's - # SHA256 in the same commit, otherwise the download / verify - # steps will diverge. - SFW_FREE_VERSION="1.16.0" - SFW_ENTERPRISE_VERSION="1.16.0" - SFW_DIR="${RUNNER_TEMP:-/tmp}/sfw-bin" - KERNEL="$(uname -s | cut -d- -f1)" - ARCH="$(uname -m)" - USE_ENTERPRISE=false - [ -n "$SOCKET_API_KEY" ] && USE_ENTERPRISE=true - if [ "$USE_ENTERPRISE" = "true" ]; then - REPO="SocketDev/firewall-release" - SFW_VERSION="$SFW_ENTERPRISE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9c5e77a2c08683c3cca7c5fba9d380c7acca7ed6ea71c0d3919b2a723bea34b3" ;; - Linux-aarch64) ASSET="sfw-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="945708d9907f4702d91d341647576aae667ad0c411cd9c02a4f56b130512695c" ;; - Darwin-x86_64) ASSET="sfw-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="9b6faa3c4cb5d2cbbea7bad5c7a47a4a9f179a8a75f1ce2993ac0c50e5e040cf" ;; - Darwin-arm64) ASSET="sfw-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="16fbe362a24af30b75938667e7bff00ed79df24e17a8e2d0abf3ae53d5739e92" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="e8ecd768aebabc365d91306e0b5ef8b66c16b4816496934ff4998cda60590e3c" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - else - REPO="SocketDev/sfw-free" - SFW_VERSION="$SFW_FREE_VERSION" - case "${KERNEL}-${ARCH}" in - Linux-x86_64) ASSET="sfw-free-linux-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="1f24d2628aeb3995f1f2651509e37641c7c41d07749ac68594ecb5bb2dd44d8a" ;; - Linux-aarch64) ASSET="sfw-free-linux-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="474cdb684e42d33d4b697dedd7d90c159d71380be0e53c496f0e7097c3617a6c" ;; - Darwin-x86_64) ASSET="sfw-free-macos-x86_64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="b574931bc2b3c36a9bf07ac07b9c07894f8cd314efc91bc5e4fe1c371b56adca" ;; - Darwin-arm64) ASSET="sfw-free-macos-arm64" ; SFW_BIN="$SFW_DIR/sfw" ; EXPECTED_SHA256="29df049df2ef705a8ce726c6c41fe73a6034f6b1cd0d87f3f15a780d074b6d83" ;; - MINGW64_NT-x86_64|MSYS_NT-x86_64) ASSET="sfw-free-windows-x86_64.exe" ; SFW_BIN="$SFW_DIR/sfw.exe" ; EXPECTED_SHA256="fafcb65a0349ff21af4feeda170f669053efa68acb55e1b935f7ed1b2ac93ca7" ;; - *) echo "Unsupported platform: ${KERNEL}-${ARCH}" >&2; exit 1 ;; - esac - fi - if [ ! -x "$SFW_BIN" ]; then - mkdir -p "$SFW_DIR" - DOWNLOAD_URL="$(gh api "repos/${REPO}/releases/tags/v${SFW_VERSION}" \ - --jq ".assets[] | select(.name == \"$ASSET\") | .browser_download_url")" - if [ -z "$DOWNLOAD_URL" ]; then - echo "Asset ${ASSET} not found in ${REPO}@v${SFW_VERSION}" >&2 - exit 1 - fi - curl -fsSL -o "$SFW_BIN" "$DOWNLOAD_URL" - # shellcheck disable=SC1003 # `tr -d '\\'` strips the leading backslash GNU coreutils prepends to a checksum line when the path has a backslash (Windows RUNNER_TEMP). - ACTUAL_SHA256="$( (sha256sum "$SFW_BIN" 2>/dev/null || shasum -a 256 "$SFW_BIN") | cut -d' ' -f1 | tr -d '\\')" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET} (${REPO}@v${SFW_VERSION})!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - rm -f "$SFW_BIN" - exit 1 - fi - chmod +x "$SFW_BIN" - fi - echo "SFW_BIN=$SFW_BIN" >> "${GITHUB_ENV:-/dev/null}" - echo "SFW_IS_ENTERPRISE=$USE_ENTERPRISE" >> "${GITHUB_ENV:-/dev/null}" - if [ "$USE_ENTERPRISE" = "true" ]; then - echo "SOCKET_API_KEY=$SOCKET_API_KEY" >> "${GITHUB_ENV:-/dev/null}" - fi - - - &create-sfw-shims - name: Create sfw shims - shell: bash - run: | # zizmor: ignore[github-env] - SHIM_DIR="${RUNNER_TEMP:-/tmp}/sfw-shim" - rm -rf "$SHIM_DIR" - mkdir -p "$SHIM_DIR" - IS_WINDOWS=false - [[ "$OSTYPE" == msys* || "$OSTYPE" == cygwin* ]] && IS_WINDOWS=true - msys_to_win_path() { - if $IS_WINDOWS && [[ "$1" =~ ^/([a-zA-Z])/(.*) ]]; then - echo "${BASH_REMATCH[1]^^}:\\${BASH_REMATCH[2]//\//\\}" - else - echo "$1" - fi - } - strip_shim_dir() { echo "$PATH" | tr ':' '\n' | grep -vxF "$SHIM_DIR" | paste -sd: -; } - CLEAN_PATH="$(strip_shim_dir)" - # Wrapper mode ecosystems (sfw-free): - # JavaScript/TypeScript: npm, yarn, pnpm - # Python: pip, uv - # Rust: cargo - # https://github.com/SocketDev/sfw-free?tab=readme-ov-file#supported-package-managers - # - # Additional wrapper mode ecosystems (sfw-enterprise): - # Ruby: gem, bundler - # .NET: nuget - # Go: go (Linux only) - # https://github.com/SocketDev/firewall-release/wiki#support-matrix - SSL_WORKAROUND="" - SHIM_CMDS="npm yarn pnpm pip uv cargo" - if [ "$SFW_IS_ENTERPRISE" = "true" ]; then - SHIM_CMDS="npm yarn pnpm pip uv cargo gem bundler nuget" - # Go wrapper mode is only supported on Linux. - [[ "$OSTYPE" == linux* ]] && SHIM_CMDS="$SHIM_CMDS go" - else - SSL_WORKAROUND='export GIT_SSL_NO_VERIFY=true # Workaround: sfw-free does not yet set GIT_SSL_CAINFO.' - fi - for CMD in $SHIM_CMDS; do - REAL="$(PATH="$CLEAN_PATH" command -v "$CMD" 2>/dev/null || true)" - [ -z "$REAL" ] && continue - REAL="$(msys_to_win_path "$REAL")" - SHIM_LINES=('#!/bin/bash' "export PATH=\"\$(echo \"\$PATH\" | tr ':' '\n' | grep -vxF '${SHIM_DIR}' | paste -sd: -)\"") - [ -n "$SSL_WORKAROUND" ] && SHIM_LINES+=("$SSL_WORKAROUND") - SHIM_LINES+=("exec \"${SFW_BIN}\" \"${REAL}\" \"\$@\"") - printf '%s\n' "${SHIM_LINES[@]}" > "$SHIM_DIR/$CMD" - chmod +x "$SHIM_DIR/$CMD" - if $IS_WINDOWS; then - printf '@echo off\r\nset "PATH=;%%PATH%%;"\r\nset "PATH=%%PATH:;%s;=;%%"\r\nset "PATH=%%PATH:~1,-1%%"\r\n"%s" "%s" %%*\r\n' \ - "$SHIM_DIR" "$SFW_BIN" "$REAL" > "$SHIM_DIR/$CMD.cmd" - fi - done - echo "$SHIM_DIR" >> "${GITHUB_PATH:-/dev/null}" - echo "SFW_SHIM_DIR=$SHIM_DIR" >> "${GITHUB_ENV:-/dev/null}" + run: bash scripts/setup/firewall.sh - &install-dependencies name: Install dependencies - run: pnpm install --loglevel error + shell: bash + run: pnpm install --frozen-lockfile --loglevel error - # Validate the version and dist-tag against the checked-in release policy. - - name: Validate release policy and choose npm dist-tag - id: release-policy - if: ${{ inputs.dry-run == false }} + - name: Resolve release metadata + id: release-meta + env: + PREVIEW_NATIVE: ${{ inputs.dry-run && inputs.release-major == '2' }} run: | - VERSION=$(node -p "require('./package.json').version") - node scripts/release/validate-npm-policy.mts "$VERSION" - if [[ "$VERSION" == *-* ]]; then - echo "NPM_PRERELEASE_RELEASE=true" >> "$GITHUB_ENV" + version=$(node -p "require('./package.json').version") + if [[ "$PREVIEW_NATIVE" == true ]]; then + version=$(node --input-type=module -e 'import { SEA_VERSION } from "./src/sea/version.mts"; console.log(SEA_VERSION)') fi + echo "version=$version" >> "$GITHUB_OUTPUT" + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" + node scripts/release/validate-npm-policy.mts "$version" - name: Restrict latest releases to v1.x - if: ${{ inputs.dry-run == false && steps.release-policy.outputs.dist-tag == 'latest' }} + if: ${{ inputs.dry-run == false && steps.release-meta.outputs.dist-tag == 'latest' }} env: REF: ${{ github.ref }} run: | - if [ "$REF" != "refs/heads/v1.x" ]; then - echo "Refusing to publish the latest dist-tag outside refs/heads/v1.x." >&2 - exit 1 - fi + node .github/scripts/verify-release.mts latest-branch - # Compile the Maven manifest extension jar so the dist build bundles it - # into dist/manifest-scripts (the jar is never committed; it ships only in - # the published package). Invoke build-jar.sh directly, NOT via `pnpm run`: - # Socket Firewall wraps the package managers (npm/pnpm/...) it shims, so a - # `pnpm run` would route the Maven wrapper's download through sfw, which - # fails on the non-package fetch. Running bash directly keeps the Maven - # download outside the shimmed process tree. The org action allowlist forbids - # actions/setup-java, so use a JDK pre-installed on the runner image - # (JAVA_HOME_17_X64), falling back to the runner's default `java`. - - name: Build Maven manifest extension jar - run: | - if [ -n "${JAVA_HOME_17_X64:-}" ]; then - export JAVA_HOME="$JAVA_HOME_17_X64" - fi - bash src/commands/manifest/scripts/maven-extension/build-jar.sh + - name: Refuse an already-published version + if: ${{ inputs.dry-run == false }} + env: + VERSION: ${{ steps.release-meta.outputs.version }} + run: pnpm run release:preflight --version "$VERSION" - # Same for the dotnet manifest tool: built here, bundled into - # dist/manifest-scripts, never committed. The runner image's preinstalled - # .NET SDK builds it (actions/setup-dotnet is not on the org allowlist). - - name: Build dotnet manifest tool - run: bash src/commands/manifest/scripts/dotnet-tool/build-tool.sh + - name: Pack native launcher + if: contains(steps.release-meta.outputs.version, '-') + run: pnpm pack:native root --out "$RUNNER_TEMP/dist" - # PACK ONCE, PUBLISH THOSE BYTES. Each variant is built, packed to a - # tarball, and smoke-tested from that tarball; the three tarballs are - # uploaded as an artifact and the publish job stages those exact files. - # Re-packing at upload time would publish bytes nothing verified. - # - # The smoke test is the gate that a build being "green" cannot give you: - # it installs the packed tarball into a throwaway consumer and runs - # every executable the manifest declares. A tarball that installs but - # cannot run is caught here, before any release marker exists. - # Registry pages render the README from the tarball, where relative - # assets/ refs 404. Pin them to the release tag once, before the three - # packs, so every variant ships absolute, immutable asset URLs. - - name: Pin README assets to the release tag - run: node .github/scripts/pin-readme-assets.mjs - - - name: Build and pack socket + - name: Build, pack, and smoke test stable packages + if: ${{ !contains(steps.release-meta.outputs.version, '-') }} env: + VERSION: ${{ steps.release-meta.outputs.version }} SOCKET_CLI_DEBUG: ${{ inputs.debug }} run: | - INLINED_SOCKET_CLI_PUBLISHED_BUILD=1 pnpm run build:dist + # Run tool builds directly so the firewall only wraps package-manager traffic. + if [[ -n "${JAVA_HOME_17_X64:-}" ]]; then export JAVA_HOME="$JAVA_HOME_17_X64"; fi + bash src/commands/manifest/scripts/maven-extension/build-jar.sh + bash src/commands/manifest/scripts/dotnet-tool/build-tool.sh + node .github/scripts/pin-readme-assets.mjs + mkdir -p "$RUNNER_TEMP/dist" - pnpm pack --pack-destination "$RUNNER_TEMP/dist" + pack() { + local package=$1 + shift + env INLINED_SOCKET_CLI_PUBLISHED_BUILD=1 "$@" pnpm run build:dist + pnpm pack --pack-destination "$RUNNER_TEMP/dist" + PKG="$package" node .github/scripts/smoke-test-tarball.mts + } + pack socket + pack @socketsecurity/cli INLINED_SOCKET_CLI_LEGACY_BUILD=1 + pack @socketsecurity/cli-with-sentry INLINED_SOCKET_CLI_SENTRY_BUILD=1 + git restore -- package.json - - name: Smoke test socket - env: - PKG: socket - run: bash .github/scripts/smoke-test-tarball.sh + - name: Upload verified tarballs + id: upload + uses: ./.github/actions/repo/upload-artifact + with: + name: npm-release-tarballs-${{ github.run_attempt }} + path: ${{ runner.temp }}/dist - - name: Build and pack @socketsecurity/cli (legacy) - if: ${{ env.NPM_PRERELEASE_RELEASE != 'true' }} + - name: Verify artifact transfer + shell: bash env: - SOCKET_CLI_DEBUG: ${{ inputs.debug }} - run: | - INLINED_SOCKET_CLI_PUBLISHED_BUILD=1 INLINED_SOCKET_CLI_LEGACY_BUILD=1 pnpm run build:dist - pnpm pack --pack-destination "$RUNNER_TEMP/dist" + GH_TOKEN: ${{ github.token }} + ROOT_RECEIPT: ${{ steps.upload.outputs.artifact-id }}:${{ steps.upload.outputs.artifact-digest }} + VERSION: ${{ steps.release-meta.outputs.version }} + DIST_DIRECTORY: ${{ runner.temp }}/download-check + run: node .github/scripts/download-release-artifacts.mts - - name: Smoke test @socketsecurity/cli - if: ${{ env.NPM_PRERELEASE_RELEASE != 'true' }} + native-packages: + needs: verify + if: contains(needs.verify.outputs.version, '-') && (inputs.dry-run || github.ref == 'refs/heads/v1.x') + permissions: + contents: read + actions: read + # Matrix legs export distinct keys so retries retain each successful upload. + outputs: + darwin-arm64: ${{ steps.receipt.outputs.darwin-arm64 }} + linux-arm64: ${{ steps.receipt.outputs.linux-arm64 }} + linux-x64: ${{ steps.receipt.outputs.linux-x64 }} + win32-arm64: ${{ steps.receipt.outputs.win32-arm64 }} + win32-x64: ${{ steps.receipt.outputs.win32-x64 }} + strategy: + fail-fast: false + matrix: + include: + - { os: ubuntu-24.04, target: linux-x64 } + - { os: ubuntu-24.04-arm, target: linux-arm64 } + - { os: macos-15, target: darwin-arm64 } + - { os: windows-2025, target: win32-x64 } + - { os: windows-11-arm, target: win32-arm64 } + runs-on: ${{ matrix.os }} + steps: + - name: Checkout source + shell: bash env: - PKG: '@socketsecurity/cli' - run: bash .github/scripts/smoke-test-tarball.sh + CHECKOUT_REF: ${{ needs.verify.outputs.sha }} + GITHUB_TOKEN: ${{ github.token }} + SERVER_URL: ${{ github.server_url }} + REPOSITORY: ${{ github.repository }} + run: &checkout-shallow | + set -euo pipefail + git init -q + git config --local advice.detachedHead false + git remote add origin "${SERVER_URL}/${REPOSITORY}" + AUTH_B64="$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 | tr -d '\n')" + export GIT_CONFIG_COUNT=1 + export GIT_CONFIG_KEY_0="http.${SERVER_URL}/.extraheader" + export GIT_CONFIG_VALUE_0="AUTHORIZATION: basic ${AUTH_B64}" + git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" + git checkout -q --detach FETCH_HEAD + + - *release-tools - - name: Build and pack @socketsecurity/cli-with-sentry - if: ${{ env.NPM_PRERELEASE_RELEASE != 'true' }} + - *install-dependencies + + - name: Build and test the SEA env: - SOCKET_CLI_DEBUG: ${{ inputs.debug }} + NODE_OPTIONS: ${{ runner.os == 'macOS' && '--max-old-space-size=4096' || '' }} + shell: bash run: | - INLINED_SOCKET_CLI_PUBLISHED_BUILD=1 INLINED_SOCKET_CLI_SENTRY_BUILD=1 pnpm run build:dist - pnpm pack --pack-destination "$RUNNER_TEMP/dist" + pnpm build:sea + pnpm test:sea - - name: Smoke test @socketsecurity/cli-with-sentry - if: ${{ env.NPM_PRERELEASE_RELEASE != 'true' }} + - name: Download the verified launcher + shell: bash env: - PKG: '@socketsecurity/cli-with-sentry' - run: bash .github/scripts/smoke-test-tarball.sh + GH_TOKEN: ${{ github.token }} + ROOT_RECEIPT: ${{ needs.verify.outputs.receipt }} + VERSION: ${{ needs.verify.outputs.version }} + DIST_DIRECTORY: ${{ runner.temp }}/launcher + run: node .github/scripts/download-release-artifacts.mts - # The release markers belong to the `socket` package, so the version and - # the commit are read once here and handed to the publish job. The - # publish job never checks the repo out — it only needs these two - # strings plus the tarballs. - - name: Resolve release metadata - id: release-meta - run: | - git checkout -- package.json - VERSION=$(node -p "require('./package.json').version") - SHA=$(git rev-parse HEAD) - echo "version=$VERSION" >> "$GITHUB_OUTPUT" - echo "sha=$SHA" >> "$GITHUB_OUTPUT" - echo "Release subject: socket@$VERSION at $SHA" - - # Refuse a version the registry already carries, BEFORE the markers are - # cut. A re-dispatch of an already-shipped or burned number otherwise - # gets as far as the tag step, which then hard-fails on the SHA - # mismatch — after the release exists. - - name: Refuse an already-published version - if: ${{ inputs.dry-run == false }} + - name: Pack verified platform binary + shell: bash env: - VERSION: ${{ steps.release-meta.outputs.version }} - run: pnpm run release:preflight --version "$VERSION" + SOCKET_CLI_NATIVE_TEST_REQUIRE_APPLE_SIGNATURE: ${{ !inputs.dry-run && runner.os == 'macOS' && '1' || '0' }} + APPLE_TEAM_ID: ${{ !inputs.dry-run && runner.os == 'macOS' && secrets.APPLE_TEAM_ID || '' }} + APPLE_DEVELOPER_ID_APPLICATION_CERTS_P12: ${{ !inputs.dry-run && runner.os == 'macOS' && secrets.APPLE_DEVELOPER_ID_APPLICATION_CERTS_P12 || '' }} + APPLE_DEVELOPER_ID_APPLICATION_CERTS_P12_PASS: ${{ !inputs.dry-run && runner.os == 'macOS' && secrets.APPLE_DEVELOPER_ID_APPLICATION_CERTS_P12_PASS || '' }} + run: pnpm pack:native platform --out "$RUNNER_TEMP/platform" - - name: Upload verified tarballs + - name: Exercise the installed native CLI + shell: bash + env: + VERSION: ${{ needs.verify.outputs.version }} + TARGET: ${{ matrix.target }} + run: | + PKG=socket node .github/scripts/smoke-test-tarball.mts + + - name: Upload tested platform package id: upload uses: ./.github/actions/repo/upload-artifact with: - path: ${{ runner.temp }}/dist + name: native-${{ matrix.target }}-${{ github.run_attempt }} + path: ${{ runner.temp }}/platform - - name: Verify artifact transfer + - name: Record tested upload + id: receipt + shell: bash + env: + TARGET: ${{ matrix.target }} + RECEIPT: ${{ steps.upload.outputs.artifact-id }}:${{ steps.upload.outputs.artifact-digest }} + run: echo "$TARGET=$RECEIPT" >> "$GITHUB_OUTPUT" + + rehearse: + name: Verify staging inputs (dry run) + needs: [verify, native-packages] + if: ${{ !cancelled() && inputs.dry-run && needs.verify.result == 'success' && (needs.native-packages.result == 'success' || (!contains(needs.verify.outputs.version, '-') && needs.native-packages.result == 'skipped')) }} + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + steps: + - &checkout-free-release-tools + name: Install verified release toolchain shell: bash env: GH_TOKEN: ${{ github.token }} - ARTIFACT_ID: ${{ steps.upload.outputs.artifact-id }} - ARTIFACT_DIGEST: ${{ steps.upload.outputs.artifact-digest }} - VERSION: ${{ steps.release-meta.outputs.version }} - DIST_DIRECTORY: ${{ runner.temp }}/download-check - run: &download-verified-tarballs | + REPOSITORY: ${{ github.repository }} + RELEASE_SHA: ${{ needs.verify.outputs.sha }} + run: | set -euo pipefail - [[ "$ARTIFACT_ID" =~ ^[0-9]+$ ]] - [[ "$ARTIFACT_DIGEST" =~ ^[a-f0-9]{64}$ ]] - fetch_artifact() { - for _ in 1 2 3 4 5 6; do - if gh api "$1" > "$2" 2> "$RUNNER_TEMP/gh-api.err"; then - return 0 - fi - # The REST API can 404 on an artifact for a few seconds after its upload finalizes. - grep -q 'HTTP 404' "$RUNNER_TEMP/gh-api.err" || break - sleep 5 - done - cat "$RUNNER_TEMP/gh-api.err" >&2 - return 1 - } - fetch_artifact "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID" "$RUNNER_TEMP/artifact.json" - fetch_artifact "repos/$GITHUB_REPOSITORY/actions/artifacts/$ARTIFACT_ID/zip" "$RUNNER_TEMP/artifact.zip" - python3 - <<'PY' - import hashlib, json, os, pathlib, re, shutil, stat, zipfile - temporary = pathlib.Path(os.environ["RUNNER_TEMP"]) - metadata = json.loads((temporary / "artifact.json").read_text()) - if (str(metadata.get("workflow_run", {}).get("id")) != os.environ["GITHUB_RUN_ID"] - or metadata.get("name") != "npm-release-tarballs" or metadata.get("expired")): - raise SystemExit("Artifact metadata does not match this release run.") - archive = temporary / "artifact.zip" - digest = hashlib.sha256() - with archive.open("rb") as stream: - for chunk in iter(lambda: stream.read(1024 * 1024), b""): - digest.update(chunk) - if digest.hexdigest() != os.environ["ARTIFACT_DIGEST"]: - raise SystemExit("Artifact digest does not match the verified upload.") - version = os.environ["VERSION"] - if not re.fullmatch(r"[0-9]+\.[0-9]+\.[0-9]+(?:-[0-9A-Za-z.-]+)?", version): - raise SystemExit("Invalid release version.") - packages = ("socket",) if "-" in version else ( - "socket", "socketsecurity-cli", "socketsecurity-cli-with-sentry") - expected = {f"{name}-{version}.tgz" for name in packages} - with zipfile.ZipFile(archive) as bundle: - entries = bundle.infolist() - if len(entries) != len(expected) or {entry.filename for entry in entries} != expected: - raise SystemExit("Artifact package set does not match the selected release track.") - if any(entry.file_size > 512 * 1024 * 1024 - or stat.S_ISLNK(entry.external_attr >> 16) for entry in entries): - raise SystemExit("Artifact contains an invalid tarball entry.") - destination = pathlib.Path(os.environ["DIST_DIRECTORY"]) - destination.mkdir(parents=True, exist_ok=True) - for entry in entries: - with bundle.open(entry) as source, (destination / entry.filename).open("xb") as target: - shutil.copyfileobj(source, target) - PY + dir=$(mktemp -d "$RUNNER_TEMP/release-setup.XXXXXX") + cd "$dir" + mkdir -p scripts/setup .config src/sea + gh api "repos/$REPOSITORY/contents/scripts/setup/release-tools.sh?ref=$GITHUB_WORKFLOW_SHA" -H 'Accept: application/vnd.github.raw+json' > scripts/setup/release-tools.sh + for data in .config/release-tools.json src/sea/.node-version package.json; do + gh api "repos/$REPOSITORY/contents/$data?ref=$RELEASE_SHA" -H 'Accept: application/vnd.github.raw+json' > "$data" + done + bash scripts/setup/release-tools.sh + + - &collect-release + name: Download verified tarballs + shell: bash + env: + GH_TOKEN: ${{ github.token }} + ROOT_RECEIPT: ${{ needs.verify.outputs.receipt }} + NATIVE_RECEIPTS: ${{ needs.native-packages.result == 'skipped' && '{}' || toJSON(needs.native-packages.outputs) }} + VERSION: ${{ needs.verify.outputs.version }} + DIST_DIRECTORY: ${{ runner.temp }}/dist + run: | + set -euo pipefail + # Run the verifier from the workflow revision in the checkout-free staging job. + gh api "repos/$GITHUB_REPOSITORY/contents/.github/scripts/download-release-artifacts.mts?ref=$GITHUB_WORKFLOW_SHA" -H 'Accept: application/vnd.github.raw+json' > "$RUNNER_TEMP/download-release-artifacts.mts" + gh api "repos/$GITHUB_REPOSITORY/contents/.github/scripts/verify-release.mts?ref=$GITHUB_WORKFLOW_SHA" -H 'Accept: application/vnd.github.raw+json' > "$RUNNER_TEMP/verify-release.mts" + node "$RUNNER_TEMP/download-release-artifacts.mts" # Minimal-surface publish. This job binds the publish-npm environment and # mints the OIDC token, so it runs as little as possible: no repository @@ -548,8 +407,8 @@ jobs: # tarballs, cuts the release markers, and stages those bytes. publish: name: Mark and stage - needs: verify - if: ${{ inputs.mode == 'publish' && inputs.dry-run == false }} + needs: [verify, native-packages] + if: ${{ !cancelled() && needs.verify.result == 'success' && (needs.native-packages.result == 'success' || (!contains(needs.verify.outputs.version, '-') && needs.native-packages.result == 'skipped')) && inputs.mode == 'publish' && inputs.dry-run == false }} runs-on: ubuntu-latest # npm's trusted-publisher config pins this GitHub environment name (npm TP # is PER-PACKAGE, not per-branch: the socket / @socketsecurity/cli / @@ -570,50 +429,17 @@ jobs: VERSION: ${{ needs.verify.outputs.version }} steps: - # pnpm 12 provides `stage publish`; the pinned tar.gz assets are the - # same ones the verify job installs. Checksums must be bumped in - # lock-step with the version. - - name: Install pnpm - shell: bash - run: | # zizmor: ignore[github-env] - PNPM_VERSION="12.21.0" - PNPM_DIR="${RUNNER_TEMP:-/tmp}/pnpm-bin" - case "$(uname -m)" in - x86_64) ASSET="pnpm-linux-x64.tar.gz" ; EXPECTED_SHA256="84c4773bcf4a217f4083cd7b2a91e4cee6103cf42426c1282ef37d308f55a410" ;; - aarch64) ASSET="pnpm-linux-arm64.tar.gz" ; EXPECTED_SHA256="6c5913a48c93b3a556b71c3bd9bf12c6bf9fbfbbbd2dcbd1d52a85c539751b9e" ;; - *) echo "Unsupported architecture: $(uname -m)" >&2; exit 1 ;; - esac - mkdir -p "$PNPM_DIR" - curl -fsSL -o "$PNPM_DIR/$ASSET" "https://github.com/pnpm/pnpm/releases/download/v${PNPM_VERSION}/${ASSET}" - ACTUAL_SHA256="$( (sha256sum "$PNPM_DIR/$ASSET" 2>/dev/null || shasum -a 256 "$PNPM_DIR/$ASSET") | cut -d' ' -f1)" - if [ "$ACTUAL_SHA256" != "$EXPECTED_SHA256" ]; then - echo "Checksum mismatch for ${ASSET}!" >&2 - echo " Expected: ${EXPECTED_SHA256}" >&2 - echo " Actual: ${ACTUAL_SHA256}" >&2 - exit 1 - fi - tar -xzf "$PNPM_DIR/$ASSET" -C "$PNPM_DIR" - chmod +x "$PNPM_DIR/pnpm" + - *checkout-free-release-tools + - *collect-release - # digest-mismatch: error — the bytes that arrive must be the bytes the - # verify job uploaded, or the run stops. - - name: Download verified tarballs + - name: Check first-release authentication + if: contains(needs.verify.outputs.version, '-') shell: bash env: - GH_TOKEN: ${{ github.token }} - ARTIFACT_ID: ${{ needs.verify.outputs.artifact-id }} - ARTIFACT_DIGEST: ${{ needs.verify.outputs.artifact-digest }} - DIST_DIRECTORY: ${{ runner.temp }}/dist - run: *download-verified-tarballs + BOOTSTRAP_AVAILABLE: ${{ secrets.NPM_FIRST_STAGE_TOKEN != '' }} + run: | + node "$RUNNER_TEMP/verify-release.mts" first-release - # Reserve one immutable tag before npm staging so provenance can refer - # to it. An existing tag always stops this run, even at the same SHA: - # recover its stage ID from workflow logs/npm, or keep the burned version - # and prepare the next one. Never stage the same version twice. GitHub - # release creation happens only after local npm approval. - # - # Uses gh api rather than git so the token lives only in this step's - # env; the job has no checkout at all. - name: Reserve release tag once env: GH_TOKEN: ${{ github.token }} @@ -647,7 +473,7 @@ jobs: # per-package trusted publishers allow "stage publish" ONLY — a direct # `npm publish` dies at the OIDC token exchange. # - # Run from runner.temp against the pinned binary by absolute path: pnpm + # Run the pinned pnpm from runner.temp: pnpm # self-delegates to a packageManager pin whenever its cwd sits under a # manifest, and the firewall shim guards inbound package fetches while # a stage upload is outbound. This job has neither a checkout nor a @@ -655,46 +481,42 @@ jobs: - name: Stage release packages working-directory: ${{ runner.temp }} env: + FIRST_STAGE_TOKEN: ${{ contains(needs.verify.outputs.version, '-') && secrets.NPM_FIRST_STAGE_TOKEN || '' }} NPM_DIST_TAG: ${{ needs.verify.outputs.dist-tag }} VERSION: ${{ needs.verify.outputs.version }} run: | + first_stage_token=$FIRST_STAGE_TOKEN + unset FIRST_STAGE_TOKEN shopt -s nullglob TARBALLS=("$RUNNER_TEMP"/dist/*.tgz) - EXPECTED=3 - if [[ "$VERSION" == *-* ]]; then EXPECTED=1; fi - if [ "${#TARBALLS[@]}" -ne "$EXPECTED" ]; then - echo "::error::Expected $EXPECTED verified tarballs, found ${#TARBALLS[@]}." >&2 - exit 1 - fi + EXPECTED=$(node "$RUNNER_TEMP/verify-release.mts" tarball-count "${#TARBALLS[@]}") SUMMARY="$RUNNER_TEMP/npm-stage-summary.md" : > "$SUMMARY" + # Stage platform packages first. The root launcher is approved last. + if [[ "$VERSION" == *-* ]]; then + TARBALLS=("$RUNNER_TEMP"/dist/socketsecurity-socket-cli-*.tgz "$RUNNER_TEMP/dist/socket-$VERSION.tgz") + fi + umask 077 + authfile=$(mktemp "$RUNNER_TEMP/npm-first-stage.XXXXXX") + trap 'rm -f "$authfile"' EXIT + printf '%s\n' '//registry.npmjs.org/:_authToken=${NODE_AUTH_TOKEN}' > "$authfile" for tarball in "${TARBALLS[@]}"; do - echo "Staging $(basename "$tarball")" - "${RUNNER_TEMP}/pnpm-bin/pnpm" stage publish "$tarball" \ - --provenance \ - --access public \ - --tag "$NPM_DIST_TAG" \ - --json > "$RUNNER_TEMP/npm-stage.json" - node --input-type=module - "$RUNNER_TEMP/npm-stage.json" "$SUMMARY" "$tarball" <<'NODE' - import { readFileSync, appendFileSync } from 'node:fs' - import { basename } from 'node:path' - const output = readFileSync(process.argv[2], 'utf8') - const start = output.search(/^(?:\{|\[)/mu) - const value = JSON.parse(start < 0 ? output : output.slice(start)) - const rows = Array.isArray(value) ? value : Object.values(value ?? {}) - const matches = rows.filter(row => row && typeof row === 'object' && - typeof row.name === 'string' && typeof row.version === 'string' && - typeof row.stageId === 'string' && - /^[a-f\d]{8}-[a-f\d]{4}-[1-8][a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/iu.test(row.stageId)) - if (matches.length !== 1) throw new Error('Expected one npm stage ID in pnpm JSON output.') - const stage = matches[0] - const artifactName = `${stage.name.replace(/^@/u, '').replace('/', '-')}-${stage.version}.tgz` - if (basename(process.argv[4]) !== artifactName) throw new Error('Stage identity does not match the verified tarball.') - appendFileSync(process.argv[3], `- ${stage.name}@${stage.version} — stage ID: \`${stage.stageId}\`\n`) - process.stdout.write(`Stage ID: ${stage.stageId}\n`) - NODE + filename=$(basename "$tarball") + echo "Staging $filename" + ( + if [[ "$filename" == socketsecurity-socket-cli-* ]]; then + slug=${filename%-$VERSION.tgz} + name="@socketsecurity/${slug#socketsecurity-}" + if grep -Fxq "$name" "$RUNNER_TEMP/first-native-packages"; then + export NODE_AUTH_TOKEN="$first_stage_token" NPM_CONFIG_USERCONFIG="$authfile" + fi + fi + pnpm stage publish "$tarball" \ + --provenance --access public --tag "$NPM_DIST_TAG" --json + ) > "$RUNNER_TEMP/npm-stage.json" + node "$RUNNER_TEMP/verify-release.mts" stage-output "$RUNNER_TEMP/npm-stage.json" "$SUMMARY" "$tarball" + tail -n 1 "$SUMMARY" >> "$GITHUB_STEP_SUMMARY" done - cat "$SUMMARY" >> "$GITHUB_STEP_SUMMARY" echo "Staged $EXPECTED package(s). Approve each ID locally with: pnpm run approve:npm " # Prepare the next version and changelog. This job runs the installed @@ -714,10 +536,8 @@ jobs: steps: - *checkout-full-history - - *install-pnpm - - *install-node - - *download-sfw - - *create-sfw-shims + - *release-tools + - *setup-firewall - *install-dependencies - name: Prepare version and changelog @@ -758,17 +578,7 @@ jobs: GITHUB_TOKEN: ${{ github.token }} SERVER_URL: ${{ github.server_url }} REPOSITORY: ${{ github.repository }} - run: | - set -euo pipefail - git init -q - git config --local advice.detachedHead false - git remote add origin "${SERVER_URL}/${REPOSITORY}" - AUTH_B64="$(printf 'x-access-token:%s' "$GITHUB_TOKEN" | base64 | tr -d '\n')" - export GIT_CONFIG_COUNT=1 - export GIT_CONFIG_KEY_0="http.${SERVER_URL}/.extraheader" - export GIT_CONFIG_VALUE_0="AUTHORIZATION: basic ${AUTH_B64}" - git fetch --no-tags --depth=1 origin "$CHECKOUT_REF" - git checkout -q --detach FETCH_HEAD + run: *checkout-shallow - name: Apply the bump env: diff --git a/.github/workflows/release-github.yml b/.github/workflows/release-github.yml index 95cc3d960a..13b697d8ff 100644 --- a/.github/workflows/release-github.yml +++ b/.github/workflows/release-github.yml @@ -61,6 +61,19 @@ jobs: exit 1 fi + - name: Install release toolchain + shell: bash + run: | + set -euo pipefail + if [[ -f scripts/setup/release-tools.sh ]]; then + bash scripts/setup/release-tools.sh + else + # Older reserved tags can be finalized again and predate the shared installer. + tools=$(mktemp -d "$RUNNER_TEMP/release-tools-src.XXXXXX") + git archive "$GITHUB_WORKFLOW_SHA" scripts/setup/release-tools.sh .config/release-tools.json src/sea/.node-version package.json | tar -x -C "$tools" + bash "$tools/scripts/setup/release-tools.sh" + fi + - name: Validate release policy and wait for npm publication id: metadata working-directory: ${{ runner.temp }} diff --git a/.gitignore b/.gitignore index 4844374b74..b344fe321f 100644 --- a/.gitignore +++ b/.gitignore @@ -19,8 +19,10 @@ !/.github/actions/repo/upload-artifact/index.mjs !/.github/actions/repo/cache-downloads/action.yml !/.github/actions/repo/cache-downloads/index.mts +!/.github/scripts/download-release-artifacts.mts !/.github/scripts/pin-readme-assets.mjs -!/.github/scripts/smoke-test-tarball.sh +!/.github/scripts/smoke-test-tarball.mts +!/.github/scripts/verify-release.mts !/.github/workflows/ci.yml !/.github/workflows/e2e-tests.yml !/.github/workflows/publish-npm.yml @@ -246,6 +248,7 @@ !/test/utils/sea.mts !/test/unit/sea/download-bytes.test.mts !/test/unit/sea/download-cache.test.mts +!/test/unit/sea/pnpm-lock.test.mts !/test/unit/sea/runtime.test.mts !/test/unit/sea/version.test.mts !/test/unit/utils/ @@ -361,7 +364,7 @@ !/.npmrc !/.oxlintignore !/.oxlintrc.json -!/.pnpmrc +!/.config/release-tools.json !/.vscode/extensions.json !/CHANGELOG.md !/CLAUDE.md @@ -396,13 +399,17 @@ !/patches/string_decoder@0.10.31.patch !/patches/tiny-updater@3.5.3.patch !/pnpm-lock.yaml +!/pnpm-workspace.yaml !/requirements.json !/scripts/babel/transform-set-proto-plugin.js !/scripts/babel/transform-url-parse-plugin.js !/scripts/check-commit-pii.js !/scripts/check.mts !/scripts/ci/check-actions.mts +!/scripts/ci/check-bin-eol.sh !/scripts/setup/node.mts +!/scripts/setup/firewall.sh +!/scripts/setup/release-tools.sh !/scripts/setup/uv.mts !/scripts/ci/upload-artifact.mjs !/scripts/constants.js @@ -413,6 +420,8 @@ !/scripts/lint.mts !/scripts/release/add-unreleased.mts !/scripts/release/availability.mts +!/scripts/release/native-packages.mts +!/scripts/release/native-launcher.cjs !/scripts/release/approve-npm.mts !/scripts/release/prepare.mts !/scripts/release/changelog.mts @@ -428,7 +437,7 @@ !/scripts/release/validate-npm-policy.mts !/scripts/rollup/socket-modify-plugin.js !/scripts/test/native.mts -!/scripts/test/apple-signing.mts +!/scripts/lib/apple-signing.mts !/scripts/test/integration.mts !/scripts/update.mts !/scripts/utils/fs.js @@ -1076,9 +1085,12 @@ !/src/sea/licenses/socket-patch-MIT.txt !/src/sea/build/lock.mts !/src/sea/build/publish.mts +!/src/sea/build/smoke-test.mts !/src/sea/rollup-provenance.mjs +!/src/sea/pnpm-lock.mts !/src/sea/runtime.mts !/src/sea/download-bytes.mts +!/src/sea/vfs-digest.mts !/src/sea/version.mts !/src/shadow/common.mts !/src/shadow/npm-base.mts diff --git a/.husky/pre-commit b/.husky/pre-commit index 0e65d0d295..0b3049ede8 100644 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,4 +1,5 @@ if [ -z "${DISABLE_PRECOMMIT_LINT}" ]; then + bash scripts/ci/check-bin-eol.sh || exit 1 pnpm run lint-staged else echo "Skipping lint due to DISABLE_PRECOMMIT_LINT env var" diff --git a/.pnpmrc b/.pnpmrc deleted file mode 100644 index 66cedf68cc..0000000000 --- a/.pnpmrc +++ /dev/null @@ -1,14 +0,0 @@ -# Delayed dependency updates - wait 7 days (10080 minutes) before allowing new packages. -minimumReleaseAge=10080 - -# Auto-install peers. -auto-install-peers=true - -# Strict peer dependencies. -strict-peer-dependencies=false - -# Use node-linker to ensure better compatibility. -node-linker=hoisted - -# Save exact versions (like npm --save-exact). -save-exact=true \ No newline at end of file diff --git a/package.json b/package.json index a199fb7407..bc36d40aa7 100644 --- a/package.json +++ b/package.json @@ -46,8 +46,6 @@ "build:maven-extension": "bash src/commands/manifest/scripts/maven-extension/build-jar.sh", "build:sea": "node src/sea/build-sea.mts", "build:package-matrix": "node scripts/build-package-matrix.mts", - "test:native": "node scripts/test/native.mts", - "test:native:build": "node scripts/test/native.mts --build", "snapshots": "node scripts/refresh/snapshots.mts", "build:sea:internal:bootstrap": "rollup -c .config/rollup.sea.config.mjs", "check": "node scripts/check.mts", @@ -107,7 +105,9 @@ "snapshots:termless:refresh": "node scripts/refresh/snapshots.mts --update", "snapshots:vite:refresh": "pnpm run test:unit:update", "snapshots:refresh": "pnpm run snapshots:termless:refresh && pnpm run snapshots:vite:refresh", - "snapshots:refresh:dep": "node scripts/refresh/snapshots.mts --update --dep" + "snapshots:refresh:dep": "node scripts/refresh/snapshots.mts --update --dep", + "test:sea": "node scripts/test/native.mts", + "pack:native": "node scripts/release/native-packages.mts" }, "dependencies": { "@inquirer/confirm": "5.1.16", @@ -228,7 +228,9 @@ "yaml": "2.8.1", "yargs-parser": "21.1.1", "yoctocolors-cjs": "2.1.3", - "zod": "4.1.8" + "zod": "4.1.8", + "@sentry/node": "11.12.0", + "supports-color": "7.2.0" }, "typeCoverage": { "cache": true, @@ -243,9 +245,9 @@ }, "engines": { "node": ">=18.20.8", - "pnpm": ">=12.21.0" + "pnpm": ">=12.23.0" }, - "packageManager": "pnpm@12.21.0", + "packageManager": "pnpm@12.23.0", "files": [ "bin/**", "dist/**", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f9651fcb3d..c8f59b63e9 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -7,162 +7,172 @@ importers: configDependencies: {} packageManagerDependencies: pnpm: - specifier: 12.21.0 - version: 12.21.0 + specifier: 12.23.0 + version: 12.23.0 packages: - '@pnpm/exe.android-arm64@12.21.0': - resolution: {integrity: sha512-iaWidxR5B9NUBpwMznCQu1yUpKB6BjTY5BYX2lORj76VsfINdj8Z8XWSzSNrGI8qlxa28Jzdp5fiaspzOaJZlA==} + '@pnpm/exe.android-arm64@12.23.0': + resolution: {integrity: sha512-oqZu9yFInENTRA9BKiOnEqOcpr5dNMDbquxq9zKFKJy0nEC385Vw0e4wlsOAlDh90iX94GND6Fc22FVL2O2SmQ==} cpu: [arm64] os: [android] - '@pnpm/exe.android-x64@12.21.0': - resolution: {integrity: sha512-35e5v3wlwjIYxDywq+R6/z8CE4gLOEgRxt18yqz1tMRLmx2mnW+CFJI2Q8+srTNjn7gykXUC0x1k195JNikC5A==} + '@pnpm/exe.android-x64@12.23.0': + resolution: {integrity: sha512-fQRjE4Wno8ye0lxhYGmyqdcc6tv+tDGktEmgFzffZ7flp4BG/84VtdXn3i/O4BazgMbNuPdbM75aj7uDZwL7GQ==} cpu: [x64] os: [android] - '@pnpm/exe.darwin-arm64@12.21.0': - resolution: {integrity: sha512-F5OyMX/6zLSowpTZEQRojbCmPS1Pq+fyRaIinslsIe6Glh3qbyQ52u+Fe0eEzSaRuIbWZkXmAAXSWh6Q5Wrlgg==} + '@pnpm/exe.darwin-arm64@12.23.0': + resolution: {integrity: sha512-ny5+L92frsfyV3/B3zadYQuU5kBV8o2TXB5WnhBUoJ/9Mz32FVglMr8g1HmUc01yfKkjopZ4rmF1G7vs68JxIg==} cpu: [arm64] os: [darwin] - '@pnpm/exe.darwin-x64@12.21.0': - resolution: {integrity: sha512-EzpvcsaE6hrrgYeEiAFYd2rSgFybYyxXhkAY7K3y6Hg3loVfcyJ81hHczpFzi8lW5RXtUlFECRPZ8ZAMRFQYYg==} + '@pnpm/exe.darwin-x64@12.23.0': + resolution: {integrity: sha512-+MNmpJSAzb9yc80d5l4VbZ/3Teh8xtlacATUyTAx6fELUK0xwmgFi05hqzg1sXLdAPij5gcIp82VvrqY5tzPrQ==} cpu: [x64] os: [darwin] - '@pnpm/exe.freebsd-x64@12.21.0': - resolution: {integrity: sha512-wNjuEnmdLks4aayPu/QZWQ5tQM9Jn+odUp/vwQM8BXRYoulkTZhtZTHoD60N6mUdLWef1hgUeUh8llNGEUsimw==} + '@pnpm/exe.freebsd-x64@12.23.0': + resolution: {integrity: sha512-AGfkooje58I9hh4xdSDyZCPLKvjrjuvlkKTK2gsTtj6wfhVTw1jz33wB1XbERt2/0odJdEfgnBPUIdalRnb7Fw==} cpu: [x64] os: [freebsd] - '@pnpm/exe.linux-arm64-musl@12.21.0': - resolution: {integrity: sha512-Ceit9zn4g5ZqCJtx1fV8eJE7p8aeXMrGZ+Dc01vRqZLIUNgNeI+Ur0ruyqxtsnJx6rGADyXzohumxPLHjaJ5AQ==} + '@pnpm/exe.linux-arm64-musl@12.23.0': + resolution: {integrity: sha512-C09Z3tFnPz7CYiae326dGlJcRUNCBtlJvMc04S9M8YKACebHHyamxCItLAisvGdHVf1BawtU9shV0FngjYxMwA==} cpu: [arm64] os: [linux] libc: [musl] - '@pnpm/exe.linux-arm64@12.21.0': - resolution: {integrity: sha512-4Oj/iF2TDCe2lcH0n4TupPR5sSdrNLclJB6xBElLMPCUOAvBhdf2rRlSaO5M4erJ6g4Fyy7YTXTpcmfFsKyxEA==} + '@pnpm/exe.linux-arm64@12.23.0': + resolution: {integrity: sha512-RLby8T0CIWAbljrbmjaX6S3PYhMHnLbUp+IDcOmZIY1/+wy8hJoQpjMPZlV4VJIGl8lZKUXtxJcLJ2XZ1z2SVw==} cpu: [arm64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-ppc64@12.21.0': - resolution: {integrity: sha512-s2o7rdSDeUTBFsNqxptpZXlTgT6cojmMVUOvTQvFNSv6Easian02ha4tR32fwwD97Au4YzIIjMCwywCF4D82Sw==} + '@pnpm/exe.linux-loong64@12.23.0': + resolution: {integrity: sha512-XytxNoKD9/PcugxRHmBptRNDxUYwBtQZwBauJ3lKXFJ3sqHPZSjjFxIMX4HTWQn7FqCVnQlF+tbewjUnvQz0dQ==} + cpu: [loong64] + os: [linux] + libc: [glibc] + + '@pnpm/exe.linux-ppc64@12.23.0': + resolution: {integrity: sha512-1h9+mBpdmlFA5LW6fAfd5UnLgHakNkEsS1R67mEXY1J6WLLnZcWFJs7Cbde0BD034CRTUa99MaILAuSs2ERf7Q==} cpu: [ppc64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-riscv64@12.21.0': - resolution: {integrity: sha512-EYv3GzxeBTITCuM3yGHHbpRFpUvyulkXpQ6LsjKAQNL3iaba1E6h9iDmlouLb3Io4AMMsfdk0/uG6poQ41uewA==} + '@pnpm/exe.linux-riscv64@12.23.0': + resolution: {integrity: sha512-SlPz2UxUshIxgyBRKT0PHncYr2pIoFOxf6WR68HCkhGmASGljYlYYwRVfefgoIPM603x4Fcge9/B1Z3aIq1bSQ==} cpu: [riscv64] os: [linux] libc: [glibc] - '@pnpm/exe.linux-s390x@12.21.0': - resolution: {integrity: sha512-8VXGNGVNEfs7pL9GTZOzFxjFEnMt4WL3rLOADR5/kPQ7ROTV9GfpVI2DPO/zArXFSkvfc9Zad/WypHLbvzoaTQ==} + '@pnpm/exe.linux-s390x@12.23.0': + resolution: {integrity: sha512-Hk8jKY0i9sjyKPJFYC71lu7Mq5ahb5sWT2zCqNxzzBCrivvCqv5GVfZurLETC5TsSusE9TRWFpynLgG+iaXmSA==} cpu: [s390x] os: [linux] libc: [glibc] - '@pnpm/exe.linux-x64-musl@12.21.0': - resolution: {integrity: sha512-MnC5vpIXYubhDZCgCwlfJMg7Cg6HupN2IuouT9gD/tUmOfVdQYqeyYccWbthyo/Jeto8de1oQlxeRN1+1Hl2DQ==} + '@pnpm/exe.linux-x64-musl@12.23.0': + resolution: {integrity: sha512-7+9bD4LBQ5r+7nLnIhDgMnvMm7a7cfc28NogU3NY1sM0+0Jz7K+IwxZb4BJDY/AN1s3F26TgZ3az/bjeCshmXA==} cpu: [x64] os: [linux] libc: [musl] - '@pnpm/exe.linux-x64@12.21.0': - resolution: {integrity: sha512-8eufCjHXspKbNS/kh8q4Q0gqJoOuvC4Q5pgos6XS8By/nAMtP+jf8F1Cw9er840kfAX+PJ/ts+A9qnLE91rvXQ==} + '@pnpm/exe.linux-x64@12.23.0': + resolution: {integrity: sha512-vu/N1nUJxLA0IIumbxL/rR6leGA+++SQY0XL+5KPJ1O2kyvzJoLQYL1ibLGO7TRqsZ90wclboEdhIIWvr3Qsig==} cpu: [x64] os: [linux] libc: [glibc] - '@pnpm/exe.netbsd-x64@12.21.0': - resolution: {integrity: sha512-eyh1M8hQZCkLWxuva7S/fc1SbFbgqg0/5di0dgWmyiuc2Io3dbWVihDun8X+XM8zsR5uhIDvvZpbS9aZQbCovg==} + '@pnpm/exe.netbsd-x64@12.23.0': + resolution: {integrity: sha512-c85UPtAJfPR5+ghXS8UGRQlgxwqvz2PFaPaEzIVwUdBU+5DB4X2iuMAMlMXWS6hJ/OjqhKM6tpwyEc4Kkz40Fg==} cpu: [x64] os: [netbsd] - '@pnpm/exe.win32-arm64@12.21.0': - resolution: {integrity: sha512-7xTxxUXo/grRLivSeIl6B21gnsz7ooe5EMPcJmQqwxc8WLJVReN8MzrlHru8bqXfVr4X3+6ZGZscntKenlCBqQ==} + '@pnpm/exe.win32-arm64@12.23.0': + resolution: {integrity: sha512-lx0B8HPaUEG/ovIC0PmA6HhMhXh6ud0pAWVTDNxZvAfAzuGm0RM78SCT/oBY80lbJnwA9al4sTUroqozZK9hVA==} cpu: [arm64] os: [win32] - '@pnpm/exe.win32-x64@12.21.0': - resolution: {integrity: sha512-9TpkJemVApxJ1Z1w0ZFGN+AuSx4nJOqXSJUqMqDvaXTYwGOzvBiiWdFP9GN0ketiWCQS1Q0/pza2E7I3pP0OBQ==} + '@pnpm/exe.win32-x64@12.23.0': + resolution: {integrity: sha512-OnbBaQWQcw31m5APFNKcM8kdmM6H7k8MoaOnA2m1LsWAHX7AZKB5cdJfNwhHGBfkURcwWk1bnMXBdllujMiCFw==} cpu: [x64] os: [win32] - pnpm@12.21.0: - resolution: {integrity: sha512-Zv2CeO4ok1zpUXktNDZ/869cQyonVkRYIwKVM4NbjaUpu+C+UTCv1W7QcT+4eJ5Hutgtk71a4v5UsVVi1idu8A==} + pnpm@12.23.0: + resolution: {integrity: sha512-AtqU/68TP0YHQyKv5VL5DUC19xriWa77zNrMUIWx1hfpjWXgEx9XSLm2dEWXjuUFXX1ZpHPx7vDVBIVP781ZdQ==} engines: {node: '>=18'} hasBin: true snapshots: - '@pnpm/exe.android-arm64@12.21.0': + '@pnpm/exe.android-arm64@12.23.0': optional: true - '@pnpm/exe.android-x64@12.21.0': + '@pnpm/exe.android-x64@12.23.0': optional: true - '@pnpm/exe.darwin-arm64@12.21.0': + '@pnpm/exe.darwin-arm64@12.23.0': optional: true - '@pnpm/exe.darwin-x64@12.21.0': + '@pnpm/exe.darwin-x64@12.23.0': optional: true - '@pnpm/exe.freebsd-x64@12.21.0': + '@pnpm/exe.freebsd-x64@12.23.0': optional: true - '@pnpm/exe.linux-arm64-musl@12.21.0': + '@pnpm/exe.linux-arm64-musl@12.23.0': optional: true - '@pnpm/exe.linux-arm64@12.21.0': + '@pnpm/exe.linux-arm64@12.23.0': optional: true - '@pnpm/exe.linux-ppc64@12.21.0': + '@pnpm/exe.linux-loong64@12.23.0': optional: true - '@pnpm/exe.linux-riscv64@12.21.0': + '@pnpm/exe.linux-ppc64@12.23.0': optional: true - '@pnpm/exe.linux-s390x@12.21.0': + '@pnpm/exe.linux-riscv64@12.23.0': optional: true - '@pnpm/exe.linux-x64-musl@12.21.0': + '@pnpm/exe.linux-s390x@12.23.0': optional: true - '@pnpm/exe.linux-x64@12.21.0': + '@pnpm/exe.linux-x64-musl@12.23.0': optional: true - '@pnpm/exe.netbsd-x64@12.21.0': + '@pnpm/exe.linux-x64@12.23.0': optional: true - '@pnpm/exe.win32-arm64@12.21.0': + '@pnpm/exe.netbsd-x64@12.23.0': optional: true - '@pnpm/exe.win32-x64@12.21.0': + '@pnpm/exe.win32-arm64@12.23.0': optional: true - pnpm@12.21.0: + '@pnpm/exe.win32-x64@12.23.0': + optional: true + + pnpm@12.23.0: optionalDependencies: - '@pnpm/exe.android-arm64': 12.21.0 - '@pnpm/exe.android-x64': 12.21.0 - '@pnpm/exe.darwin-arm64': 12.21.0 - '@pnpm/exe.darwin-x64': 12.21.0 - '@pnpm/exe.freebsd-x64': 12.21.0 - '@pnpm/exe.linux-arm64': 12.21.0 - '@pnpm/exe.linux-arm64-musl': 12.21.0 - '@pnpm/exe.linux-ppc64': 12.21.0 - '@pnpm/exe.linux-riscv64': 12.21.0 - '@pnpm/exe.linux-s390x': 12.21.0 - '@pnpm/exe.linux-x64': 12.21.0 - '@pnpm/exe.linux-x64-musl': 12.21.0 - '@pnpm/exe.netbsd-x64': 12.21.0 - '@pnpm/exe.win32-arm64': 12.21.0 - '@pnpm/exe.win32-x64': 12.21.0 + '@pnpm/exe.android-arm64': 12.23.0 + '@pnpm/exe.android-x64': 12.23.0 + '@pnpm/exe.darwin-arm64': 12.23.0 + '@pnpm/exe.darwin-x64': 12.23.0 + '@pnpm/exe.freebsd-x64': 12.23.0 + '@pnpm/exe.linux-arm64': 12.23.0 + '@pnpm/exe.linux-arm64-musl': 12.23.0 + '@pnpm/exe.linux-loong64': 12.23.0 + '@pnpm/exe.linux-ppc64': 12.23.0 + '@pnpm/exe.linux-riscv64': 12.23.0 + '@pnpm/exe.linux-s390x': 12.23.0 + '@pnpm/exe.linux-x64': 12.23.0 + '@pnpm/exe.linux-x64-musl': 12.23.0 + '@pnpm/exe.netbsd-x64': 12.23.0 + '@pnpm/exe.win32-arm64': 12.23.0 + '@pnpm/exe.win32-x64': 12.23.0 --- lockfileVersion: '9.0' @@ -360,6 +370,9 @@ importers: '@rollup/pluginutils': specifier: 5.3.0 version: 5.3.0(rollup@4.50.1(patch_hash=071f391315feb3e71235ac70bfbf18a993f10a53259f3ec37507a614a5645f9f)) + '@sentry/node': + specifier: 11.12.0 + version: 11.12.0(rollup@4.50.1(patch_hash=071f391315feb3e71235ac70bfbf18a993f10a53259f3ec37507a614a5645f9f)) '@socketregistry/hyrious__bun.lockb': specifier: 1.0.19 version: 1.0.19 @@ -552,6 +565,9 @@ importers: semver: specifier: 7.7.2 version: 7.7.2 + supports-color: + specifier: 7.2.0 + version: 7.2.0 svgo: specifier: 4.1.0 version: 4.1.0 @@ -584,7 +600,7 @@ importers: version: 0.1.0 vitest: specifier: 5.1.1 - version: 5.1.1(@types/node@24.3.1)(@vitest/coverage-v8@5.1.1)(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)) + version: 5.1.1(@opentelemetry/api@1.10.0)(@types/node@24.3.1)(@vitest/coverage-v8@5.1.1)(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)) which: specifier: '=5.0.0' version: 5.0.0 @@ -1342,6 +1358,9 @@ packages: resolution: {integrity: sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==} engines: {node: '>=18.0.0'} + '@isaacs/nonrecursive-glob-match@1.1.0': + resolution: {integrity: sha512-GPm/Dbvk5RLmhRnxXIa7nTpK0xtl4E0wj0MslsuNiJ1FIROU+2+9lgUC/dgF7Ey4QCWhfEsgxilMRMCdHPfDfw==} + '@isaacs/string-locale-compare@1.1.0': resolution: {integrity: sha512-SQ7Kzhh9+D+ZW9MA0zkYv3VXhIDNx+LzM6EJ+/65I3QY+enU6Itte7E5XX7EWrqLW2FN4n06GWzBnPoC3th2aQ==} @@ -1651,6 +1670,135 @@ packages: '@open-draft/until@2.1.0': resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==} + '@opentelemetry/api@1.10.0': + resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} + engines: {node: '>=8.0.0'} + + '@oxc-parser/binding-android-arm-eabi@0.152.0': + resolution: {integrity: sha512-393VtirINkae4XHBTkq/yQxhOwEr4V+r0et37P2fp+sYZSdYgZTRDPo5Um8vBh0QjMZ+RmaMy4PP0qwr4cTMwA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@oxc-parser/binding-android-arm64@0.152.0': + resolution: {integrity: sha512-iYFcExATJNZ0rZj0o02THbD1Nc9jAW0nVgIQPee6ejbSASpbZXlIMw8jxtpzaG14JQTWwGSZ6U5dEtRJXE6V3Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@oxc-parser/binding-darwin-arm64@0.152.0': + resolution: {integrity: sha512-fnU+DfUzi5/rFy0LzmipYRz06PAUUkOS8kCJQ3Eg6oqlunC1XZXoffFqxmdL51RmcbYtUG3P8DVG1U5fckoa2A==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@oxc-parser/binding-darwin-x64@0.152.0': + resolution: {integrity: sha512-Y3U2okryWTs7hDld6UhjJwLNf8/do+x4g4C+1U5SiGwrTLwbO83WJYJA8+l9iFSilWBgnfpd/+U76tfeNxUHzA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@oxc-parser/binding-freebsd-x64@0.152.0': + resolution: {integrity: sha512-XkhkRrrPffEw+ZLv/d/5pEni0buxinm/E/N6fLbJCunD1DBbeCTtVP23ESV+4CWCWdSz397asks1ViGslpmWiQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@oxc-parser/binding-linux-arm-gnueabihf@0.152.0': + resolution: {integrity: sha512-MLzsRRbdfmdzo6JEhbC1yKU9ItfvM8tEf18HM32jCiNYZEz6J3bRBRl3cTkKR0vBdrk9ZVlcARXtwHccs+epDA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-parser/binding-linux-arm-musleabihf@0.152.0': + resolution: {integrity: sha512-HHerTEJz7Iy10Ji6BGsk4gqG6PU0UzFuBu91jIEOX89FnrI5ECWSEr7BLpkYQhp7U0QFtMnBhNfQKI0hYZK78w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@oxc-parser/binding-linux-arm64-gnu@0.152.0': + resolution: {integrity: sha512-9Bb8GyzZ2uSLzRDZ27usaKokr07mxiBe2dDF5b6bd2janmaJTT1gL51UfP7AU30yFiXrJvcRyFKREAgKwZYs0w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-arm64-musl@0.152.0': + resolution: {integrity: sha512-om7iDMUroI74A/lfRRWY9/Ev3VWrVsrUZ4tyvyh8raBey/sdcfyAD7tYWc+iykAiotnmftyKTpUKFr1QnaBrAQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-linux-ppc64-gnu@0.152.0': + resolution: {integrity: sha512-Lf1OL2lMTqwDMFC6jnRb30B+WYHKV0XT+bPHcFM6xHtNVwxpobiTzUIvKH6a0LWpvfwyru8Yu6zCGHqqFHH+gg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-riscv64-gnu@0.152.0': + resolution: {integrity: sha512-BYWSMQK+YJ9ZILStPcmmiSVq8KEG9Qdq/c4BHPC3rUEq/fEDCVjUIwdj5ZzjgZ9P9is9PKu0tcAXzq1ZXg4urQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-riscv64-musl@0.152.0': + resolution: {integrity: sha512-d2LqHNNNqdH185sRK5dPKWZu201JrNu9/CRFuVEuT+ht7n/QaVblEMWT9MALQPrDWYvhG10P+NSKJFquDWZ09w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [riscv64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-linux-s390x-gnu@0.152.0': + resolution: {integrity: sha512-8gBeHt5rA/8+pKhHl+zLggfa3L/V/L2at96p7ty6pBE7id6lFO19nFUc15u2PcjC4OYeYK465MKy1fhhbpFIGw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-x64-gnu@0.152.0': + resolution: {integrity: sha512-ltgrSF6L+yPTVsIdaAyqKq3zTqzj/1VlNbxWZuxAe8flR3sWdyNsKvdXukoO8/ucJbLickhmieRBge+o/e8Ugw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@oxc-parser/binding-linux-x64-musl@0.152.0': + resolution: {integrity: sha512-LcMp6BvrBnewSfdkLHoSqidhoAq4syKOTBV5TYHWd+2VnGkfD/nPRRVIzTBt/Lkbt7pfOFDGtkiTntFS0p6sQQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@oxc-parser/binding-openharmony-arm64@0.152.0': + resolution: {integrity: sha512-jbhoMCslVxzRCRNQ8TSHxjYdSKRvk8O6ciLVDkahJvmyHDzBqba/bMQHM6ULKj/rgHNNbSzlIiakdx8SEfkJzA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@oxc-parser/binding-win32-arm64-msvc@0.152.0': + resolution: {integrity: sha512-JZYVlhv36mr/nertnRB7vchJECOBb1Lz6lltalILsB+o9M/is+H6BEDRLQKdqA4JKs6NjJszo46+iM5sfwj6jQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@oxc-parser/binding-win32-ia32-msvc@0.152.0': + resolution: {integrity: sha512-1X9oganvVsunRH0lH10UU05N+H9atpX6WsOybByUjwnfcd3h/0tYwvuv16XuHglrIUOnxV2TodbLVEwwafd64g==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ia32] + os: [win32] + + '@oxc-parser/binding-win32-x64-msvc@0.152.0': + resolution: {integrity: sha512-sw0M80/dn9rcpu+Rqqph/C+MjvDDce6MlXmFjsNQtPEymha0eJy3ml6+foSUTqFfpDIDyHZZ4eoJ43IoMe8bJw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@oxc-project/types@0.152.0': + resolution: {integrity: sha512-oM/5rLBm2tPkg0iBgkH/FOeR3PCDpY19GTgAZjMFM8h9WI9VW7cLgzp6nwtarYKmovavIQZ+Fe/RKX/8C8O/Rw==} + '@oxc-project/types@0.156.0': resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} @@ -2253,6 +2401,44 @@ packages: cpu: [x64] os: [win32] + '@sentry/bundler-plugins@11.12.0': + resolution: {integrity: sha512-7vBXoHMoYKjYu08anYv5I0nplSWOfQyl7BqV0VOrLxEtGoOpk1+DxL2dyBiaWoAtISkaqJEV/ft813OsCGuuMg==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + peerDependencies: + rollup: 4.50.1 + webpack: '>=5.1.0' + peerDependenciesMeta: + rollup: + optional: true + webpack: + optional: true + + '@sentry/conventions@0.32.0': + resolution: {integrity: sha512-WkSQcDhUUsz1SwxR23LpmyPKba+dgxxiH0DWV4VSM9yaAvhhl87ppW2Ts3g4piIKCVflc31aJeWy+biUbYfsMQ==} + engines: {node: '>=14'} + + '@sentry/core@11.12.0': + resolution: {integrity: sha512-HKER7EcRpPPgC8mLRe5BzP6njfRYFZ53BFLZxVp1whWbY6lp/b2mvTBk4q6+rKsUFhLhRDsd6jL8y/8ddEWv6A==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + + '@sentry/node@11.12.0': + resolution: {integrity: sha512-MNSZDOd92Twrq5Z4ZAkxZdIfhr3YGytFb1T+vh5bNXVHkqByWpI/P2VtTSrzBR4Pi1IDRMz0i8t/OWNOsuAuBg==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + + '@sentry/opentelemetry@11.12.0': + resolution: {integrity: sha512-oWJwUdc2OSSvyOPXn/E1nWkC3GV5KNTWfR5prbw/0XxlKJepdlBsW19y+FAE9n3QznZ52aMZmetWEAFMsPJ0KQ==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + peerDependencies: + '@opentelemetry/api': ^1.9.0 + + '@sentry/server-runtime-injection@11.12.0': + resolution: {integrity: sha512-fAZjCFyEfhvyfEdbav0/X13Yqbom5Ka1+hG0Nyl6bd7GxkQIWd68unSIw/Rvzfj/DSO8A1JidezST3D6omALkw==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + + '@sentry/server-utils@11.12.0': + resolution: {integrity: sha512-gAP5FLhXSiMs9vsU7guc54QNY1OzUJmhqyXMjhiP4SYlhQltoKtipcyo8pFWVsmylIzIkA8e2eGR6e0YA6YF3A==} + engines: {node: '>=20.19.0 <22.0.0 || >=22.12.0 <23.0.0 || >=23.2.0'} + '@sigstore/bundle@4.0.0': resolution: {integrity: sha512-NwCl5Y0V6Di0NexvkTqdoVfmjTaQwoLM236r89KEojGmq/jMls8S+zb7yOwAPdXvbwfKDlP+lmXgAL4vKSQT+A==} engines: {node: ^20.17.0 || >=22.9.0} @@ -3346,6 +3532,10 @@ packages: resolution: {integrity: sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==} engines: {node: '>=12'} + dotenv@17.4.2: + resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} + engines: {node: '>=12'} + drawille-blessed-contrib@1.0.0: resolution: {integrity: sha512-WnHMgf5en/hVOsFhxLI8ZX0qTJmerOsVjIMQmn4cR1eI8nLGu+L7w5ENbul+lZ6w827A3JakCuernES5xbHLzQ==} @@ -3750,6 +3940,10 @@ packages: resolution: {integrity: sha512-Wjlyrolmm8uDpm/ogGyXZXb1Z+Ca2B8NbJwqBVg0axK9GbBeoS7yGV6vjXnYdGm6X53iehEuxxbyiKp8QmN4Vw==} engines: {node: 18 || 20 || >=22} + glob@14.0.6: + resolution: {integrity: sha512-OwXjVP2svY5EyLY75Vek96C8qK43gqrt4xsZ+qSILdnaEiJPXkd62mcfUSNx/TQErQRdu5uM5kF67sfONragKw==} + engines: {node: 18 || 20 || >=22} + globals@14.0.0: resolution: {integrity: sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==} engines: {node: '>=18'} @@ -4417,6 +4611,10 @@ packages: resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} engines: {node: 18 || 20 || >=22} + minimatch@11.0.9: + resolution: {integrity: sha512-KCFkfyjqerNlSstjlhIGNXIKZGA/6O4V4RlhZ+Dsr621SPPw0mzlypE9D9ZOoPiVefHID+j7/XuMMlqfD/F60Q==} + engines: {node: 20 || >=22} + minimatch@3.1.2: resolution: {integrity: sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==} @@ -4692,6 +4890,10 @@ packages: outvariant@1.4.3: resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==} + oxc-parser@0.152.0: + resolution: {integrity: sha512-ZztsZgaCWmPeKYMdoTT5e0oV/oxD1NeLWNR3kAtr/G707cUPYaaozRlVDHLCGnszHJRszN9mJwmPNpqgwloC0A==} + engines: {node: ^20.19.0 || >=22.12.0} + oxc-resolver@11.9.0: resolution: {integrity: sha512-u714L0DBBXpD0ERErCQlun2XwinuBfIGo2T8bA7xE8WLQ4uaJudO/VOEQCWslOmcDY2nEkS+UVir5PpyvSG23w==} @@ -4810,6 +5012,10 @@ packages: resolution: {integrity: sha512-3O/iVVsJAPsOnpwWIeD+d6z/7PmqApyQePUtCndjatj/9I5LylHvt5qluFaBT3I5h3r1ejfR056c+FCv+NnNXg==} engines: {node: 18 || 20 || >=22} + path-scurry@3.0.0: + resolution: {integrity: sha512-1pTbQqH1wIwMi/eleQ5leFTTCkzFsPcgXNjwOA8YGGW/W4/kHT3dssE7Z6NH+zuqNLOzOB0uaD61yl7cAcVhgg==} + engines: {node: 18 || 20 || >=22} + path-type@6.0.0: resolution: {integrity: sha512-Vj7sf++t5pBD637NSfkxpHSMfWaeig5+DKWLhcqIYx6mWQz5hdJTGDVMQiJcw1ZYkhs7AazKDGpRVji1LJCZUQ==} engines: {node: '>=18'} @@ -5066,6 +5272,11 @@ packages: engines: {node: '>=10'} hasBin: true + sentry@0.49.0: + resolution: {integrity: sha512-9tjS0jTx5FQzhwAGhpcnwvqE0MlQiwJtunsIUNqGkw6E9CBOMbijlamIDUqvZTDtJAveVwa9L5ziP44bOJUzcQ==} + engines: {node: '>=20.0'} + hasBin: true + setprototypeof@1.2.0: resolution: {integrity: sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==} @@ -6692,6 +6903,8 @@ snapshots: dependencies: minipass: 7.1.3 + '@isaacs/nonrecursive-glob-match@1.1.0': {} + '@isaacs/string-locale-compare@1.1.0': {} '@jridgewell/gen-mapping@0.3.13': @@ -7093,6 +7306,67 @@ snapshots: '@open-draft/until@2.1.0': {} + '@opentelemetry/api@1.10.0': {} + + '@oxc-parser/binding-android-arm-eabi@0.152.0': + optional: true + + '@oxc-parser/binding-android-arm64@0.152.0': + optional: true + + '@oxc-parser/binding-darwin-arm64@0.152.0': + optional: true + + '@oxc-parser/binding-darwin-x64@0.152.0': + optional: true + + '@oxc-parser/binding-freebsd-x64@0.152.0': + optional: true + + '@oxc-parser/binding-linux-arm-gnueabihf@0.152.0': + optional: true + + '@oxc-parser/binding-linux-arm-musleabihf@0.152.0': + optional: true + + '@oxc-parser/binding-linux-arm64-gnu@0.152.0': + optional: true + + '@oxc-parser/binding-linux-arm64-musl@0.152.0': + optional: true + + '@oxc-parser/binding-linux-ppc64-gnu@0.152.0': + optional: true + + '@oxc-parser/binding-linux-riscv64-gnu@0.152.0': + optional: true + + '@oxc-parser/binding-linux-riscv64-musl@0.152.0': + optional: true + + '@oxc-parser/binding-linux-s390x-gnu@0.152.0': + optional: true + + '@oxc-parser/binding-linux-x64-gnu@0.152.0': + optional: true + + '@oxc-parser/binding-linux-x64-musl@0.152.0': + optional: true + + '@oxc-parser/binding-openharmony-arm64@0.152.0': + optional: true + + '@oxc-parser/binding-win32-arm64-msvc@0.152.0': + optional: true + + '@oxc-parser/binding-win32-ia32-msvc@0.152.0': + optional: true + + '@oxc-parser/binding-win32-x64-msvc@0.152.0': + optional: true + + '@oxc-project/types@0.152.0': {} + '@oxc-project/types@0.156.0': {} '@oxc-resolver/binding-android-arm-eabi@11.9.0': @@ -7516,6 +7790,53 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.50.1': optional: true + '@sentry/bundler-plugins@11.12.0(rollup@4.50.1(patch_hash=071f391315feb3e71235ac70bfbf18a993f10a53259f3ec37507a614a5645f9f))': + dependencies: + '@sentry/core': 11.12.0 + dotenv: 17.4.2 + glob: 14.0.6 + magic-string: 0.30.19 + oxc-parser: 0.152.0 + sentry: 0.49.0 + optionalDependencies: + rollup: 4.50.1(patch_hash=071f391315feb3e71235ac70bfbf18a993f10a53259f3ec37507a614a5645f9f) + + '@sentry/conventions@0.32.0': {} + + '@sentry/core@11.12.0': + dependencies: + '@sentry/conventions': 0.32.0 + + '@sentry/node@11.12.0(rollup@4.50.1(patch_hash=071f391315feb3e71235ac70bfbf18a993f10a53259f3ec37507a614a5645f9f))': + dependencies: + '@opentelemetry/api': 1.10.0 + '@sentry/bundler-plugins': 11.12.0(rollup@4.50.1(patch_hash=071f391315feb3e71235ac70bfbf18a993f10a53259f3ec37507a614a5645f9f)) + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + '@sentry/opentelemetry': 11.12.0(@opentelemetry/api@1.10.0) + '@sentry/server-runtime-injection': 11.12.0 + '@sentry/server-utils': 11.12.0 + transitivePeerDependencies: + - rollup + - webpack + + '@sentry/opentelemetry@11.12.0(@opentelemetry/api@1.10.0)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + + '@sentry/server-runtime-injection@11.12.0': + dependencies: + '@sentry/core': 11.12.0 + '@sentry/server-utils': 11.12.0 + + '@sentry/server-utils@11.12.0': + dependencies: + '@opentelemetry/api': 1.10.0 + '@sentry/conventions': 0.32.0 + '@sentry/core': 11.12.0 + '@sigstore/bundle@4.0.0': dependencies: '@sigstore/protobuf-specs': 0.5.0 @@ -8012,7 +8333,7 @@ snapshots: obug: 3.0.0 std-env: 4.3.0 tinyrainbow: 3.2.0 - vitest: 5.1.1(@types/node@24.3.1)(@vitest/coverage-v8@5.1.1)(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)) + vitest: 5.1.1(@opentelemetry/api@1.10.0)(@types/node@24.3.1)(@vitest/coverage-v8@5.1.1)(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)) '@vitest/istanbul-lib-coverage@2.1.0': {} @@ -8588,6 +8909,8 @@ snapshots: dotenv@17.2.3: {} + dotenv@17.4.2: {} + drawille-blessed-contrib@1.0.0(patch_hash=bc7802f29a5252694b94e911ea0fef9939529d6bd866c9e189539ae23f54187c): {} drawille-canvas-blessed-contrib@0.1.3(patch_hash=baf1e92576f78c2c86283e7a3182ddd59d52cd7e86ad9fe21d1c4ccc2274bcf3): @@ -9046,6 +9369,12 @@ snapshots: minipass: 7.1.3 path-scurry: 2.0.2 + glob@14.0.6: + dependencies: + minimatch: 11.0.9 + minipass: 7.1.3 + path-scurry: 3.0.0 + globals@14.0.0: {} globals@15.15.0: {} @@ -9865,6 +10194,11 @@ snapshots: dependencies: brace-expansion: 5.0.12 + minimatch@11.0.9: + dependencies: + '@isaacs/nonrecursive-glob-match': 1.1.0 + brace-expansion: 2.0.2(patch_hash=eac47f4a81cd7be766bd391c6bf91ac462816eb2f3c5f99270419ac752d6f02d) + minimatch@3.1.2: dependencies: brace-expansion: 2.0.2(patch_hash=eac47f4a81cd7be766bd391c6bf91ac462816eb2f3c5f99270419ac752d6f02d) @@ -10182,6 +10516,30 @@ snapshots: outvariant@1.4.3: {} + oxc-parser@0.152.0: + dependencies: + '@oxc-project/types': 0.152.0 + optionalDependencies: + '@oxc-parser/binding-android-arm-eabi': 0.152.0 + '@oxc-parser/binding-android-arm64': 0.152.0 + '@oxc-parser/binding-darwin-arm64': 0.152.0 + '@oxc-parser/binding-darwin-x64': 0.152.0 + '@oxc-parser/binding-freebsd-x64': 0.152.0 + '@oxc-parser/binding-linux-arm-gnueabihf': 0.152.0 + '@oxc-parser/binding-linux-arm-musleabihf': 0.152.0 + '@oxc-parser/binding-linux-arm64-gnu': 0.152.0 + '@oxc-parser/binding-linux-arm64-musl': 0.152.0 + '@oxc-parser/binding-linux-ppc64-gnu': 0.152.0 + '@oxc-parser/binding-linux-riscv64-gnu': 0.152.0 + '@oxc-parser/binding-linux-riscv64-musl': 0.152.0 + '@oxc-parser/binding-linux-s390x-gnu': 0.152.0 + '@oxc-parser/binding-linux-x64-gnu': 0.152.0 + '@oxc-parser/binding-linux-x64-musl': 0.152.0 + '@oxc-parser/binding-openharmony-arm64': 0.152.0 + '@oxc-parser/binding-win32-arm64-msvc': 0.152.0 + '@oxc-parser/binding-win32-ia32-msvc': 0.152.0 + '@oxc-parser/binding-win32-x64-msvc': 0.152.0 + oxc-resolver@11.9.0: optionalDependencies: '@oxc-resolver/binding-android-arm-eabi': 11.9.0 @@ -10334,6 +10692,11 @@ snapshots: lru-cache: 11.2.2 minipass: 7.1.3 + path-scurry@3.0.0: + dependencies: + lru-cache: 11.2.2 + minipass: 7.1.3 + path-type@6.0.0: {} pathe@2.0.3: {} @@ -10592,6 +10955,8 @@ snapshots: semver@7.7.2: {} + sentry@0.49.0: {} + setprototypeof@1.2.0: optional: true @@ -11107,7 +11472,7 @@ snapshots: jiti: 2.7.0 yaml: 2.8.1 - vitest@5.1.1(@types/node@24.3.1)(@vitest/coverage-v8@5.1.1)(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)): + vitest@5.1.1(@opentelemetry/api@1.10.0)(@types/node@24.3.1)(@vitest/coverage-v8@5.1.1)(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)): dependencies: '@types/chai': 5.2.2 '@vitest/mocker': 5.1.1(vite@8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1)) @@ -11124,6 +11489,7 @@ snapshots: vite: 8.3.8(@types/node@24.3.1)(jiti@2.7.0)(yaml@2.8.1) why-is-node-running: 3.2.1 optionalDependencies: + '@opentelemetry/api': 1.10.0 '@types/node': 24.3.1 '@vitest/coverage-v8': 5.1.1(vitest@5.1.1) transitivePeerDependencies: diff --git a/scripts/build-package-matrix.mts b/scripts/build-package-matrix.mts index ab2cc26057..dc5bb92d6c 100644 --- a/scripts/build-package-matrix.mts +++ b/scripts/build-package-matrix.mts @@ -1,10 +1,11 @@ #!/usr/bin/env node /* eslint-disable no-await-in-loop -- Package variants and staged files must be processed serially. */ -import { spawnSync } from 'node:child_process' +import { execFileSync, spawnSync } from 'node:child_process' import { promises as fs } from 'node:fs' import os from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' +import { isDeepStrictEqual } from 'node:util' import { gunzipSync } from 'node:zlib' import crossSpawn from 'cross-spawn' @@ -13,22 +14,21 @@ import { parse as parseYaml } from 'yaml' import { isMainModule } from './lib/is-main-module.mts' import { type ScriptMeta, runMain } from './lib/run-main.mts' +import { nativeOptionalDependencies } from './release/packages.mts' import { SEA_RELEASE_POLICY, SEA_VERSION } from '../src/sea/version.mts' const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..') const DEFAULT_OUTPUT = path.join(ROOT, 'build/package-matrix') const PRE_RELEASE_PREFIX = `${SEA_RELEASE_POLICY.versionHint}-${SEA_RELEASE_POLICY.identifier}.` const VARIANTS = [ - { expectedName: 'socket', version: '1.14.1' }, { expectedName: 'socket' }, + { expectedName: 'socket', native: true }, { expectedName: '@socketsecurity/cli', - version: '1.14.1', env: { INLINED_SOCKET_CLI_LEGACY_BUILD: '1' }, }, { expectedName: '@socketsecurity/cli-with-sentry', - version: '1.14.1', env: { INLINED_SOCKET_CLI_SENTRY_BUILD: '1' }, }, ] as const @@ -37,6 +37,7 @@ type Variant = { expectedName: string version: string artifact: string + native?: boolean env?: Record } @@ -59,9 +60,40 @@ export function currentPrereleaseVersion(version: string): string { return parsed.version } -export function makeVariants(version: string): Variant[] { +function stableMatrixVersion(manifestVersion: string): string { + if (semver.satisfies(manifestVersion, '1.x')) { + return manifestVersion + } + const tags = execFileSync( + 'git', + ['tag', '--merged', 'HEAD', '--list', 'v1.*'], + { + cwd: ROOT, + encoding: 'utf8', + }, + ) + const stable = semver.maxSatisfying( + tags + .trim() + .split('\n') + .map(tag => tag.slice(1)), + '1.x', + ) + if (!stable) { + throw new Error( + 'Fetch the stable v1 release tags before building the matrix from a prerelease checkout.', + ) + } + return stable +} + +export function makeVariants( + stableVersion: string, + prereleaseVersion: string, +): Variant[] { return VARIANTS.map(variant => { - const resolvedVersion = 'version' in variant ? variant.version : version + const resolvedVersion = + 'native' in variant ? prereleaseVersion : stableVersion return { ...variant, version: resolvedVersion, @@ -87,22 +119,23 @@ export function updateRootManifest(raw: string, version: string): string { return updated } -export function validatePrivateVirtualStore( +export async function validatePrivateVirtualStore( workspace: string, virtualStoreDir: unknown, -): void { +): Promise { if (typeof virtualStoreDir !== 'string') { throw new Error('pnpm did not report its virtual store directory') } - const actual = path.resolve(workspace, 'node_modules', virtualStoreDir) - const expected = path.resolve(workspace, 'node_modules/.pnpm') - const matches = - process.platform === 'win32' - ? actual.toLowerCase() === expected.toLowerCase() - : actual === expected - if (!matches) { + // Resolve workspace aliases (including Windows short paths), but keep the + // expected suffix literal so a redirected node_modules or .pnpm is rejected. + const [root, actual] = await Promise.all([ + fs.realpath(workspace), + fs.realpath(path.resolve(workspace, 'node_modules', virtualStoreDir)), + ]) + const expected = path.join(root, 'node_modules', '.pnpm') + if (actual !== expected) { throw new Error( - `pnpm virtual store escaped the private workspace: ${actual}; expected ${expected}; configured ${virtualStoreDir}`, + `pnpm virtual store escaped the private workspace: ${actual}`, ) } } @@ -138,23 +171,11 @@ export async function verifyPrivateVirtualStore( const modules = parseYaml(await fs.readFile(modulesPath, 'utf8')) as { virtualStoreDir?: unknown } - let workspacePath = workspace - let virtualStoreDir = modules.virtualStoreDir - if (process.platform === 'win32' && typeof virtualStoreDir === 'string') { - workspacePath = await fs.realpath(workspace) - const actualPath = await fs.realpath( - path.resolve(workspace, 'node_modules', virtualStoreDir), - ) - virtualStoreDir = path.relative( - path.join(workspacePath, 'node_modules'), - actualPath, - ) - } - validatePrivateVirtualStore(workspacePath, virtualStoreDir) + await validatePrivateVirtualStore(workspace, modules.virtualStoreDir) } export function readPackagedManifest(bytes: Buffer): Record { - // npm pack produces a gzip compressed POSIX tar archive. + // pnpm packs npm packages as gzip-compressed POSIX tar archives. const tar = gunzipSync(bytes) for (let offset = 0; offset + 512 <= tar.length; ) { const header = tar.subarray(offset, offset + 512) @@ -199,9 +220,21 @@ export function validatePackagedManifest( 'socket-pnpm': 'bin/pnpm-cli.js', 'socket-yarn': 'bin/yarn-cli.js', } - const expectedBins = - variant.expectedName === '@socketsecurity/cli' && - variant.env?.['INLINED_SOCKET_CLI_LEGACY_BUILD'] + if ( + variant.native && + !isDeepStrictEqual( + manifest['optionalDependencies'], + nativeOptionalDependencies(variant.version), + ) + ) { + throw new Error( + `Native launcher optional dependencies mismatch: ${variant.artifact}`, + ) + } + const expectedBins = variant.native + ? { socket: 'socket.cjs' } + : variant.expectedName === '@socketsecurity/cli' && + variant.env?.['INLINED_SOCKET_CLI_LEGACY_BUILD'] ? { cli: 'bin/cli.js', ...standardBins } : variant.expectedName === '@socketsecurity/cli-with-sentry' ? { @@ -221,7 +254,7 @@ export function validatePackagedManifest( `Tarball metadata mismatch: expected ${variant.expectedName}@${variant.version}, got ${String(manifest['name'])}@${String(manifest['version'])}`, ) } - if (JSON.stringify(manifest['bin']) !== JSON.stringify(expectedBins)) { + if (!isDeepStrictEqual(manifest['bin'], expectedBins)) { throw new Error(`Tarball CLI bin map mismatch: ${variant.artifact}`) } } @@ -303,7 +336,6 @@ async function main(): Promise { } const output = args.length ? path.resolve(ROOT, args[1]!) : DEFAULT_OUTPUT await assertOutputAvailable(output) - const variants = makeVariants(currentPrereleaseVersion(SEA_VERSION)) const temporary = await fs.mkdtemp( path.join(os.tmpdir(), 'socket-package-matrix-'), ) @@ -322,6 +354,12 @@ async function main(): Promise { const packagePath = path.join(workspace, 'package.json') const lockPath = path.join(workspace, 'pnpm-lock.yaml') const basePackage = await fs.readFile(packagePath, 'utf8') + const variants = makeVariants( + stableMatrixVersion( + (JSON.parse(basePackage) as { version: string }).version, + ), + currentPrereleaseVersion(SEA_VERSION), + ) const baseLock = await fs.readFile(lockPath, 'utf8') run( workspace, @@ -330,7 +368,6 @@ async function main(): Promise { 'install', '--frozen-lockfile', '--ignore-scripts', - '--pm-on-fail=ignore', '--config.enable-global-virtual-store=false', '--virtual-store-dir=node_modules/.pnpm', ], @@ -347,6 +384,21 @@ async function main(): Promise { updateRootManifest(basePackage, variant.version), ) await fs.writeFile(lockPath, baseLock) + if (variant.native) { + // The release stages the native launcher for this version; platform + // binaries are built and tested on their respective runners. + run( + workspace, + 'pnpm', + ['pack:native', 'root', '--out', stagedOutput], + privateEnv, + ) + await verifyPackagedVariant( + path.join(stagedOutput, variant.artifact), + variant, + ) + continue + } const env = { ...privateEnv, INLINED_SOCKET_CLI_PUBLISHED_BUILD: '1', diff --git a/scripts/ci/check-bin-eol.sh b/scripts/ci/check-bin-eol.sh new file mode 100644 index 0000000000..c62cc7a086 --- /dev/null +++ b/scripts/ci/check-bin-eol.sh @@ -0,0 +1,13 @@ +#!/usr/bin/env bash +set -euo pipefail + +# Read the staged manifest and attributes so unstaged fixes cannot mask a bad commit. +git show :package.json | + jq -je '.bin | (if type == "string" then [.] else values end)[] | ., "\u0000"' | + git check-attr --cached -z --stdin eol | + while IFS= read -r -d '' file && IFS= read -r -d '' attribute && IFS= read -r -d '' value; do + if [[ "$value" != lf ]]; then + echo "$file: expected $attribute=lf for its shebang, got $attribute=$value. Check .gitattributes." >&2 + exit 1 + fi + done diff --git a/scripts/ci/upload-artifact.mjs b/scripts/ci/upload-artifact.mjs index 9f1cccc03b..b9d24dde76 100644 --- a/scripts/ci/upload-artifact.mjs +++ b/scripts/ci/upload-artifact.mjs @@ -13,7 +13,7 @@ const MAX_ARCHIVE_BYTES = 5 * 1024 * 1024 * 1024 export class ArtifactUploadError extends Error { constructor(code) { super( - `Artifact upload failed. Where: release artifact service. Saw: ${code}; wanted three verified tarballs stored successfully. Fix: inspect the release inputs and retry the job.`, + `Artifact upload failed. Where: release artifact service. Saw: ${code}; wanted the verified tarballs stored successfully. Fix: inspect the release inputs and retry the job.`, ) this.code = code } @@ -82,14 +82,20 @@ function artifactHttpsUrl(value) { } } -export async function readReleaseTarballs(directory) { +export async function readReleaseTarballs(directory, single = false) { try { if (!(await lstat(directory)).isDirectory()) { throw new Error('invalid directory') } const names = (await readdir(directory)).sort() if ( - names.length !== 3 || + (single + ? names.length !== 1 + : names.length !== 3 && + !( + names.length === 1 && + /^socket-[0-9]+\.[0-9]+\.[0-9]+-rc\.[0-9]+\.tgz$/u.test(names[0]) + )) || names.some(name => !/^[\da-z][\w.+-]*\.tgz$/i.test(name)) ) { throw new Error('invalid tarballs') @@ -159,18 +165,30 @@ export async function uploadReleaseArtifact(config, dependencies = {}) { const ids = readArtifactBackendIds(token) const baseUrl = artifactHttpsUrl(env.ACTIONS_RESULTS_URL) const expiresAt = artifactExpiration(env.GITHUB_RETENTION_DAYS) - const names = await readReleaseTarballs(directory) + const names = await readReleaseTarballs(directory, name.startsWith('native-')) const scratch = await mkdtemp( path.join(env.RUNNER_TEMP ?? os.tmpdir(), 'release-artifact-'), ) try { const archive = path.join(scratch, 'artifact.zip') try { - await execute('zip', ['-q', '-0', archive, ...names], { - cwd: directory, - timeout: 120_000, - maxBuffer: 1024 * 1024, - }) + // Windows ships bsdtar. Use its system path to avoid Git's tar on PATH; + // -a selects ZIP from the .zip suffix and -cf creates the named archive. + // On macOS and Linux, zip -q -0 quietly stores the already-compressed .tgz files. + await execute( + process.platform === 'win32' + ? path.join(process.env.SystemRoot, 'System32', 'tar.exe') + : 'zip', + process.platform === 'win32' + ? ['-a', '-cf', archive, ...names] + : ['-q', '-0', archive, ...names], + { + cwd: directory, + timeout: 120_000, + // Cap each output stream at 1 MiB (1,024 KiB × 1,024 bytes per KiB). + maxBuffer: 1_048_576, + }, + ) } catch { throw new ArtifactUploadError('ARCHIVE_CREATION_FAILED') } diff --git a/scripts/test/apple-signing.mts b/scripts/lib/apple-signing.mts similarity index 100% rename from scripts/test/apple-signing.mts rename to scripts/lib/apple-signing.mts diff --git a/scripts/release/approve-npm.mts b/scripts/release/approve-npm.mts index 01b5e8af34..87254bfe9a 100644 --- a/scripts/release/approve-npm.mts +++ b/scripts/release/approve-npm.mts @@ -1,16 +1,23 @@ #!/usr/bin/env node import { spawnSync } from 'node:child_process' +import { readFileSync } from 'node:fs' import { parseArgs } from 'node:util' -import { RELEASE_PACKAGES } from './packages.mts' +import { waitForNpmVersion } from './availability.mts' +import { releasePackagesForVersion } from './packages.mts' import { npmDistTagForRelease } from './validate-npm-policy.mts' -import { readReleasePolicy } from '../../src/sea/version.mts' +import { + type ReleasePolicy, + readReleasePolicy, +} from '../../src/sea/version.mts' import { isMainModule } from '../lib/is-main-module.mts' import { runMain } from '../lib/run-main.mts' const STAGE_ID = /^[a-f\d]{8}-[a-f\d]{4}-[1-8][a-f\d]{3}-[89ab][a-f\d]{3}-[a-f\d]{12}$/iu -const PNPM_STAGE_VERSION = '12.21.0' +const { packageManager } = JSON.parse( + readFileSync(new URL('../../package.json', import.meta.url), 'utf8'), +) as { packageManager: string } interface GitHubRepositoryContext { readonly nameWithOwner: string @@ -23,9 +30,12 @@ function run(command: string, args: string[], inherit = false): string { stdio: inherit ? 'inherit' : ['ignore', 'pipe', 'pipe'], timeout: 120_000, }) + if (result.error) { + throw result.error + } if (result.status !== 0) { throw new Error( - `${command} ${args.join(' ')} failed: ${result.stderr ?? ''}`, + `${command} ${args.join(' ')} failed: ${result.stderr || result.stdout || result.signal || result.status}`, ) } return result.stdout?.trim() ?? '' @@ -35,24 +45,33 @@ export function pnpmStageInvocation( version: string, args: string[], ): { command: string; args: string[] } { - const major = Number.parseInt(version.split('.')[0] ?? '', 10) - return major >= 11 + return `pnpm@${version}` === packageManager ? { command: 'pnpm', args } : { command: 'corepack', - args: [`pnpm@${PNPM_STAGE_VERSION}`, '--pm-on-fail=ignore', ...args], + args: [packageManager, '--pm-on-fail=ignore', ...args], } } function runPnpmStage(args: string[], inherit = false): string { - const currentVersion = run('pnpm', ['--version']) + // pnpm run exposes the manager itself, bypassing non-executable Windows cmd shims. + const manager = process.env['npm_config_user_agent']?.startsWith('pnpm/') + ? process.env['npm_execpath'] || 'pnpm' + : 'pnpm' + const usesNode = /\.[cm]?js$/iu.test(manager) + const command = usesNode ? process.execPath : manager + const prefix = usesNode ? [manager] : [] + const currentVersion = run(command, [...prefix, '--version']) const invocation = pnpmStageInvocation(currentVersion, args) - return run(invocation.command, invocation.args, inherit) + return invocation.command === 'pnpm' + ? run(command, [...prefix, ...args], inherit) + : run(invocation.command, invocation.args, inherit) } function validateStage( value: unknown, id: string, + policy: ReleasePolicy, ): { name: string; version: string } { if (!value || typeof value !== 'object' || Array.isArray(value)) { throw new Error('npm returned an invalid stage.') @@ -70,11 +89,15 @@ function validateStage( ) { throw new Error('npm stage ID, package, or version is invalid.') } - if (!RELEASE_PACKAGES.includes(name as (typeof RELEASE_PACKAGES)[number])) { + if (!releasePackagesForVersion(version).includes(name)) { throw new Error(`Unexpected npm package in stage: ${name}`) } - if (version.includes('-') && name !== 'socket') { - throw new Error('Prerelease stages may only contain the socket package.') + const expectedTag = npmDistTagForRelease(version, policy) + // npm makes the dist-tag immutable when the package is staged. + if (stage['tag'] !== expectedTag) { + throw new Error( + `Expected npm stage dist-tag ${expectedTag} for ${name}@${version}, got ${String(stage['tag'])}.`, + ) } return { name, version } } @@ -85,7 +108,7 @@ export function stageActionForStatus(status: unknown): StageAction { if (status === 'validating') { return 'wait' } - if (status === 'staged') { + if (status === 'staged' || status === 'awaiting_approval') { return 'approve' } if (status === 'published') { @@ -171,10 +194,9 @@ async function approve(id: string): Promise { } catch { throw new Error('npm stage view did not return JSON.') } - stage = validateStage(value, id) + stage = validateStage(value, id, policy) status = (value as Record)['status'] const action = stageActionForStatus(status) - npmDistTagForRelease(stage.version, policy) if (action === 'approve') { shouldApprove = true break @@ -222,18 +244,33 @@ async function approve(id: string): Promise { `Tag v${stage.version} does not contain ${stage.name}@${stage.version}.`, ) } + if (stage.name === 'socket' && stage.version.includes('-')) { + await Promise.all( + releasePackagesForVersion(stage.version) + .slice(1) + .map(name => + waitForNpmVersion(name, stage.version, { timeoutMs: 5000 }), + ), + ) + } runPnpmStage( ['stage', 'approve', id, '--registry=https://registry.npmjs.org'], true, ) process.stdout.write(`Approved ${stage.name}@${stage.version}.\n`) + } else { + process.stdout.write(`npm stage ${id} is already published.\n`) + } + + // The socket stage starts one finalizer per release. That workflow waits for + // every sibling, so stable packages can still be approved in any order. + if (stage.name === 'socket') { + dispatchGitHubRelease(stage.version, repository) } else { process.stdout.write( - `npm stage ${id} is already published; retrying GitHub release finalization.\n`, + `The socket@${stage.version} stage triggers GitHub finalization. Retry its stage ID if finalization times out.\n`, ) } - - dispatchGitHubRelease(stage.version, repository) } async function main(args = process.argv.slice(2)): Promise { diff --git a/scripts/release/native-launcher.cjs b/scripts/release/native-launcher.cjs new file mode 100644 index 0000000000..64b741eb1b --- /dev/null +++ b/scripts/release/native-launcher.cjs @@ -0,0 +1,57 @@ +'use strict' +const { spawn } = require('node:child_process') +const { readFileSync } = require('node:fs') +const path = require('node:path') + +const name = `@socketsecurity/socket-cli-${process.platform}-${process.arch}` +const expected = require('./package.json').optionalDependencies[name] +if (!expected) { + throw new Error( + `Unsupported Socket CLI platform: ${process.platform}-${process.arch}`, + ) +} +let manifest +try { + manifest = require.resolve(`${name}/package.json`) +} catch { + throw new Error( + `Could not find ${name}. Install socket with optional dependencies enabled on a supported platform.`, + ) +} +// A consumer may already have a different version hoisted into node_modules. +const installed = JSON.parse(readFileSync(manifest, 'utf8')) +if (installed.name !== name || installed.version !== expected) { + throw new Error( + `Expected ${name}@${expected}, found ${installed.name}@${installed.version}.`, + ) +} +const executable = process.platform === 'win32' ? 'socket.exe' : 'socket' +const binary = path.join(path.dirname(manifest), executable) +const args = process.argv.slice(2) +if (process.platform !== 'win32' && process.execve) { + // Preserve the PID a service supervisor signals when cancelling a scan. + process.execve(binary, [binary, ...args], process.env) +} +const child = spawn(binary, args, { stdio: 'inherit' }) +// Older Unix Node versions need a forwarding wrapper. Windows console +// control events already reach the attached native child. +const signals = + process.platform === 'win32' ? [] : ['SIGTERM', 'SIGINT', 'SIGHUP'] +const forward = signal => child.kill(signal) +for (const signal of signals) { + process.on(signal, forward) +} +child.on('error', error => { + console.error(error.message) + process.exitCode = 1 +}) +child.on('close', (code, signal) => { + for (const watched of signals) { + process.off(watched, forward) + } + if (signal) { + process.kill(process.pid, signal) + } else if (process.exitCode === undefined) { + process.exitCode = code ?? 1 + } +}) diff --git a/scripts/release/native-packages.mts b/scripts/release/native-packages.mts new file mode 100644 index 0000000000..fb64c65a06 --- /dev/null +++ b/scripts/release/native-packages.mts @@ -0,0 +1,148 @@ +import { createHash } from 'node:crypto' +import { createReadStream } from 'node:fs' +import { + chmod, + copyFile, + mkdir, + mkdtemp, + readFile, + rm, + writeFile, +} from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { parseArgs } from 'node:util' + +import crossSpawn from 'cross-spawn' + +import { nativeOptionalDependencies, nativePackageName } from './packages.mts' +import { SEA_VERSION } from '../../src/sea/version.mts' +import { + persistNativeSigningReceipt, + prepareNativeTestBinary, +} from '../lib/apple-signing.mts' +import { isMainModule } from '../lib/is-main-module.mts' +import { runMain } from '../lib/run-main.mts' + +const root = path.resolve(import.meta.dirname, '../..') +async function main() { + const { positionals, values } = parseArgs({ + allowPositionals: true, + options: { out: { type: 'string' }, sea: { type: 'string' } }, + }) + const [kind] = positionals + if ( + positionals.length !== 1 || + !['root', 'platform'].includes(kind ?? '') || + !values.out + ) { + throw new Error('Expected root or platform and --out .') + } + const output = path.resolve(values.out) + await mkdir(output, { recursive: true }) + const stage = await mkdtemp(path.join(os.tmpdir(), 'socket-native-pack-')) + try { + const common = { + version: SEA_VERSION, + license: 'MIT', + repository: { + type: 'git', + url: 'git+https://github.com/SocketDev/socket-cli.git', + }, + } + await copyFile(path.join(root, 'LICENSE'), path.join(stage, 'LICENSE')) + let manifest + if (kind === 'platform') { + const { arch, platform } = process + const name = nativePackageName(platform, arch) + const triple = `${platform === 'win32' ? 'win' : platform}-${arch}` + const source = path.resolve(values.sea ?? path.join(root, 'build/sea')) + const receiptPath = path.join(source, `socket-${triple}.manifest.json`) + const receiptText = await readFile(receiptPath, 'utf8') + const receipt = JSON.parse(receiptText) + const filename = platform === 'win32' ? 'socket.exe' : 'socket' + const staged = path.join(stage, filename) + await copyFile( + path.join( + source, + `socket-${triple}${platform === 'win32' ? '.exe' : ''}`, + ), + staged, + ) + const digest = createHash('sha256') + for await (const chunk of createReadStream(staged)) { + digest.update(chunk) + } + const sourceSha256 = digest.digest('hex') + if ( + receipt.application?.name !== 'socket' || + receipt.application.version !== SEA_VERSION || + receipt.target?.triple !== triple || + receipt.target.os !== platform || + receipt.target.arch !== arch || + receipt.payloads?.find((p: { id: string }) => p.id === 'socket-vfs') + ?.sha256 !== sourceSha256 + ) { + throw new Error('SEA manifest does not match the native package.') + } + await chmod(staged, 0o755) + const signing = await prepareNativeTestBinary({ + binaryPath: staged, + sourceSha256, + }) + await persistNativeSigningReceipt( + signing, + path.join(stage, 'signing.json'), + ) + await writeFile(path.join(stage, 'manifest.json'), receiptText) + manifest = { + ...common, + name, + os: [platform], + cpu: [arch], + ...(platform === 'linux' ? { libc: ['glibc'] } : {}), + files: [filename, 'manifest.json', 'signing.json'], + } + } else { + const launcher = await readFile( + path.join(import.meta.dirname, 'native-launcher.cjs'), + 'utf8', + ) + await writeFile( + path.join(stage, 'socket.cjs'), + '#!/usr/bin/env node\n' + launcher, + ) + await chmod(path.join(stage, 'socket.cjs'), 0o755) + manifest = { + ...common, + name: 'socket', + bin: { socket: 'socket.cjs' }, + optionalDependencies: nativeOptionalDependencies(SEA_VERSION), + } + } + await writeFile( + path.join(stage, 'package.json'), + JSON.stringify(manifest, null, 2) + '\n', + ) + // Keep pnpm pack here: it rejects CRLF shebangs that would break CLI startup on Unix. + const result = crossSpawn.sync( + 'pnpm', + ['pack', '--pack-destination', output], + { cwd: stage, stdio: 'inherit' }, + ) + if (result.error) { + throw result.error + } + if (result.status !== 0) { + throw new Error('pnpm pack failed.') + } + } finally { + await rm(stage, { recursive: true, force: true }) + } +} +if (isMainModule(import.meta.url)) { + runMain(main, { + describe: 'packs the native RC launcher or the host SEA package', + help: 'Usage: pnpm run pack:native --out [--sea ]', + }) +} diff --git a/scripts/release/packages.mts b/scripts/release/packages.mts index 7e76262fa2..09962616b3 100644 --- a/scripts/release/packages.mts +++ b/scripts/release/packages.mts @@ -1,3 +1,30 @@ +const nativeTargets = [ + 'darwin-arm64', + 'linux-arm64', + 'linux-x64', + 'win32-arm64', + 'win32-x64', +] + +export function nativePackageName(platform: string, arch: string): string { + const target = `${platform}-${arch}` + if (!nativeTargets.includes(target)) { + throw new Error(`Unsupported native target: ${target}`) + } + return `@socketsecurity/socket-cli-${target}` +} + +export function nativeOptionalDependencies( + version: string, +): Record { + return Object.fromEntries( + nativeTargets.map(target => [ + `@socketsecurity/socket-cli-${target}`, + version, + ]), + ) +} + export const RELEASE_PACKAGES = [ 'socket', '@socketsecurity/cli', @@ -5,5 +32,7 @@ export const RELEASE_PACKAGES = [ ] as const export function releasePackagesForVersion(version: string): readonly string[] { - return version.includes('-') ? ['socket'] : RELEASE_PACKAGES + return version.includes('-') + ? ['socket', ...Object.keys(nativeOptionalDependencies(version))] + : RELEASE_PACKAGES } diff --git a/scripts/release/registry.mts b/scripts/release/registry.mts index fd3c272605..3da577def1 100644 --- a/scripts/release/registry.mts +++ b/scripts/release/registry.mts @@ -1,6 +1,6 @@ import semver from 'semver' -import { RELEASE_PACKAGES } from './packages.mts' +import { RELEASE_PACKAGES, releasePackagesForVersion } from './packages.mts' import { matchesReleasePolicy } from '../../src/sea/version.mts' import type { ReleasePolicy } from '../../src/sea/version.mts' @@ -157,7 +157,7 @@ export async function assertReleaseVersionsAvailable( ' Fix: pass --version with the bump step version.', ) } - const packages = onPrereleaseMajor ? ['socket'] : [...RELEASE_PACKAGES] + const packages = releasePackagesForVersion(version) const results = await Promise.allSettled( packages.map(async name => { const document = await readRegistryDocument(name, version, fetcher) diff --git a/scripts/setup/firewall.sh b/scripts/setup/firewall.sh new file mode 100644 index 0000000000..2a1142ec44 --- /dev/null +++ b/scripts/setup/firewall.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash +# Install the verified Socket Firewall and wrap the package managers present on this runner. +set -euo pipefail + +version=1.16.0 +commands=(npm yarn pnpm pip uv cargo) +if [[ -n "${SOCKET_API_KEY:-}" ]]; then + repo=SocketDev/firewall-release + prefix=sfw + commands+=(gem bundler nuget) + [[ "$RUNNER_OS" != Linux ]] || commands+=(go) +else + repo=SocketDev/sfw-free + prefix=sfw-free +fi + +case "$RUNNER_OS-$RUNNER_ARCH" in + Linux-X64) target=linux-x86_64 ;; + Linux-ARM64) target=linux-arm64 ;; + macOS-X64) target=macos-x86_64 ;; + macOS-ARM64) target=macos-arm64 ;; + Windows-X64) target=windows-x86_64.exe ;; + *) echo "Unsupported Socket Firewall target: $RUNNER_OS-$RUNNER_ARCH" >&2; exit 1 ;; +esac +asset="$prefix-$target" +case "$asset" in + sfw-linux-x86_64) digest=9c5e77a2c08683c3cca7c5fba9d380c7acca7ed6ea71c0d3919b2a723bea34b3 ;; + sfw-linux-arm64) digest=945708d9907f4702d91d341647576aae667ad0c411cd9c02a4f56b130512695c ;; + sfw-macos-x86_64) digest=9b6faa3c4cb5d2cbbea7bad5c7a47a4a9f179a8a75f1ce2993ac0c50e5e040cf ;; + sfw-macos-arm64) digest=16fbe362a24af30b75938667e7bff00ed79df24e17a8e2d0abf3ae53d5739e92 ;; + sfw-windows-x86_64.exe) digest=e8ecd768aebabc365d91306e0b5ef8b66c16b4816496934ff4998cda60590e3c ;; + sfw-free-linux-x86_64) digest=1f24d2628aeb3995f1f2651509e37641c7c41d07749ac68594ecb5bb2dd44d8a ;; + sfw-free-linux-arm64) digest=474cdb684e42d33d4b697dedd7d90c159d71380be0e53c496f0e7097c3617a6c ;; + sfw-free-macos-x86_64) digest=b574931bc2b3c36a9bf07ac07b9c07894f8cd314efc91bc5e4fe1c371b56adca ;; + sfw-free-macos-arm64) digest=29df049df2ef705a8ce726c6c41fe73a6034f6b1cd0d87f3f15a780d074b6d83 ;; + sfw-free-windows-x86_64.exe) digest=fafcb65a0349ff21af4feeda170f669053efa68acb55e1b935f7ed1b2ac93ca7 ;; +esac + +temp=$RUNNER_TEMP +if [[ "$RUNNER_OS" == Windows ]]; then temp=$(cygpath -u "$temp"); fi +dir=$(mktemp -d "$temp/socket-firewall.XXXXXX") +bin="$dir/sfw" +if [[ "$RUNNER_OS" == Windows ]]; then bin+=.exe; fi +url=$(gh api "repos/$repo/releases/tags/v$version" --jq ".assets[] | select(.name == \"$asset\") | .browser_download_url") +curl -fsSL "$url" -o "$bin" +if command -v sha256sum >/dev/null; then checksum=(sha256sum); else checksum=(shasum -a 256); fi +(cd "$dir" && echo "$digest ${bin##*/}" | "${checksum[@]}" -c -) +chmod +x "$bin" + +shims="$dir/shims" +mkdir "$shims" +for command in "${commands[@]}"; do + real=$(command -v "$command") || continue + { + echo '#!/usr/bin/env bash' + # Nested package-manager invocations must reach the original tools. + printf 'shims=%q\n' "$shims" + cat <<'SH' +path=:$PATH: +path=${path//:"$shims":/:} +path=${path#:} +export PATH=${path%:} +SH + printf 'exec %q %q "$@"\n' "$bin" "$real" + } > "$shims/$command" + chmod +x "$shims/$command" + if [[ "$RUNNER_OS" == Windows ]]; then + printf '@echo off\r\nset "PATH=;%%PATH%%;"\r\nset "PATH=%%PATH:;%s;=;%%"\r\nset "PATH=%%PATH:~1,-1%%"\r\n"%s" "%s" %%*\r\n' \ + "$(cygpath -w "$shims")" "$(cygpath -w "$bin")" "$(cygpath -w "$real")" > "$shims/$command.cmd" + fi +done +if [[ "$RUNNER_OS" == Windows ]]; then shims=$(cygpath -w "$shims"); fi +echo "$shims" >> "$GITHUB_PATH" +if [[ "$prefix" == sfw ]]; then echo "SOCKET_API_KEY=$SOCKET_API_KEY" >> "$GITHUB_ENV"; fi diff --git a/scripts/setup/release-tools.sh b/scripts/setup/release-tools.sh new file mode 100644 index 0000000000..8b7c2dbffc --- /dev/null +++ b/scripts/setup/release-tools.sh @@ -0,0 +1,72 @@ +#!/usr/bin/env bash +# Install checksum-verified tools into a private runner directory. Compatibility +# test jobs select their matrix Node before calling this with --keep-node. +set -euo pipefail +root=$(cd "$(dirname "$0")/../.." && pwd) +cd "$root" +node_version=$(tr -d '\r\n' < src/sea/.node-version) +# Windows jq can emit CRLF when invoked from Git Bash. +read_setting() { jq -er "$@" | tr -d '\r'; } +pnpm_version=$(read_setting '.packageManager | capture("^pnpm@(?[0-9]+\\.[0-9]+\\.[0-9]+)$").v' package.json) +npm_version=$(read_setting '.npm.version' .config/release-tools.json) +[[ "$node_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+(-[a-zA-Z0-9.-]+)?$ ]] +[[ "$npm_version" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]] +case "${RUNNER_OS:?}" in + Linux) os=linux ;; + macOS) os=darwin ;; + Windows) os=win32 ;; + *) exit 1 ;; +esac +temp=${RUNNER_TEMP:?} +if [[ "$os" == win32 ]]; then temp=$(cygpath -u "$temp"); fi +dir=$(mktemp -d "$temp/socket-tools.XXXXXX") +bin="$dir/bin" +mkdir "$bin" +arch=$(echo "${RUNNER_ARCH:?}" | tr '[:upper:]' '[:lower:]') +check_sha256() { + if command -v sha256sum >/dev/null; then sha256sum -c -; else shasum -a 256 -c -; fi +} +if [[ "${1:-}" != --keep-node ]]; then + base="https://nodejs.org/dist/v$node_version" + if [[ "$os" == win32 ]]; then archive="node-v$node_version-win-$arch.zip"; else archive="node-v$node_version-$os-$arch.tar.xz"; fi + curl -fsSL "$base/SHASUMS256.txt" -o "$dir/sums" + curl -fsSL "$base/$archive" -o "$dir/$archive" + (cd "$dir" && awk -v file="$archive" '$2 == file { print; found++ } END { if (found != 1) exit 1 }' sums | check_sha256) + if [[ "$os" == win32 ]]; then + unzip -q "$dir/$archive" -d "$dir" + node_bin="$dir/node-v$node_version-win-$arch" + else + tar -xJf "$dir/$archive" -C "$dir" + node_bin="$dir/node-v$node_version-$os-$arch/bin" + fi + export PATH="$node_bin:$PATH" + [[ "$(node -p 'process.versions.node' | tr -d '\r')" == "$node_version" ]] +fi +target="$os-$arch" +if [[ "$os" == win32 ]]; then ext=zip; else ext=tar.gz; fi +asset="pnpm-$target.$ext" +curl -fsSL "https://github.com/pnpm/pnpm/releases/download/v$pnpm_version/$asset" -o "$dir/$asset" +expected=$(read_setting --arg target "$target" '.pnpm[$target]' .config/release-tools.json) +(cd "$dir" && echo "$expected $asset" | check_sha256) +if [[ "$os" == win32 ]]; then unzip -q "$dir/$asset" -d "$bin"; else tar -xzf "$dir/$asset" -C "$bin"; fi +curl -fsSL "https://registry.npmjs.org/npm/-/npm-$npm_version.tgz" -o "$dir/npm.tgz" +expected=$(read_setting '.npm.integrity' .config/release-tools.json) +actual=$(openssl dgst -sha512 -binary "$dir/npm.tgz" | openssl base64 -A) +[[ "sha512-$actual" == "$expected" ]] +mkdir "$bin/npm-cli" +tar -xzf "$dir/npm.tgz" --strip-components=1 -C "$bin/npm-cli" +for command in npm npx; do + printf '#!/bin/sh\nexec node "$(dirname "$0")/npm-cli/bin/%s-cli.js" "$@"\n' "$command" > "$bin/$command" + chmod +x "$bin/$command" + if [[ "$os" == win32 ]]; then + printf '%s\r\n' '@echo off' "node \"%~dp0npm-cli/bin/$command-cli.js\" %*" > "$bin/$command.cmd" + fi +done +export PATH="$bin:$PATH" +[[ "$(pnpm --version | tr -d '\r')" == "$pnpm_version" && "$(npm --version | tr -d '\r')" == "$npm_version" ]] +runner_path() { + if [[ "$os" == win32 ]]; then cygpath -w "$1"; else echo "$1"; fi +} +if [[ -n "${node_bin:-}" ]]; then runner_path "$node_bin" >> "$GITHUB_PATH"; fi +runner_path "$bin" >> "$GITHUB_PATH" +echo "Release tools: $(node --version), pnpm $pnpm_version, npm $npm_version" diff --git a/scripts/test/native.mts b/scripts/test/native.mts index e948ed33c3..100afceecd 100644 --- a/scripts/test/native.mts +++ b/scripts/test/native.mts @@ -1,4 +1,3 @@ -import type { SpawnSyncOptions } from 'node:child_process' import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' import { promises as fs } from 'node:fs' @@ -13,7 +12,8 @@ import { assertSnapshotDependenciesCurrent } from '../refresh/snapshots/dependen import { persistNativeSigningReceipt, prepareNativeTestBinary, -} from './apple-signing.mts' +} from '../lib/apple-signing.mts' +import type { SpawnSyncOptions } from 'node:child_process' type NativeManifest = { application: { name: string; version: string } @@ -129,12 +129,17 @@ async function main(): Promise { const vitestArgs = userArgs.filter( arg => arg !== '--build' && arg !== '--require-apple-signature', ) + if (vitestArgs.length === 0) { + vitestArgs.push('test/native') + } const updatesSnapshots = vitestArgs.some( arg => arg === '-u' || arg === '--update', ) if ( !updatesSnapshots && - vitestArgs.some(arg => arg.endsWith('cli.native.test.mts')) + vitestArgs.some( + arg => arg === 'test/native' || arg.endsWith('cli.native.test.mts'), + ) ) { await assertSnapshotDependenciesCurrent() } @@ -196,10 +201,7 @@ async function main(): Promise { process.env['SOCKET_CLI_NATIVE_TEST_ARTIFACTS'] = artifactsDir process.env['SOCKET_CLI_NATIVE_TEST_RECEIPT_PATH'] = receiptPath if (build) { - runPnpm( - ['build:sea', '--', '--prototype'], - sanitizeNativeEnvironment(process.env), - ) + runPnpm(['build:sea'], sanitizeNativeEnvironment(process.env)) } // Snapshot the verified artifact into this run's private stage so another @@ -353,11 +355,11 @@ function sanitizeNativeEnvironment( const SCRIPT_META: ScriptMeta = { describe: 'runs integration tests against the host-native Socket SEA binary', - help: `Usage: pnpm run test:native [vitest options] - pnpm run test:native:build [vitest options] + help: `Usage: pnpm run test:sea [vitest options] + pnpm build:sea && pnpm test:sea [vitest options] The native lane requires a matching build/sea/socket-- binary - and manifest. The :build variant creates the prototype first. Native test + and manifest. Build it first with pnpm build:sea. Native test package-manager caches are isolated and test files run serially. Pass Vitest options after the script name to filter test files or tests.`, diff --git a/src/commands/manifest/scripts/run.mts b/src/commands/manifest/scripts/run.mts index 4260c44eae..6dcce2344c 100644 --- a/src/commands/manifest/scripts/run.mts +++ b/src/commands/manifest/scripts/run.mts @@ -563,8 +563,26 @@ async function invokeDotnetTool( : opts.env return await withTmpDir('socket-dotnet-facts-', async tmp => { const recordsFile = path.join(tmp, 'records.tsv') + // An external dotnet process cannot open Node's in-process VFS mount. + let executableDll = toolDll + if (isStandaloneSea()) { + const toolDir = path.join(tmp, 'dotnet-tool') + await fs.mkdir(toolDir) + const embeddedDir = path.dirname(toolDll) + // fs.cp delegates to the host filesystem. Read the DLL and its + // adjacent runtime files through the VFS and write them to disk. + /* eslint-disable no-await-in-loop -- Finish each copy before temporary-directory cleanup can run. */ + for (const name of await fs.readdir(embeddedDir)) { + await fs.writeFile( + path.join(toolDir, name), + await fs.readFile(path.join(embeddedDir, name)), + ) + } + /* eslint-enable no-await-in-loop */ + executableDll = path.join(toolDir, path.basename(toolDll)) + } const args = [ - toolDll, + executableDll, '--records', recordsFile, '--entry', diff --git a/src/commands/optimize/cmd-optimize-pnpm-versions.test.mts b/src/commands/optimize/cmd-optimize-pnpm-versions.test.mts index 597ae4bcc8..75779a0401 100644 --- a/src/commands/optimize/cmd-optimize-pnpm-versions.test.mts +++ b/src/commands/optimize/cmd-optimize-pnpm-versions.test.mts @@ -24,7 +24,7 @@ async function prepareFixture(version: 'pnpm8' | 'pnpm9') { const cwd = await mkdtemp( path.join(os.tmpdir(), `socket-optimize-${version}-`), ) - onTestFinished(() => rm(cwd, { force: true, recursive: true })) + onTestFinished(() => rm(cwd, { force: true, maxRetries: 5, recursive: true })) await Promise.all( [PACKAGE_JSON, PNPM_LOCK_YAML, PNPM_WORKSPACE_YAML].map(filename => @@ -46,13 +46,10 @@ async function prepareFixture(version: 'pnpm8' | 'pnpm9') { CI: '1', PATH: [binPath, process.env.PATH].join(path.delimiter), } - const pnpm = path.join( - binPath, - process.platform === 'win32' ? 'pnpm.cmd' : PNPM, - ) - const { stdout } = await spawn(pnpm, ['--version'], { cwd, env }) + const options = { cwd, env, shell: process.platform === 'win32' } + const { stdout } = await spawn(PNPM, ['--version'], options) expect(stdout.trim()).toBe(pnpmVersion) - await spawn(pnpm, ['install', '--no-frozen-lockfile'], { cwd, env }) + await spawn(PNPM, ['install', '--no-frozen-lockfile'], options) return { cwd, env } } @@ -67,7 +64,7 @@ describe('socket optimize - pnpm versions', { timeout: 60_000 }, async () => { it( 'should optimize packages with pnpm v8', - { timeout: 30_000 }, + { timeout: 120_000 }, async () => { const { cwd, env } = fixture const packageJsonPath = path.join(cwd, PACKAGE_JSON) @@ -161,7 +158,7 @@ describe('socket optimize - pnpm versions', { timeout: 60_000 }, async () => { it( 'should optimize packages with pnpm v9', - { timeout: 30_000 }, + { timeout: 120_000 }, async () => { const { cwd, env } = fixture const packageJsonPath = path.join(cwd, PACKAGE_JSON) @@ -208,7 +205,7 @@ describe('socket optimize - pnpm versions', { timeout: 60_000 }, async () => { it( 'should handle --pin flag with pnpm v9', - { timeout: 30_000 }, + { timeout: 120_000 }, async () => { const { cwd, env } = fixture const packageJsonPath = path.join(cwd, PACKAGE_JSON) diff --git a/src/sea/README.md b/src/sea/README.md index 9d289293a3..0eb2ed6baa 100644 --- a/src/sea/README.md +++ b/src/sea/README.md @@ -6,7 +6,7 @@ A release config is required at `.config/release.json`, `release.json`, or `.rel ## Release recovery -The npm workflow reserves the version tag and stages the verified package files. It does not create a GitHub release. Approve each stage ID with `pnpm run approve:npm `; the command uses pnpm 11 for stage commands and dispatches `release-github.yml`. That workflow waits until every package for the version is public before publishing the GitHub release. +The npm workflow reserves the version tag and stages the verified package files. It does not create a GitHub release. Approve each stage ID with `pnpm run approve:npm `; the command uses the repository’s pinned pnpm for stage commands and dispatches `release-github.yml`. That workflow waits until every package for the version is public before publishing the GitHub release. | npm status | Action | | --- | --- | @@ -24,11 +24,13 @@ The CLI already runs on Node. SEA keeps that runtime and uses Node's VFS to embe ## Build ```sh -pnpm build:sea -- --prototype +pnpm build:sea ``` The builder uses Node `v27.0.0-alpha.0.1.1`. It verifies the Node archive against the release `SHASUMS256.txt`. Node 27 is a prerelease, so these builds are experimental. +Release and native-build jobs use this same Node version. They install the pnpm version pinned in `package.json` and the npm version pinned in `.config/release-tools.json`. pnpm packs the tarballs, installs them in a clean consumer for smoke testing, and stages them for release. The native smoke test installs the launcher and its matching platform tarball offline. + Build on the target OS and architecture. The builder supports `darwin`, `linux`, and `win32`, with `x64` and `arm64` archives where Node publishes them. Cross-target builds fail. The builder creates a private temporary copy of the distribution. It does not replace the checkout's `dist` or `external` directories. It writes the executable and manifest to `build/sea`. Use `--output-dir` or `SOCKET_CLI_SEA_OUTPUT_DIR` to select another directory; the command-line option takes precedence. @@ -57,16 +59,29 @@ Use the executable's `--version` output and the adjacent manifest's recorded Soc ## Native terminal tests -Use Node 26.13.0 and build the prototype on the host OS before running its native tests: +Use the Node version in `src/sea/.node-version` and build the prototype on the host OS before running its native tests: Run `pnpm snapshots` to verify the terminal screenshots and print the HTML report path. Use `pnpm snapshots:termless:refresh` to refresh the images, `pnpm snapshots:vite:refresh` for Vitest unit snapshots, or `pnpm snapshots:refresh` for both. ```sh -pnpm build:sea -- --prototype -SOCKET_CLI_NATIVE_TEST_ARTIFACTS=build/native-test-artifacts/run-1 pnpm test:native test/native/commands/cli.native.test.mts test/native/commands/cli-behavior.native.test.mts +pnpm build:sea +SOCKET_CLI_NATIVE_TEST_ARTIFACTS=build/native-test-artifacts/run-1 pnpm test:sea test/native/commands/cli.native.test.mts test/native/commands/cli-behavior.native.test.mts node scripts/test/terminal-report.mts --artifacts build/native-test-artifacts/run-1 --output build/native-test-artifacts/run-1/index.html ``` Choose a fresh run directory each time; it stores checkpoint PNG/SVG files, the animation, and signing receipt. On macOS, configured Developer ID credentials sign the staged binary; CI exposes signing secrets only on trusted pushes. Terminal images trim unused rows while preserving internal spacing. Each animation uses a shared height across its checkpoints. + +### Build, test, and publish the RC + +Run `pnpm build:sea` on the target OS and CPU. Before accepting the executable and manifest, the builder smoke tests `--help` and `--version`. Run `socket sea smoke-test` to verify that every staged file can be read from the mounted VFS with its original bytes. It also runs the embedded Coana cache helper against an empty temporary cache and checks its cache-miss exit code. On targets that bundle uv, the same command extracts it, runs `uv --version`, checks the pinned version, and removes the executable. The builder also runs `patch --version` on targets with socket-patch, generates .NET facts for a dependency-free project with package sources disabled, and checks cleanup of extracted tools. A minimal npm project also exercises the embedded cdxgen capability check. Run `pnpm test:sea` for the native suite. + +The release workflow builds the five platform packages on their matching runners. Each runner installs the actual `socket` launcher tarball with its matching platform tarball in an empty consumer and runs help and version through the installed command. The launcher declares exact-version optional dependencies under `@socketsecurity/socket-cli--`. Linux packages target glibc. The pinned Node release provides macOS arm64, Linux arm64/x64 and Windows arm64/x64 archives. + +Use the existing publish workflow. To rehearse from a v1 checkout, choose **publish**, **dry-run**, and release major **2**. To release, prepare and merge the RC version first. The publish job stages verified platform tarballs before the launcher under `rc-2.1.0`. Approve platform stage IDs first and the launcher last with `pnpm run approve:npm `. + +For the first release of a new name, an npm organization maintainer must provision a short-lived granular token with write permission to create public packages in the `@socketsecurity` scope. It does not need 2FA bypass. Store it as `NPM_FIRST_STAGE_TOKEN` in the protected GitHub `publish-npm` environment. CI checks package names against the public registry before reserving the tag and supplies the token only for first-time native staging. Approval uses maintainer 2FA. + +Once each package exists, configure trusted staging for subsequent releases: +`npm trust github @socketsecurity/ --repository SocketDev/socket-cli --file publish-npm.yml --environment publish-npm --allow-stage-publish`. Remove the bootstrap token when the initial stages are complete. Configure trust near the next publish since unused new connections expire after two days. See [npm stage](https://docs.npmjs.com/cli/v11/commands/npm-stage/) and [trusted publishers](https://docs.npmjs.com/trusted-publishers/). diff --git a/src/sea/bootstrap.mts b/src/sea/bootstrap.mts index b0870940b0..5c30d7023a 100644 --- a/src/sea/bootstrap.mts +++ b/src/sea/bootstrap.mts @@ -1,7 +1,79 @@ /** Load the complete root Socket distribution relative to the SEA VFS main. */ +import assert from 'node:assert/strict' +import { execFileSync } from 'node:child_process' +import { once } from 'node:events' +import { promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { Worker } from 'node:worker_threads' + +import { cleanupBundledTool, getBundledTool } from './runtime.mts' +import { digestVfs } from './vfs-digest.mts' + +// The builder records its inputs in the bootstrap, outside the archive being tested. +declare const INLINED_SEA_SMOKE_TEST: null | { + digest: string + uvVersion?: string +} + // Node places the VFS main at its mount root. Expose that stable root before // loading Socket so native payload adapters can read embedded files by path. ;( globalThis as typeof globalThis & { __socketSeaVfsRoot?: string } ).__socketSeaVfsRoot = __dirname -require('./dist/cli.js') + +async function smokeTest(): Promise { + const seaSmokeTest = INLINED_SEA_SMOKE_TEST + assert.ok(seaSmokeTest, 'Missing SEA build inputs for the smoke test') + // Node adds this bootstrap at the mount root alongside the archive entries. + const entries = (await fs.readdir(__dirname)).filter( + name => name !== path.basename(__filename), + ) + assert.equal( + digestVfs(__dirname, entries), + seaSmokeTest.digest, + 'Embedded VFS differs from build inputs', + ) + // The SEA ships the Coana cache helper. A lookup in a private empty cache + // exercises its VFS entrypoint without fetching a Coana release. + const cache = await fs.mkdtemp(path.join(os.tmpdir(), 'socket-coana-smoke-')) + try { + const worker = new Worker(path.join(__dirname, 'dist/coana-cache.mjs'), { + argv: ['lookup', '0.0.0', 'cli'], + env: { ...process.env, XDG_CACHE_HOME: cache }, + }) + const [code] = await once(worker, 'exit') + assert.equal(code, 4, 'Expected a Coana cache miss') + } finally { + await fs.rm(cache, { recursive: true, force: true }) + } + if (seaSmokeTest.uvVersion) { + const uv = await getBundledTool('uv') + try { + const output = execFileSync(uv, ['--version'], { + encoding: 'utf8', + timeout: 15_000, + }) + const [name, version] = output.trim().split(/\s+/u) + assert.equal(name, 'uv') + assert.equal(version, seaSmokeTest.uvVersion) + process.stdout.write(output) + } finally { + await cleanupBundledTool(uv) + } + } + console.log('VFS smoke test passed') +} + +if ( + process.argv.length === 4 && + process.argv[2] === 'sea' && + process.argv[3] === 'smoke-test' +) { + void smokeTest().catch(error => { + console.error(error) + process.exitCode = 1 + }) +} else { + require('./dist/cli.js') +} diff --git a/src/sea/build-sea.mts b/src/sea/build-sea.mts index bf95c66624..9f36771406 100644 --- a/src/sea/build-sea.mts +++ b/src/sea/build-sea.mts @@ -9,17 +9,19 @@ import { fileURLToPath, pathToFileURL } from 'node:url' import { gunzipSync } from 'node:zlib' import { seaArchivePaths } from './archive-paths.mts' -import { findLockedPackageIntegrity, parsePnpmLock } from './pnpm-lock.mts' import { acquireBuildLock } from './build/lock.mts' import { publishArtifactPair } from './build/publish.mts' +import { smokeTestSea } from './build/smoke-test.mts' import { createSeaCapabilities } from './capabilities.mts' import { downloadBytes } from './download-bytes.mts' import { cachedDownload } from './download-cache.mts' import { NODE_VERSION } from './node-version.mts' +import { findLockedPackageIntegrity, parsePnpmLock } from './pnpm-lock.mts' import { updateSeaReadmeVersion } from './readme-version.mts' import { stageSynp } from './stage/synp.mts' import { stageUv } from './stage/uv.mts' import { SEA_VERSION } from './version.mts' +import { digestVfs } from './vfs-digest.mts' import { quotePowerShell } from '../utils/quote-powershell.mts' const SEA_DIRECTORY = path.dirname(fileURLToPath(import.meta.url)) @@ -33,35 +35,12 @@ const DEFAULT_OUT = path.join(REPOSITORY_ROOT, 'build/sea') const TARGETS = [ ['darwin', 'arm64', 'darwin-arm64'], - ['darwin', 'x64', 'darwin-x64'], ['linux', 'arm64', 'linux-arm64'], ['linux', 'x64', 'linux-x64'], ['win32', 'arm64', 'win-arm64'], ['win32', 'x64', 'win-x64'], ] as const -export function getSocketPatchPackageName( - platform: string, - arch: string, - libc?: 'gnu' | 'musl', -): string { - if (platform === 'linux') { - if (!libc) { - throw new Error('Linux socket-patch package selection requires libc') - } - return `@socketsecurity/socket-patch-linux-${arch}-${libc}` - } - const packagePlatform = platform === 'win32' ? 'win32' : platform - return `@socketsecurity/socket-patch-${packagePlatform}-${arch}` -} - -function detectLinuxLibc(): 'gnu' | 'musl' { - const { header } = process.report.getReport() as { - header?: { glibcVersionRuntime?: string } - } - return header?.glibcVersionRuntime ? 'gnu' : 'musl' -} - function sha256(data: Buffer): string { return createHash('sha256').update(data).digest('hex') } @@ -203,6 +182,8 @@ export function findNodeArchiveSha256( return matches.length === 1 ? matches[0] : undefined } +export { findLockedPackageIntegrity } from './pnpm-lock.mts' + function readTarEntries( archive: Buffer, binaryEntry: string, @@ -319,11 +300,8 @@ async function stageSocketPatch( | undefined > { const [platform, arch] = target - const packageName = getSocketPatchPackageName( - platform, - arch, - platform === 'linux' ? detectLinuxLibc() : undefined, - ) + const packagePlatform = platform === 'win32' ? 'win32' : platform + const packageName = `@socketsecurity/socket-patch-${packagePlatform}-${arch}` const lock = await fs.readFile( path.join(REPOSITORY_ROOT, 'pnpm-lock.yaml'), 'utf8', @@ -558,8 +536,8 @@ async function stageCdxgenApi( const workerUtils = path.join(payloadRoot, 'utils') await fs.mkdir(workerUtils, { recursive: true }) await fs.copyFile( - path.join(REPOSITORY_ROOT, 'src/utils/is-record.mjs'), - path.join(workerUtils, 'is-record.mjs'), + path.join(REPOSITORY_ROOT, 'src/utils/is-object-object.mjs'), + path.join(workerUtils, 'is-object-object.mjs'), ) // Keep a concrete VFS path for cdxgen's plugin-directory override. The // marker does not install or expose any plugin executable. @@ -775,7 +753,7 @@ async function run( env?: NodeJS.ProcessEnv, cwd = REPOSITORY_ROOT, ): Promise { - const { spawn } = await import('node:child_process') + const { default: spawn } = await import('cross-spawn') await new Promise((resolve, reject) => { const child = spawn(command, args, { cwd, @@ -798,18 +776,15 @@ export function parseArgs( platform?: string arch?: string outputDir: string - prototype: boolean } { const result: { platform?: string arch?: string outputDir: string - prototype: boolean } = { outputDir: env['SOCKET_CLI_SEA_OUTPUT_DIR'] ? path.resolve(env['SOCKET_CLI_SEA_OUTPUT_DIR']) : DEFAULT_OUT, - prototype: false, } for (const arg of argv) { if (arg === '--') { @@ -817,9 +792,7 @@ export function parseArgs( } const [key, ...rest] = arg.replace(/^--/, '').split('=') const value = rest.join('=') - if (key === 'prototype' && value === '') { - result.prototype = true - } else if (key === 'platform') { + if (key === 'platform') { result.platform = value } else if (key === 'arch') { result.arch = value @@ -838,11 +811,6 @@ export function parseArgs( async function main(): Promise { const options = parseArgs() - if (!options.prototype) { - throw new Error( - 'This is an experimental core-only prototype, not a release builder. Pass --prototype explicitly.', - ) - } const target = TARGETS.find( ([platform, arch]) => (options.platform ?? process.platform) === platform && @@ -1152,16 +1120,12 @@ async function main(): Promise { rootFiles, }) if (process.platform === 'win32') { - const sourceList = archivePaths - .map(filename => quotePowerShell(path.join(stage, filename))) - .join(', ') + // Windows PowerShell's Compress-Archive may emit backslashes in ZIP + // entry names. Node's VFS resolves POSIX paths such as dist/cli.js. + // Git Bash also ships GNU tar, which cannot write ZIP archives. await run( - 'powershell', - [ - '-NoProfile', - '-Command', - `Compress-Archive -LiteralPath @(${sourceList}) -DestinationPath ${quotePowerShell(archive)} -Force`, - ], + path.join(process.env['SystemRoot']!, 'System32', 'tar.exe'), + ['--format', 'zip', '-cf', archive, ...archivePaths], undefined, stage, ) @@ -1178,6 +1142,10 @@ async function main(): Promise { { SEA_BOOTSTRAP: path.join(SEA_DIRECTORY, 'bootstrap.mts'), SEA_OUTPUT: bootstrap, + SEA_SMOKE_TEST: JSON.stringify({ + digest: digestVfs(stage, archivePaths), + uvVersion: uvPayload?.version, + }), }, ) @@ -1203,6 +1171,13 @@ async function main(): Promise { await run('codesign', ['--sign', '-', output]) } + await smokeTestSea( + output, + path.join(stage, 'smoke-test'), + SEA_VERSION, + socketPatchVersion, + capabilities, + ) const appVersion = SEA_VERSION const payloads: Array> = [ { diff --git a/src/sea/build/smoke-test.mts b/src/sea/build/smoke-test.mts new file mode 100644 index 0000000000..5827284a5d --- /dev/null +++ b/src/sea/build/smoke-test.mts @@ -0,0 +1,107 @@ +import assert from 'node:assert/strict' +import { execFile } from 'node:child_process' +import { promises as fs } from 'node:fs' +import path from 'node:path' +import { promisify } from 'node:util' + +import type { SeaCapabilities } from '../capabilities.mts' + +const exec = promisify(execFile) + +export async function smokeTestSea( + executable: string, + cwd: string, + version: string, + patchVersion: string, + capabilities: SeaCapabilities, +): Promise { + await fs.mkdir(cwd) + const tmp = path.join(cwd, 'tmp') + await fs.mkdir(tmp) + const env = { + PATH: process.env['PATH'], + SystemRoot: process.env['SystemRoot'], + // NuGet and MSBuild locate machine-wide configuration and SDKs here. + ProgramData: process.env['ProgramData'], + ProgramFiles: process.env['ProgramFiles'], + 'ProgramFiles(x86)': process.env['ProgramFiles(x86)'], + ProgramW6432: process.env['ProgramW6432'], + DOTNET_ROOT: process.env['DOTNET_ROOT'], + DOTNET_CLI_HOME: cwd, + DOTNET_CLI_TELEMETRY_OPTOUT: '1', + MSBUILDDISABLENODEREUSE: '1', + HOME: cwd, + USERPROFILE: cwd, + APPDATA: cwd, + LOCALAPPDATA: cwd, + CI: '1', + NO_UPDATE_NOTIFIER: '1', + SOCKET_CLI_API_BASE_URL: 'http://127.0.0.1:1/v0/', + SOCKET_CLI_NO_API_TOKEN: '1', + SOCKET_CLI_CONFIG: '{}', + TMP: tmp, + TEMP: tmp, + TMPDIR: tmp, + } + const run = (args: string[], timeout = 30_000) => + exec(executable, args, { cwd, env, timeout, windowsHide: true }) + + assert.match((await run(['--help'])).stdout, /\$ socket /u) + assert.equal( + (await run(['--version'])).stdout.trim().split(/\s+/u)[0], + version, + ) + + if (capabilities.available.includes('socket-patch')) { + const { stdout } = await run(['patch', '--version']) + assert.equal(stdout.trim(), `socket-patch ${patchVersion}`) + } + const { stdout } = await run(['sea', 'smoke-test']) + assert.match(stdout, /^VFS smoke test passed$/mu) + await fs.writeFile( + path.join(cwd, 'NuGet.Config'), + '', + ) + await fs.writeFile( + path.join(cwd, 'Smoke.csproj'), + 'net8.0true', + ) + await run(['manifest', 'dotnet', 'Smoke.csproj'], 60_000) + const facts = JSON.parse( + await fs.readFile(path.join(cwd, 'Smoke.csproj.socket.facts.json'), 'utf8'), + ) + assert.equal(facts.metadata.tool, 'dotnet') + assert.ok( + facts.projects.some( + (project: { id: string }) => project.id === 'Smoke.csproj', + ), + ) + + assert.deepEqual( + (await fs.readdir(tmp)).filter( + name => + name.startsWith('socket-cli-sea-') || + name.startsWith('socket-dotnet-facts-'), + ), + [], + ) + + const cdxgen = capabilities.unavailable.find( + tool => tool.id === 'manifest-cdxgen-npm-lock-v3' || tool.id === 'cdxgen', + ) + if (cdxgen) { + await fs.writeFile( + path.join(cwd, 'package.json'), + '{"name":"smoke","version":"1.0.0"}', + ) + await fs.writeFile( + path.join(cwd, 'package-lock.json'), + '{"lockfileVersion":3,"packages":{}}', + ) + await assert.rejects( + run(['manifest', 'cdxgen', '--type', 'npm']), + (err: Error & { code?: number; stderr?: string }) => + err.code === 1 && Boolean(err.stderr?.includes(cdxgen.reason)), + ) + } +} diff --git a/src/sea/pnpm-lock.mts b/src/sea/pnpm-lock.mts index ab1937097f..2760458a6b 100644 --- a/src/sea/pnpm-lock.mts +++ b/src/sea/pnpm-lock.mts @@ -1,3 +1,6 @@ +import { readFile } from 'node:fs/promises' +import path from 'node:path' + import { parse, parseAllDocuments } from 'yaml' interface PnpmLockPackage { @@ -30,6 +33,9 @@ export function parsePnpmLock( ): PnpmLock { const packageDocuments: PnpmLock[] = [] for (const document of parseAllDocuments(source)) { + if (document.errors.length) { + throw document.errors[0] + } const value = document.toJS() as PnpmLock | undefined const packages = value?.packages if (!packages || typeof packages !== 'object' || Array.isArray(packages)) { @@ -81,6 +87,23 @@ function hasProjectDependencies(lockfile: PnpmLock): boolean { ) } +export async function readPnpmLock( + root: string, + lockfile = 'pnpm-lock.yaml', +): Promise { + const source = await readFile(path.join(root, lockfile), 'utf8') + const workspace = await readFile( + path.join(root, 'pnpm-workspace.yaml'), + 'utf8', + ).catch((error: NodeJS.ErrnoException) => { + if (error.code === 'ENOENT') { + return undefined + } + throw error + }) + return parsePnpmLock(source, workspace) +} + export function findLockedPackageIntegrity( source: string, packageName: string, diff --git a/src/sea/rollup-provenance.mjs b/src/sea/rollup-provenance.mjs index fc21113606..188edeb54e 100644 --- a/src/sea/rollup-provenance.mjs +++ b/src/sea/rollup-provenance.mjs @@ -4,7 +4,7 @@ import { promises as fs } from 'node:fs' import path from 'node:path' import url from 'node:url' -import { parsePnpmLock } from './pnpm-lock.mts' +import { readPnpmLock } from './pnpm-lock.mts' const legalFilenamePattern = /^(?:license|licence|copying|copyright|notice|patents?)(?:[._ -].*)?$/i @@ -518,10 +518,7 @@ function serializeInventory(records, { bundleId, lockfilePath }) { } async function readLock(root, lockfilePath) { - const lock = parsePnpmLock( - await fs.readFile(path.join(root, lockfilePath), 'utf8'), - await fs.readFile(path.join(root, 'pnpm-workspace.yaml'), 'utf8'), - ) + const lock = await readPnpmLock(root, lockfilePath) if (!lock || typeof lock.packages !== 'object' || !lock.packages) { throw new Error( `Lockfile does not contain a packages graph: ${lockfilePath}`, diff --git a/src/sea/vfs-digest.mts b/src/sea/vfs-digest.mts new file mode 100644 index 0000000000..c7f6407522 --- /dev/null +++ b/src/sea/vfs-digest.mts @@ -0,0 +1,29 @@ +import { createHash } from 'node:crypto' +import { readFileSync, readdirSync, statSync } from 'node:fs' +import path from 'node:path' + +/** Hash the paths, directory entries, and bytes that the runtime can read. */ +export function digestVfs(root: string, entries: string[]): string { + const hash = createHash('sha256') + function visit(relative: string): void { + const filename = path.join(root, relative) + const stat = statSync(filename) + if (stat.isDirectory()) { + hash.update(JSON.stringify(['dir', relative])) + for (const name of readdirSync(filename).sort()) { + visit(`${relative}/${name}`) + } + } else if (stat.isFile()) { + const digest = createHash('sha256') + .update(readFileSync(filename)) + .digest('hex') + hash.update(JSON.stringify(['file', relative, digest])) + } else { + throw new Error(`Unexpected VFS entry ${relative}`) + } + } + for (const entry of [...entries].sort()) { + visit(entry) + } + return hash.digest('hex') +} diff --git a/src/utils/pnpm.mts b/src/utils/pnpm.mts index 4176c6bb73..75e3219454 100644 --- a/src/utils/pnpm.mts +++ b/src/utils/pnpm.mts @@ -5,8 +5,8 @@ import semver from 'semver' import { readFileUtf8 } from './fs.mts' import { isRecord } from './objects.mts' -import { idToNpmPurl } from './spec.mts' import { stripBom } from './strings.mts' +import { idToNpmPurl } from './spec.mts' import type { LockfileObject, PackageSnapshot } from '@pnpm/lockfile.fs' import type { SemVer } from 'semver' @@ -60,28 +60,24 @@ export function isPnpmDepPath(maybeDepPath: string): boolean { export function parsePnpmLockfile( lockfileContent: unknown, ): LockfileObject | null { - let result: unknown + let result if (typeof lockfileContent === 'string') { try { const documents = loadAll(stripBom(lockfileContent)).filter(isRecord) - result = documents.findLast(hasProjectDependencies) ?? documents.at(-1) + // pnpm 12 places package-manager metadata before the project graph. + result = + documents.find( + doc => + !Object.values(doc['importers'] ?? {}).some( + importer => + isRecord(importer) && + ('packageManagerDependencies' in importer || + 'configDependencies' in importer), + ), + ) ?? documents.at(-1) } catch {} } - return isRecord(result) ? (result as unknown as LockfileObject) : null -} - -function hasProjectDependencies(document: Record): boolean { - const importers = document['importers'] - if (!isRecord(importers)) { - return false - } - return Object.values(importers).some( - importer => - isRecord(importer) && - ['dependencies', 'devDependencies', 'optionalDependencies'].some( - key => isRecord(importer[key]) && Object.keys(importer[key]).length > 0, - ), - ) + return isRecord(result) ? (result as LockfileObject) : null } export function parsePnpmLockfileVersion(version: unknown): SemVer | undefined { diff --git a/test/lib/native/cli-harness.mts b/test/lib/native/cli-harness.mts index 62fa21e864..3e1b5776d1 100644 --- a/test/lib/native/cli-harness.mts +++ b/test/lib/native/cli-harness.mts @@ -5,12 +5,12 @@ import { createTerminal } from '@termless/core' import { createXtermBackend } from '@termless/xtermjs' import { expect, onTestFinished } from 'vitest' +import { normalizeBackendOutput } from '../terminal/output.mts' import { captureCheckpoint, createRecording, expectTerminalAnimation, } from '../termless/animation.mts' -import { normalizeBackendOutput } from '../terminal/output.mts' export interface NativeTestEnvironment { readonly binary: string @@ -131,12 +131,16 @@ export async function captureFlow(options: { cwd: fixture.cwd, env: nativeSpawnEnvironment(args, env), }) - await fixture.terminal.waitFor(expectedText, 30_000) - await fixture.terminal.waitForStable(200, 30_000) + // These commands exit on their own. Poll the process before reading the full + // terminal so a missing diagnostic is reported with the actual exit and screen. await expect - .poll(() => fixture.terminal.exitInfo, { timeout: 30_000 }) - .toBe(`exit=${exitCode}`) + .poll(() => fixture.terminal.exitInfo, { timeout: 50_000 }) + .not.toBeNull() + await fixture.terminal.waitForStable(200, 5_000) fixture.normalizer.flush() + expect(fixture.terminal.exitInfo, fixture.terminal.screen.getText()).toBe( + `exit=${exitCode}`, + ) expect(fixture.terminal.scrollback.getText().trim()).toBe('') expect(fixture.terminal.screen.getText()).toContain(expectedText) const checkpoint = await captureCheckpoint( diff --git a/test/native-launcher.test.mts b/test/native-launcher.test.mts new file mode 100644 index 0000000000..0b6bca0b6d --- /dev/null +++ b/test/native-launcher.test.mts @@ -0,0 +1,109 @@ +import { execFile, spawn } from 'node:child_process' +import { once } from 'node:events' +import { copyFile, mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises' +import os from 'node:os' +import path from 'node:path' +import { promisify } from 'node:util' + +import { afterEach, beforeEach, describe, expect, it } from 'vitest' + +const run = promisify(execFile) +const name = `@socketsecurity/socket-cli-${process.platform}-${process.arch}` +const version = '2.1.0-rc.0' +describe('installed native launcher', () => { + let root: string + let launcher: string + let platform: string + + beforeEach(async () => { + root = await mkdtemp(path.join(os.tmpdir(), 'socket launcher ')) + const modules = path.join(root, 'node_modules') + const app = path.join(modules, 'socket') + platform = path.join(modules, name) + await mkdir(app, { recursive: true }) + await mkdir(platform, { recursive: true }) + launcher = path.join(app, 'socket.cjs') + await copyFile( + new URL('../scripts/release/native-launcher.cjs', import.meta.url), + launcher, + ) + await writeFile( + path.join(app, 'package.json'), + JSON.stringify({ + name: 'socket', + version, + optionalDependencies: { [name]: version }, + }), + ) + await writeFile( + path.join(platform, 'package.json'), + JSON.stringify({ name, version }), + ) + if (process.platform === 'win32') { + await copyFile( + path.join(process.env['SystemRoot']!, 'System32', 'cmd.exe'), + path.join(platform, 'socket.exe'), + ) + } else { + await writeFile( + path.join(platform, 'socket'), + '#!/bin/sh\nexec /bin/sh "$@"\n', + { mode: 0o755 }, + ) + } + }) + + afterEach(async () => { + await rm(root, { recursive: true, force: true }) + }) + + it('uses the matching hoisted package and preserves its exit code', async () => { + const args = + process.platform === 'win32' ? ['/d', '/c', 'exit 37'] : ['-c', 'exit 37'] + await expect( + run(process.execPath, [launcher, ...args]), + ).rejects.toMatchObject({ code: 37 }) + }) + + it('rejects a different hoisted version before starting it', async () => { + await writeFile( + path.join(platform, 'package.json'), + JSON.stringify({ name, version: '2.1.0-rc.1' }), + ) + await expect( + run(process.execPath, [launcher, 'unused']), + ).rejects.toMatchObject({ + stderr: expect.stringContaining(`Expected ${name}@${version}`), + }) + }) + + it.skipIf(process.platform === 'win32').each(['host', 'without execve'])( + 'passes a targeted termination signal to the running executable (%s)', + async mode => { + // A service supervisor signals the launcher PID directly (no terminal group). + const options = [] + if (mode === 'without execve') { + const preload = path.join(root, 'old-node.cjs') + await writeFile(preload, 'process.execve = undefined') + options.push('--require', preload) + } + const child = spawn( + process.execPath, + [...options, launcher, '-c', 'printf "%s\\n" "$$"; exec sleep 20'], + { stdio: ['ignore', 'pipe', 'pipe'] }, + ) + const exited = once(child, 'exit') + const [output] = await once(child.stdout, 'data') + const nativePid = Number(String(output).trim()) + try { + child.kill('SIGTERM') + await expect(exited).resolves.toEqual([null, 'SIGTERM']) + expect(() => process.kill(nativePid, 0)).toThrow() + } finally { + try { + process.kill(nativePid, 'SIGKILL') + } catch {} + } + }, + ) +}) diff --git a/test/native/commands/cli.native.test.mts b/test/native/commands/cli.native.test.mts index 6eb646c134..9798b389a3 100644 --- a/test/native/commands/cli.native.test.mts +++ b/test/native/commands/cli.native.test.mts @@ -22,7 +22,7 @@ import { const binary = process.env['SOCKET_CLI_NATIVE_TEST_BINARY'] if (!binary) { - throw new Error('Use pnpm test:native to run native CLI tests') + throw new Error('Use pnpm test:sea to run native CLI tests') } const snapshotDir = path.join(process.cwd(), 'test/snapshots/termless') diff --git a/test/native/commands/tui.native.test.mts b/test/native/commands/tui.native.test.mts index ba72602630..28c0831e20 100644 --- a/test/native/commands/tui.native.test.mts +++ b/test/native/commands/tui.native.test.mts @@ -12,7 +12,7 @@ import { const binary = process.env['SOCKET_CLI_NATIVE_TEST_BINARY'] if (!binary) { - throw new Error('Use pnpm test:native to run native CLI tests') + throw new Error('Use pnpm test:sea to run native CLI tests') } const snapshotDir = path.join(process.cwd(), 'test/snapshots/termless') diff --git a/test/package-matrix.test.mts b/test/package-matrix.test.mts index 3dc7a52c61..86ecbc3bec 100644 --- a/test/package-matrix.test.mts +++ b/test/package-matrix.test.mts @@ -1,4 +1,11 @@ -import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises' +import { + mkdir, + mkdtemp, + readFile, + rm, + symlink, + writeFile, +} from 'node:fs/promises' import { createRequire } from 'node:module' import os from 'node:os' import path from 'node:path' @@ -18,12 +25,6 @@ import { verifyPrivateVirtualStore, } from '../scripts/build-package-matrix.mts' -const packageManager = ( - JSON.parse( - await readFile(new URL('../package.json', import.meta.url), 'utf8'), - ) as { packageManager: string } -).packageManager - function tarEntry(name: string, contents: string): Buffer { const data = Buffer.from(contents) const header = Buffer.alloc(512) @@ -59,11 +60,13 @@ describe('package matrix helpers', () => { }) it('defines the four stable and prerelease package variants', () => { - expect(makeVariants('2.1.0-rc.3').map(({ artifact }) => artifact)).toEqual([ - 'socket-1.14.1.tgz', + expect( + makeVariants('1.16.0', '2.1.0-rc.3').map(({ artifact }) => artifact), + ).toEqual([ + 'socket-1.16.0.tgz', 'socket-2.1.0-rc.3.tgz', - '@socketsecurity-cli-1.14.1.tgz', - '@socketsecurity-cli-with-sentry-1.14.1.tgz', + '@socketsecurity-cli-1.16.0.tgz', + '@socketsecurity-cli-with-sentry-1.16.0.tgz', ]) }) @@ -87,16 +90,57 @@ describe('package matrix helpers', () => { expect(() => validatePackagedManifest( { ...manifest, bin: { socket: 'wrong.js' } }, - makeVariants('2.1.0-rc.0')[0]!, + makeVariants('1.14.1', '2.1.0-rc.0')[0]!, ), ).toThrow('CLI bin map mismatch') expect(() => - validatePackagedManifest(manifest, makeVariants('2.1.0-rc.0')[0]!), + validatePackagedManifest( + manifest, + makeVariants('1.14.1', '2.1.0-rc.0')[0]!, + ), ).not.toThrow() }) + it('requires the native launcher and exact platform pins for the RC', () => { + const variant = makeVariants('1.14.1', '2.1.0-rc.3')[1]! + const manifest = { + name: 'socket', + version: variant.version, + bin: { socket: 'socket.cjs' }, + optionalDependencies: { + '@socketsecurity/socket-cli-darwin-arm64': variant.version, + '@socketsecurity/socket-cli-linux-arm64': variant.version, + '@socketsecurity/socket-cli-linux-x64': variant.version, + '@socketsecurity/socket-cli-win32-arm64': variant.version, + '@socketsecurity/socket-cli-win32-x64': variant.version, + }, + } + expect(() => validatePackagedManifest(manifest, variant)).not.toThrow() + expect(() => + validatePackagedManifest( + { + ...manifest, + bin: { socket: 'bin/cli.js' }, + }, + variant, + ), + ).toThrow('CLI bin map mismatch') + expect(() => + validatePackagedManifest( + { + ...manifest, + optionalDependencies: { + ...manifest.optionalDependencies, + '@socketsecurity/socket-cli-linux-x64': 'latest', + }, + }, + variant, + ), + ).toThrow('optional dependencies mismatch') + }) + it('validates the legacy CLI bin alias on the scoped package', () => { - const variant = makeVariants('2.1.0-rc.0')[2]! + const variant = makeVariants('1.14.1', '2.1.0-rc.0')[2]! const standardBins = { socket: 'bin/cli.js', 'socket-npm': 'bin/npm-cli.js', @@ -116,34 +160,42 @@ describe('package matrix helpers', () => { ).not.toThrow() }) - it('requires pnpm to keep its virtual store inside the private workspace', () => { - const workspace = '/tmp/private-package-workspace' - expect(() => validatePrivateVirtualStore(workspace, '.pnpm')).not.toThrow() - expect(() => - validatePrivateVirtualStore( - workspace, - '../../../../shared/pnpm/store/links', - ), - ).toThrow('pnpm virtual store escaped the private workspace') - }) + it('accepts workspace aliases and rejects redirected virtual stores', async () => { + const directory = await mkdtemp(path.join(os.tmpdir(), 'matrix-paths-')) + const workspace = path.join(directory, 'workspace') + const alias = path.join(directory, 'alias') + const store = path.join(workspace, 'node_modules', '.pnpm') + const shared = path.join(directory, 'shared') + try { + await mkdir(store, { recursive: true }) + await mkdir(shared) + await symlink(workspace, alias, 'junction') + await expect( + validatePrivateVirtualStore(alias, store), + ).resolves.toBeUndefined() + await expect( + validatePrivateVirtualStore(alias, '.pnpm'), + ).resolves.toBeUndefined() + await expect(validatePrivateVirtualStore(alias, shared)).rejects.toThrow( + 'pnpm virtual store escaped the private workspace', + ) - it.skipIf(process.platform !== 'win32')( - 'accepts Windows paths with different letter casing', - () => { - expect(() => - validatePrivateVirtualStore( - 'C:\\Users\\runneradmin\\AppData\\Local\\Temp\\matrix-private-pnpm-test', - 'c:\\users\\RUNNERADMIN\\AppData\\Local\\Temp\\matrix-private-pnpm-test\\node_modules\\.pnpm', - ), - ).not.toThrow() - }, - ) + await rm(store, { recursive: true }) + await symlink(shared, store, 'junction') + await expect(validatePrivateVirtualStore(alias, '.pnpm')).rejects.toThrow( + 'pnpm virtual store escaped the private workspace', + ) + } finally { + await rm(directory, { recursive: true, force: true }) + } + }) it('keeps a nested pnpm install local despite user-level global-store settings', async () => { - const workspace = await mkdtemp( + const directory = await mkdtemp( path.join(os.tmpdir(), 'matrix-private-pnpm-test-'), ) - const userConfig = path.join(workspace, 'user.npmrc') + const workspace = path.join(directory, 'workspace') + await mkdir(workspace) const fixturePackage = path.join(workspace, 'fixture-package') await mkdir(fixturePackage) await writeFile( @@ -159,17 +211,27 @@ describe('package matrix helpers', () => { JSON.stringify({ name: 'matrix-private-pnpm-test', version: '1.0.0', - packageManager, dependencies: { 'matrix-local-fixture': 'file:./fixture-package' }, }), ) + const userConfig = path.join(directory, 'user.npmrc') await writeFile(path.join(workspace, '.npmrc'), 'audit=false\n') await writeFile(userConfig, 'enable-global-virtual-store=true\n') - const env = createPrivatePnpmEnvironment(workspace, { + const userEnv = { ...process.env, + pnpm_config_cache_dir: path.join(directory, 'cache'), + pnpm_config_store_dir: path.join(directory, 'shared-store'), + pnpm_config_enable_global_virtual_store: 'true', npm_config_userconfig: userConfig, NPM_CONFIG_USERCONFIG: userConfig, - }) + } + const env = createPrivatePnpmEnvironment(workspace, userEnv) + const nestedInstall = [ + 'install', + '--offline', + '--frozen-lockfile=false', + '--config.confirmModulesPurge=false', + ] try { run( workspace, @@ -178,30 +240,22 @@ describe('package matrix helpers', () => { 'install', '--offline', '--ignore-scripts', - '--pm-on-fail=ignore', '--config.enable-global-virtual-store=false', '--virtual-store-dir=node_modules/.pnpm', ], env, ) await verifyPrivateVirtualStore(workspace) - run( - workspace, - 'pnpm', - [ - 'install', - '--offline', - '--frozen-lockfile=false', - '--pm-on-fail=ignore', - '--config.confirmModulesPurge=false', - '--config.enable-global-virtual-store=false', - '--virtual-store-dir=node_modules/.pnpm', - ], - env, - ) + run(workspace, 'pnpm', nestedInstall, env) await verifyPrivateVirtualStore(workspace) + + // Prove the same install escapes when the private environment is omitted. + run(workspace, 'pnpm', nestedInstall, userEnv) + await expect(verifyPrivateVirtualStore(workspace)).rejects.toThrow( + 'pnpm virtual store escaped the private workspace', + ) } finally { - await rm(workspace, { recursive: true, force: true }) + await rm(directory, { recursive: true, force: true }) } }, 30_000) diff --git a/test/release-approve-npm.test.mts b/test/release-approve-npm.test.mts index 4b54c4aa46..e01c12886a 100644 --- a/test/release-approve-npm.test.mts +++ b/test/release-approve-npm.test.mts @@ -1,40 +1,79 @@ import { describe, expect, it } from 'vitest' import { - packageSetForVersion, pnpmStageInvocation, stageActionForStatus, validateStage, } from '../scripts/release/approve-npm.mts' import { releasePackagesForVersion } from '../scripts/release/packages.mts' +const policy = { + mode: 'prerelease-only', + identifier: 'rc', + versionHint: '2.1.0', + distTag: 'rc-2.1.0', +} as const + const id = '12345678-1234-4123-8123-123456789abc' describe('npm stage approval', () => { it('validates stage identity and supported release package names', () => { expect( validateStage( - { id, packageName: 'socket', version: '1.14.2', status: 'staged' }, + { + id, + packageName: 'socket', + version: '1.14.2', + tag: 'latest', + status: 'staged', + }, id, + policy, ), ).toEqual({ name: 'socket', version: '1.14.2' }) expect(() => - validateStage({ id, packageName: 'other', version: '1.14.2' }, id), + validateStage( + { id, packageName: 'other', version: '1.14.2' }, + id, + policy, + ), ).toThrow('Unexpected npm package') expect(() => - validateStage({ id, packageName: 'socket', version: 'bad' }, id), + validateStage({ id, packageName: 'socket', version: 'bad' }, id, policy), ).toThrow('stage ID, package, or version is invalid') expect(() => validateStage( { id, packageName: '@socketsecurity/cli', version: '2.1.0-rc.2' }, id, + policy, ), - ).toThrow('Prerelease stages may only contain the socket package') + ).toThrow('Unexpected npm package') + }) + + it('checks the immutable npm tag for each prerelease package before approval', () => { + for (const packageName of releasePackagesForVersion('2.1.0-rc.2')) { + const stage = { + id, + packageName, + version: '2.1.0-rc.2', + status: 'awaiting_approval', + } + expect(validateStage({ ...stage, tag: 'rc-2.1.0' }, id, policy)).toEqual({ + name: packageName, + version: stage.version, + }) + for (const tag of ['latest', undefined]) { + expect(() => validateStage({ ...stage, tag }, id, policy)).toThrow( + 'Expected npm stage dist-tag rc-2.1.0', + ) + } + } }) it('maps npm states to safe retry, approval, finalization, and burn actions', () => { expect(stageActionForStatus('validating')).toBe('wait') expect(stageActionForStatus('staged')).toBe('approve') + expect(stageActionForStatus('awaiting_approval')).toBe('approve') expect(stageActionForStatus('published')).toBe('finalize') expect(stageActionForStatus('blocked')).toBe('burned') expect(stageActionForStatus('deleted')).toBe('burned') @@ -43,21 +82,28 @@ describe('npm stage approval', () => { ) }) - it('waits for every stable package but only socket for prereleases', () => { + it('waits for every stable package but all native packages for prereleases', () => { expect(releasePackagesForVersion('1.14.2')).toEqual([ 'socket', '@socketsecurity/cli', '@socketsecurity/cli-with-sentry', ]) - expect(releasePackagesForVersion('2.1.0-rc.2')).toEqual(['socket']) + expect(releasePackagesForVersion('2.1.0-rc.2')).toEqual([ + 'socket', + '@socketsecurity/socket-cli-darwin-arm64', + '@socketsecurity/socket-cli-linux-arm64', + '@socketsecurity/socket-cli-linux-x64', + '@socketsecurity/socket-cli-win32-arm64', + '@socketsecurity/socket-cli-win32-x64', + ]) }) - it('uses pnpm 12 for stage commands when the workspace pnpm is older', () => { + it('uses the pinned pnpm for stage commands', () => { expect(pnpmStageInvocation('10.33.0', ['stage', 'view', id])).toEqual({ command: 'corepack', - args: ['pnpm@12.21.0', '--pm-on-fail=ignore', 'stage', 'view', id], + args: ['pnpm@12.23.0', '--pm-on-fail=ignore', 'stage', 'view', id], }) - expect(pnpmStageInvocation('11.17.0', ['stage', 'view', id])).toEqual({ + expect(pnpmStageInvocation('12.23.0', ['stage', 'view', id])).toEqual({ command: 'pnpm', args: ['stage', 'view', id], }) diff --git a/test/release-artifact-download.test.mts b/test/release-artifact-download.test.mts index 3d72427974..606e88e451 100644 --- a/test/release-artifact-download.test.mts +++ b/test/release-artifact-download.test.mts @@ -28,6 +28,7 @@ const workflow = parse( jobs: { verify: { steps: DownloadStep[] } publish: { steps: DownloadStep[] } + rehearse: { steps: DownloadStep[] } } } const download = workflow.jobs.verify.steps.find( @@ -53,45 +54,50 @@ function downloadFixture(names = filenames) { } const archive = path.join(root, 'fixture.zip') if (process.platform === 'win32') { - execFileSync('powershell.exe', [ - '-NoProfile', - '-NonInteractive', - '-Command', - `Compress-Archive -Path '${path.join(source, '*')}' -DestinationPath '${archive}' -Force`, - ]) + execFileSync( + path.join(process.env['SystemRoot']!, 'System32', 'tar.exe'), + ['-a', '-cf', archive, ...names], + { cwd: source }, + ) } else { - execFileSync('zip', ['-q', '-0', archive, ...names], { cwd: source }) + execFileSync('zip', ['-q', archive, ...names], { cwd: source }) } const metadata = path.join(root, 'fixture.json') writeFileSync( metadata, JSON.stringify({ workflow_run: { id: 123 }, - name: 'npm-release-tarballs', + name: 'npm-release-tarballs-1', expired: false, }), ) + writeFileSync( + path.join(bin, 'fake-gh.cjs'), + `const fs = require('node:fs') +const endpoint = process.argv[3] +const id = endpoint.match(/artifacts\\/(\\d+)/)[1] +const fixture = JSON.parse(process.env.ARTIFACT_FIXTURES)[id] +process.stdout.write(fs.readFileSync(endpoint.endsWith('/zip') ? fixture.archive : fixture.metadata)) +`, + ) writeFileSync( path.join(bin, 'gh'), - '#!/bin/sh\ncase "$2" in */zip) cat "$FIXTURE_ARCHIVE";; *) cat "$FIXTURE_METADATA";; esac\n', + '#!/bin/sh\nexec node "$(dirname "$0")/fake-gh.cjs" "$@"\n', { mode: 0o700 }, ) const env = { ...process.env, PATH: `${bin}${path.delimiter}${process.env['PATH'] ?? ''}`, - ARTIFACT_ID: '456', - ARTIFACT_DIGEST: createHash('sha256') - .update(readFileSync(archive)) - .digest('hex'), + ROOT_RECEIPT: + '456:' + createHash('sha256').update(readFileSync(archive)).digest('hex'), DIST_DIRECTORY: destination, - FIXTURE_ARCHIVE: archive, - FIXTURE_METADATA: metadata, + ARTIFACT_FIXTURES: JSON.stringify({ 456: { archive, metadata } }), GITHUB_REPOSITORY: 'fixture/release-cli', GITHUB_RUN_ID: '123', RUNNER_TEMP: root, VERSION: '1.2.3', } - return { destination, env, metadata } + return { destination, env, metadata, archive } } afterEach(() => { @@ -100,15 +106,78 @@ afterEach(() => { } }) +const collect = (steps: DownloadStep[]) => + steps.find(step => step.name === 'Download verified tarballs') + describe('verified release artifact download', () => { - it('uses the same download implementation in verification and publishing', () => { - expect( - workflow.jobs.publish.steps.find( - step => step.name === 'Download verified tarballs', - )?.run, - ).toBe(download) + it('rehearses the same checkout-free artifact collection used for staging', () => { + expect(collect(workflow.jobs.rehearse.steps)).toEqual( + collect(workflow.jobs.publish.steps), + ) + expect(collect(workflow.jobs.publish.steps)?.run).toContain( + '.github/scripts/download-release-artifacts.mts', + ) }) + it('requires all platform receipts before collecting an RC', () => { + const fixture = downloadFixture(['socket-2.1.0-rc.0.tgz']) + const result = spawnSync('bash', ['-c', download], { + env: { ...fixture.env, VERSION: '2.1.0-rc.0', NATIVE_RECEIPTS: '{}' }, + encoding: 'utf8', + }) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('Platform upload receipts') + }) + + it( + 'collects the tested launcher and all five independently uploaded platform packages', + { timeout: 30_000 }, + () => { + const version = '2.1.0-rc.0' + const launcher = `socket-${version}.tgz` + const fixture = downloadFixture([launcher]) + const artifacts = JSON.parse(fixture.env.ARTIFACT_FIXTURES) + const receipts: Record = {} + const expected = [launcher] + for (const [i, target] of [ + 'darwin-arm64', + 'linux-arm64', + 'linux-x64', + 'win32-arm64', + 'win32-x64', + ].entries()) { + const filename = `socketsecurity-socket-cli-${target}-${version}.tgz` + const platform = downloadFixture([filename]) + const id = String(500 + i) + writeFileSync( + platform.metadata, + JSON.stringify({ + workflow_run: { id: 123 }, + name: `native-${target}-2`, + expired: false, + }), + ) + artifacts[id] = { + archive: platform.archive, + metadata: platform.metadata, + } + receipts[target] = platform.env.ROOT_RECEIPT.replace(/^456:/u, `${id}:`) + expected.push(filename) + } + const result = spawnSync('bash', ['-c', download], { + env: { + ...fixture.env, + VERSION: version, + ARTIFACT_FIXTURES: JSON.stringify(artifacts), + NATIVE_RECEIPTS: JSON.stringify(receipts), + }, + encoding: 'utf8', + }) + expect(result.status, result.stderr).toBe(0) + expect(readdirSync(fixture.destination).sort()).toEqual(expected.sort()) + }, + ) + it('downloads and extracts the three verified tarballs', () => { const fixture = downloadFixture() const result = spawnSync('bash', ['-c', download], { @@ -126,7 +195,7 @@ describe('verified release artifact download', () => { it('refuses altered archive bytes', () => { const fixture = downloadFixture() - fixture.env.ARTIFACT_DIGEST = '0'.repeat(64) + fixture.env.ROOT_RECEIPT = '456:' + '0'.repeat(64) expect( spawnSync('bash', ['-c', download], { env: fixture.env }).status, ).not.toBe(0) diff --git a/test/release-availability.test.mts b/test/release-availability.test.mts index 9551eb3934..cc4f27df89 100644 --- a/test/release-availability.test.mts +++ b/test/release-availability.test.mts @@ -29,13 +29,20 @@ describe('npm release availability', () => { expect(wait).toHaveBeenCalledOnce() }) - it('waits for all stable package versions and only socket for prereleases', async () => { + it('waits for all stable package versions and all native packages for prereleases', async () => { expect(releasePackagesForVersion('1.14.2')).toEqual([ 'socket', '@socketsecurity/cli', '@socketsecurity/cli-with-sentry', ]) - expect(releasePackagesForVersion('2.1.0-rc.2')).toEqual(['socket']) + expect(releasePackagesForVersion('2.1.0-rc.2')).toEqual([ + 'socket', + '@socketsecurity/socket-cli-darwin-arm64', + '@socketsecurity/socket-cli-linux-arm64', + '@socketsecurity/socket-cli-linux-x64', + '@socketsecurity/socket-cli-win32-arm64', + '@socketsecurity/socket-cli-win32-x64', + ]) const fetcher = vi.fn( async () => new Response(null, { status: 200 }), diff --git a/test/release-registry.test.mts b/test/release-registry.test.mts index e6e6053867..cde5ff008a 100644 --- a/test/release-registry.test.mts +++ b/test/release-registry.test.mts @@ -32,7 +32,7 @@ describe('release registry preflight', () => { } }) - it('checks only socket for the configured prerelease track', async () => { + it('checks native packages for the configured prerelease track', async () => { const fetcher = vi.fn( async () => new Response('', { status: 404 }), ) @@ -43,8 +43,18 @@ describe('release registry preflight', () => { identifier: 'rc', distTag: 'rc-2.1.0', }), - ).resolves.toEqual({ packages: ['socket'], version: '2.1.0-rc.2' }) - expect(fetcher).toHaveBeenCalledTimes(1) + ).resolves.toEqual({ + packages: [ + 'socket', + '@socketsecurity/socket-cli-darwin-arm64', + '@socketsecurity/socket-cli-linux-arm64', + '@socketsecurity/socket-cli-linux-x64', + '@socketsecurity/socket-cli-win32-arm64', + '@socketsecurity/socket-cli-win32-x64', + ], + version: '2.1.0-rc.2', + }) + expect(fetcher).toHaveBeenCalledTimes(6) expect(fetcher.mock.calls[0]?.[0]).toBe( 'https://registry.npmjs.org/socket/2.1.0-rc.2', ) diff --git a/test/release-workflow.test.mts b/test/release-workflow.test.mts index 02eff17537..1ab5030a46 100644 --- a/test/release-workflow.test.mts +++ b/test/release-workflow.test.mts @@ -88,8 +88,10 @@ describe('v1 release workflow contract', () => { .map(step => step.run ?? '') expect(scripts.join('\n')).not.toMatch(/promote\.mts|git push/) expect(Object.keys(workflow.jobs).sort()).toEqual([ + 'native-packages', 'prepare', 'publish', + 'rehearse', 'release-pr', 'verify', ]) @@ -124,7 +126,7 @@ describe('v1 release workflow contract', () => { ) const verify = steps[verifyIndex] expect(verify?.if).toBe('${{ inputs.dry-run == false }}') - expect(verify?.run).toContain('.commit.verification.verified') + expect(verify?.run).toContain('verify-release.mts" commit') expect(verifyIndex).toBe(checkoutIndex + 1) }) @@ -133,8 +135,7 @@ describe('v1 release workflow contract', () => { step => step.name === 'Stage release packages', ) expect(stage?.run).toContain('--json') - expect(stage?.run).toContain('stageId') - expect(stage?.run).toContain('output.search(/^(?:\\{|\\[)/mu)') + expect(stage?.run).toContain('verify-release.mts" stage-output') expect(stage?.run).toContain('pnpm run approve:npm ') const tag = workflow.jobs.publish.steps.find( step => step.name === 'Reserve release tag once', @@ -149,12 +150,6 @@ describe('v1 release workflow contract', () => { }) it('parses npm stage JSON after pnpm progress output', () => { - const stage = workflow.jobs.publish.steps.find( - step => step.name === 'Stage release packages', - ) - const parser = stage?.run?.split("<<'NODE'\n")[1]?.split('\nNODE')[0] - expect(parser).toBeDefined() - const directory = mkdtempSync(path.join(tmpdir(), 'npm-stage-output-')) const outputPath = path.join(directory, 'output.json') const summaryPath = path.join(directory, 'summary.md') @@ -165,6 +160,7 @@ describe('v1 release workflow contract', () => { outputPath, [ 'GET https://example.invalid/idtoken 200 193ms', + '[WARN] Registry request was retried', 'Staging socket@2.1.0-rc.0', JSON.stringify({ socket: { @@ -176,11 +172,13 @@ describe('v1 release workflow contract', () => { '', ].join('\n'), ) - execFileSync( - process.execPath, - ['--input-type=module', '-', outputPath, summaryPath, tarballPath], - { input: parser }, - ) + execFileSync(process.execPath, [ + '.github/scripts/verify-release.mts', + 'stage-output', + outputPath, + summaryPath, + tarballPath, + ]) expect(readFileSync(summaryPath, 'utf8')).toContain(stageId) } finally { rmSync(directory, { recursive: true, force: true }) @@ -192,9 +190,7 @@ describe('v1 release workflow contract', () => { step => step.name === 'Stage release packages', ) expect(stage?.env?.VERSION).toBe('${{ needs.verify.outputs.version }}') - expect(stage?.run).toContain( - 'if [[ "$VERSION" == *-* ]]; then EXPECTED=1; fi', - ) + expect(stage?.run).toContain('verify-release.mts" tarball-count') expect(stage?.run).not.toContain('NPM_PRERELEASE_RELEASE') }) @@ -224,19 +220,19 @@ describe('v1 release workflow contract', () => { expect(finalize?.run).not.toContain('releases/tags/${TAG}') }) - it('publishes only socket for the configured prerelease policy', () => { + it('publishes the native CLI for the configured prerelease policy', () => { const verifySteps = workflow.jobs.verify.steps const versionGuard = verifySteps.find( - step => step.name === 'Validate release policy and choose npm dist-tag', + step => step.name === 'Resolve release metadata', ) const versionGuardIndex = verifySteps.findIndex( - step => step.name === 'Validate release policy and choose npm dist-tag', + step => step.name === 'Resolve release metadata', ) const buildIndex = verifySteps.findIndex( - step => step.name === 'Build Maven manifest extension jar', + step => step.name === 'Pack native launcher', ) expect(versionGuard).toBeDefined() - expect(versionGuard?.if).toBe('${{ inputs.dry-run == false }}') + expect(versionGuard?.if).toBeUndefined() expect(versionGuard?.run).toContain('validate-npm-policy.mts') expect(versionGuardIndex).toBeGreaterThanOrEqual(0) expect(versionGuardIndex).toBeLessThan(buildIndex) @@ -247,16 +243,17 @@ describe('v1 release workflow contract', () => { expect(prepareStep?.env?.SOCKET_CLI_RELEASE_MAJOR).toBe( '${{ inputs.release-major }}', ) - expect( - workflow.jobs.verify.steps.find( - step => step.name === 'Build and pack @socketsecurity/cli (legacy)', - )?.if, - ).toBe("${{ env.NPM_PRERELEASE_RELEASE != 'true' }}") - expect( - workflow.jobs.verify.steps.find( - step => step.name === 'Build and pack @socketsecurity/cli-with-sentry', - )?.if, - ).toBe("${{ env.NPM_PRERELEASE_RELEASE != 'true' }}") + const stable = verifySteps.find( + step => step.name === 'Build, pack, and smoke test stable packages', + ) + expect(stable?.if).toBe( + "${{ !contains(steps.release-meta.outputs.version, '-') }}", + ) + expect(stable?.run?.match(/^pack .+$/gmu)).toEqual([ + 'pack socket', + 'pack @socketsecurity/cli INLINED_SOCKET_CLI_LEGACY_BUILD=1', + 'pack @socketsecurity/cli-with-sentry INLINED_SOCKET_CLI_SENTRY_BUILD=1', + ]) const manifest = JSON.parse( readFileSync(new URL('../package.json', import.meta.url), 'utf8'), @@ -307,7 +304,7 @@ describe('v1 release workflow contract', () => { expect(workflow.jobs.verify.permissions['id-token']).toBeUndefined() expect(workflow.on.workflow_dispatch.inputs['dry-run']?.default).toBe(true) expect(workflow.jobs.publish.if).toBe( - "${{ inputs.mode == 'publish' && inputs.dry-run == false }}", + "${{ !cancelled() && needs.verify.result == 'success' && (needs.native-packages.result == 'success' || (!contains(needs.verify.outputs.version, '-') && needs.native-packages.result == 'skipped')) && inputs.mode == 'publish' && inputs.dry-run == false }}", ) }) diff --git a/test/setup-uv.test.mts b/test/setup-uv.test.mts index 57e36708fb..f6356d694a 100644 --- a/test/setup-uv.test.mts +++ b/test/setup-uv.test.mts @@ -258,7 +258,7 @@ it('installs uv after Node and before SFW shims through its registered script', const steps = workflow.jobs['e2e-tests']!.steps const node = steps.findIndex(step => step.name === 'Install Node.js') const uv = steps.findIndex(step => step.name === 'Install uv') - const shims = steps.findIndex(step => step.name === 'Create sfw shims') + const shims = steps.findIndex(step => step.name === 'Set up Socket Firewall') expect(node).toBeGreaterThanOrEqual(0) expect(uv).toBeGreaterThan(node) expect(shims).toBeGreaterThan(uv) diff --git a/test/unit/scripts/test/apple-signing.test.mts b/test/unit/scripts/test/apple-signing.test.mts index 22d869ba2d..6340940455 100644 --- a/test/unit/scripts/test/apple-signing.test.mts +++ b/test/unit/scripts/test/apple-signing.test.mts @@ -7,7 +7,7 @@ import { afterEach, describe, expect, it } from 'vitest' import { persistNativeSigningReceipt, prepareNativeTestBinary, -} from '../../../../scripts/test/apple-signing.mts' +} from '../../../../scripts/lib/apple-signing.mts' const dirs: string[] = [] afterEach(async () => { diff --git a/test/unit/sea/build-sea.test.mts b/test/unit/sea/build-sea.test.mts index 73caf45530..257f504624 100644 --- a/test/unit/sea/build-sea.test.mts +++ b/test/unit/sea/build-sea.test.mts @@ -1,5 +1,13 @@ import { execFile } from 'node:child_process' -import { mkdir, mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises' +import { + copyFile, + mkdir, + mkdtemp, + readFile, + rm, + stat, + writeFile, +} from 'node:fs/promises' import os from 'node:os' import path from 'node:path' import { fileURLToPath } from 'node:url' @@ -22,6 +30,7 @@ import { renderSeaReadme, updateSeaReadmeVersion, } from '../../../src/sea/readme-version.mts' +import { digestVfs } from '../../../src/sea/vfs-digest.mts' import { readSeaNodeVersion } from '../../utils/sea.mts' const execFileAsync = promisify(execFile) @@ -234,12 +243,22 @@ describe('SEA archive paths', () => { }) describe('SEA bootstrap Rollup config', () => { - it('compiles the TypeScript bootstrap through the real Rollup configuration', async () => { + it('smoke tests the packaged bootstrap and detects a changed payload', async () => { const directory = await mkdtemp( path.join(os.tmpdir(), 'sea-bootstrap-test-'), ) const output = path.join(directory, 'bootstrap.cjs') try { + const resources = path.join(directory, 'resources') + await mkdir(resources) + const payload = path.join(resources, 'payload') + await writeFile(payload, 'build') + await mkdir(path.join(directory, 'dist')) + await copyFile( + path.join(root, 'src/vendor/coana-cache.mjs'), + path.join(directory, 'dist/coana-cache.mjs'), + ) + const entries = ['resources', 'dist'] await execFileAsync( process.execPath, [ @@ -249,9 +268,24 @@ describe('SEA bootstrap Rollup config', () => { '--file', output, ], - { timeout: 30_000 }, + { + env: { + ...process.env, + SEA_SMOKE_TEST: JSON.stringify({ + digest: digestVfs(directory, entries), + }), + }, + timeout: 30_000, + }, ) - expect((await stat(output)).size).toBeGreaterThan(0) + const run = () => + execFileAsync(process.execPath, [output, 'sea', 'smoke-test']) + expect((await run()).stdout).toContain('VFS smoke test passed') + await writeFile(payload, 'other') + await expect(run()).rejects.toMatchObject({ + code: 1, + stderr: expect.stringContaining('Embedded VFS differs'), + }) } finally { await rm(directory, { recursive: true, force: true }) } diff --git a/test/upload-artifact.test.mts b/test/upload-artifact.test.mts index 5f1e3a2025..7e16dc9ed7 100644 --- a/test/upload-artifact.test.mts +++ b/test/upload-artifact.test.mts @@ -82,8 +82,13 @@ async function createUploadFixture() { } const execute = vi.fn( async (command: string, args: string[], options: { cwd: string }) => { - expect(command).toBe('zip') - expect(args.slice(0, 2)).toEqual(['-q', '-0']) + const windows = process.platform === 'win32' + expect(command).toBe( + windows + ? path.join(process.env['SystemRoot']!, 'System32', 'tar.exe') + : 'zip', + ) + expect(args.slice(0, 2)).toEqual(windows ? ['-a', '-cf'] : ['-q', '-0']) expect(args.slice(3)).toEqual([...files].sort()) expect(options).toMatchObject({ cwd: directory, timeout: 120_000 }) await writeFile(args[2]!, archiveBytes)