diff --git a/.changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md b/.changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md new file mode 100644 index 00000000..562b9180 --- /dev/null +++ b/.changeset/sw-157-sw-131-sw-130-sw-129-remediation-and-template-safety.md @@ -0,0 +1,5 @@ +--- +'@diginodes/stellarforge-cli': patch +--- + +Improve generated-project failure handling and template safety. Missing or non-executable npm launchers now produce runtime-version remediation instead of a generic test failure; template sources reject symlink, filesystem-entry, and Unicode/case-collision hazards before writing; generated POSIX file modes are constrained while executable assets retain execute permission. diff --git a/docs/reference/commands.md b/docs/reference/commands.md index 66c6a238..b5b85ed9 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -173,7 +173,7 @@ The supported invocation location is the generated project root or any nested di When both are present, the Node.js project test workflow is selected first. -StellarForge does not execute package script text directly. It delegates through npm or Cargo and preserves external-process failures. +StellarForge does not execute package script text directly. It delegates through npm or Cargo and preserves external-process failures. If npm or its supported launcher cannot be started, the failure is reported as a missing/permission-denied runtime prerequisite with the supported versions (`Node.js >=22.13.0 <25`, `npm >=10.9.0`) instead of being reported as a test-script failure. StellarForge never falls back to another package manager or installs tools automatically, and the message does not echo environment values. ### Exit behavior diff --git a/docs/reference/template-generation.md b/docs/reference/template-generation.md index d3f28f23..fc9a8b04 100644 --- a/docs/reference/template-generation.md +++ b/docs/reference/template-generation.md @@ -7,10 +7,12 @@ StellarForge generates projects from project-controlled template directories onl 1. The project name and final destination are validated before generation. 2. The selected template comes from the controlled template registry. 3. Template contents are rendered into a temporary staging directory located beside the final destination. -4. Every template entry is checked before it is copied. Symbolic links and unsupported filesystem entry types are rejected. -5. Text substitution supports only the allowlisted `projectName` and `templateId` tokens. Unknown tokens fail generation; no expression evaluation is performed. -6. Files containing NUL bytes are treated as binary and copied byte-for-byte without substitution. -7. The completed staging directory is promoted to the final destination only after all template files render successfully. +4. Every template entry is checked before it is copied. The source root is resolved to its real path, each entry must resolve inside that root, and symbolic links and unsupported filesystem entry types are rejected. Dangling, escaping, and internal symlink entries are all refused; no symlink target is copied. +5. Template paths are validated for cross-platform portability before writing. Paths that differ only by Unicode normalization or case folding are rejected on every host, and the error names both relative paths. Distinct non-colliding paths remain supported. +6. Generated POSIX file modes are restricted: regular files use `0644`, files with any source execute bit use `0755`, and directories use `0755`. Setuid, setgid, sticky, and group/world write bits are never copied. On Windows, POSIX mode bits are not meaningful, so generation does not apply chmod and the ordinary writable-file behavior applies. +7. Text substitution supports only the allowlisted `projectName` and `templateId` tokens. Unknown tokens fail generation; no expression evaluation is performed. +8. Files containing NUL bytes are treated as binary and copied byte-for-byte without substitution. +9. The completed staging directory is promoted to the final destination only after all template files render successfully. ## Limits diff --git a/docs/reference/troubleshooting.md b/docs/reference/troubleshooting.md index fc96572d..c6033908 100644 --- a/docs/reference/troubleshooting.md +++ b/docs/reference/troubleshooting.md @@ -125,7 +125,7 @@ A supported test project must have either: Node.js projects are run through `npm run test`; Cargo projects are run through `cargo test`. -A failing project test is preserved as a subprocess failure instead of being converted to success. +A failing project test is preserved as a subprocess failure instead of being converted to success. If npm or its launcher is missing or cannot be executed, the error identifies that prerequisite and references the supported `Node.js >=22.13.0 <25` and `npm >=10.9.0` ranges; it does not include environment values. Install a supported runtime and rerun `stellarforge doctor` before retrying. You may invoke `stellarforge test` from the project root or a nested directory. Discovery is bounded by the filesystem root, a `.git` boundary, or the generated `.stellarforge.json` marker, and examines at most eight parent directories. If more than one project root is found, run the command from the single generated project root. diff --git a/src/commands/test.ts b/src/commands/test.ts index 324e6905..6bd1761a 100644 --- a/src/commands/test.ts +++ b/src/commands/test.ts @@ -1,11 +1,11 @@ import { Command } from 'commander'; -import { - superviseDevProcesses, - type DevOrchestratorOptions, -} from '../dev/orchestrator.js'; +import type { DevOrchestratorOptions } from '../dev/orchestrator.js'; import type { DevProcessSpec } from '../dev/project.js'; import { TerminalOutput } from '../output/terminal.js'; -import { resolveTestProcessPlan } from '../testing/project.js'; +import { + resolveTestProcessPlan, + superviseTestProcesses, +} from '../testing/project.js'; export interface TestCommandOptions extends DevOrchestratorOptions { readonly cwd?: () => string; @@ -24,6 +24,6 @@ export function createTestCommand(options: TestCommandOptions = {}): Command { output.info( `Running ${plan.length} project test workflow${plan.length === 1 ? '' : 's'}.`, ); - await superviseDevProcesses(plan, { ...options, output }); + await superviseTestProcesses(plan, { ...options, output }); }); } diff --git a/src/generator/template-generation.ts b/src/generator/template-generation.ts index 1e2be9a0..e378e924 100644 --- a/src/generator/template-generation.ts +++ b/src/generator/template-generation.ts @@ -1,4 +1,5 @@ import { + chmodSync, existsSync, lstatSync, mkdirSync, @@ -67,6 +68,13 @@ export const GENERATED_MARKER_FILENAME = '.stellarforge.json'; /** Package identifier recorded in the generated provenance marker. */ export const GENERATOR_PACKAGE_NAME = '@diginodes/stellarforge-cli'; +interface RenderedTemplateFile { + readonly relativePath: string; + readonly content: Buffer | string; + readonly substitutions: readonly string[]; + readonly mode: number; +} + function isWithin(root: string, candidate: string): boolean { const pathFromRoot = relative(root, candidate); @@ -78,18 +86,6 @@ function isWithin(root: string, candidate: string): boolean { ); } -function assertSafeEntryName(name: string): void { - if ( - name.length === 0 || - name === '.' || - name === '..' || - name.includes('/') || - name.includes('\\') - ) { - throw new ValidationCliError('Template contains an unsafe file path.'); - } -} - function renderText( input: string, variables: Readonly>, @@ -251,11 +247,15 @@ function visitTemplateTree( const sourceStat = lstatSync(sourcePath); - if (sourceStat.isSymbolicLink()) { - throw new ValidationCliError( - 'Template symbolic links are not supported.', - ); - } + const rendered = renderText(content.toString('utf8'), variables); + return { + relativePath: entry.relativePath, + content: rendered.content, + substitutions: rendered.substitutions, + mode: entry.mode, + }; + }); +} if (sourceStat.isDirectory()) { visitDirectory(relativePath); @@ -270,13 +270,11 @@ function visitTemplateTree( continue; } - if (!sourceStat.isFile()) { - throw new ValidationCliError( - 'Template contains an unsupported filesystem entry.', - ); - } - - const content = readFileSync(sourcePath); + if (!isWithin(stagingRoot, destinationPath)) { + throw new ValidationCliError( + 'Template file path escapes the trusted project root.', + ); + } if (isBinary(content)) { visitFile(destinationRelativePath, content, []); @@ -286,6 +284,10 @@ function visitTemplateTree( const rendered = renderText(content.toString('utf8'), variables); visitFile(destinationRelativePath, rendered.content, rendered.substitutions); } + + const mode = resolveGeneratedFileMode(file.mode); + writeFileSync(destinationPath, file.content, { mode }); + chmodSync(destinationPath, mode); } function assertDestinationContainment(root: string, destination: string): void { @@ -391,6 +393,7 @@ export function generateProjectFromTemplate( projectName: context.input.projectName, templateId: context.template.templateId, }; + const renderedFiles = renderTemplateFiles(tree, variables); if (options.dryRun) { const files: ProjectGenerationPreviewFile[] = []; @@ -436,16 +439,15 @@ export function generateProjectFromTemplate( ); } - mkdirSync(dirname(destinationPath), { recursive: true }); - writeFileSync(destinationPath, content); - }, - (relativePath) => { - const destinationPath = resolve(stagingRoot, relativePath); - if (!isWithin(stagingRoot, destinationPath)) { - throw new ValidationCliError( - 'Template file path escapes the trusted project root.', - ); - } + const destinationPath = resolveStagingPath( + stagingRoot, + entry.relativePath, + ); + mkdirSync(destinationPath, { + recursive: true, + mode: GENERATED_DIRECTORY_MODE, + }); + } mkdirSync(destinationPath, { recursive: false }); }, @@ -456,7 +458,7 @@ export function generateProjectFromTemplate( // Re-validate immediately before the mutating write phase. The checks // above can be invalidated by a concurrent destination replacement while - // copyTemplateTree was still running (it only writes into the unrelated + // staging was still running (it only writes into the unrelated // staging directory, never into `destination`), so this closes the // time-of-check/time-of-use gap rather than relying on the earlier check. assertDestinationContainment(root, destination); diff --git a/src/generator/template-sources.ts b/src/generator/template-sources.ts index 4d32cc63..6f47e1fa 100644 --- a/src/generator/template-sources.ts +++ b/src/generator/template-sources.ts @@ -1,3 +1,5 @@ +import { lstatSync, readdirSync, realpathSync } from 'node:fs'; +import { isAbsolute, join, relative, resolve, sep } from 'node:path'; import { fileURLToPath } from 'node:url'; import { ValidationCliError } from '../errors/errors.js'; import { TEMPLATE_IDS, type TemplateId } from './template-registry.js'; @@ -8,6 +10,23 @@ const BUNDLED_TEMPLATE_DIRECTORIES: Record = string >; +export const GENERATED_FILE_MODE = 0o644; +export const GENERATED_EXECUTABLE_FILE_MODE = 0o755; +export const GENERATED_DIRECTORY_MODE = 0o755; + +const EXECUTABLE_BITS = 0o111; + +export interface TemplateSourceEntry { + readonly relativePath: string; + readonly type: 'file' | 'directory'; + readonly mode: number; +} + +export interface TemplateSourceTree { + readonly root: string; + readonly entries: readonly TemplateSourceEntry[]; +} + export function resolveBundledTemplateRoot(templateId: string): string { const directory = BUNDLED_TEMPLATE_DIRECTORIES[templateId as TemplateId]; @@ -22,3 +41,146 @@ export function resolveBundledTemplateRoot(templateId: string): string { new URL(`../../templates/${directory}/`, import.meta.url), ); } + +function isWithin(root: string, candidate: string): boolean { + const pathFromRoot = relative(root, candidate); + + return ( + pathFromRoot.length > 0 && + pathFromRoot !== '..' && + !pathFromRoot.startsWith(`..${sep}`) && + !isAbsolute(pathFromRoot) + ); +} + +function assertSafeEntryName(name: string): void { + if ( + name.length === 0 || + name === '.' || + name === '..' || + name.includes('/') || + name.includes('\\') + ) { + throw new ValidationCliError('Template contains an unsafe file path.'); + } +} + +function portablePathKey(relativePath: string): string { + return relativePath.split('\\').join('/').normalize('NFD').toLowerCase(); +} + +export function assertPortableTemplatePaths( + relativePaths: readonly string[], +): void { + const seen = new Map(); + + for (const relativePath of [...new Set(relativePaths)].sort()) { + const key = portablePathKey(relativePath); + const previous = seen.get(key); + + if (previous !== undefined && previous !== relativePath) { + throw new ValidationCliError( + `Template contains colliding paths '${previous}' and '${relativePath}'.`, + ); + } + + seen.set(key, relativePath); + } +} + +export function resolveGeneratedFileMode(sourceMode: number): number { + return (sourceMode & EXECUTABLE_BITS) === 0 + ? GENERATED_FILE_MODE + : GENERATED_EXECUTABLE_FILE_MODE; +} + +function collectEntries( + root: string, + relativeDirectory: string, + entries: TemplateSourceEntry[], +): void { + const sourceDirectory = resolve(root, relativeDirectory); + const dirents = readdirSync(sourceDirectory, { withFileTypes: true }).sort( + (a, b) => { + if (a.name < b.name) return -1; + if (a.name > b.name) return 1; + return 0; + }, + ); + + for (const dirent of dirents) { + assertSafeEntryName(dirent.name); + + const relativePath = join(relativeDirectory, dirent.name); + const sourcePath = resolve(root, relativePath); + + if (!isWithin(root, sourcePath)) { + throw new ValidationCliError( + 'Template file path escapes the trusted project root.', + ); + } + + const stat = lstatSync(sourcePath); + + if (stat.isSymbolicLink() || dirent.isSymbolicLink()) { + throw new ValidationCliError( + 'Template symbolic links are not supported.', + ); + } + + const realSourcePath = realpathSync(sourcePath); + if (!isWithin(root, realSourcePath)) { + throw new ValidationCliError( + 'Template file path escapes the trusted project root.', + ); + } + + if (stat.isDirectory() && dirent.isDirectory()) { + entries.push({ + relativePath, + type: 'directory', + mode: stat.mode, + }); + collectEntries(root, relativePath, entries); + continue; + } + + if (!stat.isFile() || !dirent.isFile()) { + throw new ValidationCliError( + 'Template contains an unsupported filesystem entry.', + ); + } + + entries.push({ + relativePath, + type: 'file', + mode: stat.mode, + }); + } +} + +export function collectTemplateSourceTree(templateRoot: string): TemplateSourceTree { + const root = resolve(templateRoot); + const rootStat = lstatSync(root, { throwIfNoEntry: false }); + + if (rootStat === undefined) { + throw new ValidationCliError('Selected template source is unavailable.'); + } + + if (rootStat.isSymbolicLink()) { + throw new ValidationCliError( + 'Template source must not be a symbolic link.', + ); + } + + if (!rootStat.isDirectory()) { + throw new ValidationCliError('Selected template source is unavailable.'); + } + + const realRoot = realpathSync(root); + const entries: TemplateSourceEntry[] = []; + collectEntries(realRoot, '.', entries); + assertPortableTemplatePaths(entries.map((entry) => entry.relativePath)); + + return { root: realRoot, entries }; +} diff --git a/src/process/npm.ts b/src/process/npm.ts index d730e96c..8ae61a47 100644 --- a/src/process/npm.ts +++ b/src/process/npm.ts @@ -3,6 +3,11 @@ export interface NpmInvocation { readonly args: readonly string[]; } +export type NpmInvocationFailure = 'executable-not-found' | 'permission-denied'; + +const SUPPORTED_RUNTIME_REMEDIATION = + 'Install a supported Node.js runtime (>=22.13.0 <25) and npm (>=10.9.0), then make sure npm is available on PATH.'; + export function createNpmInvocation(args: readonly string[]): NpmInvocation { if (process.platform === 'win32') { return { @@ -16,3 +21,63 @@ export function createNpmInvocation(args: readonly string[]): NpmInvocation { args: [...args], }; } + +export function isNpmInvocation(spec: NpmInvocation): boolean { + const commandIsNpm = + spec.command === 'npm' || + /(?:^|[\\/])npm(?:\.cmd|\.exe)?$/iu.test(spec.command); + const usesWindowsLauncher = + spec.command === 'cmd.exe' && + spec.args[0] === '/d' && + spec.args[1] === '/s' && + spec.args[2] === '/c' && + spec.args[3] === 'npm'; + + return commandIsNpm || usesWindowsLauncher; +} + +function hasCode(error: Error, code: string): boolean { + return ( + (error as NodeJS.ErrnoException).code === code || + new RegExp(`\\b${code}\\b`).test(error.message) + ); +} + +export function classifyNpmInvocationError( + error: unknown, +): NpmInvocationFailure | undefined { + return classifyNpmInvocationErrorWithDepth(error, 0); +} + +function classifyNpmInvocationErrorWithDepth( + error: unknown, + depth: number, +): NpmInvocationFailure | undefined { + if (!(error instanceof Error) || depth > 4) { + return undefined; + } + + if (hasCode(error, 'ENOENT')) { + return 'executable-not-found'; + } + + if (hasCode(error, 'EACCES') || hasCode(error, 'EPERM')) { + return 'permission-denied'; + } + + if (error.cause instanceof Error) { + return classifyNpmInvocationErrorWithDepth(error.cause, depth + 1); + } + + return undefined; +} + +export function npmInvocationRemediation( + failure: NpmInvocationFailure, +): string { + if (failure === 'executable-not-found') { + return `Unable to find npm or its supported launcher. ${SUPPORTED_RUNTIME_REMEDIATION}`; + } + + return `npm or its supported launcher could not be executed. ${SUPPORTED_RUNTIME_REMEDIATION}`; +} diff --git a/src/testing/project.ts b/src/testing/project.ts index 4b76c8ff..34afa1aa 100644 --- a/src/testing/project.ts +++ b/src/testing/project.ts @@ -100,3 +100,28 @@ export function resolveTestProcessPlan(cwd: string): readonly DevProcessSpec[] { 'No supported StellarForge test workflow was found. Run `stellarforge test` from the generated project root or a nested directory inside it. Expected a package.json test script or a Cargo.toml workspace.', ); } + +export async function superviseTestProcesses( + specs: readonly DevProcessSpec[], + options: DevOrchestratorOptions = {}, +): Promise { + const usesNpm = specs.some(isNpmInvocation); + + try { + await superviseDevProcesses(specs, options); + } catch (error) { + if (!usesNpm || !(error instanceof SubprocessCliError)) { + throw error; + } + + const failure = classifyNpmInvocationError(error.cause); + + if (failure === undefined) { + throw error; + } + + throw new SubprocessCliError(npmInvocationRemediation(failure), { + cause: error, + }); + } +} diff --git a/tests/generator-file-permissions.test.ts b/tests/generator-file-permissions.test.ts new file mode 100644 index 00000000..b964eed5 --- /dev/null +++ b/tests/generator-file-permissions.test.ts @@ -0,0 +1,112 @@ +import { + chmodSync, + mkdirSync, + readFileSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { generateProjectFromTemplate } from '../src/generator/template-generation.js'; +import type { GenerationContext } from '../src/generator/types.js'; +import { withTempDirectory } from './helpers/index.js'; + +function context(root: string): GenerationContext { + return { + input: { projectName: 'demo-app', cwd: root, templateId: 'basic-app' }, + destination: { + projectName: 'demo-app', + destination: join(root, 'demo-app'), + }, + template: { templateId: 'basic-app' }, + }; +} + +function createTemplate(root: string): { + readonly templateRoot: string; + readonly executable: string; + readonly regular: string; +} { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + const executable = join(templateRoot, 'run.sh'); + const regular = join(templateRoot, 'README.md'); + + writeFileSync(executable, '#!/bin/sh\necho ok\n'); + writeFileSync(regular, '# {{projectName}}\n'); + + return { templateRoot, executable, regular }; +} + +describe('generated-file permission policy (SW-130)', () => { + it.skipIf(process.platform === 'win32')( + 'preserves executable assets and constrains regular file modes on POSIX', + () => + withTempDirectory((root) => { + const { templateRoot, executable, regular } = createTemplate(root); + chmodSync(executable, 0o755); + chmodSync(regular, 0o666); + + generateProjectFromTemplate(context(root), { templateRoot }); + + const generatedExecutable = join(root, 'demo-app', 'run.sh'); + const generatedRegular = join(root, 'demo-app', 'README.md'); + + expect(statSync(generatedExecutable).mode & 0o777).toBe(0o755); + expect(statSync(generatedRegular).mode & 0o777).toBe(0o644); + expect(statSync(generatedRegular).mode & 0o022).toBe(0); + }), + ); + + it.skipIf(process.platform === 'win32')( + 'does not copy privileged or group/world write bits from source metadata', + () => + withTempDirectory((root) => { + const { templateRoot, executable } = createTemplate(root); + chmodSync(executable, 0o4777); + + generateProjectFromTemplate(context(root), { templateRoot }); + + expect( + statSync(join(root, 'demo-app', 'run.sh')).mode & 0o7777, + ).toBe(0o755); + }), + ); + + it('keeps generated npm project metadata usable after installation', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + writeFileSync( + join(templateRoot, 'package.json'), + JSON.stringify({ + name: '{{projectName}}', + private: true, + scripts: { check: 'node --check src/index.js', test: 'node --test' }, + }), + ); + + generateProjectFromTemplate(context(root), { templateRoot }); + + const generatedPackage = JSON.parse( + readFileSync(join(root, 'demo-app', 'package.json'), 'utf8'), + ) as { + readonly name?: unknown; + readonly scripts?: Record; + }; + expect(generatedPackage.name).toBe('demo-app'); + expect(generatedPackage.scripts?.check).toBe('node --check src/index.js'); + expect(generatedPackage.scripts?.test).toBe('node --test'); + })); + + it('generates successfully on Windows without POSIX chmod support', () => + withTempDirectory((root) => { + const { templateRoot } = createTemplate(root); + + generateProjectFromTemplate(context(root), { templateRoot }); + + expect(readFileSync(join(root, 'demo-app', 'run.sh'), 'utf8')).toContain( + 'echo ok', + ); + })); +}); diff --git a/tests/generator-path-collisions.test.ts b/tests/generator-path-collisions.test.ts new file mode 100644 index 00000000..b0299fbc --- /dev/null +++ b/tests/generator-path-collisions.test.ts @@ -0,0 +1,128 @@ +import { + existsSync, + mkdirSync, + readFileSync, + writeFileSync, +} from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { assertPortableTemplatePaths } from '../src/generator/template-sources.js'; +import { generateProjectFromTemplate } from '../src/generator/template-generation.js'; +import type { GenerationContext } from '../src/generator/types.js'; +import { withTempDirectory } from './helpers/index.js'; + +const ORIGINAL_PLATFORM = process.platform; + +function onPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { + value: platform, + configurable: true, + }); +} + +afterEach(() => { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); +}); + +function context(root: string): GenerationContext { + return { + input: { projectName: 'demo-app', cwd: root, templateId: 'basic-app' }, + destination: { + projectName: 'demo-app', + destination: join(root, 'demo-app'), + }, + template: { templateId: 'basic-app' }, + }; +} + +function bothPathsAreDistinct( + first: string, + second: string, + firstContent: string, +): boolean { + return ( + existsSync(first) && + existsSync(second) && + readFileSync(first, 'utf8') === firstContent + ); +} + +describe('portable template path policy (SW-129)', () => { + it('rejects case-folding collisions before creating any generated file', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + const first = join(templateRoot, 'README.md'); + const second = join(templateRoot, 'readme.md'); + writeFileSync(first, 'first'); + writeFileSync(second, 'second'); + + if (!bothPathsAreDistinct(first, second, 'first')) return; + + expect(() => + generateProjectFromTemplate(context(root), { templateRoot }), + ).toThrow(/colliding paths 'README\.md' and 'readme\.md'/); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + })); + + it('rejects Unicode normalization collisions before creating any generated file', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(templateRoot); + const first = join(templateRoot, 'caf\u00E9.txt'); + const second = join(templateRoot, 'cafe\u0301.txt'); + writeFileSync(first, 'first'); + writeFileSync(second, 'second'); + + if (!bothPathsAreDistinct(first, second, 'first')) return; + + expect(() => + generateProjectFromTemplate(context(root), { templateRoot }), + ).toThrow(/colliding paths/); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + })); + + it('reports identical collision guidance on Linux, macOS, and Windows', () => { + const paths = ['src/Caf\u00E9.txt', 'src/cafe\u0301.txt']; + let expectedMessage: string | undefined; + + for (const platform of ['linux', 'darwin', 'win32'] as const) { + onPlatform(platform); + + let message: string | undefined; + try { + assertPortableTemplatePaths(paths); + } catch (error) { + message = error instanceof Error ? error.message : undefined; + } + + expect(message).toBeDefined(); + if (expectedMessage === undefined) { + expectedMessage = message; + } else { + expect(message).toBe(expectedMessage); + } + } + }); + + it('keeps valid non-colliding case-distinct paths supported', () => + withTempDirectory((root) => { + const templateRoot = join(root, 'template'); + mkdirSync(join(templateRoot, 'src'), { recursive: true }); + writeFileSync(join(templateRoot, 'package.json'), '{"name":"demo"}'); + writeFileSync(join(templateRoot, 'src', 'Alpha.ts'), 'alpha'); + writeFileSync(join(templateRoot, 'src', 'beta.ts'), 'beta'); + + generateProjectFromTemplate(context(root), { templateRoot }); + + expect( + readFileSync(join(root, 'demo-app', 'src', 'Alpha.ts'), 'utf8'), + ).toBe('alpha'); + expect( + readFileSync(join(root, 'demo-app', 'src', 'beta.ts'), 'utf8'), + ).toBe('beta'); + })); +}); diff --git a/tests/generator-symlink-ancestor.test.ts b/tests/generator-symlink-ancestor.test.ts index 66096911..2a61ba7b 100644 --- a/tests/generator-symlink-ancestor.test.ts +++ b/tests/generator-symlink-ancestor.test.ts @@ -41,6 +41,23 @@ function canCreateSymlinks(): boolean { const symlinksSupported = canCreateSymlinks(); +function canCreateFileSymlinks(): boolean { + const fixture = createTempDirectoryFixture(); + try { + symlinkSync( + join(fixture.path, 'probe-target'), + join(fixture.path, 'probe-link'), + ); + return true; + } catch { + return false; + } finally { + fixture.cleanup(); + } +} + +const fileSymlinksSupported = canCreateFileSymlinks(); + function createMinimalTemplate(root: string): string { const templateRoot = join(root, 'template'); mkdirSync(join(templateRoot, 'src'), { recursive: true }); @@ -321,3 +338,80 @@ describe('generator symlink-ancestor containment (SW-032)', () => { }), ); }); + +describe('bundled template source symlink policy (SW-131)', () => { + it.skipIf(!symlinksSupported && !fileSymlinksSupported)( + 'rejects a dangling symlink entry before writing the generated project', + () => + withTempDirectory((root) => { + const templateRoot = createMinimalTemplate(root); + + if (fileSymlinksSupported) { + symlinkSync( + join(templateRoot, 'missing-target.txt'), + join(templateRoot, 'dangling.txt'), + ); + } else { + symlinkSync( + join(root, 'missing-target-dir'), + join(templateRoot, 'dangling-dir'), + 'junction', + ); + } + + expect(() => + generateProjectFromTemplate( + createContext(root, join(root, 'demo-app')), + { templateRoot }, + ), + ).toThrow('Template symbolic links are not supported.'); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + expect(stagingLeftovers(root)).toEqual([]); + }), + ); + + it.skipIf(!symlinksSupported)( + 'rejects a symlink whose resolved target escapes the template root', + () => + withTempDirectory((root) => { + const templateRoot = createMinimalTemplate(root); + const outside = createTempDirectoryFixture(); + try { + const outsideFile = join(outside.path, 'secret.txt'); + writeFileSync(outsideFile, 'outside-template-content'); + symlinkSync(outsideFile, join(templateRoot, 'escape.txt')); + + expect(() => + generateProjectFromTemplate( + createContext(root, join(root, 'demo-app')), + { templateRoot }, + ), + ).toThrow(ValidationCliError); + expect(existsSync(join(root, 'demo-app'))).toBe(false); + expect(stagingLeftovers(root)).toEqual([]); + expect(stagingLeftovers(outside.path)).toEqual([]); + } finally { + outside.cleanup(); + } + }), + ); + + it('continues to generate regular files and directories', () => + withTempDirectory((root) => { + const templateRoot = createMinimalTemplate(root); + const destination = join(root, 'demo-app'); + + const result = generateProjectFromTemplate( + createContext(root, destination), + { templateRoot }, + ); + + expect(result.destination).toBe(destination); + expect(readFileSync(join(destination, 'package.json'), 'utf8')).toContain( + '"name":"demo-app"', + ); + expect( + readFileSync(join(destination, 'src', 'index.ts'), 'utf8'), + ).toContain('"demo-app"'); + })); +}); diff --git a/tests/test-missing-npm-remediation.test.ts b/tests/test-missing-npm-remediation.test.ts new file mode 100644 index 00000000..30c7d152 --- /dev/null +++ b/tests/test-missing-npm-remediation.test.ts @@ -0,0 +1,156 @@ +import { afterEach, describe, expect, it } from 'vitest'; +import { createTestCommand } from '../src/commands/test.js'; +import type { DevProcessSpec } from '../src/dev/project.js'; +import { SubprocessCliError } from '../src/errors/errors.js'; +import { createNpmInvocation } from '../src/process/npm.js'; +import { + createCapturedTerminalOutput, + FakeChildProcess, +} from './helpers/index.js'; + +const ORIGINAL_PLATFORM = process.platform; + +function onPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { + value: platform, + configurable: true, + }); +} + +afterEach(() => { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); +}); + +function npmPlan(label = 'demo:test'): readonly DevProcessSpec[] { + const npm = createNpmInvocation(['run', 'test']); + return [{ label, command: npm.command, args: npm.args, cwd: '/workspace' }]; +} + +function errnoError(code: 'ENOENT' | 'EACCES'): Error { + const error = new Error( + `spawn npm ${code} PATH=/secret-runtime-path SECRET_TOKEN=do-not-echo`, + ) as NodeJS.ErrnoException; + error.code = code; + return error; +} + +async function rejectionOf(running: Promise): Promise { + return running.then( + () => undefined, + (reason: unknown) => reason, + ); +} + +describe('test workflow package-manager remediation (SW-157)', () => { + it('classifies executable-not-found separately from a failing test script', async () => { + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => npmPlan(), + spawnProcess: () => { + throw errnoError('ENOENT'); + }, + }); + + const error = await rejectionOf(command.parseAsync(['node', 'test'])); + + expect(error).toBeInstanceOf(SubprocessCliError); + const message = (error as SubprocessCliError).userMessage; + expect(message).toContain('Unable to find npm or its supported launcher'); + expect(message).toContain('Node.js >=22.13.0 <25'); + expect(message).toContain('npm >=10.9.0'); + expect(message).not.toContain('exited unexpectedly'); + expect(message).not.toContain('SECRET_TOKEN'); + expect(message).not.toContain('/secret-runtime-path'); + }); + + it('reports permission-denied with the same supported runtime guidance', async () => { + const child = new FakeChildProcess(); + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => npmPlan(), + spawnProcess: () => child, + }); + + const running = command.parseAsync(['node', 'test']); + const childFailure = child.fail(errnoError('EACCES')); + const error = await rejectionOf(running); + await childFailure; + + expect(error).toBeInstanceOf(SubprocessCliError); + const message = (error as SubprocessCliError).userMessage; + expect(message).toContain('could not be executed'); + expect(message).toContain('Node.js >=22.13.0 <25'); + expect(message).toContain('npm >=10.9.0'); + expect(message).not.toContain('SECRET_TOKEN'); + }); + + it('preserves an ordinary test-script failure without missing-npm guidance', async () => { + const child = new FakeChildProcess(); + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => npmPlan(), + spawnProcess: () => child, + }); + + const running = command.parseAsync(['node', 'test']); + const childResult = child.finish(9); + const error = await rejectionOf(running); + await childResult; + + expect(error).toBeInstanceOf(SubprocessCliError); + const message = (error as SubprocessCliError).userMessage; + expect(message).toContain('with code 9'); + expect(message).not.toContain('supported Node.js runtime'); + }); + + it('keeps the Windows npm launcher and reports its startup failure', async () => { + onPlatform('win32'); + let spawned = false; + const plan = npmPlan(); + + const command = createTestCommand({ + cwd: () => '/workspace', + resolvePlan: () => plan, + spawnProcess: (spec) => { + spawned = true; + expect(spec.command).toBe('cmd.exe'); + expect(spec.args.slice(0, 4)).toEqual(['/d', '/s', '/c', 'npm']); + throw errnoError('ENOENT'); + }, + }); + + const error = await rejectionOf(command.parseAsync(['node', 'test'])); + + expect(spawned).toBe(true); + expect((error as SubprocessCliError).userMessage).toContain( + 'Unable to find npm or its supported launcher', + ); + }); + + it('does not echo the supplied process environment', async () => { + const captured = createCapturedTerminalOutput(); + const command = createTestCommand({ + cwd: () => '/workspace', + output: captured.output, + environment: { + PATH: '/usr/bin', + SECRET_TOKEN: 'super-secret-value', + }, + resolvePlan: () => npmPlan(), + spawnProcess: () => { + throw errnoError('ENOENT'); + }, + }); + + const error = await rejectionOf(command.parseAsync(['node', 'test'])); + + expect((error as SubprocessCliError).userMessage).not.toContain( + 'super-secret-value', + ); + expect(captured.stdoutText()).not.toContain('super-secret-value'); + expect(captured.stderrText()).not.toContain('super-secret-value'); + }); +});