From adaddae854aef87bec7a79bc6cc77d81070e9b55 Mon Sep 17 00:00:00 2001 From: jdalton Date: Tue, 24 Nov 2026 14:55:15 -0500 Subject: [PATCH] fix(cli): restore release builds and route tool updates --- .claude/skills/bump-bundled-tools/SKILL.md | 15 - .claude/skills/bump-cli-tools/SKILL.md | 15 + .../references/cli-tools.md} | 12 +- .claude/skills/bump-coana/SKILL.md | 2 + .config/rollup.dist.config.mjs | 10 +- .github/workflows/publish-npm.yml | 19 +- .gitignore | 5 +- .../coana-fix-dynamic-sbom-inference.test.mts | 2 +- src/commands/fix/coana-fix-pr-files.test.mts | 2 +- src/commands/fix/coana-fix.mts | 2 +- src/commands/fix/handle-fix-limit.test.mts | 2 +- .../scan/perform-reachability-analysis.mts | 2 +- .../perform-reachability-analysis.test.mts | 2 +- src/sea/README.md | 2 +- src/sea/archive-paths.mts | 4 +- src/sea/bootstrap.mts | 28 ++ src/sea/build-sea.mts | 89 +++++- src/sea/capabilities.mts | 18 +- src/sea/paths/coana.mts | 26 ++ src/sea/runtime.mts | 33 +- src/sea/stage/coana.mts | 301 ++++++++++++++++++ src/utils/coana-release.test.mts | 6 +- .../{coana-release.mts => coana/release.mts} | 182 +++++++++-- src/utils/pnpm.mts | 2 +- test/lib/termless/animation.mts | 6 +- test/unit/sea/build-sea.test.mts | 7 +- 26 files changed, 685 insertions(+), 109 deletions(-) delete mode 100644 .claude/skills/bump-bundled-tools/SKILL.md create mode 100644 .claude/skills/bump-cli-tools/SKILL.md rename .claude/skills/{bump-bundled-tools/references/bundled-tools.md => bump-cli-tools/references/cli-tools.md} (52%) create mode 100644 src/sea/paths/coana.mts create mode 100644 src/sea/stage/coana.mts rename src/utils/{coana-release.mts => coana/release.mts} (75%) diff --git a/.claude/skills/bump-bundled-tools/SKILL.md b/.claude/skills/bump-bundled-tools/SKILL.md deleted file mode 100644 index 3fd98217d6..0000000000 --- a/.claude/skills/bump-bundled-tools/SKILL.md +++ /dev/null @@ -1,15 +0,0 @@ ---- -name: bump-bundled-tools -description: Update a versioned tool bundled in the native CLI. Use when bumping socket-patch, uv, cdxgen, or synp. -user-invocable: true ---- - -# Bump a bundled native tool - -Take a tool name and its exact upstream version as `$ARGUMENTS`; ask if either -is missing. Read [the bundled tool inventory](references/bundled-tools.md), -then follow that tool's matching `bump-*` skill. Update one tool per change. - -Check the target-specific payload and manifest after building. Keep any tool -unavailable while its provenance, license, or notice checks remain unresolved. -Do not add a new tool here unless the builder stages it into the VFS. diff --git a/.claude/skills/bump-cli-tools/SKILL.md b/.claude/skills/bump-cli-tools/SKILL.md new file mode 100644 index 0000000000..81e51e64e4 --- /dev/null +++ b/.claude/skills/bump-cli-tools/SKILL.md @@ -0,0 +1,15 @@ +--- +name: bump-cli-tools +description: Route Socket CLI tool updates to their release workflows. Use when a request spans tools or the tool's packaging path is unclear. +allowed-tools: Read, Edit, Write, Bash, Glob +user-invocable: true +--- + +# Update CLI tools + +Take the requested tool names and exact upstream versions as `$ARGUMENTS`. Ask +only for missing values. Read [the tool inventory](references/cli-tools.md), +then follow each matching `bump-*` skill. + +For multiple tools, follow each workflow and keep separate changes in separate +PRs unless the user asks to combine them. diff --git a/.claude/skills/bump-bundled-tools/references/bundled-tools.md b/.claude/skills/bump-cli-tools/references/cli-tools.md similarity index 52% rename from .claude/skills/bump-bundled-tools/references/bundled-tools.md rename to .claude/skills/bump-cli-tools/references/cli-tools.md index 4631298b47..99bf21c3c4 100644 --- a/.claude/skills/bump-bundled-tools/references/bundled-tools.md +++ b/.claude/skills/bump-cli-tools/references/cli-tools.md @@ -1,13 +1,9 @@ -# Tools bundled in the native CLI +# Pinned CLI tools -| Tool and type | Pin | Staging path | Target and status | Skill | +| Tool | Pin | Delivery | Notes | Skill | | --- | --- | --- | --- | --- | -| `socket-patch` executable | `dependencies.@socketsecurity/socket-patch` in `package.json` | `src/sea/build-sea.mts` → `resources/socket-patch` | Built for targets with a matching locked platform package; the manifest records its digest. | [bump-socket-patch](../../bump-socket-patch/SKILL.md) | +| Coana CLI | `COANA_CLI_VERSION` in `src/constants.mts` | Downloaded from the Socket API on first use and cached by the CLI. | Not part of the native executable. | [bump-coana](../../bump-coana/SKILL.md) | +| Socket Patch executable | `dependencies.@socketsecurity/socket-patch` in `package.json` | `src/sea/build-sea.mts` → `resources/socket-patch` | Built for targets with a matching locked platform package; the manifest records its digest. | [bump-socket-patch](../../bump-socket-patch/SKILL.md) | | `uv` executable | `src/sea/stage/uv-pins.json` | `src/sea/stage/uv.mts` → `tools/uv` | Target archives are checksum-verified; the manifest records each binary digest. | [bump-uv](../../bump-uv/SKILL.md) | | `cdxgen` JavaScript API | `devDependencies.@cyclonedx/cdxgen` in `package.json` | `.config/rollup.cdxgen-sea.config.mjs` and `src/sea/build-sea.mts` → `tools/cdxgen` | `darwin-arm64` only; capability stays disabled until provenance and notices are resolved. | [bump-cdxgen](../../bump-cdxgen/SKILL.md) | | `synp` JavaScript package | `devDependencies.synp` in `package.json` | `src/sea/stage/synp.mts` → `tools/synp` | `darwin-arm64` only; Yarn Classic stays disabled until provenance and notices are resolved. | [bump-synp](../../bump-synp/SKILL.md) | - -Node is the SEA runtime; use [bump-node-sea](../../bump-node-sea/SKILL.md). -Coana runs from a Socket API download; use [bump-coana](../../bump-coana/SKILL.md). -The .NET facts helper is built from source and requires a compatible .NET SDK. -Socket Python CLI has no version pin or VFS staging step in this repo. diff --git a/.claude/skills/bump-coana/SKILL.md b/.claude/skills/bump-coana/SKILL.md index 654a56a779..259dfa9c7c 100644 --- a/.claude/skills/bump-coana/SKILL.md +++ b/.claude/skills/bump-coana/SKILL.md @@ -7,6 +7,8 @@ user-invocable: true # Bump the Coana CLI +For a new release, check for the Socket CLI PR created by Coana's `Publish CLI` workflow (`publish-cli.yml`). It normally opens the PR and refreshes `src/vendor/coana-cache.mjs`. Continue on that PR instead of opening a duplicate. Use these steps for a manual bump. + Take the exact Coana version as `$ARGUMENTS` in `X.Y.Z` form; ask if it is missing. Read [the pin and snapshot notes](references/pin-and-snapshots.md). diff --git a/.config/rollup.dist.config.mjs b/.config/rollup.dist.config.mjs index d3d44cfb96..c51acb8900 100644 --- a/.config/rollup.dist.config.mjs +++ b/.config/rollup.dist.config.mjs @@ -90,7 +90,7 @@ function relativeBlessedPath(filepath) { ) } -// The cache script vendored from coana-package-manager, which coana-release.mts +// The cache script vendored from coana-package-manager, which coana/release.mts // runs with `node`. async function copyCoanaCache() { const filepath = path.join(constants.srcPath, 'vendor/coana-cache.mjs') @@ -489,6 +489,14 @@ 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/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 6480a9f066..40315d6591 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -309,14 +309,6 @@ jobs: - *install-dependencies - - name: Build and test the SEA - env: - NODE_OPTIONS: ${{ runner.os == 'macOS' && '--max-old-space-size=4096' || '' }} - shell: bash - run: | - pnpm build:sea - pnpm test:sea - - name: Download the verified launcher shell: bash env: @@ -326,6 +318,17 @@ jobs: DIST_DIRECTORY: ${{ runner.temp }}/launcher run: node .github/scripts/download-release-artifacts.mts + - name: Build and test the SEA + env: + NODE_OPTIONS: ${{ runner.os == 'macOS' && '--max-old-space-size=4096' || '' }} + SOCKET_CLI_API_TOKEN: ${{ startsWith(needs.verify.outputs.version, '2.') && !startsWith(matrix.target, 'win32-') && secrets.SOCKET_API_TOKEN_FOR_CLI_AND_SFW || '' }} # zizmor: ignore[secrets-outside-env] + SOCKET_CLI_COANA_REQUIRED: ${{ startsWith(needs.verify.outputs.version, '2.') && '1' || '0' }} + shell: bash + run: | + pnpm build:sea + unset SOCKET_CLI_API_TOKEN + pnpm test:sea + - name: Pack verified platform binary shell: bash env: diff --git a/.gitignore b/.gitignore index b344fe321f..3d333045cc 100644 --- a/.gitignore +++ b/.gitignore @@ -1071,6 +1071,8 @@ !/src/sea/readme-version.mts !/src/sea/.node-version !/src/sea/node-version.mts +!/src/sea/paths/ +!/src/sea/paths/** !/src/sea/licenses/cdxgen-third-party/boolbase-1.0.0-ISC.txt !/src/sea/licenses/cdxgen-third-party/err-code-2.0.3-MIT.txt !/src/sea/licenses/cdxgen-third-party/imurmurhash-0.1.4-MIT.txt @@ -1128,7 +1130,8 @@ !/src/utils/bin.mts !/src/utils/check-input.mts !/src/utils/cmd.mts -!/src/utils/coana-release.mts +!/src/utils/coana/ +!/src/utils/coana/** !/src/utils/coana-release.test.mts !/src/utils/coana.mts !/src/utils/coana.test.mts diff --git a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts index 8d40524d5b..d1fa67000e 100644 --- a/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts +++ b/src/commands/fix/coana-fix-dynamic-sbom-inference.test.mts @@ -22,7 +22,7 @@ const mockGitUntrackedFiles = vi.hoisted(() => const mockGitCommit = vi.hoisted(() => vi.fn()) const mockGenerateSocketFactsForFix = vi.hoisted(() => vi.fn()) -vi.mock('../../utils/coana-release.mts', () => ({ +vi.mock('../../utils/coana/release.mts', () => ({ spawnCoana: mockSpawnCoana, })) diff --git a/src/commands/fix/coana-fix-pr-files.test.mts b/src/commands/fix/coana-fix-pr-files.test.mts index 1ed7327c8d..a07269c740 100644 --- a/src/commands/fix/coana-fix-pr-files.test.mts +++ b/src/commands/fix/coana-fix-pr-files.test.mts @@ -18,7 +18,7 @@ const mockGitUnstagedModifiedFiles = vi.hoisted(() => vi.fn()) const mockGitUntrackedFiles = vi.hoisted(() => vi.fn()) const mockGitCommit = vi.hoisted(() => vi.fn()) -vi.mock('../../utils/coana-release.mts', () => ({ +vi.mock('../../utils/coana/release.mts', () => ({ spawnCoana: mockSpawnCoana, })) diff --git a/src/commands/fix/coana-fix.mts b/src/commands/fix/coana-fix.mts index c5b9173419..bc3a3d303b 100644 --- a/src/commands/fix/coana-fix.mts +++ b/src/commands/fix/coana-fix.mts @@ -23,7 +23,7 @@ import { } from '../../constants.mts' import { handleApiCall } from '../../utils/api.mts' import { joinAnd } from '../../utils/arrays.mts' -import { spawnCoana } from '../../utils/coana-release.mts' +import { spawnCoana } from '../../utils/coana/release.mts' import { isReachabilityReportPath, isSocketFactsFile, diff --git a/src/commands/fix/handle-fix-limit.test.mts b/src/commands/fix/handle-fix-limit.test.mts index 3244669c58..acb34ed11c 100644 --- a/src/commands/fix/handle-fix-limit.test.mts +++ b/src/commands/fix/handle-fix-limit.test.mts @@ -23,7 +23,7 @@ const mockGitUntrackedFiles = vi.hoisted(() => vi.fn(async () => ({ ok: true, data: [] })), ) -vi.mock('../../utils/coana-release.mts', () => ({ +vi.mock('../../utils/coana/release.mts', () => ({ spawnCoana: mockSpawnCoana, })) diff --git a/src/commands/scan/perform-reachability-analysis.mts b/src/commands/scan/perform-reachability-analysis.mts index d109409ed9..1c77aaf411 100644 --- a/src/commands/scan/perform-reachability-analysis.mts +++ b/src/commands/scan/perform-reachability-analysis.mts @@ -6,7 +6,7 @@ import path from 'node:path' import { isOmittedReachValue } from './reachability-units.mts' import constants, { COANA_CLI_VERSION } from '../../constants.mts' import { handleApiCall } from '../../utils/api.mts' -import { spawnCoana } from '../../utils/coana-release.mts' +import { spawnCoana } from '../../utils/coana/release.mts' import { extractTier1ReachabilityScanId, isReachabilityReportPath, diff --git a/src/commands/scan/perform-reachability-analysis.test.mts b/src/commands/scan/perform-reachability-analysis.test.mts index 325d67524f..4e584928ef 100644 --- a/src/commands/scan/perform-reachability-analysis.test.mts +++ b/src/commands/scan/perform-reachability-analysis.test.mts @@ -62,7 +62,7 @@ vi.mock('../../utils/organization.mts', () => ({ hasEnterpriseOrgPlan: mockHasEnterpriseOrgPlan, })) -vi.mock('../../utils/coana-release.mts', () => ({ +vi.mock('../../utils/coana/release.mts', () => ({ spawnCoana: mockSpawnCoana, })) diff --git a/src/sea/README.md b/src/sea/README.md index 0eb2ed6baa..44babfcd91 100644 --- a/src/sea/README.md +++ b/src/sea/README.md @@ -47,7 +47,7 @@ The build stages and embeds the `cdxgen` and `synp` APIs for darwin-arm64, but t Rollup creates a notice inventory from each bundled dependency graph. Some pinned packages omit their license text from npm; exact package-version entries in `.config/rollup.cdxgen-sea.config.mjs` and `src/sea/rollup-provenance.mjs` supply the missing text. A dependency bump cannot reuse a mismatched entry, so the inventory records a missing-text obligation. README files are not used as license text or shipped as notice documents. -The build does not embed Coana, Python, or a JVM toolchain. It does not add a runtime path to download helper tools. Socket API requests and project inputs keep their existing network behavior. +The 2.x RC embeds Coana's CLI and analyzers for Linux and macOS. Its build needs a Socket API token with Coana artifact access; without access, the build fails. Windows, Python, and JVM capabilities remain unavailable. The runtime does not download helper tools. ## Manifest diff --git a/src/sea/archive-paths.mts b/src/sea/archive-paths.mts index d31e92f1d3..e1cd29a6f4 100644 --- a/src/sea/archive-paths.mts +++ b/src/sea/archive-paths.mts @@ -1,10 +1,12 @@ export function seaArchivePaths({ hasCdxgen, + hasCoana = false, hasSynp, hasUv, rootFiles, }: { hasCdxgen: boolean + hasCoana?: boolean hasSynp: boolean hasUv: boolean rootFiles: string[] @@ -14,6 +16,6 @@ export function seaArchivePaths({ 'external', ...rootFiles, 'resources', - ...(hasCdxgen || hasSynp || hasUv ? ['tools'] : []), + ...(hasCdxgen || hasCoana || hasSynp || hasUv ? ['tools'] : []), ] } diff --git a/src/sea/bootstrap.mts b/src/sea/bootstrap.mts index 5c30d7023a..960a992b22 100644 --- a/src/sea/bootstrap.mts +++ b/src/sea/bootstrap.mts @@ -7,12 +7,15 @@ import os from 'node:os' import path from 'node:path' import { Worker } from 'node:worker_threads' +import { SEA_COANA_VFS_PATHS } from './paths/coana.mts' 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 + coanaVersion?: string + coanaNodeVersion?: string uvVersion?: string } @@ -62,6 +65,31 @@ async function smokeTest(): Promise { await cleanupBundledTool(uv) } } + if (seaSmokeTest.coanaVersion) { + assert.equal( + await fs + .stat(path.join(__dirname, SEA_COANA_VFS_PATHS.cliWrapper)) + .then(stat => stat.isFile()), + true, + ) + assert.equal( + await fs + .stat(path.join(__dirname, SEA_COANA_VFS_PATHS.analyzers, 'repos')) + .then(stat => stat.isDirectory()), + true, + ) + const node = await getBundledTool('coana-node') + try { + const output = execFileSync(node, ['--version'], { + encoding: 'utf8', + timeout: 15_000, + }) + assert.equal(output.trim(), `v${seaSmokeTest.coanaNodeVersion}`) + process.stdout.write(output) + } finally { + await cleanupBundledTool(node) + } + } console.log('VFS smoke test passed') } diff --git a/src/sea/build-sea.mts b/src/sea/build-sea.mts index 9f36771406..ab2fbf3e0e 100644 --- a/src/sea/build-sea.mts +++ b/src/sea/build-sea.mts @@ -18,10 +18,12 @@ 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 { stageCoana } from './stage/coana.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 { getErrorCause } from '../utils/errors.mts' import { quotePowerShell } from '../utils/quote-powershell.mts' const SEA_DIRECTORY = path.dirname(fileURLToPath(import.meta.url)) @@ -41,6 +43,27 @@ const TARGETS = [ ['win32', 'x64', 'win-x64'], ] as const +export function getSocketPatchPackageName( + platform: string, + arch: string, + options?: { libc?: 'glibc' | 'musl' | undefined } | undefined, +): string { + if (platform === 'linux') { + const libc = options?.libc + const packageLibc = libc === 'musl' ? 'musl' : 'gnu' + return `@socketsecurity/socket-patch-linux-${arch}-${packageLibc}` + } + const packagePlatform = platform === 'win32' ? 'win32' : platform + return `@socketsecurity/socket-patch-${packagePlatform}-${arch}` +} + +function detectLinuxLibc(): 'glibc' | 'musl' { + const { header } = process.report.getReport() as { + header?: { glibcVersionRuntime?: string } + } + return header?.glibcVersionRuntime ? 'glibc' : 'musl' +} + function sha256(data: Buffer): string { return createHash('sha256').update(data).digest('hex') } @@ -300,8 +323,9 @@ async function stageSocketPatch( | undefined > { const [platform, arch] = target - const packagePlatform = platform === 'win32' ? 'win32' : platform - const packageName = `@socketsecurity/socket-patch-${packagePlatform}-${arch}` + const packageName = getSocketPatchPackageName(platform, arch, { + libc: platform === 'linux' ? detectLinuxLibc() : undefined, + }) const lock = await fs.readFile( path.join(REPOSITORY_ROOT, 'pnpm-lock.yaml'), 'utf8', @@ -536,8 +560,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-object-object.mjs'), - path.join(workerUtils, 'is-object-object.mjs'), + path.join(REPOSITORY_ROOT, 'src/utils/is-record.mjs'), + path.join(workerUtils, 'is-record.mjs'), ) // Keep a concrete VFS path for cdxgen's plugin-directory override. The // marker does not install or expose any plugin executable. @@ -940,6 +964,7 @@ async function main(): Promise { : undefined return { cdxgenApi, synpPayload } })(), + stageCoana(stage, target[0], target[1], nodeRuntime.executable), stageUv(stage, target[0], target[1]), // Rollup copies this helper into manifest-scripts for standalone builds. run('pnpm', ['run', 'build:maven-extension']), @@ -948,19 +973,23 @@ async function main(): Promise { '.NET facts helper', 'socket-patch payload', 'cdxgen and synp payloads', + 'Coana payload', 'uv payload', 'Maven manifest extension', ] as const const prepResults = await Promise.allSettled(prepTasks) - const prepErrors = prepResults.flatMap((result, index) => - result.status === 'rejected' - ? [ - new Error(`SEA preparation failed: ${prepLabels[index]}`, { - cause: result.reason, - }), - ] - : [], - ) + delete process.env['SOCKET_CLI_API_TOKEN'] + const prepErrors = prepResults.flatMap((result, index) => { + if (result.status !== 'rejected') { + return [] + } + return [ + new Error( + `SEA preparation failed: ${prepLabels[index]}: ${getErrorCause(result.reason)}`, + { cause: result.reason }, + ), + ] + }) if (prepErrors.length > 0) { throw new AggregateError( prepErrors, @@ -979,10 +1008,15 @@ async function main(): Promise { }> ).value const uvPayload = ( - prepResults[3] as PromiseFulfilledResult< + prepResults[4] as PromiseFulfilledResult< Awaited> > ).value + const coanaPayload = ( + prepResults[3] as PromiseFulfilledResult< + Awaited> + > + ).value const socketPatchHashFile = socketPatch ? path.join(stage, 'resources', 'socket-patch.sha256') : undefined @@ -1101,6 +1135,7 @@ async function main(): Promise { const capabilities = createSeaCapabilities({ triple, hasCdxgen: Boolean(cdxgenApi), + hasCoana: Boolean(coanaPayload), hasSynp: Boolean(synpPayload), hasSocketPatch: Boolean(socketPatch), hasUv: Boolean(uvPayload), @@ -1115,6 +1150,7 @@ async function main(): Promise { // materialized only at invocation time. const archivePaths = seaArchivePaths({ hasCdxgen: Boolean(cdxgenApi), + hasCoana: Boolean(coanaPayload), hasSynp: Boolean(synpPayload), hasUv: Boolean(uvPayload), rootFiles, @@ -1144,6 +1180,8 @@ async function main(): Promise { SEA_OUTPUT: bootstrap, SEA_SMOKE_TEST: JSON.stringify({ digest: digestVfs(stage, archivePaths), + coanaVersion: coanaPayload?.version, + coanaNodeVersion: coanaPayload ? NODE_VERSION : undefined, uvVersion: uvPayload?.version, }), }, @@ -1328,6 +1366,29 @@ async function main(): Promise { sha256: synpPayload.integrity, }) } + if (coanaPayload) { + payloads.push({ + id: 'coana', + version: coanaPayload.version, + file: `${coanaPayload.vfsDirectory}/`, + sha256: await digestTree(coanaPayload.directory), + components: { + cli: { + sha256: coanaPayload.cliSha256, + size: coanaPayload.cliSize, + }, + analyzers: { + sha256: coanaPayload.analyzersSha256, + size: coanaPayload.analyzersSize, + }, + node: { + version: NODE_VERSION, + sha256: coanaPayload.nodeSha256, + size: coanaPayload.nodeSize, + }, + }, + }) + } if (uvPayload) { payloads.push({ id: 'uv', diff --git a/src/sea/capabilities.mts b/src/sea/capabilities.mts index 8c3d276461..553e445f34 100644 --- a/src/sea/capabilities.mts +++ b/src/sea/capabilities.mts @@ -7,6 +7,7 @@ export type SeaCapabilities = { export function createSeaCapabilities({ hasCdxgen, + hasCoana = false, hasSocketPatch, hasSynp, hasUv, @@ -15,6 +16,7 @@ export function createSeaCapabilities({ }: { triple: string hasCdxgen: boolean + hasCoana?: boolean hasSynp: boolean hasSocketPatch: boolean hasUv: boolean @@ -25,6 +27,7 @@ export function createSeaCapabilities({ 'socket-core', 'manifest-dotnet-facts', ...(hasSocketPatch ? ['socket-patch'] : []), + ...(hasCoana ? ['coana'] : []), ...(hasUv ? ['uv'] : []), ], unavailable: [ @@ -58,11 +61,16 @@ export function createSeaCapabilities({ ? 'The Synp API is bundled for Yarn Classic, but source provenance remains unverified and its third-party notice inventory has missing-license-text obligations.' : 'No Synp API payload is embedded because no compatible cdxgen VFS API payload is available for this target.', }, - { - id: 'coana', - reason: - 'No Coana executable or verified payload is embedded in this core SEA build.', - }, + ...(!hasCoana + ? [ + { + id: 'coana', + reason: triple.startsWith('win-') + ? 'Coana is not available for Windows SEA builds.' + : 'No verified Coana CLI and analyzer payloads are embedded in this SEA build.', + }, + ] + : []), ...(!hasSocketPatch ? [ { diff --git a/src/sea/paths/coana.mts b/src/sea/paths/coana.mts new file mode 100644 index 0000000000..b5d286bb52 --- /dev/null +++ b/src/sea/paths/coana.mts @@ -0,0 +1,26 @@ +import path from 'node:path' + +export const SEA_COANA_VFS_PATHS = Object.freeze({ + analyzers: 'tools/coana/analyzers', + cli: 'tools/coana/cli', + cliWrapper: 'tools/coana/cli/cli-wrapper.mjs', + manifest: 'tools/coana/manifest.json', + node: 'tools/coana/node', + nodeDigest: 'tools/coana/node.sha256', + root: 'tools/coana', +}) + +export function seaCoanaPaths(root: string) { + const directory = path.join(root, ...SEA_COANA_VFS_PATHS.root.split('/')) + const fromRoot = (relative: string) => path.join(root, ...relative.split('/')) + return { + analyzers: fromRoot(SEA_COANA_VFS_PATHS.analyzers), + cli: fromRoot(SEA_COANA_VFS_PATHS.cli), + cliWrapper: fromRoot(SEA_COANA_VFS_PATHS.cliWrapper), + manifest: fromRoot(SEA_COANA_VFS_PATHS.manifest), + node: fromRoot(SEA_COANA_VFS_PATHS.node), + nodeDigest: fromRoot(SEA_COANA_VFS_PATHS.nodeDigest), + repos: path.join(fromRoot(SEA_COANA_VFS_PATHS.analyzers), 'repos'), + root: directory, + } +} diff --git a/src/sea/runtime.mts b/src/sea/runtime.mts index 58e3c6e99d..4394896055 100644 --- a/src/sea/runtime.mts +++ b/src/sea/runtime.mts @@ -7,6 +7,8 @@ import { Readable, type Writable } from 'node:stream' import { fileURLToPath } from 'node:url' import { Worker } from 'node:worker_threads' +import { SEA_COANA_VFS_PATHS } from './paths/coana.mts' + import type { StdioOptions } from 'node:child_process' /** @@ -61,10 +63,12 @@ type SeaGlobal = typeof globalThis & { __socketSeaVfsRoot?: string } // absent files remain unavailable and fail closed here. const embeddedJsToolEntrypoints = Object.freeze({ cdxgen: 'tools/cdxgen/sea-worker.mjs', + 'coana-cache': 'dist/coana-cache.mjs', synp: 'tools/synp/bin/synp.js', }) const embeddedNativeToolPaths = Object.freeze({ + 'coana-node': SEA_COANA_VFS_PATHS.node, uv: (platform: string) => `tools/uv/${platform === 'win32' ? 'uv.exe' : 'uv'}`, }) @@ -152,9 +156,18 @@ export function getEmbeddedAsset(id: string): Buffer { } } +export function getEmbeddedVfsPath(relativePath: string): string { + const root = getVfsRoot() + const resolved = path.resolve(root, relativePath) + if (!resolved.startsWith(`${root}${path.sep}`)) { + throw new Error('Embedded VFS path is outside the archive root') + } + return resolved +} + /** Fail closed unless the build manifest explicitly advertises this tool. */ export function assertEmbeddedToolAvailable( - id: 'cdxgen' | 'synp', + id: 'cdxgen' | 'coana' | 'synp', capability?: 'manifest-cdxgen-npm-lock-v3' | 'manifest-cdxgen-yarn-classic', ): void { if (!isStandaloneSea()) { @@ -193,7 +206,7 @@ export function assertEmbeddedToolAvailable( ? [capability] : id === 'cdxgen' ? ['manifest-cdxgen-npm-lock-v3', 'manifest-cdxgen-yarn-classic'] - : ['synp'] + : [id] if (required.some(tool => manifest.available.includes(tool))) { return } @@ -218,7 +231,7 @@ export function assertEmbeddedToolAvailable( } export async function getBundledTool(id: string): Promise { - if (id !== 'socket-patch' && id !== 'uv') { + if (id !== 'socket-patch' && id !== 'uv' && id !== 'coana-node') { throw new Error( `Bundled tool '${id}' is not configured in this SEA foundation`, ) @@ -229,12 +242,18 @@ export async function getBundledTool(id: string): Promise { ) } - if (id === 'uv') { - const relative = embeddedNativeToolPaths.uv(process.platform) + if (id === 'uv' || id === 'coana-node') { + const relative = + id === 'uv' + ? embeddedNativeToolPaths.uv(process.platform) + : embeddedNativeToolPaths['coana-node'] const source = path.join(getVfsRoot(), relative) const binary = await fs.readFile(source) const expectedDigest = await fs.readFile( - path.join(getVfsRoot(), 'tools/uv/uv.sha256'), + path.join( + getVfsRoot(), + id === 'uv' ? 'tools/uv/uv.sha256' : SEA_COANA_VFS_PATHS.nodeDigest, + ), 'utf8', ) const actualDigest = createHash('sha256').update(binary).digest('hex') @@ -242,7 +261,7 @@ export async function getBundledTool(id: string): Promise { !/^[a-f0-9]{64}$/.test(expectedDigest.trim()) || actualDigest !== expectedDigest.trim() ) { - throw new Error('Embedded uv payload failed SHA-256 verification') + throw new Error(`Embedded ${id} payload failed SHA-256 verification`) } const directory = await fs.mkdtemp( path.join(os.tmpdir(), 'socket-cli-sea-'), diff --git a/src/sea/stage/coana.mts b/src/sea/stage/coana.mts new file mode 100644 index 0000000000..2822fb9a2f --- /dev/null +++ b/src/sea/stage/coana.mts @@ -0,0 +1,301 @@ +import { createHash } from 'node:crypto' +import { createWriteStream, promises as fs } from 'node:fs' +import os from 'node:os' +import path from 'node:path' +import { Readable, Transform } from 'node:stream' +import { pipeline } from 'node:stream/promises' + +import { x as extractTar } from 'tar' + +import { getDefaultOrgSlug } from '../../commands/ci/fetch-default-org-slug.mts' +import { COANA_CLI_VERSION } from '../../constants.mts' +import { apiFetch, sendApiRequest } from '../../utils/api.mts' +import { envAsBoolean } from '../../utils/env.mts' +import { SEA_COANA_VFS_PATHS, seaCoanaPaths } from '../paths/coana.mts' + +const COMPONENTS = ['analyzers', 'cli'] as const +const MAX_COMPONENT_BYTES = 512 * 1024 * 1024 +const MAX_EXPANDED_BYTES = 2 * 1024 * 1024 * 1024 +const SUPPORTED_TARGETS = new Set(['darwin-arm64', 'linux-arm64', 'linux-x64']) + +type Component = { + sha256: string + size: number + url: string +} + +type CoanaArtifacts = { + components: Record + version: string +} + +function sha256(bytes: Uint8Array): string { + return createHash('sha256').update(bytes).digest('hex') +} + +function isComponent(value: unknown): value is Component { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false + } + const component = value as Record + return ( + typeof component['sha256'] === 'string' && + /^[a-f0-9]{64}$/u.test(component['sha256']) && + typeof component['size'] === 'number' && + Number.isSafeInteger(component['size']) && + component['size'] > 0 && + component['size'] <= MAX_COMPONENT_BYTES && + typeof component['url'] === 'string' && + URL.canParse(component['url']) && + new URL(component['url']).protocol === 'https:' + ) +} + +function parseArtifacts(value: unknown): CoanaArtifacts { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error('the API returned an invalid response') + } + const response = value as Record + const components = response['components'] + if ( + response['version'] !== COANA_CLI_VERSION || + !components || + typeof components !== 'object' || + Array.isArray(components) + ) { + throw new Error( + `the API did not return the pinned Coana version ${COANA_CLI_VERSION}`, + ) + } + const parsed = components as Record + for (const name of COMPONENTS) { + if (!isComponent(parsed[name])) { + throw new Error(`the API returned invalid ${name} download metadata`) + } + } + return { + version: COANA_CLI_VERSION, + components: Object.fromEntries( + COMPONENTS.map(name => [name, parsed[name] as Component]), + ), + } +} + +async function fetchArtifacts(org: string): Promise { + const result = await sendApiRequest( + `orgs/${encodeURIComponent(org)}/coana-cli/artifacts`, + { + body: { components: [...COMPONENTS], version: COANA_CLI_VERSION }, + method: 'POST', + }, + ) + if (!result.ok) { + throw new Error( + `the Socket API denied Coana artifact access: ${result.message}${result.cause ? ` (${result.cause})` : ''}`, + ) + } + return parseArtifacts(result.data) +} + +async function downloadComponent( + component: Component, + destination: string, + name: string, +): Promise { + const response = await apiFetch(component.url, { timeout: 300_000 }) + if (!response.ok || !response.body) { + await response.body?.cancel() + throw new Error(`${name} download returned HTTP ${response.status}`) + } + const hash = createHash('sha256') + let received = 0 + await pipeline( + Readable.from(response.body), + new Transform({ + transform(chunk: Buffer, _encoding, callback) { + received += chunk.length + if (received > component.size) { + callback(new Error(`${name} exceeded its declared size`)) + return + } + hash.update(chunk) + callback(null, chunk) + }, + flush(callback) { + if (received !== component.size) { + callback( + new Error( + `${name} size mismatch: expected ${component.size} bytes, received ${received}`, + ), + ) + } else if (hash.digest('hex') !== component.sha256) { + callback(new Error(`${name} failed SHA-256 verification`)) + } else { + callback() + } + }, + }), + createWriteStream(destination, { flags: 'wx', mode: 0o600 }), + ) +} + +async function extractComponent( + archive: string, + destination: string, +): Promise { + let expandedBytes = 0 + await extractTar({ + cwd: destination, + file: archive, + strict: true, + preserveOwner: false, + filter(name, entry) { + const normalized = name.replaceAll('\\', '/') + if ( + normalized.startsWith('/') || + /^[a-zA-Z]:/u.test(normalized) || + normalized.split('/').some(part => part === '..') + ) { + throw new Error(`Coana archive contains an unsafe path: ${name}`) + } + if ('type' in entry && entry.type === 'Directory') { + return true + } + if (!('type' in entry) || entry.type !== 'File') { + throw new Error(`Coana archive contains an unsupported entry: ${name}`) + } + expandedBytes += entry.size + if (expandedBytes > MAX_EXPANDED_BYTES) { + throw new Error('Coana archive exceeds the expanded-size limit') + } + return true + }, + }) +} + +async function normalizeTimes(directory: string): Promise { + const timestamp = new Date('1980-01-01T00:00:00.000Z') + await Promise.all( + (await fs.readdir(directory, { withFileTypes: true })).map(async entry => { + const filename = path.join(directory, entry.name) + if (entry.isDirectory()) { + await normalizeTimes(filename) + } else if (!entry.isFile()) { + throw new Error(`Unsupported Coana payload entry: ${filename}`) + } + await fs.utimes(filename, timestamp, timestamp) + }), + ) + await fs.utimes(directory, timestamp, timestamp) +} + +export type StagedCoana = { + version: string + cliSha256: string + cliSize: number + analyzersSha256: string + analyzersSize: number + nodeSha256: string + nodeSize: number + directory: string + vfsDirectory: string +} + +/** Download, verify, and stage the pinned Coana release for supported SEA targets. */ +export async function stageCoana( + stageRoot: string, + platform: string, + arch: string, + nodeExecutable: string, +): Promise { + const target = `${platform}-${arch}` + if (!SUPPORTED_TARGETS.has(target)) { + return undefined + } + const required = envAsBoolean(process.env['SOCKET_CLI_COANA_REQUIRED']) + if (!required) { + return undefined + } + + const org = await getDefaultOrgSlug() + if (!org.ok) { + throw new Error( + `Coana ${COANA_CLI_VERSION} download failed. Where: organization lookup. Saw: ${org.message}${org.cause ? ` (${org.cause})` : ''}; wanted: a default organization with Coana reachability access. Fix: check the build token and its organization access.`, + ) + } + let artifacts: CoanaArtifacts + try { + artifacts = await fetchArtifacts(org.data) + } catch (error) { + throw new Error( + `Coana ${COANA_CLI_VERSION} download failed for ${org.data}. Where: Socket API artifact access. Saw: ${error instanceof Error ? error.message : String(error)}; wanted: the pinned CLI and analyzer artifacts. Fix: ensure SOCKET_API_TOKEN_FOR_CLI_AND_SFW can access Coana reachability artifacts for this organization, then retry the 2.x RC build.`, + { cause: error }, + ) + } + + const temporaryDirectory = await fs.mkdtemp( + path.join(os.tmpdir(), 'socket-coana-build-'), + ) + const paths = seaCoanaPaths(stageRoot) + try { + await fs.mkdir(paths.root, { recursive: true }) + const componentEntries = await Promise.all( + COMPONENTS.map(async name => { + const component = artifacts.components[name]! + const archive = path.join(temporaryDirectory, `${name}.tar.gz`) + const destination = name === 'cli' ? paths.cli : paths.analyzers + await downloadComponent(component, archive, `Coana ${name}`) + await fs.mkdir(destination, { recursive: true }) + await extractComponent(archive, destination) + return [ + name, + { sha256: component.sha256, size: component.size }, + ] as const + }), + ) + const componentDigests = Object.fromEntries(componentEntries) + + const cli = await fs.stat(paths.cliWrapper).catch(() => undefined) + const repos = await fs.stat(paths.repos).catch(() => undefined) + if (!cli?.isFile() || !repos?.isDirectory()) { + throw new Error( + 'Coana archives do not contain cli-wrapper.mjs and analyzer repos/', + ) + } + + await fs.copyFile(nodeExecutable, paths.node) + await fs.chmod(paths.node, 0o755) + const nodeBytes = await fs.readFile(paths.node) + const nodeSha256 = sha256(nodeBytes) + await fs.writeFile(paths.nodeDigest, `${nodeSha256}\n`) + await fs.writeFile( + paths.manifest, + `${JSON.stringify( + { + version: artifacts.version, + components: componentDigests, + nodeSha256, + }, + null, + 2, + )}\n`, + ) + await normalizeTimes(paths.root) + return { + version: artifacts.version, + cliSha256: componentDigests['cli']!.sha256, + cliSize: componentDigests['cli']!.size, + analyzersSha256: componentDigests['analyzers']!.sha256, + analyzersSize: componentDigests['analyzers']!.size, + nodeSha256, + nodeSize: nodeBytes.length, + directory: paths.root, + vfsDirectory: SEA_COANA_VFS_PATHS.root, + } + } catch (error) { + await fs.rm(paths.root, { recursive: true, force: true }) + throw error + } finally { + await fs.rm(temporaryDirectory, { recursive: true, force: true }) + } +} diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 20545a6cf9..442a582580 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -12,8 +12,8 @@ * the build copies there. * * Related Files: - * - utils/coana-release.mts (implementation) - * - vendor/coana-cache.mjs (the cache script) + * - utils/coana/release.mts (implementation) + * - src/vendor/coana-cache.mjs (the cache script) */ import { promises as fs } from 'node:fs' @@ -32,7 +32,7 @@ import { import { spawn } from './spawn.mts' import constants, { SOCKET_CLI_API_TOKEN_VARIABLES } from '../constants.mts' -import { spawnCoana } from './coana-release.mts' +import { spawnCoana } from './coana/release.mts' import { overrideCachedConfig, resetConfigForTesting } from './config.mts' import { getCliUserAgent, diff --git a/src/utils/coana-release.mts b/src/utils/coana/release.mts similarity index 75% rename from src/utils/coana-release.mts rename to src/utils/coana/release.mts index ed275922d6..34ff4c95ca 100644 --- a/src/utils/coana-release.mts +++ b/src/utils/coana/release.mts @@ -13,6 +13,7 @@ */ import { createHash } from 'node:crypto' +import { promises as fs } from 'node:fs' import path from 'node:path' import { Readable, Transform } from 'node:stream' import { pipeline } from 'node:stream/promises' @@ -20,29 +21,37 @@ import { pipeline } from 'node:stream/promises' import semver from 'semver' import { x as extractTar } from 'tar' -import { debugDir, debugFn } from './debug.mts' -import { logger } from './logger.mts' -import { spawn } from './spawn.mts' -import { getDefaultOrgSlug } from '../commands/ci/fetch-default-org-slug.mts' +import { debugDir, debugFn } from '../debug.mts' +import { logger } from '../logger.mts' +import { spawn } from '../spawn.mts' +import { getDefaultOrgSlug } from '../../commands/ci/fetch-default-org-slug.mts' import constants, { COANA_CLI_VERSION, ERROR_UNABLE_RESOLVE_ORG, SOCKET_CLI_API_TOKEN_VARIABLES, -} from '../constants.mts' -import { apiFetch, sendApiRequest } from './api.mts' -import { getErrorCause } from './errors.mts' -import { withTmpDir } from './fs.mts' +} from '../../constants.mts' +import { apiFetch, sendApiRequest } from '../api.mts' +import { getErrorCause } from '../errors.mts' +import { withTmpDir } from '../fs.mts' import { getCliUserAgent, getDefaultApiBaseUrl, getDefaultProxyUrl, resolveDefaultApiToken, -} from './sdk.mts' -import { isStandaloneSea } from '../sea/runtime.mts' +} from '../sdk.mts' +import { SEA_COANA_VFS_PATHS } from '../../sea/paths/coana.mts' +import { + assertEmbeddedToolAvailable, + cleanupBundledTool, + getBundledTool, + getEmbeddedVfsPath, + isStandaloneSea, + runEmbeddedJsTool, +} from '../../sea/runtime.mts' -import type { CResult } from '../types.mts' -import type { SpawnOptions } from './spawn.mts' -import type { Spinner } from './spinner.mts' +import type { CResult } from '../../types.mts' +import type { SpawnOptions } from '../spawn.mts' +import type { Spinner } from '../spinner.mts' type CoanaArtifacts = { cli: CoanaComponent @@ -376,6 +385,17 @@ async function runCoanaCache( args: string[], env: NodeJS.ProcessEnv, ): Promise { + if (isStandaloneSea()) { + const result = await runEmbeddedJsTool('coana-cache', args, { + env, + stdio: 'pipe', + }) + return { + exitCode: result.code ?? 1, + stderr: result.stderr?.trim() ?? '', + stdout: result.stdout?.trim() ?? '', + } + } try { const result = await spawn( constants.execPath, @@ -400,6 +420,74 @@ async function runCoanaCache( } } +async function cacheEmbeddedCoana( + env: NodeJS.ProcessEnv, +): Promise<{ cliPath: string; analyzersPath: string }> { + const manifest = JSON.parse( + await fs.readFile(getEmbeddedVfsPath(SEA_COANA_VFS_PATHS.manifest), 'utf8'), + ) as { + components?: Record + version?: unknown + } + const manifestComponents = manifest.components + if ( + manifest.version !== COANA_CLI_VERSION || + !manifestComponents || + typeof manifestComponents !== 'object' + ) { + throw new Error( + `Embedded Coana metadata does not match pinned version ${COANA_CLI_VERSION}`, + ) + } + const components = await Promise.all( + (['analyzers', 'cli'] as const).map(async component => { + const sha256 = manifestComponents[component]?.sha256 + if (typeof sha256 !== 'string' || !SHA256_REGEXP.test(sha256)) { + throw new Error(`Embedded Coana ${component} metadata is invalid`) + } + const lookup = await runCoanaCache( + ['lookup', COANA_CLI_VERSION, component], + env, + ) + if (lookup.exitCode === NOT_CACHED_EXIT_CODE) { + const cached = await withTmpDir( + 'socket-coana-embedded-', + async source => { + const extracted = path.join(source, 'component') + await fs.cp( + getEmbeddedVfsPath( + component === 'cli' + ? SEA_COANA_VFS_PATHS.cli + : SEA_COANA_VFS_PATHS.analyzers, + ), + extracted, + { recursive: true }, + ) + return await runCoanaCache( + ['install', COANA_CLI_VERSION, component, sha256, extracted], + env, + ) + }, + ) + if (cached.exitCode !== 0 || !cached.stdout) { + throw new Error( + cached.stderr || `Could not install embedded Coana ${component}`, + ) + } + return [component, cached.stdout] as const + } else if (lookup.exitCode === 0 && lookup.stdout) { + return [component, lookup.stdout] as const + } else { + throw new Error( + lookup.stderr || `Could not read the Coana ${component} cache`, + ) + } + }), + ) + const paths = Object.fromEntries(components) + return { cliPath: paths['cli']!, analyzersPath: paths['analyzers']! } +} + /** * Run the Coana CLI, downloading it into the cache that Coana and the Socket * CLIs share when the cache lacks the version. Returns a CResult with Coana's @@ -431,14 +519,6 @@ export async function spawnCoana( const localPath = process.env['SOCKET_CLI_COANA_LOCAL_PATH'] const standaloneSea = isStandaloneSea() - if (standaloneSea && !localPath) { - return { - ok: false, - message: 'Coana is unavailable in the standalone Socket build', - cause: - 'Set SOCKET_CLI_COANA_LOCAL_PATH to a native Coana executable to run Coana from a standalone build.', - } - } if ( standaloneSea && localPath && @@ -452,6 +532,17 @@ export async function spawnCoana( 'SOCKET_CLI_COANA_LOCAL_PATH must name a native Coana executable; the standalone JavaScript Worker adapter is not configured.', } } + if ( + standaloneSea && + !localPath && + (coanaVersion || COANA_CLI_VERSION) !== COANA_CLI_VERSION + ) { + return { + ok: false, + message: 'The standalone Socket build includes one Coana version', + cause: `This build includes Coana ${COANA_CLI_VERSION}; remove the version override or use that version.`, + } + } let apiToken: string | undefined try { @@ -497,30 +588,59 @@ export async function spawnCoana( } } + let embeddedPaths: { cliPath: string; analyzersPath: string } | undefined + if (standaloneSea && !localPath) { + try { + assertEmbeddedToolAvailable('coana') + embeddedPaths = await cacheEmbeddedCoana(userEnv) + env['REPOS_PATH'] = embeddedPaths.analyzersPath + } catch (error) { + return { + ok: false, + message: 'Could not prepare the embedded Coana CLI', + cause: getErrorCause(error), + } + } + } + let scriptPath = localPath if (!scriptPath) { - const coanaDirCResult = await getCoanaCliDir( - coanaVersion || COANA_CLI_VERSION, - org, - userEnv, - spinner, - ) - if (!coanaDirCResult.ok) { - return coanaDirCResult + if (embeddedPaths) { + scriptPath = path.join(embeddedPaths.cliPath, 'cli-wrapper.mjs') + } else { + const coanaDirCResult = await getCoanaCliDir( + coanaVersion || COANA_CLI_VERSION, + org, + userEnv, + spinner, + ) + if (!coanaDirCResult.ok) { + return coanaDirCResult + } + scriptPath = path.join(coanaDirCResult.data, 'cli-wrapper.mjs') } - scriptPath = path.join(coanaDirCResult.data, 'cli-wrapper.mjs') } // A local path may name a native binary. const isBinary = !scriptPath.endsWith('.js') && !scriptPath.endsWith('.mjs') + let nodePath: string | undefined try { + const executable = isBinary + ? scriptPath + : standaloneSea + ? (nodePath = await getBundledTool('coana-node')) + : constants.execPath const spawnResult = await spawn( - isBinary ? scriptPath : constants.execPath, + executable, isBinary ? args : [scriptPath, ...args], { cwd, env, spinner, stdio }, ) return { ok: true, data: String(spawnResult.stdout) } } catch (e) { return coanaSpawnErrorResult(e) + } finally { + if (nodePath) { + await cleanupBundledTool(nodePath) + } } } diff --git a/src/utils/pnpm.mts b/src/utils/pnpm.mts index 75e3219454..c3529a9533 100644 --- a/src/utils/pnpm.mts +++ b/src/utils/pnpm.mts @@ -77,7 +77,7 @@ export function parsePnpmLockfile( ) ?? documents.at(-1) } catch {} } - return isRecord(result) ? (result as LockfileObject) : null + return isRecord(result) ? (result as unknown as LockfileObject) : null } export function parsePnpmLockfileVersion(version: unknown): SemVer | undefined { diff --git a/test/lib/termless/animation.mts b/test/lib/termless/animation.mts index 4f0cf68633..510f33d44e 100644 --- a/test/lib/termless/animation.mts +++ b/test/lib/termless/animation.mts @@ -377,11 +377,7 @@ export async function expectTerminalAnimation( ) } try { - await assertSamePixels( - baselineRasterizer, - expectedSvg, - actualSvg, - ) + await assertSamePixels(baselineRasterizer, expectedSvg, actualSvg) } catch (error) { await writeFile( path.join(flowDir, `${checkpoint.name}.expected.png`), diff --git a/test/unit/sea/build-sea.test.mts b/test/unit/sea/build-sea.test.mts index 257f504624..d86ed230c5 100644 --- a/test/unit/sea/build-sea.test.mts +++ b/test/unit/sea/build-sea.test.mts @@ -118,12 +118,15 @@ describe('SEA lockfile metadata', () => { dependencies: { '@socketsecurity/socket-patch': string } } const version = packageJson.dependencies['@socketsecurity/socket-patch'] - for (const libc of ['gnu', 'musl'] as const) { - const packageName = getSocketPatchPackageName('linux', 'x64', libc) + for (const libc of ['glibc', 'musl'] as const) { + const packageName = getSocketPatchPackageName('linux', 'x64', { libc }) expect(findLockedPackageIntegrity(lock, packageName, version)).toMatch( /^sha512-/, ) } + expect(getSocketPatchPackageName('linux', 'x64')).toBe( + '@socketsecurity/socket-patch-linux-x64-gnu', + ) }) })