Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
/cso refuses npm apps whose installed packages don't match the lockfile (GST-3664) (#4797)
Garry Tan64fe9e523104
diff --git a/changelog.d/cso-npm-installed-identity-check.md b/changelog.d/cso-npm-installed-identity-check.mdnew file mode 100644index 000000000..207631c3b--- /dev/null+++ b/changelog.d/cso-npm-installed-identity-check.md@@ -0,0 +1,4 @@+---+important: security+---+**`/cso --comprehensive` now refuses to prepare an npm app whose installed packages don't match its lockfile.** After the offline install, preparation checks the packages in the top-level `node_modules` and in each package's own `node_modules`, bundled packages included, against `package-lock.json`: the name and version in each `package.json` must match its lockfile entry (compared the way npm records versions, so `v1.2.3` matches `1.2.3`), and a package there that the lockfile doesn't list, or that has no `package.json`, stops preparation. The error names the package and what differs. (GST-3664)diff --git a/lib/cso/preparation-executor.ts b/lib/cso/preparation-executor.tsindex c43ecc318..c96a4073b 100644--- a/lib/cso/preparation-executor.ts+++ b/lib/cso/preparation-executor.ts@@ -1040,6 +1040,91 @@ function provePreparedProjection(};}+/** npm writes `semver.clean(version, loose)` into the lock, so an installed manifest is compared in that form. */+function npmLockVersion(version: unknown): unknown {+ if (typeof version !== 'string') return version;+ const match =+ /^(\d+)\.(\d+)\.(\d+)(?:-?([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/.exec(+ version.trim().replace(/^[=v]+/, ''),+ );+ if (!match) return version;+ const number = (part: string) => (Number.isSafeInteger(Number(part)) ? String(Number(part)) : undefined);+ const core = match.slice(1, 4).map(number);+ if (core.includes(undefined)) return version;+ const pre = match[4]?.split('.').map((part) => (/^\d+$/.test(part) ? (number(part) ?? part) : part));+ return core.join('.') + (pre ? `-${pre.join('.')}` : '');+}++/** Lock-reading scanners report the lock's versions, so the installed npm tree must hold exactly those packages. */+export function proveNpmLockIdentities(+ plan: PreparationPlan,+ preparedRoot: string,+ deadline: number,+ signal?: AbortSignal,+): void {+ const lock = plan.metadata.find(+ (item) => item.path === 'npm-shrinkwrap.json' || item.path === 'package-lock.json',+ );+ if (!lock) fail('INVALID_SCHEMA', 'Node preparation plan omitted its npm lock');+ const packages: Record<string, Record<string, unknown>> = JSON.parse(lock.content).packages ?? {};+ const unlisted = (path: string) =>+ fail('INCOMPATIBLE_INPUT', `Installed npm package ${path} is not listed in the lockfile`);+ const pending = ['node_modules'];+ while (pending.length) {+ checkDeadline(deadline, signal);+ const dir = pending.pop()!;+ let items: fs.Dirent[];+ try {+ items = fs.readdirSync(join(preparedRoot, dir), { withFileTypes: true });+ } catch (error: any) {+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;+ throw error;+ }+ for (const item of items) {+ if (item.name.startsWith('.')) continue;+ const path = `${dir}/${item.name}`;+ if (item.isSymbolicLink()) {+ if (packages[path]?.link !== true) unlisted(path);+ continue;+ }+ if (!item.isDirectory()) unlisted(path);+ if (item.name.startsWith('@') && dir.endsWith('node_modules')) {+ pending.push(path);+ continue;+ }+ pending.push(`${path}/node_modules`);+ if (!Object.hasOwn(packages, path) || packages[path].link === true) unlisted(path);+ }+ }+ for (const [path, entry] of Object.entries(packages)) {+ checkDeadline(deadline, signal);+ if (!path.split('/').includes('node_modules') || entry.link === true) continue;+ try {+ fs.lstatSync(join(preparedRoot, path));+ } catch (error: any) {+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') continue;+ throw error;+ }+ const manifestPath = join(preparedRoot, path, 'package.json');+ const stat = fs.lstatSync(manifestPath, { throwIfNoEntry: false });+ if (!stat?.isFile() || stat.size > 1024 * 1024)+ fail('INCOMPATIBLE_INPUT', `Installed npm package ${path} has no readable package.json`);+ let installed: any;+ try {+ installed = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));+ } catch {+ fail('INCOMPATIBLE_INPUT', `Installed npm package ${path} has an invalid package.json`);+ }+ const name = typeof entry.name === 'string' ? entry.name : path.split('node_modules/').at(-1);+ const installedName = typeof installed?.name === 'string' ? installed.name.trim() : installed?.name;+ if (installedName !== name || npmLockVersion(installed?.version) !== entry.version)+ fail(+ 'INCOMPATIBLE_INPUT',+ `Installed npm package ${path} does not match the lockfile: the lock says ${name}@${String(entry.version)}, the installed package.json says ${JSON.stringify(String(installed?.name).slice(0, 80))}@${JSON.stringify(String(installed?.version).slice(0, 80))}`,+ );+ }+}+function validateAcquisitionReceipt(receipt: AcquisitionReceipt,request: PreparationAcquireRequest,@@ -1489,6 +1574,8 @@ export class PreparationExecutor {),preparedManifestHash = projection.manifestHash,preparedDependencyHash = projection.dependencyHash;+ if (options.plan.stack === 'node')+ proveNpmLockIdentities(options.plan, preparedRoot, options.deadline, options.signal);if (treeHash(options.snapshot, MAX_SOURCE_BYTES, options.deadline, false, options.signal) !== sourceHash)diff --git a/test/cso-preparation-adversarial.test.ts b/test/cso-preparation-adversarial.test.tsindex 89bebee6f..10a442e0f 100644--- a/test/cso-preparation-adversarial.test.ts+++ b/test/cso-preparation-adversarial.test.ts@@ -81,8 +81,8 @@ class PreparedSymlinkRunner implements PreparationSandboxRunner {fs.mkdirSync(preparedRoot, { mode: 0o700 });fs.cpSync(request.sourceRoot, preparedRoot, { recursive: true });fs.mkdirSync(path.join(preparedRoot, 'node_modules/.bin'), { recursive: true });- fs.mkdirSync(path.join(preparedRoot, 'node_modules/lib'), { recursive: true });- fs.writeFileSync(path.join(preparedRoot, 'node_modules/lib/tool.js'), 'export default 1;\n');+ fs.mkdirSync(path.join(preparedRoot, 'node_modules/.cache'), { recursive: true });+ fs.writeFileSync(path.join(preparedRoot, 'node_modules/.cache/tool.js'), 'export default 1;\n');fs.writeFileSync(path.join(call, 'outside.txt'), 'outside\n');fs.symlinkSync(this.linkTarget, path.join(preparedRoot, 'node_modules/.bin/tool'));return { preparedRoot, receipt: offlineReceipt(request) };@@ -165,7 +165,7 @@ afterEach(() => {describe('CSO preparation adversarial regressions', () => {test('accepts a contained relative symlink in a prepared dependency tree', async () => {- const prepared = await prepareWithLink('../lib/tool.js');+ const prepared = await prepareWithLink('../.cache/tool.js');expect(prepared.preparedManifestHash).toMatch(/^[a-f0-9]{64}$/);});diff --git a/test/cso-preparation-executor.test.ts b/test/cso-preparation-executor.test.tsindex 5123df45b..b54dc7f17 100644--- a/test/cso-preparation-executor.test.ts+++ b/test/cso-preparation-executor.test.ts@@ -10,7 +10,7 @@ import { inspectPreparation, type CsoStack } from '../lib/cso/preparation';import {admitPreparationRuntime, admitPreparationSidecar, PreparationExecutor,type AcquisitionReceipt, type OfflinePreparationReceipt, type PreparationAcquireRequest,- type PreparationSandboxRunner, type OfflinePreparationRequest, preparedIdentityEntry } from '../lib/cso/preparation-executor';+ type PreparationSandboxRunner, type OfflinePreparationRequest, preparedIdentityEntry, proveNpmLockIdentities } from '../lib/cso/preparation-executor';import { CSO_HELPER_ABI } from '../lib/cso/runtime-catalog';import { DockerPreparationSandboxRunner, isBlockedRegistryAddress, RegistryEgressBroker } from '../lib/cso/preparation-docker';import { completeRuntimeCatalogFixture, qualifiedRuntimeFixture, unqualifiedRuntimeCatalog } from './helpers/cso-runtime-catalog';@@ -294,6 +294,114 @@ describe('CSO constrained dependency preparation executor', () => {expect(runner.disposed).toHaveLength(1);expect(fs.existsSync(runner.disposed[0])).toBe(false);});+ const installManifest = (prepared: string, lockPath: string, manifest: object) =>+ writeTree(prepared, { [`${lockPath}/package.json`]: JSON.stringify(manifest) });+ async function prepareWith(source: string, install: (prepared: string) => void) {+ const plan = inspectPreparation(source, 'node'), admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: catalog('node') });+ const runner = new FakeRunner(), executor = new PreparationExecutor({ cache: cacheFixture(), runner }), deadline = Date.now() + 60_000;+ const closure = await executor.acquire({ plan, admission, snapshot: source, deadline });+ runner.mutatePrepared = install;+ try { return { prepared: await executor.prepareOffline({ plan, admission, snapshot: source, closure, deadline }), runner }; }+ catch (error) { return { error, runner }; }+ }+ function bundledSnapshot(): string {+ const base = root('cso-executor-node-bundled-');+ writeTree(base, {+ 'package.json': JSON.stringify({ name: 'app', version: '1.0.0', dependencies: { wrapper: '2.0.0' } }),+ 'package-lock.json': JSON.stringify({ name: 'app', lockfileVersion: 3, packages: {+ '': { name: 'app', version: '1.0.0', dependencies: { wrapper: '2.0.0' } },+ 'node_modules/wrapper': { version: '2.0.0', resolved: 'https://registry.npmjs.org/wrapper/-/wrapper-2.0.0.tgz', integrity: `sha512-${h512(artifactBytes('node'))}`, bundleDependencies: ['child'] },+ 'node_modules/wrapper/node_modules/child': { version: '1.1.0', inBundle: true },+ } }),+ });+ return base;+ }+ test('npm preparation refuses an installed package whose version differs from the lock', async () => {+ const { error, runner } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '0.9.0' }));+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ expect((error as Error).message).toContain('node_modules/cookie');+ expect(runner.disposed).toHaveLength(1);+ });+ test('npm preparation refuses an installed package whose name differs from the lock', async () => {+ const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'not-cookie', version: '1.0.0' }));+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ });+ test('npm preparation refuses a bundled package whose installed version differs from the lock', async () => {+ const { error } = await prepareWith(bundledSnapshot(), prepared => {+ installManifest(prepared, 'node_modules/wrapper', { name: 'wrapper', version: '2.0.0' });+ installManifest(prepared, 'node_modules/wrapper/node_modules/child', { name: 'child', version: '1.0.0' });+ });+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ expect((error as Error).message).toContain('node_modules/wrapper/node_modules/child');+ });+ test('npm preparation refuses an installed package the lock does not list', async () => {+ const { error } = await prepareWith(bundledSnapshot(), prepared => {+ installManifest(prepared, 'node_modules/wrapper', { name: 'wrapper', version: '2.0.0' });+ installManifest(prepared, 'node_modules/wrapper/node_modules/child', { name: 'child', version: '1.1.0' });+ installManifest(prepared, 'node_modules/wrapper/node_modules/@hidden/extra', { name: '@hidden/extra', version: '1.0.0' });+ });+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ expect((error as Error).message).toContain('node_modules/wrapper/node_modules/@hidden/extra is not listed');+ });+ for (const [label, install] of [+ ['invalid JSON', (prepared: string) => writeTree(prepared, { 'node_modules/cookie/package.json': '{not json' })],+ ['a directory', (prepared: string) => fs.mkdirSync(path.join(prepared, 'node_modules/cookie/package.json'), { recursive: true })],+ ] as const) test(`npm preparation refuses an installed package.json that is ${label}`, async () => {+ const { error, runner } = await prepareWith(snapshot('node'), install);+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT'); expect(runner.disposed).toHaveLength(1);+ });+ for (const [label, install, message] of [+ ['a listed package directory with no package.json', (prepared: string) => writeTree(prepared, { 'node_modules/cookie/index.js': 'module.exports = 1;' }), 'node_modules/cookie has no readable package.json'],+ ['an unlisted package directory with no package.json', (prepared: string) => writeTree(prepared, { 'node_modules/extra/index.js': 'module.exports = 1;' }), 'node_modules/extra is not listed'],+ ['a loose module file in node_modules', (prepared: string) => writeTree(prepared, { 'node_modules/cookie.js': 'module.exports = 1;' }), 'node_modules/cookie.js is not listed'],+ ['an unlisted symlink in node_modules', (prepared: string) => { installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '1.0.0' }); fs.symlinkSync('cookie', path.join(prepared, 'node_modules/extra')); }, 'node_modules/extra is not listed'],+ ] as const) test(`npm preparation refuses ${label}`, async () => {+ const { error, runner } = await prepareWith(snapshot('node'), install);+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ expect((error as Error).message).toContain(message);+ expect(runner.disposed).toHaveLength(1);+ });+ test('npm preparation bounds installed manifest values it echoes in its refusal', async () => {+ const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'x'.repeat(5000), version: 'y'.repeat(5000) }));+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ expect((error as Error).message.length).toBeLessThan(400);+ expect((error as Error).message).toContain('the lock says [email protected]');+ });+ test('npm preparation compares versions the way npm normalizes them', async () => {+ for (const version of ['v1.0.0', '=1.0.0', ' 1.0.0 ', '1.0.0+build.5', '01.0.0']) {+ const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: ' cookie ', version }));+ expect(error).toBeUndefined();+ }+ for (const version of ['v2.0.0', '1.0.0-beta', '1.0', 'latest']) {+ const { error } = await prepareWith(snapshot('node'), prepared => installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version }));+ expect(errorCode(error)).toBe('INCOMPATIBLE_INPUT');+ }+ });+ test('npm lock identity check honors cancellation and the deadline', () => {+ const source = snapshot('node'), plan = inspectPreparation(source, 'node'), prepared = root('cso-executor-identity-');+ installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '1.0.0' });+ expect(() => proveNpmLockIdentities(plan, prepared, Date.now() + 60_000)).not.toThrow();+ const controller = new AbortController(); controller.abort();+ for (const [deadline, signal, code] of [[Date.now() + 60_000, controller.signal, 'CANCELLED'], [Date.now() - 1, undefined, 'DEADLINE']] as const) {+ let caught: unknown;+ try { proveNpmLockIdentities(plan, prepared, deadline, signal); } catch (error) { caught = error; }+ expect(errorCode(caught)).toBe(code);+ }+ });+ test('npm preparation accepts installed packages that match the lock', async () => {+ for (const [source, install] of [+ [snapshot('node'), (prepared: string) => installManifest(prepared, 'node_modules/cookie', { name: 'cookie', version: '1.0.0' })],+ [snapshot('node'), (prepared: string) => writeTree(prepared, { 'node_modules/.package-lock.json': '{}', 'node_modules/.bin/tool': '' })],+ [bundledSnapshot(), (prepared: string) => {+ installManifest(prepared, 'node_modules/wrapper', { name: 'wrapper', version: '2.0.0' });+ installManifest(prepared, 'node_modules/wrapper/node_modules/child', { name: 'child', version: '1.1.0' });+ }],+ ] as const) {+ const { prepared, error } = await prepareWith(source, install);+ expect(error).toBeUndefined(); expect(prepared!.preparedManifestHash).toMatch(/^[a-f0-9]{64}$/);+ }+ });+test('Rails PostgreSQL requires and records a same-catalog qualified sidecar', async () => {const source = snapshot('rails'), plan = inspectPreparation(source, 'rails'), runtimes = catalog('rails', 'postgresql');const admission = admitPreparationRuntime({ plan, platform: 'linux/amd64', catalog: runtimes });