diff --git a/.claude/skills/bump-cli-tools/references/cli-tools.md b/.claude/skills/bump-cli-tools/references/cli-tools.md index 99bf21c3c..614528da1 100644 --- a/.claude/skills/bump-cli-tools/references/cli-tools.md +++ b/.claude/skills/bump-cli-tools/references/cli-tools.md @@ -5,5 +5,5 @@ | 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) | +| `cdxgen` JavaScript API | `devDependencies.@cyclonedx/cdxgen` in `package.json` | `.config/rollup.cdxgen-sea.config.mjs` and `src/sea/build-sea.mts` → `tools/cdxgen` | Generates SBOMs for npm and Yarn Classic. | [bump-cdxgen](../../bump-cdxgen/SKILL.md) | +| `synp` JavaScript package | `devDependencies.synp` in `package.json` | `src/sea/stage/synp.mts` → `tools/synp` | Converts Yarn Classic lockfiles for cdxgen. | [bump-synp](../../bump-synp/SKILL.md) | diff --git a/.config/rollup.cdxgen-sea.config.mjs b/.config/rollup.cdxgen-sea.config.mjs index 0e3b16c79..64125bbe5 100644 --- a/.config/rollup.cdxgen-sea.config.mjs +++ b/.config/rollup.cdxgen-sea.config.mjs @@ -10,6 +10,7 @@ import jsonPlugin from '@rollup/plugin-json' import { nodeResolve } from '@rollup/plugin-node-resolve' import { readPnpmLock } from '../src/sea/pnpm-lock.mts' +import { seaWorkerTypeScript } from '../src/sea/rollup-workers.mts' const root = path.resolve( path.dirname(url.fileURLToPath(import.meta.url)), @@ -492,19 +493,23 @@ function thirdPartyNoticePlugin() { } export default { - input: - process.env.SEA_CDXGEN_INPUT || - path.join(root, 'node_modules/@cyclonedx/cdxgen/lib/cli/index.js'), + input: { + 'lib/cli/index': + process.env.SEA_CDXGEN_INPUT || + path.join(root, 'node_modules/@cyclonedx/cdxgen/lib/cli/index.js'), + 'sea-worker': path.join(root, 'src/sea/adapters/cdxgen-worker.mts'), + }, output: { dir: process.env.SEA_CDXGEN_OUTPUT || path.join(root, 'dist/sea-cdxgen-api'), format: 'es', - entryFileNames: 'lib/cli/index.js', + entryFileNames: '[name].js', chunkFileNames: 'lib/cli/chunks/[name]-[hash].js', assetFileNames: 'lib/cli/assets/[name]-[hash][extname]', }, external: id => id.startsWith('node:'), plugins: [ + seaWorkerTypeScript(), nodeResolve({ preferBuiltins: true, exportConditions: ['node'] }), jsonPlugin(), commonjsPlugin(), diff --git a/.config/rollup.dist.config.mjs b/.config/rollup.dist.config.mjs index c51acb890..d8dfbf942 100644 --- a/.config/rollup.dist.config.mjs +++ b/.config/rollup.dist.config.mjs @@ -11,6 +11,10 @@ import { nodeResolve } from '@rollup/plugin-node-resolve' import fastGlob from 'fast-glob' import trash from 'trash' +import baseConfig, { + EXTERNAL_PACKAGES, + getBuildPackageName, +} from './rollup.base.config.mjs' import constants from '../scripts/constants.js' import { isDirEmptySync } from '../scripts/lib/fs.js' import { hasKeys } from '../scripts/lib/objects.js' @@ -25,14 +29,14 @@ import { isBuiltin, normalizeId, } from '../scripts/utils/packages.js' +import { + COANA_CACHE_SOURCE_PATH, + coanaCacheDistPath, +} from '../src/paths/coana.mts' import { includedModulesInventoryPlugin, writeCopiedPackageInventory, } from '../src/sea/rollup-provenance.mjs' -import baseConfig, { - EXTERNAL_PACKAGES, - getBuildPackageName, -} from './rollup.base.config.mjs' const { CONSTANTS, @@ -93,8 +97,8 @@ function relativeBlessedPath(filepath) { // 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') - const destPath = path.join(constants.distPath, 'coana-cache.mjs') + const filepath = path.join(constants.srcPath, COANA_CACHE_SOURCE_PATH) + const destPath = coanaCacheDistPath(constants.distPath) await fs.copyFile(filepath, destPath) } diff --git a/.config/rollup.synp-sea.config.mjs b/.config/rollup.synp-sea.config.mjs index 8d5e6da89..f78accfed 100644 --- a/.config/rollup.synp-sea.config.mjs +++ b/.config/rollup.synp-sea.config.mjs @@ -8,6 +8,8 @@ import url from 'node:url' import commonjsPlugin from '@rollup/plugin-commonjs' import { nodeResolve } from '@rollup/plugin-node-resolve' +import { seaWorkerTypeScript } from '../src/sea/rollup-workers.mts' + const root = path.resolve( path.dirname(url.fileURLToPath(import.meta.url)), '..', @@ -192,7 +194,7 @@ function noticesPlugin() { export default { input: process.env.SEA_SYNP_INPUT || - path.join(root, 'src/sea/adapters/synp-worker.mjs'), + path.join(root, 'src/sea/adapters/synp-worker.mts'), output: { dir: process.env.SEA_SYNP_OUTPUT || path.join(root, 'dist/sea-synp'), format: 'cjs', @@ -215,6 +217,7 @@ export default { 'worker_threads', ].includes(id), plugins: [ + seaWorkerTypeScript(), nodeResolve({ preferBuiltins: true, exportConditions: ['node'] }), commonjsPlugin(), noticesPlugin(), diff --git a/.config/tsconfig.scripts.json b/.config/tsconfig.scripts.json index 068e31a81..6577fc90b 100644 --- a/.config/tsconfig.scripts.json +++ b/.config/tsconfig.scripts.json @@ -19,6 +19,7 @@ "../scripts/release/packages.mts", "../scripts/refresh/**/*.mts", "../scripts/test/**/*.mts", + "../src/paths/*.mts", "../src/sea/version.mts" ], "exclude": ["../node_modules/**"] diff --git a/.github/workflows/publish-npm.yml b/.github/workflows/publish-npm.yml index 40315d659..c3489d08e 100644 --- a/.github/workflows/publish-npm.yml +++ b/.github/workflows/publish-npm.yml @@ -321,12 +321,9 @@ jobs: - 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 diff --git a/.gitignore b/.gitignore index 3d333045c..ac788ddad 100644 --- a/.gitignore +++ b/.gitignore @@ -194,10 +194,12 @@ !/src/external/blessed-contrib/lib/layout/ !/src/external/blessed-contrib/lib/widget/ !/src/external/blessed-contrib/lib/widget/charts/ +!/src/paths/ +!/src/paths/*.mts !/src/sea/ -!/src/sea/archive-paths.mts !/src/sea/adapters/ !/src/sea/build/ +!/src/sea/build/cdxgen-fixture.mts !/src/sea/stage/ !/src/sea/stage/** !/src/sea/download-cache.mts @@ -1062,9 +1064,9 @@ !/src/npx-cli.mts !/src/pnpm-cli.mts !/src/sea/README.md -!/src/sea/adapters/cdxgen-worker.mjs +!/src/sea/adapters/cdxgen-worker.mts !/src/sea/adapters/cdxgen.mts -!/src/sea/adapters/synp-worker.mjs +!/src/sea/adapters/synp-worker.mts !/src/sea/adapters/synp.mts !/src/sea/bootstrap.mts !/src/sea/build-sea.mts @@ -1089,6 +1091,7 @@ !/src/sea/build/publish.mts !/src/sea/build/smoke-test.mts !/src/sea/rollup-provenance.mjs +!/src/sea/rollup-workers.mts !/src/sea/pnpm-lock.mts !/src/sea/runtime.mts !/src/sea/download-bytes.mts @@ -1181,8 +1184,6 @@ !/src/utils/npm-config.mts !/src/utils/npm-spec.mts !/src/utils/objects.mts -!/src/utils/is-record.mjs -!/src/utils/is-record.d.mts !/src/utils/organization.mts !/src/utils/output-formatting.mts !/src/utils/package-environment.mts diff --git a/scripts/setup/uv.mts b/scripts/setup/uv.mts index 431830eb9..5edbee746 100644 --- a/scripts/setup/uv.mts +++ b/scripts/setup/uv.mts @@ -13,21 +13,17 @@ import path from 'node:path' import process from 'node:process' import { promisify } from 'node:util' +import { uvReleaseUrl } from '../../src/paths/uv.mts' +import pins from '../../src/sea/stage/uv-pins.json' with { type: 'json' } import { isMainModule } from '../lib/is-main-module.mts' import { runMain } from '../lib/run-main.mts' const execFile = promisify(execFileCallback) -const UV_VERSION = '0.12.15' -const UV_DIGESTS = { - arm64: - 'wtjxaDy/A91/eSUbn927LdJEsQy9JRpFfmaXqOxiSafoi+wHEFaNWvjxOpqwoMAky7UrBd0icT6PCttBpagKvA==', - x64: 'HnyqtvfbH/vq3MTydIYAbCr6hS8kC8kuZpXxrGJ/Nr2dac/wJQA3Z6S9bx95TYCTBdOZ1kPbDjtrzfIgwi4xDw==', -} - export interface UvRelease { archiveRoot: string asset: string digest: string + url: string version: string } @@ -71,13 +67,13 @@ export function uvSetupRelease(platform: string, arch: string): UvRelease { 'a platform outside Linux x64 or arm64', ) } - const target = arch === 'x64' ? 'x86_64' : 'aarch64' - const archiveRoot = 'uv-' + target + '-unknown-linux-gnu' + const pin = pins.targets[`linux-${arch}`] return { - archiveRoot, - asset: archiveRoot + '.tar.gz', - digest: UV_DIGESTS[arch], - version: UV_VERSION, + archiveRoot: path.posix.dirname(pin.executable), + asset: pin.archive, + digest: pin.sha256, + url: uvReleaseUrl(pin.archive), + version: pins.version, } } @@ -128,11 +124,7 @@ export async function installUvForCi( const fetcher = dependencies.fetcher ?? fetch const extract = dependencies.extract ?? extractUvArchive const probe = dependencies.probe ?? probeUvVersion - const url = - 'https://github.com/astral-sh/uv/releases/download/' + - release.version + - '/' + - release.asset + const { url } = release let bytes: Buffer try { const response = await fetcher(url, { @@ -149,11 +141,11 @@ export async function installUvForCi( } throw new UvSetupError('DOWNLOAD_FAILED', url, 'a failed download') } - if (createHash('sha512').update(bytes).digest('base64') !== release.digest) { + if (createHash('sha256').update(bytes).digest('hex') !== release.digest) { throw new UvSetupError( 'CHECKSUM_MISMATCH', release.asset, - 'a SHA-512 digest mismatch', + 'a SHA-256 digest mismatch', ) } const directory = await mkdtemp(path.join(runnerTemp, 'socket-uv-')) diff --git a/src/commands/manifest/bazel/bin-detect.mts b/src/commands/manifest/bazel/bin-detect.mts index f0c4bc840..67292b5b8 100644 --- a/src/commands/manifest/bazel/bin-detect.mts +++ b/src/commands/manifest/bazel/bin-detect.mts @@ -11,7 +11,7 @@ import { isNodeScript, resolveBazelExecutable, } from './process.mts' -import { isStandaloneSea } from '../../../sea/runtime.mts' +import { isSea } from '../../../sea/runtime.mts' import { InputError } from '../../../utils/errors.mts' /** @@ -28,7 +28,7 @@ export async function resolveBazelBinary( env: NodeJS.ProcessEnv, cwd: string, ): Promise { - if (isStandaloneSea()) { + if (isSea()) { const override = explicit ?? env['SOCKET_CLI_BAZEL_PATH'] if (!override) { throw new InputError( diff --git a/src/commands/manifest/bazel/process.test.mts b/src/commands/manifest/bazel/process.test.mts index e1e4829c2..37b73e406 100644 --- a/src/commands/manifest/bazel/process.test.mts +++ b/src/commands/manifest/bazel/process.test.mts @@ -16,7 +16,7 @@ import path from 'node:path' import { setTimeout as sleep } from 'node:timers/promises' import cmdShim from 'cmd-shim' -import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { resolveBazelBinary } from './bin-detect.mts' import { @@ -406,11 +406,9 @@ if (args.includes('info')) { process.stdout.write(${JSON.stringify(`install_base it('stops what a launcher started when the timeout expires', async () => { const record = writeParentLauncher({ detached: false }) - await expect( - spawnBazel(launcher, [], { cwd, timeout: 500 }), - ).rejects.toBeInstanceOf(BazelTimeoutError) + await expireLauncherTimeout(record) expect(await waitForExit(readChildPid(record))).toBe(true) - }) + }, 30_000) it('stops what a launcher started when cancelled', async () => { const record = writeParentLauncher({ detached: false }) @@ -424,22 +422,38 @@ if (args.includes('info')) { process.stdout.write(${JSON.stringify(`install_base it('settles a timeout when an escaped process keeps the output open', async () => { const record = writeParentLauncher({ detached: true }) - const startedAt = Date.now() try { - await expect( - spawnBazel(launcher, [], { cwd, timeout: 500 }), - ).rejects.toBeInstanceOf(BazelTimeoutError) - expect(Date.now() - startedAt).toBeLessThan(15_000) + await expireLauncherTimeout(record) } finally { - const pid = readChildPid(record) - if (isAlive(pid)) { - process.kill(pid, 'SIGKILL') + if (existsSync(record)) { + const pid = readChildPid(record) + if (isAlive(pid)) { + process.kill(pid, 'SIGKILL') + } + // Windows can report process exit before inherited handles release the cwd. + expect(await waitForExit(pid)).toBe(true) } - // Windows can report process exit before inherited handles release the cwd. - expect(await waitForExit(pid)).toBe(true) } }, 30_000) + async function expireLauncherTimeout(record: string): Promise { + // Give the real launcher time to report its child before firing the timeout. + vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] }) + const result = spawnBazel(launcher, [], { cwd, timeout: 500 }).catch( + (e: unknown) => e, + ) + try { + await waitForFile(record) + } finally { + try { + await vi.runAllTimersAsync() + } finally { + vi.useRealTimers() + } + } + expect(await result).toBeInstanceOf(BazelTimeoutError) + } + function writeParentLauncher(options: { detached: boolean }): string { const record = path.join(cwd, 'child.pid') writeFileSync( @@ -447,7 +461,9 @@ if (args.includes('info')) { process.stdout.write(${JSON.stringify(`install_base `const { spawn } = require('node:child_process') const fs = require('node:fs') const child = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1000)'], { detached: ${options.detached}, stdio: 'inherit' }) -fs.writeFileSync(${JSON.stringify(record)}, String(child.pid)) +const record = ${JSON.stringify(record)} +fs.writeFileSync(record + '.tmp', String(child.pid)) +fs.renameSync(record + '.tmp', record) ${options.detached ? 'child.unref()' : ''} `, ) @@ -498,10 +514,14 @@ async function waitForExit(pid: number): Promise { } async function waitForFile(file: string): Promise { - while (!existsSync(file)) { + const deadline = Date.now() + 10_000 + while (!existsSync(file) && Date.now() < deadline) { // eslint-disable-next-line no-await-in-loop await sleep(50) } + if (!existsSync(file)) { + throw new Error('Bazel test launcher did not report its child PID') + } } describe('splitBazelFlags', () => { diff --git a/src/commands/manifest/bazel/python-shim.mts b/src/commands/manifest/bazel/python-shim.mts index 63c1063df..7d4f14efb 100644 --- a/src/commands/manifest/bazel/python-shim.mts +++ b/src/commands/manifest/bazel/python-shim.mts @@ -11,7 +11,7 @@ import os from 'node:os' import path from 'node:path' import { findBazelExecutable, prependBazelPath } from './process.mts' -import { isStandaloneSea } from '../../../sea/runtime.mts' +import { isSea } from '../../../sea/runtime.mts' import { InputError } from '../../../utils/errors.mts' export type PythonShimResult = { @@ -53,7 +53,7 @@ export async function provisionPythonShim( env: NodeJS.ProcessEnv, cwd: string, ): Promise { - if (isStandaloneSea()) { + if (isSea()) { const override = env['SOCKET_CLI_PYTHON_PATH'] if (!override) { throw new InputError( diff --git a/src/commands/manifest/bazel/python-shim.test.mts b/src/commands/manifest/bazel/python-shim.test.mts index 4410428bb..cec4feaac 100644 --- a/src/commands/manifest/bazel/python-shim.test.mts +++ b/src/commands/manifest/bazel/python-shim.test.mts @@ -17,9 +17,9 @@ import { getBazelEnvironmentValue, } from './process.mts' import { provisionPythonShim } from './python-shim.mts' -import { isStandaloneSea } from '../../../sea/runtime.mts' +import { isSea } from '../../../sea/runtime.mts' -vi.mock('../../../sea/runtime.mts', () => ({ isStandaloneSea: vi.fn() })) +vi.mock('../../../sea/runtime.mts', () => ({ isSea: vi.fn() })) const python = await findBazelExecutable( process.platform === 'win32' ? 'python' : 'python3', @@ -32,7 +32,7 @@ describe('provisionPythonShim', () => { const shims: string[] = [] beforeEach(() => { - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) cwd = mkdtempSync(path.join(os.tmpdir(), 'bazel python ')) }) @@ -137,7 +137,7 @@ describe('provisionPythonShim', () => { if (!python) { throw new Error('Python fixture is unavailable') } - vi.mocked(isStandaloneSea).mockReturnValue(true) + vi.mocked(isSea).mockReturnValue(true) const env = getBazelEnvironment({ SOCKET_CLI_PYTHON_PATH: path.relative(cwd, python), Path: 'existing-path', diff --git a/src/commands/manifest/cmd-manifest-cdxgen.mts b/src/commands/manifest/cmd-manifest-cdxgen.mts index dc01c3100..6d8ab3baf 100644 --- a/src/commands/manifest/cmd-manifest-cdxgen.mts +++ b/src/commands/manifest/cmd-manifest-cdxgen.mts @@ -9,7 +9,7 @@ import colors from 'yoctocolors-cjs' import { runCdxgen } from './run-cdxgen.mts' import constants, { FLAG_HELP } from '../../constants.mts' import { commonFlags, outputFlags } from '../../flags.mts' -import { isStandaloneSea } from '../../sea/runtime.mts' +import { isSea } from '../../sea/runtime.mts' import { joinAnd } from '../../utils/arrays.mts' import { filterFlags, isHelpFlag } from '../../utils/cmd.mts' import { logger } from '../../utils/logger.mts' @@ -300,7 +300,7 @@ async function run( // The standalone build must not start cdxgen just to display its help: // cdxgen is an optional payload and can be unavailable for this target. // Keep this local help useful without resolving or installing that payload. - if (yargv.help && isStandaloneSea()) { + if (yargv.help && isSea()) { logger.log(` Usage socket manifest cdxgen [options] [path] @@ -340,7 +340,7 @@ Only one npm project is supported in this standalone build. Other cdxgen modes a const { spawnPromise } = await runCdxgen(yargv) - if (isStandaloneSea()) { + if (isSea()) { // The embedded Worker exposes an awaited result. Avoid translating its // synthetic exit event into process.exit(), which can bypass CLI error // formatting and telemetry drain on rejection or cancellation. diff --git a/src/commands/manifest/convert_gradle_to_maven.mts b/src/commands/manifest/convert_gradle_to_maven.mts index 69cdcd814..a52eb1aca 100644 --- a/src/commands/manifest/convert_gradle_to_maven.mts +++ b/src/commands/manifest/convert_gradle_to_maven.mts @@ -3,7 +3,7 @@ import path from 'node:path' import constants from '../../constants.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' -import { isStandaloneSea } from '../../sea/runtime.mts' +import { isSea } from '../../sea/runtime.mts' import { logger } from '../../utils/logger.mts' import { spawn } from '../../utils/spawn.mts' @@ -24,7 +24,7 @@ export async function convertGradleToMaven({ let selectedBin: string try { - selectedBin = resolveBuildToolBin('gradle', cwd, bin, isStandaloneSea()) + selectedBin = resolveBuildToolBin('gradle', cwd, bin, isSea()) } catch (error) { process.exitCode = 1 logger.fail(error instanceof Error ? error.message : String(error)) diff --git a/src/commands/manifest/convert_sbt_to_maven.mts b/src/commands/manifest/convert_sbt_to_maven.mts index 7cf4dffb1..a2a33bec2 100644 --- a/src/commands/manifest/convert_sbt_to_maven.mts +++ b/src/commands/manifest/convert_sbt_to_maven.mts @@ -3,7 +3,7 @@ import path from 'node:path' import constants from '../../constants.mts' import { resolveBuildToolBin } from './scripts/build-tool.mts' -import { isStandaloneSea } from '../../sea/runtime.mts' +import { isSea } from '../../sea/runtime.mts' import { errorMessage } from '../../utils/errors.mts' import { safeReadFile } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' @@ -42,7 +42,7 @@ export async function convertSbtToMaven({ let selectedBin: string try { - selectedBin = resolveBuildToolBin('sbt', cwd, bin, isStandaloneSea()) + selectedBin = resolveBuildToolBin('sbt', cwd, bin, isSea()) } catch (error) { process.exitCode = 1 logger.fail(error instanceof Error ? error.message : String(error)) diff --git a/src/commands/manifest/run-cdxgen.mts b/src/commands/manifest/run-cdxgen.mts index 58ffb6d36..eb62c430c 100644 --- a/src/commands/manifest/run-cdxgen.mts +++ b/src/commands/manifest/run-cdxgen.mts @@ -10,10 +10,7 @@ import { convertYarnClassicToNpmLock, removeOwnedPackageLock, } from '../../sea/adapters/synp.mts' -import { - assertEmbeddedToolAvailable, - isStandaloneSea, -} from '../../sea/runtime.mts' +import { assertEmbeddedToolAvailable, isSea } from '../../sea/runtime.mts' import { spawnCdxgenDlx, spawnSynpDlx } from '../../utils/dlx.mts' import { findUp } from '../../utils/fs.mts' import { logger } from '../../utils/logger.mts' @@ -72,7 +69,7 @@ function argvObjectToArray(argvObj: ArgvObject): string[] { } export async function runCdxgen(argvObj: ArgvObject): Promise { - if (isStandaloneSea()) { + if (isSea()) { const unsupported = new Set([ 'deep', 'evidence', @@ -294,7 +291,7 @@ export async function runCdxgen(argvObj: ArgvObject): Promise { if (abortController.signal.aborted) { const reason = abortController.signal.reason as { code?: unknown } if (typeof reason?.code === 'string') { - if (isStandaloneSea()) { + if (isSea()) { await removeOwnedPackageLock(generatedLock) const canceled = Promise.resolve({ code: null, diff --git a/src/commands/manifest/scripts/run.mts b/src/commands/manifest/scripts/run.mts index 6dcce2344..3033dfdb9 100644 --- a/src/commands/manifest/scripts/run.mts +++ b/src/commands/manifest/scripts/run.mts @@ -6,7 +6,7 @@ import { resolveBuildToolBin, socketFactsFileName } from './build-tool.mts' import { serializeExcludePathPatterns } from './exclude-paths-glob.mts' import { parseRecords } from './records.mts' import constants from '../../../constants.mts' -import { isStandaloneSea } from '../../../sea/runtime.mts' +import { isSea } from '../../../sea/runtime.mts' import { withTmpDir } from '../../../utils/fs.mts' import { getOrInsert } from '../../../utils/get-or-insert.mts' import { spawn } from '../../../utils/spawn.mts' @@ -294,12 +294,7 @@ async function invokeGradle( task: string, tmpDirPrefix: string, ): Promise { - const bin = resolveBuildToolBin( - 'gradle', - opts.projectDir, - opts.bin, - isStandaloneSea(), - ) + const bin = resolveBuildToolBin('gradle', opts.projectDir, opts.bin, isSea()) const initScript = manifestScriptsPath(initScriptFilename) return await withTmpDir(tmpDirPrefix, async tmp => { const recordsFile = path.join(tmp, 'records.tsv') @@ -353,12 +348,7 @@ async function invokeSbtIn( pluginDestFilename: string, task: string, ): Promise { - const bin = resolveBuildToolBin( - 'sbt', - opts.projectDir, - opts.bin, - isStandaloneSea(), - ) + const bin = resolveBuildToolBin('sbt', opts.projectDir, opts.bin, isSea()) await writeSbtPlugin(globalBase, pluginSourceFilename, pluginDestFilename) const recordsFile = path.join(globalBase, 'records.tsv') // The global base is shared across sbt roots: a build that dies before @@ -431,12 +421,7 @@ async function invokeMaven( coanaTask: string, tmpDirPrefix: string, ): Promise { - const bin = resolveBuildToolBin( - 'maven', - opts.projectDir, - opts.bin, - isStandaloneSea(), - ) + const bin = resolveBuildToolBin('maven', opts.projectDir, opts.bin, isSea()) const jarPath = manifestScriptsPath( 'maven-extension', 'coana-maven-extension.jar', @@ -565,7 +550,7 @@ async function invokeDotnetTool( const recordsFile = path.join(tmp, 'records.tsv') // An external dotnet process cannot open Node's in-process VFS mount. let executableDll = toolDll - if (isStandaloneSea()) { + if (isSea()) { const toolDir = path.join(tmp, 'dotnet-tool') await fs.mkdir(toolDir) const embeddedDir = path.dirname(toolDll) diff --git a/src/commands/patch/cmd-patch.mts b/src/commands/patch/cmd-patch.mts index 552713111..91e4ab9b8 100644 --- a/src/commands/patch/cmd-patch.mts +++ b/src/commands/patch/cmd-patch.mts @@ -11,7 +11,7 @@ import constants from '../../constants.mts' import { cleanupBundledTool, getBundledTool, - isStandaloneSea, + isSea, } from '../../sea/runtime.mts' import type { CliCommandContext } from '../../utils/meow-with-subcommands.mts' @@ -87,17 +87,17 @@ async function run( ): Promise { const { ENV } = constants - const standalone = isStandaloneSea() - if (standalone && isSelfUpdate(argv)) { + const runningInSea = isSea() + if (runningInSea && isSelfUpdate(argv)) { throw new Error( 'socket-patch self-update is unavailable in the standalone Socket build because it cannot replace the bundled executable.', ) } - let explicitBinPath = standalone + let explicitBinPath = runningInSea ? ENV.SOCKET_CLI_SOCKET_PATCH_PATH : undefined let bundledBinPath: string | undefined - if (standalone) { + if (runningInSea) { // The explicit override takes precedence; otherwise extract only the // verified embedded payload. Neither branch consults PATH. if (explicitBinPath) { diff --git a/src/commands/scan/generate-uv-member-sboms.mts b/src/commands/scan/generate-uv-member-sboms.mts index 9941d626a..043fe0cc9 100644 --- a/src/commands/scan/generate-uv-member-sboms.mts +++ b/src/commands/scan/generate-uv-member-sboms.mts @@ -12,7 +12,7 @@ import constants from '../../constants.mts' import { cleanupBundledTool, getBundledTool, - isStandaloneSea, + isSea, } from '../../sea/runtime.mts' import { InputError, getErrorMessage } from '../../utils/errors.mts' import { isDirSync } from '../../utils/fs.mts' @@ -27,7 +27,7 @@ const UV_SBOM_FILENAME = 'socket-uv-cdx.json' const UV_PATH_ENV = 'SOCKET_CLI_UV_PATH' function resolveUvExecutable(): string { - if (!isStandaloneSea()) { + if (!isSea()) { return 'uv' } const override = process.env[UV_PATH_ENV] diff --git a/src/commands/scan/generate-uv-member-sboms.test.mts b/src/commands/scan/generate-uv-member-sboms.test.mts index 24d15be7e..d1659cd07 100644 --- a/src/commands/scan/generate-uv-member-sboms.test.mts +++ b/src/commands/scan/generate-uv-member-sboms.test.mts @@ -22,7 +22,7 @@ vi.mock('../../utils/spawn.mts', () => ({ spawn: mockSpawn })) vi.mock('../../sea/runtime.mts', () => ({ cleanupBundledTool: mockCleanupBundledTool, getBundledTool: mockGetBundledTool, - isStandaloneSea: mockSea, + isSea: mockSea, })) const sbom = JSON.stringify({ diff --git a/src/paths/coana.mts b/src/paths/coana.mts new file mode 100644 index 000000000..4989975d7 --- /dev/null +++ b/src/paths/coana.mts @@ -0,0 +1,14 @@ +import path from 'node:path' + +export const COANA_CACHE_FILENAME = 'coana-cache.mjs' +export const COANA_CACHE_SOURCE_PATH = `vendor/${COANA_CACHE_FILENAME}` + +export function coanaCacheDistPath(distDirectory: string): string { + return path.join(distDirectory, COANA_CACHE_FILENAME) +} + +export const COANA_CLI_WRAPPER_FILENAME = 'cli-wrapper.mjs' + +export function coanaCliWrapperPath(cliDirectory: string): string { + return path.join(cliDirectory, COANA_CLI_WRAPPER_FILENAME) +} diff --git a/src/paths/uv.mts b/src/paths/uv.mts new file mode 100644 index 000000000..cf09287c7 --- /dev/null +++ b/src/paths/uv.mts @@ -0,0 +1,9 @@ +import pins from '../sea/stage/uv-pins.json' with { type: 'json' } + +export function uvReleaseUrl(archive: string): string { + return `${pins.repository}/releases/download/${pins.version}/${archive}` +} + +export function uvLicenseUrl(filename: string): string { + return `${pins.repository}/raw/${pins.version}/${filename}` +} diff --git a/src/sea/README.md b/src/sea/README.md index 44babfcd9..98986a2c1 100644 --- a/src/sea/README.md +++ b/src/sea/README.md @@ -37,17 +37,17 @@ The builder creates a private temporary copy of the distribution. It does not re The builder stages independent payloads in parallel. It waits for all staging jobs before cleanup. It builds the .NET facts helper before Rollup copies the distribution. -Verified source downloads are cached under `~/.cache/socket-sea/downloads`; each cache hit is checked against its pinned digest, and Node's `SHASUMS256.txt` is fetched fresh for each build. The runtime executable does not access this cache or download helper tools. +The builder caches downloads in `~/.cache/socket-sea/downloads` and checks each cache hit against its pinned digest. It fetches Node's `SHASUMS256.txt` on every build. ## Embedded tools The build embeds the .NET facts helper, `socket-patch`, and `uv` when a verified payload exists for the target. The .NET helper still needs a compatible .NET SDK from the project or `PATH`. The scan command uses `SOCKET_CLI_UV_PATH` when set. Otherwise, it extracts embedded `uv` to a temporary directory when needed. -The build stages and embeds the `cdxgen` and `synp` APIs for darwin-arm64, but the manifest marks both features unavailable. Their source provenance and third-party notice obligations are not resolved, so the CLI refuses to run them. Their notice files stay with this build because the payloads are already embedded in the executable. +The bundled `cdxgen` generates SBOMs from npm lockfile v3 and Yarn Classic projects. Yarn Classic needs an existing `node_modules` directory for Synp. The manifest records source verification and third-party notices. 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 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. +The Node CLI and SEA download Coana from the Socket API on a cache miss. The SEA bundles Node to run Coana. SEA builds need no Coana credentials. Python and JVM runtimes remain external. ## Manifest @@ -75,7 +75,9 @@ Terminal images trim unused rows while preserving internal spacing. Each animati ### 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. +Run `pnpm build:sea` on the target OS and CPU. The builder checks help and version output and runs `patch --version` where available. It generates .NET facts with package sources disabled and generates SBOMs for npm and Yarn Classic fixtures. + +`socket sea smoke-test` verifies VFS integrity and checks that an empty Coana cache reports a miss. It checks the bundled Node and uv versions and removes the extracted executables. 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. diff --git a/src/sea/adapters/cdxgen-worker.mjs b/src/sea/adapters/cdxgen-worker.mts similarity index 70% rename from src/sea/adapters/cdxgen-worker.mjs rename to src/sea/adapters/cdxgen-worker.mts index d5aa7e18c..cd50d9bfb 100644 --- a/src/sea/adapters/cdxgen-worker.mjs +++ b/src/sea/adapters/cdxgen-worker.mts @@ -12,8 +12,7 @@ import { fileURLToPath } from 'node:url' import util from 'node:util' import { workerData } from 'node:worker_threads' -// eslint-disable-next-line import-x/no-unresolved, n/no-missing-import -- The worker path resolves in its staged SEA VFS payload. -import { isRecord } from './utils/is-record.mjs' +import { isRecord } from '../../utils/objects.mts' const ipc = workerData?.socketIpc if ( @@ -28,28 +27,26 @@ if ( // cdxgen probes host tools while importing its API. A nonempty allowlist // prevents those probes from spawning commands; the restricted npm API path // does not need any subprocesses. -process.env.CDXGEN_PLUGINS_DIR = path.join( +process.env['CDXGEN_PLUGINS_DIR'] = path.join( path.dirname(fileURLToPath(import.meta.url)), 'plugins-empty', ) -process.env.CDXGEN_ALLOWED_COMMANDS = 'socket-sea-no-commands-allowed' +process.env['CDXGEN_ALLOWED_COMMANDS'] = 'socket-sea-no-commands-allowed' const denied = () => { throw new Error( 'Standalone cdxgen cannot start subprocesses or access the network', ) } -for (const name of [ - 'spawn', - 'spawnSync', - 'exec', - 'execSync', - 'execFile', - 'execFileSync', - 'fork', -]) { - childProcess[name] = denied -} +Object.assign(childProcess, { + spawn: denied, + spawnSync: denied, + exec: denied, + execSync: denied, + execFile: denied, + execFileSync: denied, + fork: denied, +}) for (const module of [http, https]) { module.request = denied module.get = denied @@ -66,10 +63,10 @@ syncBuiltinESMExports() const isolatedRoot = path.resolve(ipc.projectPath) const originalRoot = path.resolve(ipc.sourceRoot) -const packageJson = JSON.parse( +const packageJson: unknown = JSON.parse( await readFile(path.join(isolatedRoot, 'package.json'), 'utf8'), ) -const packageLock = JSON.parse( +const packageLock: unknown = JSON.parse( await readFile(path.join(isolatedRoot, 'package-lock.json'), 'utf8'), ) if (!isRecord(packageJson)) { @@ -78,17 +75,18 @@ if (!isRecord(packageJson)) { if (!isRecord(packageLock)) { throw new Error('Malformed npm package-lock.json') } -if (![1, 3].includes(packageLock.lockfileVersion)) { +const lockfileVersion = packageLock['lockfileVersion'] +if (lockfileVersion !== 1 && lockfileVersion !== 3) { throw new Error( 'The standalone cdxgen API supports package-lock versions 1 and 3 only', ) } -if (packageJson.workspaces || packageJson.workspace) { +if (packageJson['workspaces'] || packageJson['workspace']) { throw new Error('The standalone cdxgen API does not support workspaces') } -const hasLocalDependency = value => +const hasLocalDependency = (value: unknown) => typeof value === 'string' && /^(?:file:|link:|workspace:)/i.test(value) -const validPackageName = name => { +const validPackageName = (name: string) => { if (typeof name !== 'string' || !name || name.includes('\\')) { return false } @@ -97,7 +95,7 @@ const validPackageName = name => { return false } return name.startsWith('@') - ? parts.length === 2 && parts[0].length > 1 + ? parts.length === 2 && parts[0]!.length > 1 : parts.length === 1 } for (const group of [ @@ -121,9 +119,9 @@ for (const group of [ } } const inspectV1Dependencies = ( - dependencies, + dependencies: unknown, dependencyPath = 'dependencies', -) => { +): void => { if (dependencies === undefined) { return } @@ -137,42 +135,43 @@ const inspectV1Dependencies = ( if (!isRecord(dependency)) { throw new Error(`Malformed package-lock v1 dependency '${name}'`) } - if (typeof dependency.version !== 'string' || !dependency.version) { + if (typeof dependency['version'] !== 'string' || !dependency['version']) { throw new Error(`Malformed package-lock v1 version for '${name}'`) } for (const metadataKey of [ '_socketOptionalDependencies', '_socketPeerDependencies', ]) { + const metadata = dependency[metadataKey] if ( - dependency[metadataKey] !== undefined && - (!Array.isArray(dependency[metadataKey]) || - dependency[metadataKey].some(item => typeof item !== 'string')) + metadata !== undefined && + (!Array.isArray(metadata) || + metadata.some(item => typeof item !== 'string')) ) { throw new Error(`Malformed Synp dependency metadata for '${name}'`) } } if ( - hasLocalDependency(dependency.version) || - hasLocalDependency(dependency.resolved) || - dependency.link + hasLocalDependency(dependency['version']) || + hasLocalDependency(dependency['resolved']) || + dependency['link'] ) { throw new Error( 'The standalone cdxgen API does not support local or linked lockfile entries', ) } inspectV1Dependencies( - dependency.dependencies, + dependency['dependencies'], `${dependencyPath}.${name}.dependencies`, ) } } const checkRootDependencyGroup = ( - group, - lockDependencies, - groupName, - optional, - optionalNames = new Set(), + group: unknown, + lockDependencies: unknown, + groupName: string, + optional: boolean, + optionalNames = new Set(), ) => { if (group === undefined) { return @@ -193,48 +192,58 @@ const checkRootDependencyGroup = ( } } -if (packageLock.lockfileVersion === 1) { - const rootDependencies = packageLock.dependencies ?? {} +if (lockfileVersion === 1) { + const rootDependencies = packageLock['dependencies'] ?? {} if (!isRecord(rootDependencies)) { throw new Error('Malformed package-lock v1 dependencies map') } inspectV1Dependencies(rootDependencies) checkRootDependencyGroup( - packageJson.dependencies, + packageJson['dependencies'], rootDependencies, 'dependencies', false, - new Set(Object.keys(packageJson.optionalDependencies || {})), + new Set(Object.keys(packageJson['optionalDependencies'] || {})), ) checkRootDependencyGroup( - packageJson.devDependencies, + packageJson['devDependencies'], rootDependencies, 'devDependencies', false, ) checkRootDependencyGroup( - packageJson.optionalDependencies, + packageJson['optionalDependencies'], rootDependencies, 'optionalDependencies', true, ) checkRootDependencyGroup( - packageJson.peerDependencies, + packageJson['peerDependencies'], rootDependencies, 'peerDependencies', true, ) - const resolveV1Dependency = (name, ownDependencies, ancestorMaps) => + const resolveV1Dependency = ( + name: string, + ownDependencies: unknown, + ancestorMaps: readonly unknown[], + ) => Boolean( (isRecord(ownDependencies) && Object.hasOwn(ownDependencies, name)) || ancestorMaps.some(map => isRecord(map) && Object.hasOwn(map, name)), ) - const validateV1Graph = (dependencies, ancestorMaps = []) => { + const validateV1Graph = ( + dependencies: unknown, + ancestorMaps: readonly unknown[] = [], + ): void => { for (const [packageName, dependency] of Object.entries( dependencies || {}, )) { - const requires = dependency.requires + if (!isRecord(dependency)) { + throw new Error(`Malformed package-lock v1 dependency '${packageName}'`) + } + const requires = dependency['requires'] if (requires !== undefined && !isRecord(requires)) { throw new Error( `Malformed package-lock v1 requires map for '${packageName}'`, @@ -247,8 +256,8 @@ if (packageLock.lockfileVersion === 1) { `Malformed package-lock v1 requirement spec for '${packageName}'`, ) } - const optional = new Set(dependency._socketOptionalDependencies || []) - const peers = new Set(dependency._socketPeerDependencies || []) + const optional = dependency['_socketOptionalDependencies'] + const peers = dependency['_socketPeerDependencies'] const visibleMaps = [dependencies, ...ancestorMaps] for (const requiredName of Object.keys(requires || {})) { if (!validPackageName(requiredName)) { @@ -259,24 +268,27 @@ if (packageLock.lockfileVersion === 1) { if ( !resolveV1Dependency( requiredName, - dependency.dependencies, + dependency['dependencies'], visibleMaps, ) && - !optional.has(requiredName) && - !Object.hasOwn(dependency.optionalDependencies || {}, requiredName) && - !peers.has(requiredName) + !(Array.isArray(optional) && optional.includes(requiredName)) && + !Object.hasOwn( + dependency['optionalDependencies'] || {}, + requiredName, + ) && + !(Array.isArray(peers) && peers.includes(requiredName)) ) { throw new Error( `package-lock v1 is missing required '${requiredName}' for '${packageName}'`, ) } } - validateV1Graph(dependency.dependencies, visibleMaps) + validateV1Graph(dependency['dependencies'], visibleMaps) } } validateV1Graph(rootDependencies) } else { - const packages = packageLock.packages + const packages = packageLock['packages'] if ( !isRecord(packages) || !Object.hasOwn(packages, '') || @@ -300,13 +312,13 @@ if (packageLock.lockfileVersion === 1) { ) { throw new Error(`Invalid package-lock v3 package path '${packagePath}'`) } - if (typeof dependency.version !== 'string' || !dependency.version) { + if (typeof dependency['version'] !== 'string' || !dependency['version']) { throw new Error(`Missing package-lock v3 version for '${packagePath}'`) } if ( - hasLocalDependency(dependency.version) || - hasLocalDependency(dependency.resolved) || - dependency.link + hasLocalDependency(dependency['version']) || + hasLocalDependency(dependency['resolved']) || + dependency['link'] ) { throw new Error( 'The standalone cdxgen API does not support local or linked lockfile entries', @@ -315,7 +327,7 @@ if (packageLock.lockfileVersion === 1) { } } - const resolveV3Dependency = (name, packagePath) => { + const resolveV3Dependency = (name: string, packagePath: string) => { let current = packagePath while (current) { const candidate = `${current}/node_modules/${name}` @@ -328,11 +340,11 @@ if (packageLock.lockfileVersion === 1) { return Object.hasOwn(packages, `node_modules/${name}`) } const validateV3DependencyGroup = ( - group, - packagePath, - groupName, - optional, - optionalNames = new Set(), + group: unknown, + packagePath: string, + groupName: string, + optional: boolean, + optionalNames = new Set(), ) => { if (group === undefined) { return @@ -355,9 +367,13 @@ if (packageLock.lockfileVersion === 1) { } } const rootOptionalNames = new Set( - Object.keys(packageJson.optionalDependencies || {}), + Object.keys(packageJson['optionalDependencies'] || {}), ) - const validateV3RootGroup = (group, groupName, optional) => { + const validateV3RootGroup = ( + group: unknown, + groupName: string, + optional: boolean, + ) => { if (group === undefined) { return } @@ -376,51 +392,60 @@ if (packageLock.lockfileVersion === 1) { } } } - validateV3RootGroup(packageJson.dependencies, 'dependencies', false) - validateV3RootGroup(packageJson.devDependencies, 'devDependencies', false) + validateV3RootGroup(packageJson['dependencies'], 'dependencies', false) + validateV3RootGroup(packageJson['devDependencies'], 'devDependencies', false) validateV3RootGroup( - packageJson.optionalDependencies, + packageJson['optionalDependencies'], 'optionalDependencies', true, ) - validateV3RootGroup(packageJson.peerDependencies, 'peerDependencies', true) + validateV3RootGroup(packageJson['peerDependencies'], 'peerDependencies', true) for (const [packagePath, dependency] of Object.entries(packages)) { + if (!isRecord(dependency)) { + throw new Error(`Malformed package-lock v3 record '${packagePath}'`) + } validateV3DependencyGroup( - dependency.dependencies, + dependency['dependencies'], packagePath, 'dependencies', false, - new Set(Object.keys(dependency.optionalDependencies || {})), + new Set(Object.keys(dependency['optionalDependencies'] || {})), ) validateV3DependencyGroup( - dependency.devDependencies, + dependency['devDependencies'], packagePath, 'devDependencies', packagePath !== '', ) validateV3DependencyGroup( - dependency.optionalDependencies, + dependency['optionalDependencies'], packagePath, 'optionalDependencies', true, ) validateV3DependencyGroup( - dependency.peerDependencies, + dependency['peerDependencies'], packagePath, 'peerDependencies', true, ) } } -// eslint-disable-next-line import-x/no-unresolved, n/no-missing-import -- The package is staged beside this worker in the SEA VFS. -const { createNodejsBom } = await import('./lib/cli/index.js') +// Rollup stages the API alongside this worker. Load it after setting up the worker. +const cdxgenEntrypoint = './lib/cli/index.js' +const { createNodejsBom } = (await import(cdxgenEntrypoint)) as { + createNodejsBom: ( + root: string, + options: Record, + ) => Promise<{ bomJson?: unknown } | undefined> +} let incompleteNotice = '' -const originalConsole = new Map() -for (const method of ['log', 'warn', 'error']) { +const originalConsole = new Map<'log' | 'warn' | 'error', typeof console.log>() +for (const method of ['log', 'warn', 'error'] as const) { const original = console[method] originalConsole.set(method, original) - console[method] = (...args) => { + console[method] = (...args: unknown[]) => { const message = util.format(...args) if ( message.includes('Unable to parse') && @@ -459,7 +484,7 @@ if (incompleteNotice) { if (!bom?.bomJson) { throw new Error('cdxgen did not produce an npm BOM') } -const rewriteTemporaryPath = sourceValue => { +const rewriteTemporaryPath = (sourceValue: string) => { const sourcePath = path.resolve( path.isAbsolute(sourceValue) ? sourceValue @@ -473,7 +498,7 @@ const rewriteTemporaryPath = sourceValue => { } return sourceValue } -const rewriteSourcePaths = (value, inEvidence = false) => { +const rewriteSourcePaths = (value: unknown, inEvidence = false): void => { if (!value || typeof value !== 'object') { return } @@ -483,13 +508,19 @@ const rewriteSourcePaths = (value, inEvidence = false) => { } return } - if (value.name === 'SrcFile' && typeof value.value === 'string') { - value.value = rewriteTemporaryPath(value.value) + if (!isRecord(value)) { + return + } + if (value['name'] === 'SrcFile' && typeof value['value'] === 'string') { + value['value'] = rewriteTemporaryPath(value['value']) } else if ( - value.name === 'cdx:npm:binPaths' && - typeof value.value === 'string' + value['name'] === 'cdx:npm:binPaths' && + typeof value['value'] === 'string' ) { - value.value = value.value.split(', ').map(rewriteTemporaryPath).join(', ') + value['value'] = value['value'] + .split(', ') + .map(rewriteTemporaryPath) + .join(', ') } const evidence = inEvidence || Object.hasOwn(value, 'identity') for (const [key, child] of Object.entries(value)) { diff --git a/src/sea/adapters/synp-worker.mjs b/src/sea/adapters/synp-worker.mts similarity index 84% rename from src/sea/adapters/synp-worker.mjs rename to src/sea/adapters/synp-worker.mts index a4ddcec92..45574c16e 100644 --- a/src/sea/adapters/synp-worker.mjs +++ b/src/sea/adapters/synp-worker.mts @@ -2,15 +2,23 @@ import { createHash } from 'node:crypto' import { open, readFile, stat } from 'node:fs/promises' -import { createRequire } from 'node:module' import path from 'node:path' import { workerData } from 'node:worker_threads' -import { isRecord } from '../../utils/is-record.mjs' +import synp from 'synp' -const require = createRequire(import.meta.url) +import { isRecord } from '../../utils/objects.mts' -async function main() { +type DependencyMap = Record +type Dependency = { + _socketOptionalDependencies?: string[] + _socketPeerDependencies?: string[] + dependencies?: DependencyMap + dev?: boolean + requires?: unknown +} + +async function main(): Promise { const ipc = workerData && workerData.socketIpc if ( !ipc || @@ -59,12 +67,17 @@ async function main() { throw new Error('Embedded Synp requires an existing node_modules directory') } - const synp = require('synp') - const converted = JSON.parse(synp.yarnToNpm(projectPath, false)) + const converted = JSON.parse(synp.yarnToNpm(projectPath, false)) as { + lockfileVersion: number + dependencies?: DependencyMap + } if (converted.lockfileVersion !== 1) { throw new Error('Synp returned an unsupported package-lock format') } - const annotateDependencies = async (dependencies, modulesPath) => { + const annotateDependencies = async ( + dependencies: DependencyMap | undefined, + modulesPath: string, + ): Promise => { if (dependencies !== undefined && !isRecord(dependencies)) { throw new Error('Synp returned a malformed dependencies map') } @@ -96,7 +109,11 @@ async function main() { converted.dependencies, path.join(projectPath, 'node_modules'), ) - const findDependency = (name, ownDependencies, ancestorMaps) => { + const findDependency = ( + name: string, + ownDependencies: DependencyMap | undefined, + ancestorMaps: ReadonlyArray, + ): Dependency | undefined => { if (isRecord(ownDependencies) && Object.hasOwn(ownDependencies, name)) { return ownDependencies[name] } @@ -106,7 +123,12 @@ async function main() { } } } - const collectDependencies = (name, entry, ancestorMaps, collected) => { + const collectDependencies = ( + name: string, + entry: Dependency | undefined, + ancestorMaps: ReadonlyArray, + collected: Set, + ): void => { if (!entry || collected.has(entry)) { return } @@ -128,7 +150,7 @@ async function main() { ) } } - const productionEntries = new Set() + const productionEntries = new Set() for (const name of [ ...Object.keys(packageJson.dependencies || {}), ...Object.keys(packageJson.optionalDependencies || {}), @@ -140,7 +162,7 @@ async function main() { productionEntries, ) } - const developmentEntries = new Set() + const developmentEntries = new Set() for (const name of Object.keys(packageJson.devDependencies || {})) { collectDependencies( name, diff --git a/src/sea/archive-paths.mts b/src/sea/archive-paths.mts deleted file mode 100644 index e1cd29a6f..000000000 --- a/src/sea/archive-paths.mts +++ /dev/null @@ -1,21 +0,0 @@ -export function seaArchivePaths({ - hasCdxgen, - hasCoana = false, - hasSynp, - hasUv, - rootFiles, -}: { - hasCdxgen: boolean - hasCoana?: boolean - hasSynp: boolean - hasUv: boolean - rootFiles: string[] -}): string[] { - return [ - 'dist', - 'external', - ...rootFiles, - 'resources', - ...(hasCdxgen || hasCoana || hasSynp || hasUv ? ['tools'] : []), - ] -} diff --git a/src/sea/bootstrap.mts b/src/sea/bootstrap.mts index 960a992b2..02430a0ec 100644 --- a/src/sea/bootstrap.mts +++ b/src/sea/bootstrap.mts @@ -1,21 +1,22 @@ /** 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 { SEA_COANA_VFS_PATHS } from './paths/coana.mts' -import { cleanupBundledTool, getBundledTool } from './runtime.mts' +import { + cleanupBundledTool, + getBundledTool, + isSea, + runEmbeddedJsTool, +} 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 + nodeVersion?: string uvVersion?: string } @@ -37,62 +38,52 @@ async function smokeTest(): Promise { 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) - } - } - 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, + if (isSea()) { + const cache = await fs.mkdtemp( + path.join(os.tmpdir(), 'socket-coana-smoke-'), ) - 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) + const result = await runEmbeddedJsTool( + 'coana-cache', + ['lookup', '0.0.0', 'cli'], + { env: { XDG_CACHE_HOME: cache }, stdio: 'pipe' }, + ) + assert.equal( + result.code, + 4, + result.stderr || 'Expected a Coana cache miss', + ) } finally { - await cleanupBundledTool(node) + await fs.rm(cache, { recursive: true, force: true }) } } + if (seaSmokeTest.uvVersion) { + const output = await readBundledVersion('uv') + const [name, version] = output.trim().split(/\s+/u) + assert.equal(name, 'uv') + assert.equal(version, seaSmokeTest.uvVersion) + process.stdout.write(`${name} ${version}\n`) + } + if (seaSmokeTest.nodeVersion) { + const output = await readBundledVersion('node') + assert.equal(output.trim(), `v${seaSmokeTest.nodeVersion}`) + process.stdout.write(output) + } console.log('VFS smoke test passed') } +async function readBundledVersion(id: 'node' | 'uv'): Promise { + const executable = await getBundledTool(id) + try { + return execFileSync(executable, ['--version'], { + encoding: 'utf8', + timeout: 15_000, + }) + } finally { + await cleanupBundledTool(executable) + } +} + if ( process.argv.length === 4 && process.argv[2] === 'sea' && diff --git a/src/sea/build-sea.mts b/src/sea/build-sea.mts index 16dd2021d..c5e5cd0e9 100644 --- a/src/sea/build-sea.mts +++ b/src/sea/build-sea.mts @@ -8,7 +8,6 @@ import path from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' import { gunzipSync } from 'node:zlib' -import { seaArchivePaths } from './archive-paths.mts' import { acquireBuildLock } from './build/lock.mts' import { publishArtifactPair } from './build/publish.mts' import { smokeTestSea } from './build/smoke-test.mts' @@ -16,9 +15,18 @@ 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 { + SEA_CAPABILITIES_PATH, + SEA_RESOURCES_DIRECTORY, + seaArchivePaths, +} from './paths/archive.mts' +import { + SEA_NODE_LICENSE_PATH, + SEA_SOCKET_PATCH_LICENSE_PATH, + seaNativeToolPaths, +} from './paths/native-tools.mts' +import { findLockedPackageIntegrity } 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' @@ -72,6 +80,21 @@ async function digestFile(filename: string): Promise { return sha256(await fs.readFile(filename)) } +async function stageNodeRuntime( + stage: string, + platform: string, + executable: string, +) { + const paths = seaNativeToolPaths('node', platform) + const binary = path.join(stage, paths.binary) + await fs.mkdir(path.dirname(binary), { recursive: true }) + await fs.copyFile(executable, binary) + const sha256 = await digestFile(binary) + const { size } = await fs.stat(binary) + await fs.writeFile(path.join(stage, paths.digest), `${sha256}\n`) + return { file: paths.binary, sha256, size } +} + async function digestTree(directory: string): Promise { const entries: Array<{ path: string @@ -358,8 +381,8 @@ async function stageSocketPatch( `${packageName}@${version} failed pnpm lockfile integrity verification`, ) } - const executableName = - platform === 'win32' ? 'socket-patch.exe' : 'socket-patch' + const binaryPath = seaNativeToolPaths('socket-patch', platform).binary + const executableName = path.basename(binaryPath) const binaryEntry = `package/${executableName}` const entries = readTarEntries(tarball, binaryEntry) const metadata = JSON.parse( @@ -382,15 +405,15 @@ async function stageSocketPatch( } const binary = entries.get(binaryEntry)! validateNativeBinary(binary, platform, arch) - const payloadDirectory = path.join(stage, 'resources') - await fs.mkdir(payloadDirectory, { recursive: true }) - await fs.writeFile(path.join(payloadDirectory, executableName), binary, { + const output = path.join(stage, binaryPath) + await fs.mkdir(path.dirname(output), { recursive: true }) + await fs.writeFile(output, binary, { mode: 0o755, flag: 'wx', }) await fs.copyFile( path.join(SEA_DIRECTORY, 'licenses/socket-patch-MIT.txt'), - path.join(payloadDirectory, 'socket-patch-LICENSE.txt'), + path.join(stage, SEA_SOCKET_PATCH_LICENSE_PATH), ) return { packageName, @@ -416,15 +439,9 @@ type StagedCdxgenApi = { } async function stageCdxgenApi( - target: readonly [string, string, string], stage: string, version: string, -): Promise { - // Only darwin-arm64 has been qualified with the Node 27 VFS Worker smoke. - if (target[0] !== 'darwin' || target[1] !== 'arm64') { - return undefined - } - +): Promise { const packageName = '@cyclonedx/cdxgen' const packageRoot = path.join( REPOSITORY_ROOT, @@ -553,16 +570,6 @@ async function stageCdxgenApi( throw new Error(`Required cdxgen license file is missing: ${licensePath}`) } await fs.copyFile(licensePath, path.join(payloadRoot, 'LICENSE')) - await fs.copyFile( - path.join(SEA_DIRECTORY, 'adapters/cdxgen-worker.mjs'), - path.join(payloadRoot, 'sea-worker.mjs'), - ) - 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'), - ) // Keep a concrete VFS path for cdxgen's plugin-directory override. The // marker does not install or expose any plugin executable. const pluginsDirectory = path.join(payloadRoot, 'plugins-empty') @@ -930,18 +937,23 @@ async function main(): Promise { const stageExternal = path.join(stage, 'external') await fs.mkdir(stageDist, { recursive: true }) await fs.mkdir(stageExternal, { recursive: true }) - await fs.mkdir(path.join(stage, 'resources'), { recursive: true }) + await fs.mkdir(path.join(stage, SEA_RESOURCES_DIRECTORY), { + recursive: true, + }) const cdxgenVersion = packageJson.devDependencies?.['@cyclonedx/cdxgen'] - if ( - !cdxgenVersion || - !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(cdxgenVersion) - ) { + const synpVersion = packageJson.devDependencies?.['synp'] + const exactVersion = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/ + if (!cdxgenVersion || !exactVersion.test(cdxgenVersion)) { throw new Error( '@cyclonedx/cdxgen must have an exact version in devDependencies to build the SEA payload', ) } - const synpVersion = packageJson.devDependencies?.['synp'] + if (!synpVersion || !exactVersion.test(synpVersion)) { + throw new Error( + 'synp must have an exact version in devDependencies to build the Yarn Classic SEA payload', + ) + } const prepTasks = [ // The 1.14.x distribution includes this first-party helper. Build it // before Rollup copies manifest-scripts into the private distribution. @@ -949,22 +961,11 @@ async function main(): Promise { run('pnpm', ['run', 'build:dotnet-tool']), stageSocketPatch(target, stage, socketPatchVersion, socketPatchLicense), (async () => { - const cdxgenApi = await stageCdxgenApi(target, stage, cdxgenVersion) - if ( - cdxgenApi && - (!synpVersion || - !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(synpVersion)) - ) { - throw new Error( - 'synp must have an exact version in devDependencies to build the Yarn Classic SEA payload', - ) - } - const synpPayload = cdxgenApi - ? await stageSynp(stage, synpVersion!) - : undefined + const cdxgenApi = await stageCdxgenApi(stage, cdxgenVersion) + const synpPayload = await stageSynp(stage, synpVersion) return { cdxgenApi, synpPayload } })(), - stageCoana(stage, target[0], target[1], nodeRuntime.executable), + stageNodeRuntime(stage, target[0], node), stageUv(stage, target[0], target[1]), // Rollup copies this helper into manifest-scripts for standalone builds. run('pnpm', ['run', 'build:maven-extension']), @@ -973,12 +974,11 @@ async function main(): Promise { '.NET facts helper', 'socket-patch payload', 'cdxgen and synp payloads', - 'Coana payload', + 'Node runtime', 'uv payload', 'Maven manifest extension', ] as const const prepResults = await Promise.allSettled(prepTasks) - delete process.env['SOCKET_CLI_API_TOKEN'] const prepErrors = prepResults.flatMap((result, index) => { if (result.status !== 'rejected') { return [] @@ -1004,7 +1004,7 @@ async function main(): Promise { const { cdxgenApi, synpPayload } = ( prepResults[2] as PromiseFulfilledResult<{ cdxgenApi: Awaited> - synpPayload: Awaited> | undefined + synpPayload: Awaited> }> ).value const uvPayload = ( @@ -1012,16 +1012,17 @@ async function main(): Promise { Awaited> > ).value - const coanaPayload = ( + const nodePayload = ( prepResults[3] as PromiseFulfilledResult< - Awaited> + Awaited> > ).value - const socketPatchHashFile = socketPatch - ? path.join(stage, 'resources', 'socket-patch.sha256') - : undefined - if (socketPatch && socketPatchHashFile) { - await fs.writeFile(socketPatchHashFile, `${socketPatch.digest}\n`) + const patchPaths = seaNativeToolPaths('socket-patch', target[0]) + if (socketPatch) { + await fs.writeFile( + path.join(stage, patchPaths.digest), + `${socketPatch.digest}\n`, + ) } // Rollup depends on the completed helper and copies it into stageDist. @@ -1051,23 +1052,12 @@ async function main(): Promise { INLINED_SOCKET_CLI_PUBLISHED_BUILD: 'true', }, ) - const synpLock = synpPayload - ? parsePnpmLock( - await fs.readFile( - path.join(REPOSITORY_ROOT, 'pnpm-lock.yaml'), - 'utf8', - ), - ) - : undefined - const synpLocator = synpPayload ? `synp@${synpPayload.version}` : undefined - const synpLockIntegrity = synpLocator - ? synpLock?.packages?.[synpLocator]?.resolution?.integrity - : undefined - if ( - synpPayload && - (typeof synpLockIntegrity !== 'string' || - !synpLockIntegrity.startsWith('sha512-')) - ) { + const synpLockIntegrity = findLockedPackageIntegrity( + await fs.readFile(path.join(REPOSITORY_ROOT, 'pnpm-lock.yaml'), 'utf8'), + synpPayload.packageName, + synpPayload.version, + ) + if (!synpLockIntegrity?.startsWith('sha512-')) { throw new Error( `pnpm-lock.yaml has no integrity for synp@${synpPayload.version}`, ) @@ -1080,11 +1070,11 @@ async function main(): Promise { 'requirements.json', 'translations.json', 'LICENSE', - 'node-runtime-LICENSE', + SEA_NODE_LICENSE_PATH, ] for (const filename of rootFiles) { const source = - filename === 'node-runtime-LICENSE' + filename === SEA_NODE_LICENSE_PATH ? nodeRuntime.licenseFile : path.join(REPOSITORY_ROOT, filename) if (!existsSync(source)) { @@ -1134,27 +1124,20 @@ async function main(): Promise { } const capabilities = createSeaCapabilities({ triple, - hasCdxgen: Boolean(cdxgenApi), - hasCoana: Boolean(coanaPayload), - hasSynp: Boolean(synpPayload), + hasCdxgen: true, + hasSynp: true, hasSocketPatch: Boolean(socketPatch), - hasUv: Boolean(uvPayload), + hasUv: true, socketPatchVersion, }) await fs.writeFile( - path.join(stage, 'resources/capabilities.json'), + path.join(stage, SEA_CAPABILITIES_PATH), `${JSON.stringify(capabilities, null, 2)}\n`, ) // VFS archives and named SEA assets are mutually exclusive in Node 27. // Native tools belong in the archive too, then are read from the VFS and // materialized only at invocation time. - const archivePaths = seaArchivePaths({ - hasCdxgen: Boolean(cdxgenApi), - hasCoana: Boolean(coanaPayload), - hasSynp: Boolean(synpPayload), - hasUv: Boolean(uvPayload), - rootFiles, - }) + const archivePaths = seaArchivePaths(rootFiles) if (process.platform === 'win32') { // Windows PowerShell's Compress-Archive may emit backslashes in ZIP // entry names. Node's VFS resolves POSIX paths such as dist/cli.js. @@ -1180,8 +1163,7 @@ async function main(): Promise { SEA_OUTPUT: bootstrap, SEA_SMOKE_TEST: JSON.stringify({ digest: digestVfs(stage, archivePaths), - coanaVersion: coanaPayload?.version, - coanaNodeVersion: coanaPayload ? NODE_VERSION : undefined, + nodeVersion: NODE_VERSION, uvVersion: uvPayload?.version, }), }, @@ -1221,15 +1203,14 @@ async function main(): Promise { { id: 'node-runtime', version: NODE_VERSION, - file: path.basename(node), - sha256: await digestFile(node), + ...nodePayload, license: 'MIT', notices: [ { type: 'license', value: 'MIT', - path: 'node-runtime-LICENSE', - sha256: await digestFile(path.join(stage, 'node-runtime-LICENSE')), + path: SEA_NODE_LICENSE_PATH, + sha256: await digestFile(path.join(stage, SEA_NODE_LICENSE_PATH)), }, ], }, @@ -1285,130 +1266,101 @@ async function main(): Promise { { type: 'license', value: socketPatch.license, - path: 'resources/socket-patch-LICENSE.txt', + path: SEA_SOCKET_PATCH_LICENSE_PATH, }, ], file: `SEA asset: socket-patch`, - source: `resources/${triple.startsWith('win-') ? 'socket-patch.exe' : 'socket-patch'}`, - digestFile: 'resources/socket-patch.sha256', + source: patchPaths.binary, + digestFile: patchPaths.digest, sha256: socketPatch.digest, }) } - if (cdxgenApi) { - payloads.push({ - id: 'cdxgen-api', - version: cdxgenApi.version, - package: cdxgenApi.packageName, - declaredLockIntegrity: cdxgenApi.declaredLockIntegrity, - sourceVerification: 'unverified', - sourceVerificationReason: - 'The frozen lockfile SRI is recorded as declared metadata. Installed Rollup module hashes are provided separately and are not authenticated against the locked tarballs or generated bundle bytes.', - sourceInventory: { - file: 'tools/cdxgen/ROLLUP-SOURCE-INVENTORY.json', - sha256: cdxgenApi.sourceInventorySha256, - moduleCount: cdxgenApi.sourceModuleCount, - }, - license: cdxgenApi.license, - notices: [ - { - type: 'license', - value: cdxgenApi.license, - path: 'tools/cdxgen/LICENSE', - }, - { - type: 'third-party-notice-inventory', - path: 'tools/cdxgen/THIRD-PARTY-NOTICES.json', - }, - ], - thirdPartyNotices: { - inventory: 'tools/cdxgen/THIRD-PARTY-NOTICES.json', - documents: cdxgenApi.noticeDocuments, - packageCount: cdxgenApi.noticePackageCount, - licenseTextCount: cdxgenApi.licenseTextCount, - noticeTextCount: cdxgenApi.noticeTextCount, - flaggedObligationCount: cdxgenApi.obligationCount, + payloads.push({ + id: 'cdxgen-api', + version: cdxgenApi.version, + package: cdxgenApi.packageName, + declaredLockIntegrity: cdxgenApi.declaredLockIntegrity, + sourceVerification: 'unverified', + sourceVerificationReason: + 'The frozen lockfile SRI is recorded as declared metadata. Installed Rollup module hashes are provided separately and are not authenticated against the locked tarballs or generated bundle bytes.', + sourceInventory: { + file: 'tools/cdxgen/ROLLUP-SOURCE-INVENTORY.json', + sha256: cdxgenApi.sourceInventorySha256, + moduleCount: cdxgenApi.sourceModuleCount, + }, + license: cdxgenApi.license, + notices: [ + { + type: 'license', + value: cdxgenApi.license, + path: 'tools/cdxgen/LICENSE', }, - file: 'tools/cdxgen/', - entrypoint: 'tools/cdxgen/sea-worker.mjs', - sha256: cdxgenApi.digest, - }) - } - if (synpPayload && typeof synpLockIntegrity === 'string') { - payloads.push({ - id: 'synp-api', - version: synpPayload.version, - package: synpPayload.packageName, - declaredLockIntegrity: synpLockIntegrity, - sourceVerification: 'unverified', - sourceVerificationReason: - 'The frozen lockfile SRI and staged payload digest are recorded. No per-module source inventory is emitted, and neither value authenticates installed or transformed source bytes against the locked tarball.', - license: synpPayload.license, - notices: [ - { - type: 'license', - value: synpPayload.license, - path: 'tools/synp/LICENSE', - }, - { - type: 'third-party-notice-inventory', - path: 'tools/synp/THIRD-PARTY-NOTICES.json', - }, - ], - thirdPartyNotices: { - inventory: 'tools/synp/THIRD-PARTY-NOTICES.json', - inventorySha256: synpPayload.noticeInventorySha256, - documents: synpPayload.noticeDocuments, - packageCount: synpPayload.noticePackageCount, - flaggedObligationCount: synpPayload.obligationCount, + { + type: 'third-party-notice-inventory', + path: 'tools/cdxgen/THIRD-PARTY-NOTICES.json', }, - file: 'tools/synp/', - entrypoint: 'tools/synp/bin/synp.js', - 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, - }, + ], + thirdPartyNotices: { + inventory: 'tools/cdxgen/THIRD-PARTY-NOTICES.json', + documents: cdxgenApi.noticeDocuments, + packageCount: cdxgenApi.noticePackageCount, + licenseTextCount: cdxgenApi.licenseTextCount, + noticeTextCount: cdxgenApi.noticeTextCount, + flaggedObligationCount: cdxgenApi.obligationCount, + }, + file: 'tools/cdxgen/', + entrypoint: 'tools/cdxgen/sea-worker.js', + sha256: cdxgenApi.digest, + }) + payloads.push({ + id: 'synp-api', + version: synpPayload.version, + package: synpPayload.packageName, + declaredLockIntegrity: synpLockIntegrity, + sourceVerification: 'unverified', + sourceVerificationReason: + 'The frozen lockfile SRI and staged payload digest are recorded. No per-module source inventory is emitted, and neither value authenticates installed or transformed source bytes against the locked tarball.', + license: synpPayload.license, + notices: [ + { + type: 'license', + value: synpPayload.license, + path: 'tools/synp/LICENSE', }, - }) - } - if (uvPayload) { - payloads.push({ - id: 'uv', - package: uvPayload.packageName, - version: uvPayload.version, - target: uvPayload.target, - source: uvPayload.sourceUrl, - archiveSha256: uvPayload.declaredArchiveSha256, - binary: uvPayload.binaryPath, - sha256: uvPayload.binarySha256, - size: uvPayload.binarySize, - license: uvPayload.license, - notices: uvPayload.noticeDocuments, - noticeInventory: { - path: uvPayload.noticeInventoryPath, - sha256: uvPayload.noticeInventorySha256, + { + type: 'third-party-notice-inventory', + path: 'tools/synp/THIRD-PARTY-NOTICES.json', }, - noticeObligations: uvPayload.noticeObligations, - }) - } + ], + thirdPartyNotices: { + inventory: 'tools/synp/THIRD-PARTY-NOTICES.json', + inventorySha256: synpPayload.noticeInventorySha256, + documents: synpPayload.noticeDocuments, + packageCount: synpPayload.noticePackageCount, + flaggedObligationCount: synpPayload.obligationCount, + }, + file: 'tools/synp/', + entrypoint: 'tools/synp/bin/synp.js', + sha256: synpPayload.integrity, + }) + payloads.push({ + id: 'uv', + package: uvPayload.packageName, + version: uvPayload.version, + target: uvPayload.target, + source: uvPayload.sourceUrl, + archiveSha256: uvPayload.declaredArchiveSha256, + binary: uvPayload.binaryPath, + sha256: uvPayload.binarySha256, + size: uvPayload.binarySize, + license: uvPayload.license, + notices: uvPayload.noticeDocuments, + noticeInventory: { + path: uvPayload.noticeInventoryPath, + sha256: uvPayload.noticeInventorySha256, + }, + noticeObligations: uvPayload.noticeObligations, + }) const manifest = { schemaVersion: 1, target: { os: target[0], arch: target[1], triple }, diff --git a/src/sea/build/cdxgen-fixture.mts b/src/sea/build/cdxgen-fixture.mts new file mode 100644 index 000000000..8d69233d6 --- /dev/null +++ b/src/sea/build/cdxgen-fixture.mts @@ -0,0 +1,78 @@ +import assert from 'node:assert/strict' +import { promises as fs } from 'node:fs' +import path from 'node:path' + +export type CdxgenFixture = 'npm' | 'yarn' + +export const CDXGEN_FIXTURE_OUTPUT = 'socket-cdx.json' + +const dependency = 'is-number' +const version = '7.0.0' +const resolved = 'https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz' +const project = { + name: 'smoke', + version: '1.0.0', + dependencies: { [dependency]: version }, +} + +export async function assertCdxgenFixtureOutput( + cwd: string, + mode: CdxgenFixture, +): Promise { + const sbom = JSON.parse( + await fs.readFile(path.join(cwd, CDXGEN_FIXTURE_OUTPUT), 'utf8'), + ) as { + bomFormat?: string + components?: Array<{ name: string; version: string }> + } + assert.equal(sbom.bomFormat, 'CycloneDX') + assert.ok( + sbom.components?.some( + component => + component.name === dependency && component.version === version, + ), + 'The SBOM must include the locked dependency', + ) + if (mode === 'yarn') { + const leftovers = await fs.readdir(cwd) + assert.ok( + !leftovers.includes('package-lock.json'), + 'Synp left its generated lockfile', + ) + assert.ok( + !leftovers.some(name => name.startsWith('.socket-cdxgen-lock-')), + 'Synp left a temporary lockfile', + ) + } +} + +export async function writeCdxgenFixture( + cwd: string, + mode: CdxgenFixture, +): Promise { + await fs.mkdir(cwd, { recursive: true }) + await fs.writeFile(path.join(cwd, 'package.json'), JSON.stringify(project)) + if (mode === 'npm') { + await fs.writeFile( + path.join(cwd, 'package-lock.json'), + JSON.stringify({ + lockfileVersion: 3, + packages: { + '': project, + [`node_modules/${dependency}`]: { version, resolved }, + }, + }), + ) + } else { + const installed = path.join(cwd, 'node_modules', dependency) + await fs.mkdir(installed, { recursive: true }) + await fs.writeFile( + path.join(installed, 'package.json'), + JSON.stringify({ name: dependency, version }), + ) + await fs.writeFile( + path.join(cwd, 'yarn.lock'), + `# yarn lockfile v1\n\n${dependency}@${version}:\n version "${version}"\n resolved "${resolved}"\n`, + ) + } +} diff --git a/src/sea/build/smoke-test.mts b/src/sea/build/smoke-test.mts index 5827284a5..f096b1c2e 100644 --- a/src/sea/build/smoke-test.mts +++ b/src/sea/build/smoke-test.mts @@ -4,6 +4,11 @@ import { promises as fs } from 'node:fs' import path from 'node:path' import { promisify } from 'node:util' +import { + assertCdxgenFixtureOutput, + writeCdxgenFixture, +} from './cdxgen-fixture.mts' + import type { SeaCapabilities } from '../capabilities.mts' const exec = promisify(execFile) @@ -43,8 +48,8 @@ export async function smokeTestSea( TEMP: tmp, TMPDIR: tmp, } - const run = (args: string[], timeout = 30_000) => - exec(executable, args, { cwd, env, timeout, windowsHide: true }) + const run = (args: string[], timeout = 30_000, directory = cwd) => + exec(executable, args, { cwd: directory, env, timeout, windowsHide: true }) assert.match((await run(['--help'])).stdout, /\$ socket /u) assert.equal( @@ -86,22 +91,20 @@ export async function smokeTestSea( [], ) - 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)), + for (const [mode, capability] of [ + ['npm', 'manifest-cdxgen-npm-lock-v3'], + ['yarn', 'manifest-cdxgen-yarn-classic'], + ] as const) { + assert.ok( + capabilities.available.includes(capability), + `Missing ${capability}`, ) + const project = path.join(cwd, mode) + // eslint-disable-next-line no-await-in-loop -- Verify each generated SBOM before the next command. + await writeCdxgenFixture(project, mode) + // eslint-disable-next-line no-await-in-loop + await run(['manifest', 'cdxgen', '--type', 'npm'], 60_000, project) + // eslint-disable-next-line no-await-in-loop + await assertCdxgenFixtureOutput(project, mode) } } diff --git a/src/sea/capabilities.mts b/src/sea/capabilities.mts index 553e445f3..5f93cda11 100644 --- a/src/sea/capabilities.mts +++ b/src/sea/capabilities.mts @@ -7,7 +7,6 @@ export type SeaCapabilities = { export function createSeaCapabilities({ hasCdxgen, - hasCoana = false, hasSocketPatch, hasSynp, hasUv, @@ -16,7 +15,6 @@ export function createSeaCapabilities({ }: { triple: string hasCdxgen: boolean - hasCoana?: boolean hasSynp: boolean hasSocketPatch: boolean hasUv: boolean @@ -27,47 +25,31 @@ export function createSeaCapabilities({ 'socket-core', 'manifest-dotnet-facts', ...(hasSocketPatch ? ['socket-patch'] : []), - ...(hasCoana ? ['coana'] : []), + 'coana', + ...(hasCdxgen ? ['manifest-cdxgen-npm-lock-v3'] : []), + ...(hasCdxgen && hasSynp ? ['manifest-cdxgen-yarn-classic', 'synp'] : []), ...(hasUv ? ['uv'] : []), ], unavailable: [ ...(hasCdxgen ? [ - { - id: 'manifest-cdxgen-npm-lock-v3', - reason: - 'The restricted npm lock v3 path passed local command smoke, but installed Rollup module bytes are not authenticated against the frozen package tarballs or generated bundle. See the explicitly unverified source inventory.', - }, { id: 'cdxgen-other-modes', reason: - 'Only one npm package-lock.json v3 project is implemented; other project types and modes are not included.', - }, - { - id: 'manifest-cdxgen-yarn-classic', - reason: - 'Synp v1.9.14 API conversion and cdxgen package-lock v1 API smoke passed, but Synp Rollup provenance remains unauthenticated and its third-party notice inventory has missing-license-text obligations.', + 'The bundled cdxgen supports npm lockfile v3 and Yarn Classic with Synp.', }, ] : [ { id: 'cdxgen', - reason: `No cdxgen API payload is embedded for ${triple}; only darwin-arm64 has a qualified VFS bundle.`, + reason: `No cdxgen API payload is embedded for ${triple}.`, }, ]), - { - id: 'synp', - reason: hasSynp - ? '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.', - }, - ...(!hasCoana + ...(!hasCdxgen || !hasSynp ? [ { - 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.', + id: 'synp', + reason: `The Yarn Classic adapter is unavailable for ${triple}.`, }, ] : []), diff --git a/src/sea/paths/archive.mts b/src/sea/paths/archive.mts new file mode 100644 index 000000000..8a0d98226 --- /dev/null +++ b/src/sea/paths/archive.mts @@ -0,0 +1,6 @@ +export const SEA_RESOURCES_DIRECTORY = 'resources' +export const SEA_CAPABILITIES_PATH = `${SEA_RESOURCES_DIRECTORY}/capabilities.json` + +export function seaArchivePaths(rootFiles: readonly string[]): string[] { + return ['dist', 'external', ...rootFiles, SEA_RESOURCES_DIRECTORY, 'tools'] +} diff --git a/src/sea/paths/coana-cache.mts b/src/sea/paths/coana-cache.mts new file mode 100644 index 000000000..7ab3dacf1 --- /dev/null +++ b/src/sea/paths/coana-cache.mts @@ -0,0 +1,3 @@ +import { COANA_CACHE_FILENAME } from '../../paths/coana.mts' + +export const SEA_COANA_CACHE_PATH = `dist/${COANA_CACHE_FILENAME}` diff --git a/src/sea/paths/coana.mts b/src/sea/paths/coana.mts deleted file mode 100644 index b5d286bb5..000000000 --- a/src/sea/paths/coana.mts +++ /dev/null @@ -1,26 +0,0 @@ -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/paths/native-tools.mts b/src/sea/paths/native-tools.mts new file mode 100644 index 000000000..6072dbd14 --- /dev/null +++ b/src/sea/paths/native-tools.mts @@ -0,0 +1,20 @@ +import { SEA_RESOURCES_DIRECTORY } from './archive.mts' + +export const SEA_NODE_LICENSE_PATH = 'node-runtime-LICENSE' +export const SEA_SOCKET_PATCH_LICENSE_PATH = `${SEA_RESOURCES_DIRECTORY}/socket-patch-LICENSE.txt` + +const TOOL_DIRECTORIES = { + node: 'tools/node', + 'socket-patch': SEA_RESOURCES_DIRECTORY, + uv: 'tools/uv', +} as const + +export type SeaNativeTool = keyof typeof TOOL_DIRECTORIES + +export function seaNativeToolPaths(id: SeaNativeTool, platform: string) { + const directory = TOOL_DIRECTORIES[id] + return { + binary: `${directory}/${id}${platform === 'win32' ? '.exe' : ''}`, + digest: `${directory}/${id}.sha256`, + } +} diff --git a/src/sea/rollup-workers.mts b/src/sea/rollup-workers.mts new file mode 100644 index 000000000..5b1ac7dbf --- /dev/null +++ b/src/sea/rollup-workers.mts @@ -0,0 +1,11 @@ +import { babel } from '@rollup/plugin-babel' + +export function seaWorkerTypeScript() { + return babel({ + babelHelpers: 'bundled', + babelrc: false, + configFile: false, + extensions: ['.mts'], + presets: ['@babel/preset-typescript'], + }) +} diff --git a/src/sea/runtime.mts b/src/sea/runtime.mts index 439489605..108f290dd 100644 --- a/src/sea/runtime.mts +++ b/src/sea/runtime.mts @@ -7,8 +7,11 @@ 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 { SEA_CAPABILITIES_PATH } from './paths/archive.mts' +import { SEA_COANA_CACHE_PATH } from './paths/coana-cache.mts' +import { seaNativeToolPaths } from './paths/native-tools.mts' +import type { SeaNativeTool } from './paths/native-tools.mts' import type { StdioOptions } from 'node:child_process' /** @@ -47,7 +50,6 @@ const sea = (() => { try { return createRequire(import.meta.url)('node:sea') as { isSea?: () => boolean - getAsset?: (key: string) => ArrayBuffer | Uint8Array } } catch { // The regular Socket CLI supports Node releases predating `node:sea`. @@ -62,17 +64,11 @@ type SeaGlobal = typeof globalThis & { __socketSeaVfsRoot?: string } // are staged under the archive root by a later helper-payload build slice; // absent files remain unavailable and fail closed here. const embeddedJsToolEntrypoints = Object.freeze({ - cdxgen: 'tools/cdxgen/sea-worker.mjs', - 'coana-cache': 'dist/coana-cache.mjs', + cdxgen: 'tools/cdxgen/sea-worker.js', + 'coana-cache': SEA_COANA_CACHE_PATH, 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'}`, -}) - function getVfsRoot(): string { const root = (globalThis as SeaGlobal).__socketSeaVfsRoot if (!root) { @@ -126,36 +122,10 @@ function signalFromAbortReason(reason: unknown): NodeJS.Signals | null { : null } -export function isStandaloneSea(): boolean { +export function isSea(): boolean { return typeof sea.isSea === 'function' && sea.isSea() } -export function getEmbeddedAsset(id: string): Buffer { - if (!isStandaloneSea()) { - throw new Error( - `Embedded asset '${id}' is available only in the standalone Socket build`, - ) - } - const files: Record = { - 'socket-patch': `resources/${process.platform === 'win32' ? 'socket-patch.exe' : 'socket-patch'}`, - 'socket-patch-sha256': 'resources/socket-patch.sha256', - } - const relative = files[id] - const root = (globalThis as SeaGlobal).__socketSeaVfsRoot - if (!relative || !root) { - throw new Error( - `Standalone Socket asset '${id}' is missing from this build`, - ) - } - try { - return readFileSync(path.join(root, relative)) - } catch { - throw new Error( - `Standalone Socket asset '${id}' is missing from this build`, - ) - } -} - export function getEmbeddedVfsPath(relativePath: string): string { const root = getVfsRoot() const resolved = path.resolve(root, relativePath) @@ -167,10 +137,10 @@ export function getEmbeddedVfsPath(relativePath: string): string { /** Fail closed unless the build manifest explicitly advertises this tool. */ export function assertEmbeddedToolAvailable( - id: 'cdxgen' | 'coana' | 'synp', + id: 'cdxgen' | 'synp', capability?: 'manifest-cdxgen-npm-lock-v3' | 'manifest-cdxgen-yarn-classic', ): void { - if (!isStandaloneSea()) { + if (!isSea()) { return } const root = (globalThis as SeaGlobal).__socketSeaVfsRoot @@ -180,7 +150,7 @@ export function assertEmbeddedToolAvailable( throw new Error('missing VFS root') } capabilities = JSON.parse( - readFileSync(path.join(root, 'resources/capabilities.json'), 'utf8'), + readFileSync(path.join(root, SEA_CAPABILITIES_PATH), 'utf8'), ) } catch { throw new Error( @@ -230,73 +200,24 @@ export function assertEmbeddedToolAvailable( ) } -export async function getBundledTool(id: string): Promise { - if (id !== 'socket-patch' && id !== 'uv' && id !== 'coana-node') { - throw new Error( - `Bundled tool '${id}' is not configured in this SEA foundation`, - ) - } - if (!isStandaloneSea()) { +export async function getBundledTool(id: SeaNativeTool): Promise { + if (!isSea()) { throw new Error( `Bundled tool '${id}' is available only in the standalone Socket build`, ) } - - 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(), - id === 'uv' ? 'tools/uv/uv.sha256' : SEA_COANA_VFS_PATHS.nodeDigest, - ), - 'utf8', - ) - const actualDigest = createHash('sha256').update(binary).digest('hex') - if ( - !/^[a-f0-9]{64}$/.test(expectedDigest.trim()) || - actualDigest !== expectedDigest.trim() - ) { - throw new Error(`Embedded ${id} payload failed SHA-256 verification`) - } - const directory = await fs.mkdtemp( - path.join(os.tmpdir(), 'socket-cli-sea-'), - ) - const filename = path.join(directory, path.basename(relative)) - try { - await fs.writeFile(filename, binary, { flag: 'wx', mode: 0o700 }) - if (process.platform !== 'win32') { - await fs.chmod(filename, 0o700) - } - extractedToolDirectories.set(filename, directory) - return filename - } catch (error) { - await fs.rm(directory, { recursive: true, force: true }) - throw error - } - } - - const binary = getEmbeddedAsset('socket-patch') - const expectedDigest = getEmbeddedAsset('socket-patch-sha256') - .toString('utf8') - .trim() - const actualDigest = createHash('sha256').update(binary).digest('hex') - if ( - !/^[a-f0-9]{64}$/.test(expectedDigest) || - actualDigest !== expectedDigest - ) { - throw new Error('Embedded socket-patch payload failed SHA-256 verification') + const paths = seaNativeToolPaths(id, process.platform) + const root = getVfsRoot() + const [binary, digest] = await Promise.all([ + fs.readFile(path.join(root, paths.binary)), + fs.readFile(path.join(root, paths.digest), 'utf8'), + ]) + if (createHash('sha256').update(binary).digest('hex') !== digest.trim()) { + throw new Error(`Embedded ${id} payload failed SHA-256 verification`) } const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'socket-cli-sea-')) - const filename = path.join( - directory, - process.platform === 'win32' ? 'socket-patch.exe' : 'socket-patch', - ) + const filename = path.join(directory, path.basename(paths.binary)) try { await fs.writeFile(filename, binary, { flag: 'wx', mode: 0o700 }) if (process.platform !== 'win32') { @@ -305,18 +226,27 @@ export async function getBundledTool(id: string): Promise { extractedToolDirectories.set(filename, directory) return filename } catch (error) { - await fs.rm(directory, { recursive: true, force: true }) + await removeExtractedToolDirectory(directory) throw error } } +function removeExtractedToolDirectory(directory: string): Promise { + return fs.rm(directory, { + recursive: true, + force: true, + maxRetries: 5, + retryDelay: 100, + }) +} + export async function cleanupBundledTool(filename: string): Promise { const directory = extractedToolDirectories.get(filename) if (!directory) { return } + await removeExtractedToolDirectory(directory) extractedToolDirectories.delete(filename) - await fs.rm(directory, { recursive: true, force: true }) } export async function runEmbeddedJsTool( @@ -324,7 +254,7 @@ export async function runEmbeddedJsTool( args: readonly string[], options: EmbeddedToolRunOptions = {}, ): Promise { - if (!isStandaloneSea()) { + if (!isSea()) { throw new Error( `Embedded JavaScript tool '${id}' is available only in the standalone Socket build`, ) diff --git a/src/sea/stage/coana.mts b/src/sea/stage/coana.mts deleted file mode 100644 index a3c7f6222..000000000 --- a/src/sea/stage/coana.mts +++ /dev/null @@ -1,302 +0,0 @@ -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 { errorMessage } from '../../utils/errors.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( - result.cause ? `${result.message} (${result.cause})` : result.message, - ) - } - 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( - `Could not fetch Coana ${COANA_CLI_VERSION} artifacts for ${org.data}: ${errorMessage(error)}. Check that the build token can access Coana artifacts for this organization.`, - { 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/sea/stage/synp.mts b/src/sea/stage/synp.mts index dd952df37..3047478fb 100644 --- a/src/sea/stage/synp.mts +++ b/src/sea/stage/synp.mts @@ -86,7 +86,7 @@ export async function stageSynp( ...process.env, SEA_SYNP_INPUT: path.join( STAGE_DIRECTORY, - '../adapters/synp-worker.mjs', + '../adapters/synp-worker.mts', ), SEA_SYNP_OUTPUT: outputRoot, }, diff --git a/src/sea/stage/uv-pins.json b/src/sea/stage/uv-pins.json index eb7ae8247..c962ed999 100644 --- a/src/sea/stage/uv-pins.json +++ b/src/sea/stage/uv-pins.json @@ -1,10 +1,8 @@ { "package": "uv", - "version": "0.12.15", + "version": "0.13.10", "license": "MIT OR Apache-2.0", "repository": "https://github.com/astral-sh/uv", - "releaseBaseUrl": "https://github.com/astral-sh/uv/releases/download/0.12.15", - "licenseBaseUrl": "https://raw.githubusercontent.com/astral-sh/uv/0.12.15", "licenseFiles": [ { "name": "LICENSE-MIT", @@ -18,39 +16,33 @@ "targets": { "darwin-arm64": { "archive": "uv-aarch64-apple-darwin.tar.gz", - "sha256": "dc304b9ed1b24174572290fba60ac3f6fe63c73a671f0439e62a91375841964d", - "executable": "uv-aarch64-apple-darwin/uv", - "binary": "uv" + "sha256": "e419bf07533bdbf48795fc793601c834dd79db57a8c49ce8e25cfe3a8639958d", + "executable": "uv-aarch64-apple-darwin/uv" }, "darwin-x64": { "archive": "uv-x86_64-apple-darwin.tar.gz", - "sha256": "e9ca61775532368fe518ab03e7a354c7ecab8ccb3c7d941c775fcc4a362b801b", - "executable": "uv-x86_64-apple-darwin/uv", - "binary": "uv" + "sha256": "153e03197588204c04fc4c81cc4bafbfa4280222a385e4ee36a87aeec0ae63b4", + "executable": "uv-x86_64-apple-darwin/uv" }, "linux-arm64": { "archive": "uv-aarch64-unknown-linux-gnu.tar.gz", - "sha256": "0e9a3499b0587d449c9ff684c0160da607826e4af1cee220bc87f378702d3e08", - "executable": "uv-aarch64-unknown-linux-gnu/uv", - "binary": "uv" + "sha256": "14590f644805a6234ffe071154340669e38137f38e60aa9629690119704107d2", + "executable": "uv-aarch64-unknown-linux-gnu/uv" }, "linux-x64": { "archive": "uv-x86_64-unknown-linux-gnu.tar.gz", - "sha256": "f97935763c04be3e692460a7aaeaaab8fc3b78fcf8b389da820b38ae7423a638", - "executable": "uv-x86_64-unknown-linux-gnu/uv", - "binary": "uv" + "sha256": "bf65ac1a0af10f92c522d91ac096c7c0a39657647b155577e7836c2cbbb4526c", + "executable": "uv-x86_64-unknown-linux-gnu/uv" }, "win32-arm64": { "archive": "uv-aarch64-pc-windows-msvc.zip", - "sha256": "a37c8e96cb1260488c8510b64c848533a3a82a2fdf9e905de7c2700ceebf6437", - "executable": "uv.exe", - "binary": "uv.exe" + "sha256": "f223bcd3fa010174ffeeb885cc1d5334bb81388640c65baa5b8b42b47017337e", + "executable": "uv.exe" }, "win32-x64": { "archive": "uv-x86_64-pc-windows-msvc.zip", - "sha256": "477bd99a84e34891f2bd4c9152ddeb74e971accccbc59c0f0301f11f08a32d46", - "executable": "uv.exe", - "binary": "uv.exe" + "sha256": "297b3881fe1adfb922becc2c1613202abb41dc83ea5ff43d472aa087ca1f8683", + "executable": "uv.exe" } } } diff --git a/src/sea/stage/uv.mts b/src/sea/stage/uv.mts index 8a17c69c3..af0df2583 100644 --- a/src/sea/stage/uv.mts +++ b/src/sea/stage/uv.mts @@ -5,9 +5,11 @@ import { promises as fs } from 'node:fs' import path from 'node:path' import { gunzipSync, inflateRawSync } from 'node:zlib' +import { uvLicenseUrl, uvReleaseUrl } from '../../paths/uv.mts' import { downloadBytes } from '../download-bytes.mts' import { cachedDownload } from '../download-cache.mts' import pins from './uv-pins.json' with { type: 'json' } +import { seaNativeToolPaths } from '../paths/native-tools.mts' const UV_VERSION = pins.version const MAX_ARCHIVE_BYTES = 40 * 1024 * 1024 @@ -21,7 +23,6 @@ type UvTargetPin = { archive: string sha256: string executable: string - binary: string } type UvPins = { @@ -29,8 +30,6 @@ type UvPins = { version: string license: string repository: string - releaseBaseUrl: string - licenseBaseUrl: string licenseFiles: Array<{ name: string; sha256: string }> targets: Record } @@ -417,7 +416,7 @@ export async function stageUv( } const target = targetFor(platform, arch) const pin = uvPins.targets[target] - const sourceUrl = `${uvPins.releaseBaseUrl}/${pin.archive}` + const sourceUrl = uvReleaseUrl(pin.archive) const archive = await cachedDownload( sourceUrl, { @@ -445,10 +444,11 @@ export async function stageUv( : readTarExecutable(archive, pin.executable) validateBinary(executable, target) - const payloadRoot = path.join(stageRoot, 'tools/uv') + const paths = seaNativeToolPaths('uv', platform) + const binaryPath = path.join(stageRoot, paths.binary) + const payloadRoot = path.dirname(binaryPath) await fs.rm(payloadRoot, { recursive: true, force: true }) await fs.mkdir(payloadRoot, { recursive: true }) - const binaryPath = path.join(payloadRoot, pin.binary) await fs.writeFile(binaryPath, executable, { flag: 'wx', mode: 0o755, @@ -458,13 +458,13 @@ export async function stageUv( } validateUvVersion(binaryPath) const binaryDigest = sha256(executable) - await fs.writeFile(path.join(payloadRoot, 'uv.sha256'), `${binaryDigest}\n`, { + await fs.writeFile(path.join(stageRoot, paths.digest), `${binaryDigest}\n`, { flag: 'wx', }) const licenseFiles: StagedUv['licenseFiles'] = [] for (const license of uvPins.licenseFiles) { - const sourceUrl = `${uvPins.licenseBaseUrl}/${license.name}` + const sourceUrl = uvLicenseUrl(license.name) const bytes = await cachedDownload( sourceUrl, { @@ -533,7 +533,7 @@ export async function stageUv( archive: pin.archive, sourceUrl, declaredArchiveSha256: pin.sha256, - binaryPath: path.relative(stageRoot, binaryPath).split(path.sep).join('/'), + binaryPath: paths.binary, binarySha256: binaryDigest, binarySize: executable.length, licenseFiles, diff --git a/src/utils/agent.mts b/src/utils/agent.mts index 99aeaf96d..43524c479 100644 --- a/src/utils/agent.mts +++ b/src/utils/agent.mts @@ -2,7 +2,7 @@ import { spawn } from './spawn.mts' import constants, { NPM, PNPM } from '../constants.mts' -import { isStandaloneSea } from '../sea/runtime.mts' +import { isSea } from '../sea/runtime.mts' import { shadowNpmInstall } from '../shadow/npm/install.mts' import type { EnvDetails } from './package-environment.mts' @@ -50,7 +50,7 @@ export function runAgentInstall( const { agent, agentExecPath, pkgPath } = pkgEnvDetails const { args = [], spinner, ...spawnOptions } = options const isNpm = agent === NPM - if (isNpm && !isStandaloneSea()) { + if (isNpm && !isSea()) { return shadowNpmInstall({ agentExecPath, cwd: pkgPath, diff --git a/src/utils/api-timeout.integration.test.mts b/src/utils/api-timeout.integration.test.mts index 73891a946..14b4aba7e 100644 --- a/src/utils/api-timeout.integration.test.mts +++ b/src/utils/api-timeout.integration.test.mts @@ -41,6 +41,8 @@ let isolatedHome = '' let certificatePath = '' // Milliseconds: this sets a three-minute lifetime for the test certificate. const TEST_CERT_VALIDITY_MS = 3 * 60 * 1000 +const OPENSSL_TIMEOUT_MS = 15_000 +const SETUP_TIMEOUT_MS = 2 * OPENSSL_TIMEOUT_MS + 10_000 function handleRequest( request: IncomingMessage, @@ -133,17 +135,23 @@ async function generateLocalhostCertificate( new Promise((resolve, reject) => { const openssl = spawn('openssl', args, { cwd: workingDirectory, - stdio: 'ignore', + stdio: ['ignore', 'ignore', 'pipe'], + timeout: OPENSSL_TIMEOUT_MS, windowsHide: true, }) + let stderr = '' + openssl.stderr.setEncoding('utf8') + openssl.stderr.on('data', (chunk: string) => { + stderr += chunk + }) openssl.once('error', reject) - openssl.once('close', code => { + openssl.once('close', (code, signal) => { if (code === 0) { resolve() } else { reject( new Error( - `OpenSSL failed to create the test certificate (${code})`, + `OpenSSL ${args[0]} failed (${code ?? signal}): ${stderr.trim()}`, ), ) } @@ -153,7 +161,9 @@ async function generateLocalhostCertificate( 'req', '-new', '-newkey', - 'rsa:2048', + 'ec', + '-pkeyopt', + 'ec_paramgen_curve:P-256', '-nodes', '-sha256', '-subj', @@ -286,7 +296,7 @@ describe('v1 direct Socket API timeout configuration', () => { '[ localhost ]', 'basicConstraints = critical,CA:FALSE', 'subjectAltName = DNS:localhost,IP:127.0.0.1', - 'keyUsage = critical,digitalSignature,keyEncipherment', + 'keyUsage = critical,digitalSignature', 'extendedKeyUsage = serverAuth', '', ].join('\n'), @@ -336,7 +346,7 @@ describe('v1 direct Socket API timeout configuration', () => { apiFetch = api.apiFetch queryApi = api.queryApiSafeTextWithStatus sendApiRequest = api.sendApiRequest - }) + }, SETUP_TIMEOUT_MS) afterAll(async () => { for (const timer of responseTimers) { @@ -349,7 +359,14 @@ describe('v1 direct Socket API timeout configuration', () => { }) } vi.unstubAllEnvs() - rmSync(isolatedHome, { force: true, recursive: true }) + if (isolatedHome) { + rmSync(isolatedHome, { + force: true, + recursive: true, + maxRetries: 5, + retryDelay: 100, + }) + } }) it('applies configured timeout to direct GET and POST requests', async () => { diff --git a/src/utils/coana-release.test.mts b/src/utils/coana-release.test.mts index 442a58258..67cfc2794 100644 --- a/src/utils/coana-release.test.mts +++ b/src/utils/coana-release.test.mts @@ -16,10 +16,12 @@ * - src/vendor/coana-cache.mjs (the cache script) */ +import { createHash } from 'node:crypto' import { promises as fs } from 'node:fs' import os from 'node:os' import path from 'node:path' +import { c as createTar } from 'tar' import { afterAll, afterEach, @@ -30,8 +32,7 @@ import { vi, } from 'vitest' -import { spawn } from './spawn.mts' -import constants, { SOCKET_CLI_API_TOKEN_VARIABLES } from '../constants.mts' +import * as api from './api.mts' import { spawnCoana } from './coana/release.mts' import { overrideCachedConfig, resetConfigForTesting } from './config.mts' import { @@ -39,7 +40,16 @@ import { getDefaultApiBaseUrl, resolveDefaultApiToken, } from './sdk.mts' +import { spawn } from './spawn.mts' +import constants, { SOCKET_CLI_API_TOKEN_VARIABLES } from '../constants.mts' +import { + COANA_CLI_WRAPPER_FILENAME, + coanaCacheDistPath, + coanaCliWrapperPath, +} from '../paths/coana.mts' +import * as seaRuntime from '../sea/runtime.mts' +const CACHE_SCRIPT = coanaCacheDistPath(constants.distPath) const VERSION = '1.2.3' // Prints what it was run with, or fails the way Coana does for some errors. @@ -83,20 +93,10 @@ describe('spawnCoana', () => { process.env['XDG_CACHE_HOME'] = path.join(tmpDir, 'cache') const extracted = path.join(tmpDir, 'extracted') await fs.mkdir(extracted) - await fs.writeFile( - path.join(extracted, 'cli-wrapper.mjs'), - FAKE_CLI_WRAPPER, - ) + await fs.writeFile(coanaCliWrapperPath(extracted), FAKE_CLI_WRAPPER) await spawn( 'node', - [ - path.join(constants.distPath, 'coana-cache.mjs'), - 'install', - VERSION, - 'cli', - 'a'.repeat(64), - extracted, - ], + [CACHE_SCRIPT, 'install', VERSION, 'cli', 'a'.repeat(64), extracted], { stdio: 'pipe' }, ) }) @@ -121,6 +121,66 @@ describe('spawnCoana', () => { expect(run.cwd).toBe(tmpDir) }) + it('downloads and runs Coana on the first SEA invocation', async () => { + const archive = path.join(tmpDir, 'coana.tar.gz') + const fixture = path.join(tmpDir, 'download-fixture') + await fs.mkdir(fixture) + await fs.writeFile(coanaCliWrapperPath(fixture), FAKE_CLI_WRAPPER) + await createTar({ cwd: fixture, file: archive, gzip: true }, [ + COANA_CLI_WRAPPER_FILENAME, + ]) + const bytes = await fs.readFile(archive) + const version = '1.2.4' + const url = 'https://example.test/coana.tar.gz' + const sea = vi.spyOn(seaRuntime, 'isSea').mockReturnValue(true) + const node = vi + .spyOn(seaRuntime, 'getBundledTool') + .mockResolvedValue(process.execPath) + const cache = vi + .spyOn(seaRuntime, 'runEmbeddedJsTool') + .mockResolvedValueOnce({ code: 4, signal: null }) + .mockImplementation(async (_id, args, options) => { + const result = await spawn(process.execPath, [CACHE_SCRIPT, ...args], { + env: options?.env, + stdio: 'pipe', + }) + return { code: 0, signal: null, stdout: result.stdout } + }) + const request = vi.spyOn(api, 'sendApiRequest').mockResolvedValue({ + ok: true, + data: { + version, + components: { + cli: { + sha256: createHash('sha256').update(bytes).digest('hex'), + size: bytes.length, + url, + }, + }, + }, + }) + const download = vi + .spyOn(api, 'apiFetch') + .mockResolvedValue(new Response(new Uint8Array(bytes))) + try { + const options = { coanaVersion: version, cwd: tmpDir } + expect((await runFake(options)).args).toEqual(['run', '.']) + expect((await runFake(options)).args).toEqual(['run', '.']) + expect(request).toHaveBeenCalledOnce() + expect(request).toHaveBeenCalledWith('orgs/acme/coana-cli/artifacts', { + body: { components: ['cli'], version }, + method: 'POST', + }) + expect(download).toHaveBeenCalledOnce() + expect(download).toHaveBeenCalledWith(url, expect.anything()) + expect(node).toHaveBeenCalledWith('node') + } finally { + for (const spy of [sea, node, cache, request, download]) { + spy.mockRestore() + } + } + }) + it('strips npm_package_* env vars to avoid E2BIG in big monorepos', async () => { process.env['npm_package_dependencies_react'] = '^18.2.0' // These carry registry and proxy settings from .npmrc. diff --git a/src/utils/coana/release.mts b/src/utils/coana/release.mts index f04b8a95c..50017b7ad 100644 --- a/src/utils/coana/release.mts +++ b/src/utils/coana/release.mts @@ -13,41 +13,41 @@ */ 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' 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 constants, { COANA_CLI_VERSION, ERROR_UNABLE_RESOLVE_ORG, SOCKET_CLI_API_TOKEN_VARIABLES, } from '../../constants.mts' +import { + COANA_CACHE_FILENAME, + coanaCacheDistPath, + coanaCliWrapperPath, +} from '../../paths/coana.mts' +import { + cleanupBundledTool, + getBundledTool, + isSea, + runEmbeddedJsTool, +} from '../../sea/runtime.mts' import { apiFetch, sendApiRequest } from '../api.mts' +import { debugDir, debugFn } from '../debug.mts' import { errorMessage } from '../errors.mts' import { withTmpDir } from '../fs.mts' +import { logger } from '../logger.mts' import { getCliUserAgent, getDefaultApiBaseUrl, getDefaultProxyUrl, resolveDefaultApiToken, } 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 { spawn } from '../spawn.mts' import type { CResult } from '../../types.mts' import type { SpawnOptions } from '../spawn.mts' @@ -82,7 +82,6 @@ type CoanaSpawnOptions = { } const CACHE_NOT_WRITABLE_EXIT_CODE = 3 -const COANA_CACHE_SCRIPT = 'coana-cache.mjs' const COMPONENT = 'cli' const NOT_CACHED_EXIT_CODE = 4 const SHA256_REGEXP = /^[0-9a-f]{64}$/ @@ -102,7 +101,7 @@ function cacheResultToCResult(result: CoanaCacheResult): CResult { ? 'Cannot write to the Coana cache' : 'The Coana cache failed', cause: - result.stderr || `${COANA_CACHE_SCRIPT} exited with ${result.exitCode}`, + result.stderr || `${COANA_CACHE_FILENAME} exited with ${result.exitCode}`, } } @@ -385,7 +384,7 @@ async function runCoanaCache( args: string[], env: NodeJS.ProcessEnv, ): Promise { - if (isStandaloneSea()) { + if (isSea()) { const result = await runEmbeddedJsTool('coana-cache', args, { env, stdio: 'pipe', @@ -399,7 +398,7 @@ async function runCoanaCache( try { const result = await spawn( constants.execPath, - [path.join(constants.distPath, COANA_CACHE_SCRIPT), ...args], + [coanaCacheDistPath(constants.distPath), ...args], { env, stdio: 'pipe' }, ) return { @@ -420,74 +419,6 @@ 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 @@ -518,32 +449,7 @@ export async function spawnCoana( } as CoanaSpawnOptions const localPath = process.env['SOCKET_CLI_COANA_LOCAL_PATH'] - const standaloneSea = isStandaloneSea() - if ( - standaloneSea && - localPath && - (localPath.endsWith('.js') || localPath.endsWith('.mjs')) - ) { - return { - ok: false, - message: - 'Cannot launch a JavaScript Coana CLI from the standalone Socket build', - cause: - '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.`, - } - } - + const runningInSea = isSea() let apiToken: string | undefined try { apiToken = await resolveDefaultApiToken() @@ -588,37 +494,18 @@ 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: errorMessage(error), - } - } - } - let scriptPath = localPath if (!scriptPath) { - 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') + const coanaDir = await getCoanaCliDir( + coanaVersion || COANA_CLI_VERSION, + org, + userEnv, + spinner, + ) + if (!coanaDir.ok) { + return coanaDir } + scriptPath = coanaCliWrapperPath(coanaDir.data) } // A local path may name a native binary. @@ -627,8 +514,8 @@ export async function spawnCoana( try { const executable = isBinary ? scriptPath - : standaloneSea - ? (nodePath = await getBundledTool('coana-node')) + : runningInSea + ? (nodePath = await getBundledTool('node')) : constants.execPath const spawnResult = await spawn( executable, diff --git a/src/utils/dlx.mts b/src/utils/dlx.mts index 10239dc98..003e7d3b6 100644 --- a/src/utils/dlx.mts +++ b/src/utils/dlx.mts @@ -29,7 +29,7 @@ import constants, { } from '../constants.mts' import { findUp } from './fs.mts' import { isYarnBerry } from './yarn-version.mts' -import { isStandaloneSea } from '../sea/runtime.mts' +import { isSea } from '../sea/runtime.mts' import type { SpawnExtra } from './spawn.mts' import type { ShadowBinOptions, ShadowBinResult } from '../shadow/npm-base.mts' @@ -61,7 +61,7 @@ export async function spawnDlx( // Standalone builds must never turn a missing embedded helper into a // package-manager install. Keep this guard ahead of lockfile detection and // shadow-bin loading so every generic dlx caller fails closed consistently. - if (isStandaloneSea()) { + if (isSea()) { throw new Error( `Cannot run '${packageSpec.name}' from a standalone Socket CLI: this helper is not bundled for this target, and runtime package installation is disabled.`, ) diff --git a/src/utils/is-record.d.mts b/src/utils/is-record.d.mts deleted file mode 100644 index ef4977156..000000000 --- a/src/utils/is-record.d.mts +++ /dev/null @@ -1 +0,0 @@ -export function isRecord(value: unknown): value is Record diff --git a/src/utils/is-record.mjs b/src/utils/is-record.mjs deleted file mode 100644 index 9b109d83a..000000000 --- a/src/utils/is-record.mjs +++ /dev/null @@ -1,4 +0,0 @@ -/** Return true for non-null object values that are not arrays. */ -export function isRecord(value) { - return value !== null && typeof value === 'object' && !Array.isArray(value) -} diff --git a/src/utils/oauth.mts b/src/utils/oauth.mts index feb479543..81ba38753 100644 --- a/src/utils/oauth.mts +++ b/src/utils/oauth.mts @@ -7,7 +7,7 @@ import path from 'node:path' import { HttpsProxyAgent } from 'hpagent' import open from 'open' -import { isRecord } from './is-record.mjs' +import { isRecord } from './objects.mts' import { getExtraCaCerts } from './api-transport.mts' diff --git a/src/utils/objects.mts b/src/utils/objects.mts index b17b6b6bc..31c5b71bc 100644 --- a/src/utils/objects.mts +++ b/src/utils/objects.mts @@ -1,4 +1,3 @@ -import { isRecord } from './is-record.mjs' const { fromEntries: ObjectFromEntries, hasOwn: ObjectHasOwn } = Object const { ownKeys: ReflectOwnKeys } = Reflect @@ -49,7 +48,11 @@ export function isObject(value: any): value is object { return value !== null && typeof value === 'object' } -export { isRecord } +export function isRecord( + value: unknown, +): value is Record { + return isObject(value) && !Array.isArray(value) +} export function toSortedObject>( obj: T, diff --git a/src/utils/self-update.mts b/src/utils/self-update.mts index 43c05d395..82eaae4ec 100644 --- a/src/utils/self-update.mts +++ b/src/utils/self-update.mts @@ -2,11 +2,11 @@ import updateNotifier from 'tiny-updater' import { logger } from './logger.mts' import constants from '../constants.mts' -import { isStandaloneSea } from '../sea/runtime.mts' +import { isSea } from '../sea/runtime.mts' /** Format a release notice for the current Socket distribution. */ export function formatUpdateNotice(current: string, latest: string): string { - return isStandaloneSea() + return isSea() ? `Socket ${current} → ${latest}. Run: socket update` : `Socket ${current} → ${latest}. Update with your favorite package manager.` } @@ -21,7 +21,7 @@ export async function runSelfUpdateCheck(): Promise { // A standalone executable cannot be updated through the npm package path. // Keep its startup independent from registry metadata and avoid suggesting // that an npm CLI update can replace this artifact. - if (isStandaloneSea()) { + if (isSea()) { return } diff --git a/test/lib/native/cli-harness.mts b/test/lib/native/cli-harness.mts index 3e1b5776d..0279bf3d0 100644 --- a/test/lib/native/cli-harness.mts +++ b/test/lib/native/cli-harness.mts @@ -114,6 +114,7 @@ export async function captureFlow(options: { checkpointName?: string env?: NodeJS.ProcessEnv prepare?: (fixture: NativeTerminalFixture) => Promise + verify?: (fixture: NativeTerminalFixture) => Promise }): Promise { const { binary } = readNativeTestEnvironment() const { @@ -143,6 +144,7 @@ export async function captureFlow(options: { ) expect(fixture.terminal.scrollback.getText().trim()).toBe('') expect(fixture.terminal.screen.getText()).toContain(expectedText) + await options.verify?.(fixture) const checkpoint = await captureCheckpoint( fixture.terminal, options.checkpointName ?? 'help', diff --git a/test/native/commands/cli.native.test.mts b/test/native/commands/cli.native.test.mts index 9798b389a..6dcbae26c 100644 --- a/test/native/commands/cli.native.test.mts +++ b/test/native/commands/cli.native.test.mts @@ -9,6 +9,11 @@ import { FLAG_HELP, FLAG_VERSION, } from '../../../src/constants.mts' +import { + CDXGEN_FIXTURE_OUTPUT, + assertCdxgenFixtureOutput, + writeCdxgenFixture, +} from '../../../src/sea/build/cdxgen-fixture.mts' import { captureFlow, createNativeTerminalFixture, @@ -218,6 +223,34 @@ describe('native Socket CLI', () => { }) }, 30_000) + it.each(['npm', 'yarn'] as const)( + 'captures the bundled cdxgen SBOM for %s', + async mode => { + await captureFlow({ + flow: `socket-cdxgen-${mode}`, + args: ['manifest', 'cdxgen', '--type', 'npm', FLAG_CONFIG, '{}'], + expectedText: `${CDXGEN_FIXTURE_OUTPUT} created!`, + exitCode: 0, + cols: 140, + rows: 24, + checkpointName: 'sbom', + prepare: ({ cwd }) => writeCdxgenFixture(cwd, mode), + verify: ({ cwd }) => assertCdxgenFixtureOutput(cwd, mode), + }) + }, + 60_000, + ) + + it('captures the bundled uv version in the SEA smoke test', async () => { + await captureFlow({ + flow: 'socket-sea-uv', + args: ['sea', 'smoke-test'], + expectedText: 'uv ', + exitCode: 0, + checkpointName: 'version', + }) + }, 60_000) + it('captures the scan setup selection and cancellation interaction', async () => { const fixture = await createNativeTerminalFixture(24) const { cwd, normalizer, terminal } = fixture diff --git a/test/setup-uv.test.mts b/test/setup-uv.test.mts index f6356d694..d59d2c718 100644 --- a/test/setup-uv.test.mts +++ b/test/setup-uv.test.mts @@ -15,6 +15,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { parse } from 'yaml' import { installUvForCi, uvSetupRelease } from '../scripts/setup/uv.mts' +import pins from '../src/sea/stage/uv-pins.json' with { type: 'json' } const directories: string[] = [] @@ -26,7 +27,7 @@ async function uvFixture(arch = 'x64') { const bytes = Buffer.from('fixture uv archive bytes') const release = { ...uvSetupRelease('linux', arch), - digest: createHash('sha512').update(bytes).digest('base64'), + digest: createHash('sha256').update(bytes).digest('hex'), } const fetcher = vi.fn(async () => new Response(bytes)) const extract = vi.fn(async (archive: string, destination: string) => { @@ -35,12 +36,15 @@ async function uvFixture(arch = 'x64') { const bin = path.join(destination, release.archiveRoot) await mkdir(bin, { recursive: true }) const executable = path.join(bin, 'uv') - await writeFile(executable, '#!/bin/sh\nprintf "uv 0.12.15\\n"\n') + await writeFile( + executable, + `#!/bin/sh\nprintf "uv ${release.version}\\n"\n`, + ) await chmod(executable, 0o755) }) const probe = vi.fn(async () => { expect(await readFile(githubPath, 'utf8')).toBe('existing-bin\n') - return 'uv 0.12.15 (fixture)' + return `uv ${release.version} (fixture)` }) return { dependencies: { extract, fetcher, probe, release }, @@ -69,15 +73,13 @@ describe('verified uv installation', () => { const installation = fixture.dependencies.extract.mock.calls[0]![1] expect(result).toEqual({ bin: path.join(installation, 'uv-' + target + '-unknown-linux-gnu'), - version: '0.12.15', + version: pins.version, }) expect(await readFile(fixture.options.githubPath, 'utf8')).toBe( 'existing-bin\n' + result.bin + '\n', ) expect(fixture.dependencies.fetcher).toHaveBeenCalledExactlyOnceWith( - 'https://github.com/astral-sh/uv/releases/download/0.12.15/uv-' + - target + - '-unknown-linux-gnu.tar.gz', + `https://github.com/astral-sh/uv/releases/download/${pins.version}/uv-${target}-unknown-linux-gnu.tar.gz`, { redirect: 'follow', signal: expect.any(AbortSignal) }, ) expect(fixture.dependencies.extract).toHaveBeenCalledTimes(1) @@ -194,7 +196,7 @@ describe('verified uv installation', () => { }, ) - it.each(['uv 0.12.14', 'python 0.12.15', ''])( + it.each(['uv 0.0.0', `python ${pins.version}`, ''])( 'rejects version output %j before exporting PATH', async output => { const fixture = await uvFixture() @@ -236,7 +238,7 @@ describe('verified uv installation', () => { }) }, ) - fixture.dependencies.probe.mockResolvedValueOnce('uv 0.12.15') + fixture.dependencies.probe.mockResolvedValueOnce(`uv ${pins.version}`) const second = await installUvForCi(fixture.options, fixture.dependencies) expect(second.bin).not.toBe(first.bin) expect(fixture.dependencies.fetcher).toHaveBeenCalledTimes(2) diff --git a/test/snapshots/termless/cli.native.socket-cdxgen-npm.svg b/test/snapshots/termless/cli.native.socket-cdxgen-npm.svg new file mode 100644 index 000000000..1df0b68e6 --- /dev/null +++ b/test/snapshots/termless/cli.native.socket-cdxgen-npm.svg @@ -0,0 +1,23 @@ + +CLI: v2.1.0-rc.0 | cmd: socket manifest cdxgen | org: (not set) | token: (not set) + + + +ℹ + Setting cdxgen --lifecycle to "pre-build" to avoid arbitrary code execution on this scan. + + Pass "--lifecycle build" to generate a BOM consisting of information obtained during the build process. + + See cdxgen BOM lifecycles documentation (​https://cyclonedx.github.io/cdxgen/#/ADVANCED?id=bom-lifecycles​) for more details. + + + +socket-cdx.json created! + + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-cdxgen-yarn.svg b/test/snapshots/termless/cli.native.socket-cdxgen-yarn.svg new file mode 100644 index 000000000..1df0b68e6 --- /dev/null +++ b/test/snapshots/termless/cli.native.socket-cdxgen-yarn.svg @@ -0,0 +1,23 @@ + +CLI: v2.1.0-rc.0 | cmd: socket manifest cdxgen | org: (not set) | token: (not set) + + + +ℹ + Setting cdxgen --lifecycle to "pre-build" to avoid arbitrary code execution on this scan. + + Pass "--lifecycle build" to generate a BOM consisting of information obtained during the build process. + + See cdxgen BOM lifecycles documentation (​https://cyclonedx.github.io/cdxgen/#/ADVANCED?id=bom-lifecycles​) for more details. + + + +socket-cdx.json created! + + + + + + + + \ No newline at end of file diff --git a/test/snapshots/termless/cli.native.socket-sea-uv.svg b/test/snapshots/termless/cli.native.socket-sea-uv.svg new file mode 100644 index 000000000..f4b635ff3 --- /dev/null +++ b/test/snapshots/termless/cli.native.socket-sea-uv.svg @@ -0,0 +1,13 @@ + +uv 0.13.10 + +v<NODE_VERSION> + +VFS smoke test passed + + + + + + + \ No newline at end of file diff --git a/test/termless/utils/self-update.test.mts b/test/termless/utils/self-update.test.mts index 2294e5ee0..24dae40eb 100644 --- a/test/termless/utils/self-update.test.mts +++ b/test/termless/utils/self-update.test.mts @@ -5,7 +5,7 @@ import { createXtermBackend } from '@termless/xtermjs' import updateNotifier from 'tiny-updater' import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest' -import { isStandaloneSea } from '../../../src/sea/runtime.mts' +import { isSea } from '../../../src/sea/runtime.mts' import { runSelfUpdateCheck } from '../../../src/utils/self-update.mts' import { captureCheckpoint, @@ -20,7 +20,7 @@ vi.mock('tiny-updater', () => ({ })) vi.mock('../../../src/sea/runtime.mts', () => ({ - isStandaloneSea: vi.fn(() => false), + isSea: vi.fn(() => false), })) vi.mock('../../../src/utils/logger.mts', () => ({ @@ -40,7 +40,7 @@ describe('self-update terminal notice screenshot', () => { it('captures mocked update notices at standard and wrapped widths', async () => { vi.stubEnv('NO_UPDATE_NOTIFIER', '') vi.stubEnv('SOCKET_CLI_FORCE_UPDATE_NOTIFIER', '1') - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) vi.mocked(updateNotifier).mockImplementation(async options => { options.logCallback?.('socket', '1.0.0', '1.1.0') return true @@ -54,7 +54,7 @@ describe('self-update terminal notice screenshot', () => { it('captures a stable command line when the notice is suppressed', async () => { vi.stubEnv('NO_UPDATE_NOTIFIER', '1') vi.stubEnv('SOCKET_CLI_FORCE_UPDATE_NOTIFIER', '1') - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) vi.mocked(updateNotifier).mockClear() vi.mocked(loggerLog).mockReset() diff --git a/test/unit/sea/build-sea.test.mts b/test/unit/sea/build-sea.test.mts index d86ed230c..e25ee4b08 100644 --- a/test/unit/sea/build-sea.test.mts +++ b/test/unit/sea/build-sea.test.mts @@ -1,13 +1,5 @@ import { execFile } from 'node:child_process' -import { - copyFile, - mkdir, - mkdtemp, - readFile, - rm, - stat, - writeFile, -} from 'node:fs/promises' +import { 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' @@ -15,7 +7,6 @@ import { promisify } from 'node:util' import { describe, expect, it } from 'vitest' -import { seaArchivePaths } from '../../../src/sea/archive-paths.mts' import { findNodeArchiveSha256, getSocketPatchPackageName, @@ -23,6 +14,7 @@ import { sha512IntegrityHex, } from '../../../src/sea/build-sea.mts' import { createSeaCapabilities } from '../../../src/sea/capabilities.mts' +import { seaArchivePaths } from '../../../src/sea/paths/archive.mts' import { findLockedPackageIntegrity } from '../../../src/sea/pnpm-lock.mts' import { NODE_VERSION_END, @@ -170,7 +162,25 @@ describe('SEA README Node version', () => { }) describe('SEA capability policy', () => { - it('keeps optional tools unavailable unless their payloads are present', () => { + it.each([false, true])( + 'advertises the available SBOM modes with Synp present: %s', + hasSynp => { + const capabilities = createSeaCapabilities({ + triple: 'linux-x64', + hasCdxgen: true, + hasSynp, + hasSocketPatch: false, + hasUv: true, + }) + expect(capabilities.available).toContain('manifest-cdxgen-npm-lock-v3') + expect( + capabilities.available.includes('manifest-cdxgen-yarn-classic'), + ).toBe(hasSynp) + expect(capabilities.available.includes('synp')).toBe(hasSynp) + }, + ) + + it('advertises on-demand Coana with the core build capabilities', () => { expect( createSeaCapabilities({ triple: 'linux-x64', @@ -179,18 +189,13 @@ describe('SEA capability policy', () => { hasSocketPatch: false, hasUv: false, }).available, - ).toEqual(['socket-core', 'manifest-dotnet-facts']) + ).toEqual(['socket-core', 'manifest-dotnet-facts', 'coana']) }) }) describe('SEA archive paths', () => { it('archives staged native tools through their shared tools parent', () => { - const paths = seaArchivePaths({ - hasCdxgen: true, - hasSynp: true, - hasUv: true, - rootFiles: ['package.json'], - }) + const paths = seaArchivePaths(['package.json']) expect(paths.filter(item => item === 'tools')).toHaveLength(1) expect(paths).not.toContain('tools/cdxgen') expect(paths).not.toContain('tools/synp') @@ -257,10 +262,6 @@ describe('SEA bootstrap Rollup config', () => { 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, diff --git a/test/unit/sea/runtime.test.mts b/test/unit/sea/runtime.test.mts index 21a230a87..7108472be 100644 --- a/test/unit/sea/runtime.test.mts +++ b/test/unit/sea/runtime.test.mts @@ -1,3 +1,4 @@ +import { createHash } from 'node:crypto' import { promises as fs } from 'node:fs' import os from 'node:os' import path from 'node:path' @@ -20,8 +21,15 @@ vi.mock('node:module', async importOriginal => { }) vi.mock('node:worker_threads', () => ({ Worker: mockWorker })) +import { + SEA_CAPABILITIES_PATH, + SEA_RESOURCES_DIRECTORY, +} from '../../../src/sea/paths/archive.mts' +import { seaNativeToolPaths } from '../../../src/sea/paths/native-tools.mts' import { assertEmbeddedToolAvailable, + cleanupBundledTool, + getBundledTool, runEmbeddedJsTool, } from '../../../src/sea/runtime.mts' @@ -49,9 +57,11 @@ describe('embedded SEA tool capabilities', () => { root = await fs.mkdtemp(path.join(os.tmpdir(), 'socket-sea-capabilities-')) seaGlobal.__socketSeaVfsRoot = root if (manifest !== undefined) { - await fs.mkdir(path.join(root, 'resources'), { recursive: true }) + await fs.mkdir(path.join(root, SEA_RESOURCES_DIRECTORY), { + recursive: true, + }) await fs.writeFile( - path.join(root, 'resources/capabilities.json'), + path.join(root, SEA_CAPABILITIES_PATH), JSON.stringify(manifest), ) } @@ -67,7 +77,7 @@ describe('embedded SEA tool capabilities', () => { }, ], }) - const entrypoint = path.join(root!, 'tools/cdxgen/sea-worker.mjs') + const entrypoint = path.join(root!, 'tools/cdxgen/sea-worker.js') await fs.mkdir(path.dirname(entrypoint), { recursive: true }) await fs.writeFile(entrypoint, '') @@ -97,4 +107,34 @@ describe('embedded SEA tool capabilities', () => { }) expect(() => assertEmbeddedToolAvailable('cdxgen')).not.toThrow() }) + + it.each(['node', 'uv', 'socket-patch'] as const)( + 'verifies and cleans up the extracted %s executable', + async id => { + await setup() + const paths = seaNativeToolPaths(id, process.platform) + const binary = path.join(root!, paths.binary) + const contents = 'fixture executable' + await fs.mkdir(path.dirname(binary), { recursive: true }) + await fs.writeFile(binary, contents) + await fs.writeFile( + path.join(root!, paths.digest), + `${createHash('sha256').update(contents).digest('hex')}\n`, + ) + const executable = await getBundledTool(id) + try { + expect(path.basename(executable)).toBe( + process.platform === 'win32' ? `${id}.exe` : id, + ) + expect(await fs.readFile(executable, 'utf8')).toBe(contents) + } finally { + await cleanupBundledTool(executable) + } + await expect(fs.stat(executable)).rejects.toMatchObject({ + code: 'ENOENT', + }) + await fs.writeFile(binary, 'changed executable') + await expect(getBundledTool(id)).rejects.toThrow(/SHA-256 verification/) + }, + ) }) diff --git a/test/unit/utils/agent.test.mts b/test/unit/utils/agent.test.mts index 0059005b7..d469e97d6 100644 --- a/test/unit/utils/agent.test.mts +++ b/test/unit/utils/agent.test.mts @@ -1,7 +1,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { NPM } from '../../../src/constants.mts' -import { isStandaloneSea } from '../../../src/sea/runtime.mts' +import { isSea } from '../../../src/sea/runtime.mts' import { shadowNpmInstall } from '../../../src/shadow/npm/install.mts' import { runAgentInstall } from '../../../src/utils/agent.mts' @@ -12,7 +12,7 @@ vi.mock('../../../src/shadow/npm/install.mts', () => ({ })) vi.mock('../../../src/sea/runtime.mts', () => ({ - isStandaloneSea: vi.fn(() => false), + isSea: vi.fn(() => false), })) vi.mock('../../../src/utils/spawn.mts', () => ({ @@ -30,7 +30,7 @@ describe('runAgentInstall', () => { } as EnvDetails it('uses the npm shadow installer outside standalone SEA', () => { - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) expect(runAgentInstall(npmDetails, { args: ['--ignore-scripts'] })).toBe( 'shadow-result', @@ -44,7 +44,7 @@ describe('runAgentInstall', () => { }) it('runs npm directly in standalone SEA', () => { - vi.mocked(isStandaloneSea).mockReturnValue(true) + vi.mocked(isSea).mockReturnValue(true) expect(runAgentInstall(npmDetails)).toBe('spawn-result') expect(shadowNpmInstall).not.toHaveBeenCalled() diff --git a/test/unit/utils/self-update.test.mts b/test/unit/utils/self-update.test.mts index 59785edc6..2494dcb5a 100644 --- a/test/unit/utils/self-update.test.mts +++ b/test/unit/utils/self-update.test.mts @@ -1,7 +1,7 @@ import updateNotifier from 'tiny-updater' import { afterEach, describe, expect, it, vi } from 'vitest' -import { isStandaloneSea } from '../../../src/sea/runtime.mts' +import { isSea } from '../../../src/sea/runtime.mts' import { formatUpdateNotice, runSelfUpdateCheck, @@ -14,7 +14,7 @@ vi.mock('tiny-updater', () => ({ })) vi.mock('../../../src/sea/runtime.mts', () => ({ - isStandaloneSea: vi.fn(() => false), + isSea: vi.fn(() => false), })) vi.mock('../../../src/utils/logger.mts', () => ({ @@ -23,14 +23,14 @@ vi.mock('../../../src/utils/logger.mts', () => ({ describe('formatUpdateNotice', () => { it('uses package manager guidance for npm installations', () => { - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) expect(formatUpdateNotice('1.0.0', '1.1.0')).toBe( 'Socket 1.0.0 → 1.1.0. Update with your favorite package manager.', ) }) it('uses the Socket update command for standalone SEA builds', () => { - vi.mocked(isStandaloneSea).mockReturnValue(true) + vi.mocked(isSea).mockReturnValue(true) expect(formatUpdateNotice('1.0.0', '1.1.0')).toBe( 'Socket 1.0.0 → 1.1.0. Run: socket update', ) @@ -45,7 +45,7 @@ describe('runSelfUpdateCheck', () => { it('checks the public npm registry', async () => { vi.stubEnv('NO_UPDATE_NOTIFIER', '') vi.stubEnv('SOCKET_CLI_FORCE_UPDATE_NOTIFIER', '') - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) await runSelfUpdateCheck() expect(updateNotifier).toHaveBeenCalledTimes(1) @@ -63,7 +63,7 @@ describe('runSelfUpdateCheck', () => { vi.stubEnv('NO_UPDATE_NOTIFIER', '') vi.stubEnv('SOCKET_CLI_FORCE_UPDATE_NOTIFIER', '1') vi.mocked(updateNotifier).mockClear() - vi.mocked(isStandaloneSea).mockReturnValue(true) + vi.mocked(isSea).mockReturnValue(true) await runSelfUpdateCheck() expect(updateNotifier).not.toHaveBeenCalled() }) @@ -71,7 +71,7 @@ describe('runSelfUpdateCheck', () => { it('bypasses the notifier cache when forced', async () => { vi.stubEnv('NO_UPDATE_NOTIFIER', '') vi.stubEnv('SOCKET_CLI_FORCE_UPDATE_NOTIFIER', '1') - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) vi.mocked(updateNotifier).mockClear() await runSelfUpdateCheck() @@ -83,7 +83,7 @@ describe('runSelfUpdateCheck', () => { it('suppresses the update check when NO_UPDATE_NOTIFIER is set', async () => { vi.stubEnv('NO_UPDATE_NOTIFIER', '1') vi.stubEnv('SOCKET_CLI_FORCE_UPDATE_NOTIFIER', '1') - vi.mocked(isStandaloneSea).mockReturnValue(false) + vi.mocked(isSea).mockReturnValue(false) vi.mocked(updateNotifier).mockClear() vi.mocked(loggerLog).mockClear()