Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion docs/reference/commands.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
10 changes: 6 additions & 4 deletions docs/reference/template-generation.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
2 changes: 1 addition & 1 deletion docs/reference/troubleshooting.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
12 changes: 6 additions & 6 deletions src/commands/test.ts
Original file line number Diff line number Diff line change
@@ -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;
Expand All @@ -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 });
});
}
72 changes: 37 additions & 35 deletions src/generator/template-generation.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {
chmodSync,
existsSync,
lstatSync,
mkdirSync,
Expand Down Expand Up @@ -67,6 +68,13 @@
/** 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);

Expand All @@ -78,18 +86,6 @@
);
}

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<Record<string, string>>,
Expand Down Expand Up @@ -251,11 +247,15 @@

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,
};
});

Check failure on line 257 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

Declaration or statement expected.

Check failure on line 257 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

Declaration or statement expected.

Check failure on line 257 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

Declaration or statement expected.

Check failure on line 257 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

Declaration or statement expected.
}

if (sourceStat.isDirectory()) {
visitDirectory(relativePath);
Expand All @@ -270,13 +270,11 @@
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, []);
Expand All @@ -285,8 +283,12 @@

const rendered = renderText(content.toString('utf8'), variables);
visitFile(destinationRelativePath, rendered.content, rendered.substitutions);
}

Check failure on line 286 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

Declaration or statement expected.

Check failure on line 286 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

Declaration or statement expected.

Check failure on line 286 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

Declaration or statement expected.

Check failure on line 286 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

Declaration or statement expected.

const mode = resolveGeneratedFileMode(file.mode);
writeFileSync(destinationPath, file.content, { mode });
chmodSync(destinationPath, mode);
}

Check failure on line 291 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

Declaration or statement expected.

Check failure on line 291 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

Declaration or statement expected.

Check failure on line 291 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

Declaration or statement expected.

Check failure on line 291 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

Declaration or statement expected.

function assertDestinationContainment(root: string, destination: string): void {
const destinationParent = dirname(destination);
Expand Down Expand Up @@ -391,6 +393,7 @@
projectName: context.input.projectName,
templateId: context.template.templateId,
};
const renderedFiles = renderTemplateFiles(tree, variables);

if (options.dryRun) {
const files: ProjectGenerationPreviewFile[] = [];
Expand Down Expand Up @@ -436,27 +439,26 @@
);
}

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 });

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

')' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

',' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

')' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

',' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

')' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

',' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

')' expected.

Check failure on line 452 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

',' expected.
},

Check failure on line 453 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

'catch' or 'finally' expected.

Check failure on line 453 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

'catch' or 'finally' expected.

Check failure on line 453 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

'catch' or 'finally' expected.

Check failure on line 453 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

'catch' or 'finally' expected.
options.isCancelled,
);

Check failure on line 455 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

Expression expected.

Check failure on line 455 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

Expression expected.

Check failure on line 455 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

Expression expected.

Check failure on line 455 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

Expression expected.

assertNotCancelled(options.isCancelled);

// 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);
Expand Down Expand Up @@ -510,7 +512,7 @@

assertNotCancelled(options.isCancelled);
renameSync(stagingRoot, destination);
} catch (error) {

Check failure on line 515 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

'try' expected.

Check failure on line 515 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

'try' expected.

Check failure on line 515 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

'try' expected.

Check failure on line 515 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

'try' expected.
rmSync(stagingRoot, { recursive: true, force: true });

if (removedExistingDestination && !existsSync(destination)) {
Expand All @@ -525,4 +527,4 @@
destination,
templateId: context.template.templateId,
};
}

Check failure on line 530 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 24

Declaration or statement expected.

Check failure on line 530 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Linked CLI MVP smoke / Node 22.13.0

Declaration or statement expected.

Check failure on line 530 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Smart Contract / Cargo metadata & tests

Declaration or statement expected.

Check failure on line 530 in src/generator/template-generation.ts

View workflow job for this annotation

GitHub Actions / Quality

Declaration or statement expected.
162 changes: 162 additions & 0 deletions src/generator/template-sources.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -8,6 +10,23 @@ const BUNDLED_TEMPLATE_DIRECTORIES: Record<TemplateId, string> =
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];
Expand All @@ -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<string, string>();

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 };
}
Loading
Loading