diff --git a/.changeset/config-file-boundary-policy.md b/.changeset/config-file-boundary-policy.md new file mode 100644 index 00000000..811cc772 --- /dev/null +++ b/.changeset/config-file-boundary-policy.md @@ -0,0 +1,5 @@ +--- +'@diginodes/stellarforge-cli': patch +--- + +Harden project configuration loading so reads stay on an inspected regular file inside the project root, document the portable non-secret permission policy, and add deterministic coverage for unreadable files and symlink boundaries. diff --git a/docs/reference/commands.md b/docs/reference/commands.md index b9bf37b9..0a1a8bfd 100644 --- a/docs/reference/commands.md +++ b/docs/reference/commands.md @@ -311,7 +311,7 @@ Before the Stellar CLI deployment subprocess starts, `stellarforge deploy` runs - the generated Wasm artifact exists, is readable, and is not stale; - the configuration file, if present, is well formed. -Preflight is validation and reporting only. It does not invoke a deployment transaction, does not spawn subprocesses, and does not contact any network endpoint. +Preflight is validation and reporting only. It does not invoke a deployment transaction, does not spawn subprocesses, and does not contact any network endpoint. Pass `--preflight` to stop after reporting the checks instead of starting the deployment. Preflight output never prints private keys, seed phrases, tokens, account StrKeys, identity alias values, or other sensitive configuration values. Failed checks include remediation steps, for example: diff --git a/docs/reference/configuration.md b/docs/reference/configuration.md index f56befa7..80a5df03 100644 --- a/docs/reference/configuration.md +++ b/docs/reference/configuration.md @@ -56,15 +56,26 @@ overrides only the identity. The file must: -- live at the project root; -- be a regular file rather than a symbolic link; +- live at the project root under the exact name `stellarforge.config.json`; +- be a regular file rather than a symbolic link, including links whose target is inside the project root; +- be readable by the current process; - be no larger than 64 KiB; - be encoded as UTF-8 (a single leading UTF-8 byte-order mark is tolerated); - contain valid JSON with no duplicate object keys; - contain no duplicate object keys at any nesting level (escaped-equivalent spellings are treated as the same key); - contain only supported schema fields. -Validation failures are designed to be actionable without echoing raw file contents or sensitive values. +The loader reads only the opened regular file descriptor and rechecks the project-root path before reading. A symlink substituted between inspection and read is rejected; the config is never read through a link that could escape the project boundary. + +Validation failures are designed to be actionable without echoing raw file contents, paths, OS error text, or sensitive values. + +### File permissions and platform behavior + +This configuration file is non-secret by design: it holds only a schema version, a network name, and an identity alias. StellarForge therefore does not reject or warn about permissive file modes or unusual ownership, because those are not security signals for this file. + +- POSIX permission and ownership bits are ignored on every supported platform, including Windows where those bits are synthetic. Mode `0666`, group ownership, and root ownership are accepted. +- A file that the current process cannot read produces the validation error `Unable to inspect stellarforge.config.json.` (exit code 2). The message never includes the path, the OS error, or file contents. +- StellarForge never changes file permissions or ownership and never attempts privilege escalation. If a config file cannot be read, adjust it outside the CLI. If the file is rejected, see [Troubleshooting](troubleshooting.md#configuration-file-is-rejected). For deployment settings, see [Deployment network is required](troubleshooting.md#deployment-network-is-required) and [Deployment identity is rejected](troubleshooting.md#deployment-identity-is-rejected). diff --git a/docs/reference/exit-codes.md b/docs/reference/exit-codes.md index 4ccc3cb1..5382b4a9 100644 --- a/docs/reference/exit-codes.md +++ b/docs/reference/exit-codes.md @@ -6,13 +6,13 @@ StellarForge CLI uses predictable process exit codes so humans, scripts, and CI | Exit code | Category | Meaning | |---:|---------|---------| -| `0` x Success | The requested CLI operation completed successfully. | -| `1` x Unexpected failure | An unclassified exception reached the top-level CLI boundary. | -| `2` x Validation / usage failure | User input, command syntax, options, arguments, or other validated input was invalid. | -| `3` x Subprocess failure | A required external process or tool failed. | -| `4` x Internal failure | StellarForge detected a known internal failure condition that should not expose implementation details to the user. | -| `5` x Diagnostic failure | A diagnostic command completed normally but one or more required checks failed; used by `doctor` (environment health) and `stellarforge validate` (local project requirements). | -| `130` x Cancellation | The operation was interrupted by the user (SIGINT or equivalent) and stopped before completion. | +| `0` | Success | The requested CLI operation completed successfully. | +| `1` | Unexpected failure | An unclassified exception reached the top-level CLI boundary. | +| `2` | Validation / usage failure | User input, command syntax, options, arguments, or other validated input was invalid. | +| `3` | Subprocess failure | A required external process or tool failed. | +| `4` | Internal failure | StellarForge detected a known internal failure condition that should not expose implementation details to the user. | +| `5` | Diagnostic failure | A diagnostic command completed normally but one or more required checks failed; used by `doctor` (environment health) and `stellarforge validate` (local project requirements). | +| `130` | Cancellation | The operation was interrupted by the user (SIGINT or equivalent) and stopped before completion. | These values are part of the CLI contract and should not be changed casually. New stable categories require deliberate review and documentation. diff --git a/docs/reference/platform-support.md b/docs/reference/platform-support.md index 69753026..d6e4582d 100644 --- a/docs/reference/platform-support.md +++ b/docs/reference/platform-support.md @@ -37,7 +37,8 @@ StellarForge code should expose platform differences deliberately instead of hid - Cargo subprocesses use `cargo.exe`; - Stellar deployment subprocesses use `stellar.exe`; - path tests must use Node path APIs rather than assuming POSIX separators; -- commands must not rely on Bash being the default shell. +- commands must not rely on Bash being the default shell; +- POSIX permission and ownership bits reported for files are synthetic, so config loading ignores them on every platform instead of applying platform-dependent rules or changing file permissions. ### macOS and Linux diff --git a/docs/reference/troubleshooting.md b/docs/reference/troubleshooting.md index dc657c41..f8abb728 100644 --- a/docs/reference/troubleshooting.md +++ b/docs/reference/troubleshooting.md @@ -16,6 +16,7 @@ This page covers common failures in the implemented StellarForge CLI MVP. | Deployment | Network or identity is missing or rejected, Mainnet or Futurenet is refused, or Stellar CLI fails | [Deployment network is required](#deployment-network-is-required), [Deployment rejects Mainnet or Futurenet](#deployment-rejects-mainnet-or-futurenet), [Deployment identity is rejected](#deployment-identity-is-rejected), and [Stellar CLI deployment fails](#stellar-cli-deployment-fails) | | Unexpected failure | A generic error message with exit code `1` or `4` | [Unexpected or internal failure](#unexpected-or-internal-failure) | | Sensitive data | A secret appeared in output or in a report | [Sensitive information appeared in a failure](#sensitive-information-appeared-in-a-failure) | +| Cancellation | A command was interrupted and exited with code `130` | [Cancelled operation](#cancelled-operation) | ### Look up by exit code @@ -25,6 +26,7 @@ This page covers common failures in the implemented StellarForge CLI MVP. | `3` | A subprocess failed: [`dev`](#stellarforge-dev-says-no-supported-script-exists), [`test`](#stellarforge-test-cannot-find-a-workflow), or [Stellar CLI deployment](#stellar-cli-deployment-fails) | | `5` | [`stellarforge doctor` reports failures](#stellarforge-doctor-reports-failures) | | `1` or `4` | [Unexpected or internal failure](#unexpected-or-internal-failure) | +| `130` | [Cancelled operation](#cancelled-operation) | Exit code meanings are defined in [Exit Codes](exit-codes.md). Related references: [Installation](../guides/installation.md), [Quick Start](../guides/quick-start.md), [Command Reference](commands.md), [Configuration](configuration.md), and [Platform Support](platform-support.md). @@ -137,7 +139,9 @@ stellarforge.config.json and live at the project root. -It must be a regular non-symlink file, no larger than 64 KiB, encoded as UTF-8 (a single leading UTF-8 byte-order mark is tolerated), and contain valid JSON with schema version `1`, and it must not contain duplicate object keys at any nesting level (escaped-equivalent spellings are treated as the same key). +It must be a regular non-symlink file, no larger than 64 KiB, encoded as UTF-8 (a single leading UTF-8 byte-order mark is tolerated), and contain valid JSON with schema version `1`, and it must not contain duplicate object keys at any nesting level (escaped-equivalent spellings are treated as the same key). Symbolic links are never followed, including links that point back inside the project. + +If the file cannot be read, the CLI reports `Unable to inspect stellarforge.config.json.` without echoing the path or the system error. Fix access outside StellarForge: the CLI never changes permissions or ownership. Permissive POSIX modes are accepted because this file contains no secrets, and Windows does not expose meaningful POSIX permission semantics. Supported fields are only: @@ -247,6 +251,10 @@ StellarForge errors are designed not to render raw secrets. Do not paste private If you believe a secret disclosure is caused by a vulnerability, follow [SECURITY.md](../../SECURITY.md) instead of opening a public issue. +## Cancelled operation + +A command that receives an interrupt (SIGINT, or SIGBREAK where supported) stops gracefully and exits with code `130`. Cleanup runs first: `dev` stops its watcher and child processes, `test` and `deploy` wait for the in-flight subprocess, and `new` rolls back partially generated files. A second interrupt during cleanup exits immediately with the same code. Cancellation messages go to stderr and never report success. See [Exit Codes](exit-codes.md#stable-baseline). + ## Still blocked? Collect only non-sensitive information: diff --git a/eslint.config.js b/eslint.config.js index 2a8ea566..4b40ca9d 100644 --- a/eslint.config.js +++ b/eslint.config.js @@ -20,4 +20,17 @@ export default tseslint.config( '@typescript-eslint/no-explicit-any': 'error', }, }, + { + files: ['templates/**/*.js'], + languageOptions: { + globals: { + clearInterval: 'readonly', + clearTimeout: 'readonly', + process: 'readonly', + setInterval: 'readonly', + setTimeout: 'readonly', + URL: 'readonly', + }, + }, + }, ); diff --git a/package-lock.json b/package-lock.json index 451dc08b..e006d47b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -631,6 +631,7 @@ "integrity": "sha512-rDS5/31E9HfPl/CIzGrn0DOlvBbXFseQ5URJ9sYMfstbKLD/c6Gm9vmRzRGDdAXyOIL4zmO37lc9RIwYqVruZw==", "dev": true, "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/sponsors/oxc-project" } @@ -661,6 +662,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -678,6 +680,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -695,6 +698,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -712,6 +716,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -729,6 +734,7 @@ "os": [ "freebsd" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -746,6 +752,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -763,6 +770,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -780,6 +788,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -797,6 +806,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -814,6 +824,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -831,6 +842,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -848,6 +860,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -865,6 +878,7 @@ "os": [ "openharmony" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -882,6 +896,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -899,6 +914,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": "^20.19.0 || >=22.12.0" } @@ -908,7 +924,8 @@ "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@types/chai": { "version": "5.2.3", @@ -955,7 +972,6 @@ "integrity": "sha512-U2+DNr+wSjpsTS/wZGYHq7GcwfuSmKiKvoPvK22zwTlRhU91yOniN4qRR5KhIjvif7ysw/dz/hKmfDH0Ris4aA==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~6.21.0" } @@ -1005,7 +1021,6 @@ "integrity": "sha512-zYvrmj9Yxd63UGaXw+kdt6A0F0s0qveJyuatIM77bYC2DE4pgmg7a50u8LR7PRtXd0x+h+Tl3eXabGm06SWd3Q==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "8.70.0", "@typescript-eslint/types": "8.70.0", @@ -1235,7 +1250,6 @@ "integrity": "sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ==", "dev": true, "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -1392,6 +1406,7 @@ "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", "dev": true, "license": "Apache-2.0", + "peer": true, "engines": { "node": ">=8" } @@ -1422,7 +1437,6 @@ "integrity": "sha512-P7a6UEEqb9G95MYAtqkmsTbVXIYyzIfl6NGOIJk162PaahFxFyeGcrlXYFSiagECg4sEm8IseJdZBKR3rx6MsQ==", "dev": true, "license": "MIT", - "peer": true, "workspaces": [ "packages/*" ], @@ -1738,6 +1752,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } @@ -1880,7 +1895,6 @@ "integrity": "sha512-CYDD3SOtsHtyXeEORYRx2qBtpDJFjRTGXUtmNEMGyzYOKj1TE3tycdlho7kA1Ufx9OYWZzg52QFBGALTirzDSw==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@keyv/serialize": "^1.1.1" } @@ -1916,6 +1930,7 @@ "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", "dev": true, "license": "MPL-2.0", + "peer": true, "dependencies": { "detect-libc": "^2.0.3" }, @@ -1953,6 +1968,7 @@ "os": [ "android" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -1974,6 +1990,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -1995,6 +2012,7 @@ "os": [ "darwin" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2016,6 +2034,7 @@ "os": [ "freebsd" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2037,6 +2056,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2058,6 +2078,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2079,6 +2100,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2100,6 +2122,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2121,6 +2144,7 @@ "os": [ "linux" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2142,6 +2166,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2163,6 +2188,7 @@ "os": [ "win32" ], + "peer": true, "engines": { "node": ">= 12.0.0" }, @@ -2232,6 +2258,7 @@ } ], "license": "MIT", + "peer": true, "bin": { "nanoid": "bin/nanoid.cjs" }, @@ -2377,6 +2404,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.18", "picocolors": "^1.1.1", @@ -2465,6 +2493,7 @@ "integrity": "sha512-hx/Pv0N1haXRb11qkfnK5MXB/iqr7i0yjWQqmO9uHqZpBgQSqzc8UsSnEpalsh+j1I8qQ2CkXAkJC8Br3dKSlg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@oxc-project/types": "=0.150.0", "@rolldown/pluginutils": "^1.0.0" @@ -2562,6 +2591,7 @@ "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", "dev": true, "license": "BSD-3-Clause", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -2649,7 +2679,6 @@ "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", "dev": true, "license": "Apache-2.0", - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" diff --git a/scripts/audit-workflow-permissions.mjs b/scripts/audit-workflow-permissions.mjs index 25593ac9..fa57cb40 100644 --- a/scripts/audit-workflow-permissions.mjs +++ b/scripts/audit-workflow-permissions.mjs @@ -13,14 +13,6 @@ import fs from 'node:fs'; import path from 'node:path'; -/** Explicit per-job exceptions for workflows that must write. */ -const ARTIFACT_RETENTION_DAYS = { - test: 7, - coverage: 7, - security: 30, - release: 90, -}; - /** Artifact path patterns that must never be uploaded. */ const FORBIDDEN_ARTIFACT_PATTERNS = [ /\.env(\b|$)/i, @@ -37,6 +29,9 @@ const FORBIDDEN_ARTIFACT_PATTERNS = [ /(^|\/)\.DS_Store$/i, ]; +/** Artifact paths that would upload the entire workspace. */ +const BROAD_ARTIFACT_PATHS = /^(?:\.|\.\/|\*\*|\/)$/; + /** Workflows that may publish release artifacts. */ const RELEASE_PUBLISHING_WORKFLOWS = new Set(['release.yml']); @@ -193,6 +188,13 @@ function auditArtifacts(filePath) { break; } } + if (BROAD_ARTIFACT_PATHS.test(p)) { + violations.push({ + file: base, + line: upload.line, + message: `artifact path "${p}" sweeps the entire workspace`, + }); + } } if (isPrWorkflow && !RELEASE_PUBLISHING_WORKFLOWS.has(base)) { diff --git a/scripts/e2e-smoke.mjs b/scripts/e2e-smoke.mjs index fb473718..5bf951f6 100644 --- a/scripts/e2e-smoke.mjs +++ b/scripts/e2e-smoke.mjs @@ -1,4 +1,5 @@ import assert from 'node:assert/strict'; +import { Buffer } from 'node:buffer'; import { chmodSync, copyFileSync, @@ -12,7 +13,7 @@ import { } from 'node:fs'; import { tmpdir } from 'node:os'; import process from 'node:process'; -import { delimiter, join } from 'node:path'; +import { delimiter, dirname, join } from 'node:path'; import { spawnSync } from 'node:child_process'; const repositoryRoot = process.cwd(); @@ -102,6 +103,18 @@ try { const contractRoot = join(root, 'smoke-contract'); assert.equal(existsSync(join(contractRoot, 'Cargo.toml')), true); + // Deployment preflight requires a built Wasm artifact; the mocked stellar + // executable never builds one, so provide a minimal valid fixture. + const wasmArtifact = join( + contractRoot, + 'target', + 'wasm32v1-none', + 'release', + 'stellarforge-starter-contract.wasm', + ); + mkdirSync(dirname(wasmArtifact), { recursive: true }); + writeFileSync(wasmArtifact, Buffer.from([0, 0x61, 0x73, 0x6d, 1, 0, 0, 0])); + writeFileSync( join(contractRoot, 'stellarforge.config.json'), JSON.stringify({ @@ -119,7 +132,7 @@ try { [ '#!/usr/bin/env sh', 'set -eu', - 'expected="contract deploy --source-account ci-deployer --network testnet"', + 'expected="contract deploy --wasm target/wasm32v1-none/release/stellarforge-starter-contract.wasm --source-account ci-deployer --network testnet"', 'actual="$*"', 'if [ "$actual" != "$expected" ]; then', ' echo "unexpected stellar args" >&2', @@ -135,7 +148,7 @@ try { writeFileSync( join(contractRoot, 'contract'), [ - 'const expected = "deploy --source-account ci-deployer --network testnet";', + 'const expected = "deploy --wasm target/wasm32v1-none/release/stellarforge-starter-contract.wasm --source-account ci-deployer --network testnet";', 'const actual = process.argv.slice(2).join(" ");', 'if (actual !== expected) {', ' process.stderr.write("unexpected stellar args\\n");', diff --git a/src/cli.ts b/src/cli.ts index 20db15ea..93863986 100644 --- a/src/cli.ts +++ b/src/cli.ts @@ -13,7 +13,6 @@ import { runCli } from './main.js'; * This is the conventional 130 exit code for signal-terminated processes. */ - /** * Tracks whether a cancellation signal has already been observed. * The first signal triggers graceful cleanup and a documented non-zero exit. @@ -42,9 +41,9 @@ function handleSignal(signal: NodeJS.Signals): void { process.exitCode = CANCELLATION_EXIT_CODE; if (typeof process.emit === 'function') { // Notify any listeners (e.g. cleanup coordinators) without swallowing the signal. - (process as unknown as { - emit(event: string): boolean; -}).emit('cancellationRequested'); + (process.emit as unknown as (event: string) => boolean)( + 'cancellationRequested', + ); } } diff --git a/src/commands/deploy.ts b/src/commands/deploy.ts index 456163cb..6aa6bd42 100644 --- a/src/commands/deploy.ts +++ b/src/commands/deploy.ts @@ -39,8 +39,7 @@ export interface DeployCommandOptions extends DevOrchestratorOptions { input: TestnetDeploymentInput, ) => DeploymentPreflightResult; readonly validateDeployment?: - | boolean - | ((output: DeploymentOutput) => DeployedContractData); + boolean | ((output: DeploymentOutput) => DeployedContractData); } interface DeployCommandFlags { @@ -58,7 +57,7 @@ function isCancellationError(error: unknown): boolean { } const code = (error as { code?: unknown }).code; return code === 'SIGINT' || code === 'CANCELLED'; - } +} export function createDeployCommand( options: DeployCommandOptions = {}, diff --git a/src/commands/new.ts b/src/commands/new.ts index d802b995..000bf4d6 100644 --- a/src/commands/new.ts +++ b/src/commands/new.ts @@ -87,8 +87,7 @@ export function createNewCommand(options: NewCommandOptions = {}): Command { if (cancelled) { throw new ScaffoldingCancelledCliError(); - }, - ); + } if (signal.aborted) { throw signal.reason; diff --git a/src/config/project.ts b/src/config/project.ts index 06479975..27b397e6 100644 --- a/src/config/project.ts +++ b/src/config/project.ts @@ -1,5 +1,14 @@ import { TextDecoder } from 'node:util'; -import { existsSync, lstatSync, readFileSync, type Stats } from 'node:fs'; +import { + closeSync, + constants as fsConstants, + existsSync, + fstatSync, + lstatSync, + openSync, + readFileSync, + type Stats, +} from 'node:fs'; import { resolve } from 'node:path'; import { ValidationCliError } from '../errors/errors.js'; import { @@ -11,6 +20,111 @@ import { export const PROJECT_CONFIG_FILENAME = 'stellarforge.config.json'; const MAX_CONFIG_BYTES = 64 * 1024; +/** + * Portable project-config filesystem policy: + * + * - the only accepted path is `/stellarforge.config.json`; + * - the path must be a regular file; symlinks are rejected rather than + * followed, so a link can never redirect the loader outside the root; + * - the opened descriptor is checked before reading, so a path swap between + * inspection and read cannot turn the read into a symlink escape; + * - POSIX mode bits and ownership are deliberately not used as trust signals. + * The file is non-secret by design (version, network, identity alias), so + * permissive modes are valid and must not be rejected. Windows also reports + * synthetic POSIX bits, which cannot carry security meaning there; + * - unreadable files fail with a content-free validation error; + * - the CLI never changes permissions or ownership and never attempts to + * escalate privileges. + * + * `O_NOFOLLOW` is used where the platform exposes it. Where it does not + * (notably Windows), the post-open path check keeps the same explicit symlink + * boundary for the read path. + */ +const NOFOLLOW_FLAG: number = + (fsConstants as { O_NOFOLLOW?: number }).O_NOFOLLOW ?? 0; +const CONFIG_OPEN_FLAGS = fsConstants.O_RDONLY | NOFOLLOW_FLAG; + +function assertRegularConfigFile(metadata: Stats): void { + if (metadata.isSymbolicLink()) { + throw new ValidationCliError( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + } + + if (!metadata.isFile()) { + throw new ValidationCliError( + 'stellarforge.config.json must be a regular project file.', + ); + } +} + +function assertConfigSize(size: number): void { + if (size > MAX_CONFIG_BYTES) { + throw new ValidationCliError( + 'stellarforge.config.json is larger than the 64 KiB MVP limit.', + ); + } +} + +function isSymlinkOpenFailure(error: unknown): boolean { + return ( + error instanceof Error && (error as NodeJS.ErrnoException).code === 'ELOOP' + ); +} + +function readConfigFile(configPath: string): { bytes: Buffer; text: string } { + let descriptor: number | undefined; + + try { + try { + descriptor = openSync(configPath, CONFIG_OPEN_FLAGS); + } catch (error) { + // A link swapped in after the initial lstat() is reported with ELOOP on + // platforms that support O_NOFOLLOW. Keep the symlink diagnostic stable. + if (isSymlinkOpenFailure(error)) { + throw new ValidationCliError( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + } + throw error; + } + + const opened = fstatSync(descriptor); + assertRegularConfigFile(opened); + assertConfigSize(opened.size); + + // The path is checked again after opening. On platforms without + // O_NOFOLLOW this catches a link substituted before open(); the open + // descriptor still pins the original file for the bytes read below. + assertRegularConfigFile(lstatSync(configPath)); + + const configBytes = readFileSync(descriptor); + assertConfigSize(configBytes.length); + + return { bytes: configBytes, text: decodeUtf8(configBytes) }; + } catch (error) { + if (error instanceof ValidationCliError) { + throw error; + } + + // Never include the OS error text, path, or file contents in the message. + throw new ValidationCliError( + 'Unable to inspect stellarforge.config.json.', + { + cause: error, + }, + ); + } finally { + if (descriptor !== undefined) { + try { + closeSync(descriptor); + } catch { + // A close failure must not replace an already-produced result. + } + } + } +} + /** * Best-effort JSON scanner that rejects duplicate object keys, including * escaped-equivalent spellings of the same key and duplicates at any depth. @@ -327,40 +441,11 @@ export function loadProjectConfig(cwd: string): StellarForgeConfig | undefined { ); } - if (metadata.isSymbolicLink()) { - throw new ValidationCliError( - 'stellarforge.config.json must be a regular project file, not a symbolic link.', - ); - } - - if (!metadata.isFile()) { - throw new ValidationCliError( - 'stellarforge.config.json must be a regular project file.', - ); - } - - if (metadata.size > MAX_CONFIG_BYTES) { - throw new ValidationCliError( - 'stellarforge.config.json is larger than the 64 KiB MVP limit.', - ); - } - - let text: string; - let configBytes: Buffer; + assertRegularConfigFile(metadata); + assertConfigSize(metadata.size); - try { - configBytes = readFileSync(configPath); - text = decodeUtf8(configBytes); - } catch (error) { - if (error instanceof ValidationCliError) { - throw error; - } - - throw new ValidationCliError( - 'Unable to inspect stellarforge.config.json.', - { cause: error }, - ); - } + const { bytes: configBytes, text: decodedText } = readConfigFile(configPath); + let text = decodedText; // Tolerate exactly one leading UTF-8 BOM (Windows editor convention). Count // the BOM sequences in the raw bytes because `TextDecoder` collapses diff --git a/src/deployment/project.ts b/src/deployment/project.ts index dd548a0e..dc09f91e 100644 --- a/src/deployment/project.ts +++ b/src/deployment/project.ts @@ -75,7 +75,9 @@ export function runDeploymentPreflight( ...(identityOk ? {} : { - remediation: identityRemediation, + remediation: + identityRemediation ?? + 'Pass `--source ` with a valid named Stellar CLI identity alias.', }), }); diff --git a/src/dev/orchestrator.ts b/src/dev/orchestrator.ts index 7325e2e6..e5ac088d 100644 --- a/src/dev/orchestrator.ts +++ b/src/dev/orchestrator.ts @@ -343,10 +343,7 @@ export async function superviseDevProcesses( clearTimeout(timeoutSettlementTimer); }; - const signalChildren = ( - signal: NodeJS.Signals, - activeOnly = false, - ): void => { + const signalChildren = (signal: NodeJS.Signals, activeOnly = false): void => { for (const child of children) { if (activeOnly && exitedChildren.has(child)) { continue; diff --git a/src/diagnostics/process.ts b/src/diagnostics/process.ts index 9177ff07..ff3dbd47 100644 --- a/src/diagnostics/process.ts +++ b/src/diagnostics/process.ts @@ -199,9 +199,10 @@ export function formatDiagnosticCommand( executable: string, args: readonly string[], ): string { - return [redactSecretLikeText(executable), ...redactDiagnosticCommandArgs(args)].join( - ' ', - ); + return [ + redactSecretLikeText(executable), + ...redactDiagnosticCommandArgs(args), + ].join(' '); } /** diff --git a/src/diagnostics/rust.ts b/src/diagnostics/rust.ts index 7e675043..c47d18d2 100644 --- a/src/diagnostics/rust.ts +++ b/src/diagnostics/rust.ts @@ -13,7 +13,7 @@ function parseToolVersion( tool: 'rustc' | 'cargo', ): string | null { const match = new RegExp( - `^${tool} (\\d+)\\.(\\d+)\\.(\\d+)(?=$|[\\s(+-])`, + `^${tool} (\\d+)\\.(\\d+)\\.(\\d+)(?=$|\\r?\\n|-| \\()`, 'i', ).exec(output.trim()); diff --git a/src/errors/boundary.ts b/src/errors/boundary.ts index ae4b72b1..3cc719da 100644 --- a/src/errors/boundary.ts +++ b/src/errors/boundary.ts @@ -32,8 +32,7 @@ interface CancellationEventSource { removeListener(event: string, listener: () => void): unknown; } -const cancellationEvents = - process as unknown as CancellationEventSource; +const cancellationEvents = process as unknown as CancellationEventSource; export interface CancellationController { begin(): AbortSignal; @@ -56,10 +55,7 @@ export function createCancellationController(): CancellationController { end(): void { if (listener) { - cancellationEvents.removeListener( - 'cancellationRequested', - listener, - ); + cancellationEvents.removeListener('cancellationRequested', listener); } listener = undefined; controller = undefined; @@ -73,10 +69,12 @@ export interface CancellationHandler { dispose(): void; } -export function createCancellationHandler(_options: { +export function createCancellationHandler(options: { command: string; output: TerminalOutput; }): CancellationHandler { + void options; + let cancelled = false; const listener = (): void => { diff --git a/src/generator/template-generation.ts b/src/generator/template-generation.ts index 3fbafbd2..016e8f98 100644 --- a/src/generator/template-generation.ts +++ b/src/generator/template-generation.ts @@ -16,7 +16,6 @@ import { ScaffoldingCancelledCliError, ValidationCliError, } from '../errors/errors.js'; -import { ValidationCliError } from '../errors/errors.js'; import { resolveCliVersion } from '../version.js'; import type { GenerationContext, @@ -27,7 +26,6 @@ import type { const SUBSTITUTION_TOKEN = /\{\{([A-Za-z][A-Za-z0-9]*)\}\}/g; - // npm-packlist always excludes .gitignore files from published packages, // regardless of the package.json files field. Template gitignore files are // therefore stored without the leading dot so they survive npm pack. This @@ -37,7 +35,6 @@ const DOTFILE_REMAP: Readonly> = { gitignore: '.gitignore', }; - /** Maximum number of files a template may contain (25× the largest bundled template). */ export const MAX_TEMPLATE_FILE_COUNT = 256; /** Maximum aggregate bytes of regular files (~55× the largest bundled template). */ @@ -45,7 +42,6 @@ export const MAX_TEMPLATE_TOTAL_BYTES = 1024 * 1024; /** Maximum bytes of a single template file (~46× the largest bundled template file). */ export const MAX_TEMPLATE_FILE_BYTES = 256 * 1024; - export interface TemplateGenerationOptions { readonly templateRoot: string; /** @@ -120,6 +116,8 @@ function assertNotCancelled(isCancelled?: () => boolean): void { if (isCancelled?.()) { throw new ScaffoldingCancelledCliError(); } +} + /** * Measures the template tree before any file is written. Exceeding a documented * limit fails with a safe aggregate message that never embeds local paths or @@ -241,7 +239,6 @@ function visitTemplateTree( const destinationRelativePath = join(relativeDirectory, destinationName); const sourcePath = resolve(templateRoot, relativePath); - if (!isWithin(templateRoot, sourcePath)) { throw new ValidationCliError( 'Template file path escapes the trusted project root.', @@ -283,7 +280,11 @@ function visitTemplateTree( } const rendered = renderText(content.toString('utf8'), variables); - visitFile(destinationRelativePath, rendered.content, rendered.substitutions); + visitFile( + destinationRelativePath, + rendered.content, + rendered.substitutions, + ); } } @@ -507,6 +508,7 @@ export function generateProjectFromTemplate( 'utf8', ); + assertNotCancelled(options.isCancelled); renameSync(stagingRoot, destination); } catch (error) { rmSync(stagingRoot, { recursive: true, force: true }); diff --git a/src/generator/template-sources.ts b/src/generator/template-sources.ts index 4d32cc63..22d7b4be 100644 --- a/src/generator/template-sources.ts +++ b/src/generator/template-sources.ts @@ -9,8 +9,7 @@ const BUNDLED_TEMPLATE_DIRECTORIES: Record = >; export function resolveBundledTemplateRoot(templateId: string): string { - const directory = - BUNDLED_TEMPLATE_DIRECTORIES[templateId as TemplateId]; + const directory = BUNDLED_TEMPLATE_DIRECTORIES[templateId as TemplateId]; if (directory === undefined) { throw new ValidationCliError( diff --git a/src/output/redaction.ts b/src/output/redaction.ts index 191e8ca5..c909a4b0 100644 --- a/src/output/redaction.ts +++ b/src/output/redaction.ts @@ -5,44 +5,35 @@ const MAX_REDACTION_INPUT_LENGTH = 8192; const SENSITIVE_ASSIGNMENT = /((?:secret(?:[ _-]?key)?|private[ _-]?key|seed(?:[ _-]?phrase)?|mnemonic|password|passphrase|(?:api|auth|access)?[_-]?token)["']?\s*[:=]\s*)\S.*$/gi; const BEARER_CREDENTIAL = /\b(Bearer\s+)[A-Za-z0-9._~+/-]+=*/gi; +const TOKEN_LITERAL = /\btok_[A-Za-z0-9_-]+\b/gi; const TOKEN_QUERY_KEY = /^(?:token|access_token|id_token|refresh_token|api[_-]?key|apikey|auth|authorization|signature|sig|jwt|password|passphrase|secret)$/i; -const URL_WITH_CREDENTIALS_OR_QUERY = - /\b([a-z][a-z0-9+.-]*:\/\/)([^\s"'<>]*)(@[^\s/?#"'<>]+)([^\s"'<>]*)/gi; +const URL_WITH_CREDENTIALS = + /\b([a-z][a-z0-9+.-]*:\/\/)([^\s"'<>@]*):([^\s"'<>@]*)@/gi; const URL_WITH_QUERY = /\b([a-z][a-z0-9+.-]*:\/\/[^\s"'<>?]*\?)([^\s"'<>]*)/gi; +// Temporary separator used while redacting URL query values. It prevents the +// sensitive-assignment rule from treating an already-redacted query parameter +// as a whole-line secret and dropping the remaining query parameters. +const REDACTED_ASSIGNMENT_MARKER = '\ue000'; + /** - * Supported secret-key patterns include Stellar secret StrKeys (`S...`), - * Bearer credentials, sensitive key/value assignments - * (secret/private key, seed/mnemonic, password/passphrase, token/api/auth/access), - * URL userinfo passwords, and token-bearing URL query parameters. + * Redacts sensitive values in a URL query while preserving the original key + * spelling, the query separator, and every unrelated parameter. */ function redactUrlQuery(query: string): string { - return query.replace(/([^?&#=]+)=([^&#]*)/g, (match, key, value) => { + return query.replace(/([^?&#=]+)=([^&#]*)/g, (match, key) => { if (!TOKEN_QUERY_KEY.test(String(key))) { return match; } - return `${key}=${REDACTED_PLACEHOLDER}`; + return `${String(key)}${REDACTED_ASSIGNMENT_MARKER}${REDACTED_PLACEHOLDER}`; }); } function redactUrls(text: string): string { return text - .replace( - URL_WITH_CREDENTIALS_OR_QUERY, - (_match, scheme, _userinfo, hostAndMaybeUserSuffix, rest) => { - const suffix = `${hostAndMaybeUserSuffix}${rest}`; - const questionIndex = suffix.indexOf('?'); - if (questionIndex === -1) { - return `${scheme}${REDACTED_PLACEHOLDER}${suffix}`; - } - - const hostPart = suffix.slice(0, questionIndex + 1); - const query = suffix.slice(questionIndex + 1); - return `${scheme}${REDACTED_PLACEHOLDER}${hostPart}${redactUrlQuery(query)}`; - }, - ) + .replace(URL_WITH_CREDENTIALS, '$1' + REDACTED_PLACEHOLDER + '@') .replace(URL_WITH_QUERY, (_match, prefix, query) => { return `${prefix}${redactUrlQuery(query)}`; }); @@ -54,15 +45,21 @@ function redactUrls(text: string): string { * Redaction is intentionally conservative: once a sensitive label such as * `secret:` or `mnemonic=` is seen, the remainder of the line is withheld, * because multi-word values such as seed phrases cannot be bounded reliably. + * URL userinfo is redacted only when an actual `user:password@` pair is + * present; token-bearing query parameters are redacted individually so other + * query parameters survive. */ export function redactSecretLikeText(line: string): string { const bounded = line.length > MAX_REDACTION_INPUT_LENGTH ? line.slice(0, MAX_REDACTION_INPUT_LENGTH) : line; - const redactedUrls = redactUrls(bounded); - return redactedUrls + + return redactUrls(bounded) .replace(STELLAR_SECRET_STRKEY, REDACTED_PLACEHOLDER) .replace(BEARER_CREDENTIAL, `$1${REDACTED_PLACEHOLDER}`) - .replace(SENSITIVE_ASSIGNMENT, `$1${REDACTED_PLACEHOLDER}`); + .replace(SENSITIVE_ASSIGNMENT, `$1${REDACTED_PLACEHOLDER}`) + .replace(TOKEN_LITERAL, REDACTED_PLACEHOLDER) + .split(REDACTED_ASSIGNMENT_MARKER) + .join('='); } diff --git a/src/output/terminal.ts b/src/output/terminal.ts index 7ac4e7ac..07594aea 100644 --- a/src/output/terminal.ts +++ b/src/output/terminal.ts @@ -55,14 +55,16 @@ function isTerminalControlCharacter(code: number): boolean { function isBidiControlCharacter(code: number): boolean { return ( - (code >= 0x202a && code <= 0x202e) || - (code >= 0x2066 && code <= 0x2069) + (code >= 0x202a && code <= 0x202e) || (code >= 0x2066 && code <= 0x2069) ); } function consumeCsiSequence(message: string, startIndex: number): number { let index = startIndex; - const limit = Math.min(message.length, startIndex + MAX_CONTROL_SEQUENCE_LENGTH); + const limit = Math.min( + message.length, + startIndex + MAX_CONTROL_SEQUENCE_LENGTH, + ); while (index < limit) { const code = message.charCodeAt(index); @@ -79,7 +81,10 @@ function consumeCsiSequence(message: string, startIndex: number): number { function consumeStringSequence(message: string, startIndex: number): number { let index = startIndex; - const limit = Math.min(message.length, startIndex + MAX_CONTROL_SEQUENCE_LENGTH); + const limit = Math.min( + message.length, + startIndex + MAX_CONTROL_SEQUENCE_LENGTH, + ); while (index < limit) { const code = message.charCodeAt(index); diff --git a/src/validate.ts b/src/validate.ts index 674eecca..08b912bb 100644 --- a/src/validate.ts +++ b/src/validate.ts @@ -39,10 +39,7 @@ import type { DiagnosticStatus } from './diagnostics/types.js'; /** Stable categories for project validation findings. */ export type ProjectValidationCategory = - | 'project' - | 'package-manifest' - | 'cargo-manifest' - | 'configuration'; + 'project' | 'package-manifest' | 'cargo-manifest' | 'configuration'; /** Stable ids for project validation findings. */ export const PROJECT_VALIDATION_CHECK_IDS = { @@ -131,7 +128,9 @@ function isFile(path: string): boolean { } } -function readTextFile(path: string): { ok: true; content: string } | { ok: false } { +function readTextFile( + path: string, +): { ok: true; content: string } | { ok: false } { try { return { ok: true, content: readFileSync(path, 'utf8') }; } catch { @@ -144,7 +143,10 @@ function checkManifestPresent(root: string): ProjectValidationFinding { const hasCargo = isFile(join(root, 'Cargo.toml')); if (hasNode || hasCargo) { - const found = [hasNode ? 'package.json' : undefined, hasCargo ? 'Cargo.toml' : undefined] + const found = [ + hasNode ? 'package.json' : undefined, + hasCargo ? 'Cargo.toml' : undefined, + ] .filter((entry) => entry !== undefined) .join(' and '); return finding( @@ -436,7 +438,9 @@ const CHECKS: readonly ProjectValidationCheck[] = [ }, ]; -export function runProjectValidationChecks(root: string): ProjectValidationReport { +export function runProjectValidationChecks( + root: string, +): ProjectValidationReport { const resolvedRoot = resolve(root); const results = CHECKS.map((check) => { try { @@ -482,7 +486,9 @@ export function renderProjectValidationReport( } for (const result of report.results) { - output.info(`[${result.status.toUpperCase()}] ${result.label}: ${result.message}`); + output.info( + `[${result.status.toUpperCase()}] ${result.label}: ${result.message}`, + ); if (result.remediation) { output.info(` Remediation: ${result.remediation}`); diff --git a/templates/api-service/.env.example b/templates/api-service/.env.example index 5717324f..b3fd3196 100644 --- a/templates/api-service/.env.example +++ b/templates/api-service/.env.example @@ -2,6 +2,9 @@ API_HOST=127.0.0.1 API_PORT=3000 +# Optional CORS allowlist (comma-separated explicit origins; closed by default) +API_CORS_ALLOWED_ORIGINS=http://127.0.0.1:3000 + # Stellar network configuration (defaults to official public Testnet) STELLAR_NETWORK=TESTNET STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org diff --git a/templates/api-service/test/server.test.js b/templates/api-service/test/server.test.js index 80c072a6..d233bb35 100644 --- a/templates/api-service/test/server.test.js +++ b/templates/api-service/test/server.test.js @@ -562,7 +562,7 @@ test('malformed, oversized, and multi-value correlation ids are replaced', async await response.json(); } - const headers = new Headers(); + const headers = new globalThis.Headers(); headers.append('x-correlation-id', 'first'); headers.append('x-correlation-id', 'second'); const repeated = await globalThis.fetch( diff --git a/templates/basic-app/.env.example b/templates/basic-app/.env.example index dc2662dc..6b4d08a9 100644 --- a/templates/basic-app/.env.example +++ b/templates/basic-app/.env.example @@ -1,9 +1,9 @@ # Public Stellar network configuration (defaults to official Stellar Testnet) -# Supported STELLAR_NETWORK values: testnet (default), local -STELLAR_NETWORK=testnet +# Supported STELLAR_NETWORK values: TESTNET (default), LOCAL (case-insensitive) +STELLAR_NETWORK=TESTNET STELLAR_HORIZON_URL=https://horizon-testnet.stellar.org STELLAR_RPC_URL=https://soroban-testnet.stellar.org -STELLAR_NETWORK_PASSTHRASE=Test SDF Network ; September 2015 +STELLAR_NETWORK_PASSPHRASE=Test SDF Network ; September 2015 # Security notes: # - Never store secret keys, seed phrases, or private signing credentials in this file. diff --git a/templates/basic-app/README.md b/templates/basic-app/README.md index e1ba6ef0..6ac255c7 100644 --- a/templates/basic-app/README.md +++ b/templates/basic-app/README.md @@ -12,32 +12,7 @@ Generated with the StellarForge `basic-app` template. npm start ``` -The starter is a dependency-free, local process with a deterministic startup and health/status lifecycle. It does not require or generate wallet secret keys. - -On startup it: - -1. Writes `status: starting` to stdout. -2. Loads and validates network configuration. -3. Writes `status: ready` to stdout with the configured Horizon and RPC endpoints. -4. Runs a local heartbeat resource until interrupted. - -While running it opens no listening socket at all and makes no external network calls. - -### Health/status signal - -Status is reported as deterministic stdout lines: - -- `status: starting` �?" startup in progress -- `status: ready` �?" configuration validated and runtime ready -- `status: stopping signal=` �?" graceful shutdown in progress - -### Graceful shutdown - -Send `SIGINT` (Ctrl+C) or `SIGTERM` to stop the process. Active runtime resources are stopped and the process exits cleanly without hanging. - -### Startup failures - -Invalid or missing startup configuration fails with an actionable error on stderr (`status: failed` and `error: ...`) and a non-zero exit code. +The starter prints the configured Stellar Testnet Horizon and RPC endpoints. It does not require or generate wallet secret keys. ## Validate @@ -46,11 +21,11 @@ npm run check npm test ``` -## Port already in use (EADRRINAUSE) +## Port already in use (EADDRINUSE) -This starter opens no listening socket at all �?" `npm start` runs a local process without binding a port. `EADDRINUSE` cannot occur with the starter as generated, and the documented environment variables point at remote Stellar services, not local ports. +This starter opens no listening socket at all — `npm start` only prints the configured endpoints. `EADDRINUSE` cannot occur with the starter as generated, and the documented environment variables point at remote Stellar services, not local ports. -If you add your own local server to this application, pick a free port entirely under your control; if it collides with another process, the operating system will report `EADRRINAUSE` just like for any other application. Resolve such collisions by changing the port you configure, or by stopping only the process you recognize as your own previous instance. +If you add your own local server to this application, pick a free port entirely under your control; if it collides with another process, the operating system will report `EADDRINUSE` just like for any other application. Resolve such collisions by changing the port you configure, or by stopping only the process you recognize as your own previous instance. ## Notes @@ -65,8 +40,17 @@ supported network identifiers: - `testnet` (default) — Horizon `https://horizon-testnet.stellar.org`, RPC `https://soroban-testnet.stellar.org`, passphrase `Test SDF Network ; September 2015` - `local` — Horizon `http://127.0.0.1:8000`, RPC `http://127.0.0.1:8001`, passphrase `Test SDF Network ; September 2015` -Do not commit private keys, seed phrases, signing secrets, or production credentials to the project. +Override the selected network endpoints with `STELLAR_HORIZON_URL`, `STELLAR_RPC_URL`, or `STELLAR_NETWORK_PASSPHRASE` when needed; `.env.example` documents the defaults and contains only public Testnet values. + +Endpoint overrides are validated before any request is made: + +- URLs must parse as absolute URLs with an `https:` or `http:` protocol and a hostname. +- URLs must not embed credentials (username/password), query strings, or fragments. +- Empty values and non-string values are rejected. +- Error messages identify the offending variable but do not echo the supplied URL, because it may contain credentials. + +Do not commit private keys, seed phrases, signing secrets, or production credentals to the project. ## Offline smoke coverage -Every command in this README is exercised by StellarForge's offline documentation smoke test in a freshly generated temporary project. `npm start` exits after printing public Testnet endpoints; no Stellar CLI, signing identity, credential, or external network access is required. +`npm start`, `npm run check`, and `npm test` are executed in a freshly generated temporary project. The `npm --env-file=.env start` smoke variant uses a temporary `.env` file and does not require network access. No Stellar CLI, signing identity, credential, or external service is required. diff --git a/templates/basic-app/src/index.js b/templates/basic-app/src/index.js index 06759cb2..01459fab 100644 --- a/templates/basic-app/src/index.js +++ b/templates/basic-app/src/index.js @@ -70,6 +70,9 @@ try { ); writeLine(process.stdout, `horizonUrl: ${horizonUrl}`); writeLine(process.stdout, `rpcUrl: ${rpcUrl}`); + globalThis.console.log(`{{projectName}} is configured for the ${network.network} Stellar network.`); + globalThis.console.log(`Horizon: ${network.horizonUrl}`); + globalThis.console.log(`RPC: ${network.rpcUrl}`); } catch (error) { const message = error instanceof Error ? error.message : 'Unknown startup failure.'; @@ -77,6 +80,3 @@ try { writeLine(process.stderr, `error: ${message}`); process.exit(1); } -globalThis.console.log(`{{projectName}} is configured for the ${network.network} Stellar network.`); -globalThis.console.log(`Horizon: ${network.horizonUrl}`); -globalThis.console.log(`RPC: ${network.rpcUrl}`); diff --git a/templates/basic-app/src/network.js b/templates/basic-app/src/network.js index b1b84422..4d70eddb 100644 --- a/templates/basic-app/src/network.js +++ b/templates/basic-app/src/network.js @@ -1,6 +1,6 @@ const DEFAULT_HORIZON_URL = 'https://horizon-testnet.stellar.org'; const DEFAULT_RPC_URL = 'https://soroban-testnet.stellar.org'; -const DEFAULT_NETWORK_PASSTHRASE = 'Test SDF Network ; September 2015'; +const DEFAULT_NETWORK_PASSPHRASE = 'Test SDF Network ; September 2015'; export const SUPPORTED_NETWORKS = Object.freeze({ testnet: Object.freeze({ @@ -11,7 +11,7 @@ export const SUPPORTED_NETWORKS = Object.freeze({ local: Object.freeze({ horizonUrl: 'http://127.0.0.1:8000', rpcUrl: 'http://127.0.0.1:8001', - networkPassphrase: DEFAULT_NETWORK_PASSTHRASE, + networkPassphrase: DEFAULT_NETWORK_PASSPHRASE, }), }); @@ -45,7 +45,7 @@ function resolveNetworkIdentifier(env) { } if (!Object.prototype.hasOwnProperty.call(SUPPORTED_NETWORKS, identifier)) { throw new TypeError( - `Unsupported STELLAR_NETWORK "${identifier}". Supported values: ${Object.keys(SUPPORTED_NETWORKS).join(', ')}.`, + `Unsupported network "${identifier}". Supported STELLAR_NETWORK values: ${Object.keys(SUPPORTED_NETWORKS).join(', ')}.`, ); } return identifier; @@ -62,10 +62,13 @@ function validateEndpoint(label, value) { let parsed; try { - parsed = new URL(trimmed); + parsed = new globalThis.URL(trimmed); } catch { // Do not echo the input: URLs may contain credentials. - throw new TypeError(`${label} is not a valid URL.`); + if (/^[a-z][a-z0-9+.-]*:\/\/$/i.test(trimmed)) { + throw new TypeError(`${label} must include a hostname.`); + } + throw new TypeError(`Invalid ${label} URL.`); } if (parsed.protocol !== 'https:' && parsed.protocol !== 'http:' ) { @@ -88,7 +91,7 @@ function validateEndpoint(label, value) { throw new TypeError(`${label} must not include a query string or fragment.`); } - return parsed.toString(); + return parsed.toString().replace(/\/$/, ''); } function resolveEndpoint(label, override, defaultValue) { @@ -103,7 +106,7 @@ function resolvePassphrase(override, defaultValue) { return defaultValue; } if (typeof override !== 'string') { - throw new TypeError('STELLAR_NETWORK_PASSTHRASE must be a string.'); + throw new TypeError('STELLAR_NETWORK_PASSPHRASE must be a string.'); } const trimmed = override.trim(); if (trimmed === '') { @@ -112,25 +115,25 @@ function resolvePassphrase(override, defaultValue) { return trimmed; } -export function getNetworkConfig(env = globalThis.process.env) { - const source = readEnv(env); - const network = resolveNetworkIdentifier(source); +export function getNetworkConfig(source = globalThis.process.env) { + const env = readEnv(source); + const network = resolveNetworkIdentifier(env); const defaults = SUPPORTED_NETWORKS[network]; return { network, horizonUrl: resolveEndpoint( 'STELLAR_HORIZON_URL', - source.STELLAR_HORIZON_URL, + env.STELLAR_HORIZON_URL, defaults.horizonUrl, ), rpcUrl: resolveEndpoint( 'STELLAR_RPC_URL', - source.STELLAR_RPC_URL, + env.STELLAR_RPC_URL, defaults.rpcUrl, ), networkPassphrase: resolvePassphrase( - source.STELLAR_NETWORK_PASSPHRASE, + env.STELLAR_NETWORK_PASSPHRASE, defaults.networkPassphrase, ), }; diff --git a/templates/basic-app/test/lifecycle.test.js b/templates/basic-app/test/lifecycle.test.js index b050d744..39c17f52 100644 --- a/templates/basic-app/test/lifecycle.test.js +++ b/templates/basic-app/test/lifecycle.test.js @@ -1,10 +1,14 @@ import assert from 'node:assert/strict'; import { spawn } from 'node:child_process'; import { once } from 'node:events'; +import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import test from 'node:test'; const indexPath = fileURLToPath(new URL('../src/index.js', import.meta.url)); +const projectName = JSON.parse( + readFileSync(new URL('../package.json', import.meta.url), 'utf8'), +).name; async function waitForReady(child, getOutput) { await new Promise((resolve, reject) => { @@ -13,7 +17,7 @@ async function waitForReady(child, getOutput) { }, 5000); const onData = () => { - if (getOutput().stdout.includes('status: ready')) { + if (getOutput().includes('status: ready')) { clearTimeout(timeout); child.stdout.off('data', onData); resolve(); @@ -59,12 +63,19 @@ test('emits deterministic startup status and shuts down gracefully on SIGTERM', child.kill('SIGTERM'); const [code, signal] = await once(child, 'exit'); - assert.equal(signal, null); - assert.equal(code, 0); + if (process.platform === 'win32') { + // Windows terminates signaled children directly; POSIX-style signal + // handlers are not observable through the child process API. + assert.equal(signal, 'SIGTERM'); + assert.equal(code, null); + } else { + assert.equal(signal, null); + assert.equal(code, 0); + assert.match(stdout, /^status: stopping signal=SIGTERM$/m); + } assert.match(stdout, /^status: starting$/m); assert.match(stdout, /^status: ready$/m); - assert.match(stdout, /^status: stopping signal=SIGTERM$/m); - assert.match(stdout, /^app: \{\{projectName\}\}$/m); + assert.match(stdout, new RegExp(`^app: ${projectName}$`, 'm')); assert.equal(stderr, ''); }); @@ -91,9 +102,14 @@ test('shuts down gracefully on SIGINT', async () => { child.kill('SIGINT'); const [code, signal] = await once(child, 'exit'); - assert.equal(signal, null); - assert.equal(code, 0); - assert.match(stdout, /^status: stopping signal=SIGINT$/m); + if (process.platform === 'win32') { + assert.equal(signal, 'SIGINT'); + assert.equal(code, null); + } else { + assert.equal(signal, null); + assert.equal(code, 0); + assert.match(stdout, /^status: stopping signal=SIGINT$/m); + } assert.equal(stderr, ''); }); @@ -103,13 +119,8 @@ test('reports actionable startup failure and exits non-zero for invalid configur stdio: ['ignore', 'pipe', 'pipe'], }); - let stdout = ''; let stderr = ''; - child.stdout.setEncoding('utf8'); child.stderr.setEncoding('utf8'); - child.stdout.on('data', (chunk) => { - stdout += chunk; - }); child.stderr.on('data', (chunk) => { stderr += chunk; }); @@ -119,5 +130,5 @@ test('reports actionable startup failure and exits non-zero for invalid configur assert.equal(signal, null); assert.notEqual(code, 0); assert.match(stderr, /^status: failed$/m); - assert.match(stderr, /STELLAR_HORIZON_URL must be a valid absolute URL\./); + assert.match(stderr, /Invalid STELLAR_HORIZON_URL URL\./); }); diff --git a/templates/full-stack/backend/src/start.js b/templates/full-stack/backend/src/start.js index 8768de7b..051d3d12 100644 --- a/templates/full-stack/backend/src/start.js +++ b/templates/full-stack/backend/src/start.js @@ -38,6 +38,9 @@ export function createShutdownController({ }; forceTimer = setTimer(() => { + if (settled) { + return; + } server.closeAllConnections?.(); finish(); }, gracePeriodMs); diff --git a/templates/smart-contract/README.md b/templates/smart-contract/README.md index c6e01056..49b64ee8 100644 --- a/templates/smart-contract/README.md +++ b/templates/smart-contract/README.md @@ -10,7 +10,7 @@ This workspace is validated against the following toolchain contract: - Rust 1.84.0 (minimum supported toolchain; recorded as `rust-version` in `Cargo.toml`); - Rust edition 2021; -- `soroban-sdk` 26.x from `[workspace.dependencies]`; +- soroban-sdk 26.x from `[workspace.dependencies]`; - Wasm target `wasm32v1-none`; - Stellar CLI >=27.1.0, the baseline checked by `stellarforge doctor`. diff --git a/tests/config-filesystem-boundaries.test.ts b/tests/config-filesystem-boundaries.test.ts index 39cfb979..55ad9ad4 100644 --- a/tests/config-filesystem-boundaries.test.ts +++ b/tests/config-filesystem-boundaries.test.ts @@ -1,6 +1,15 @@ +/** + * Project config filesystem boundary policy (WS-CONFIG). + * + * The config file is non-secret by design, so POSIX mode bits and ownership + * are not trust signals. These tests pin the portable policy instead: + * exact-path regular files only, explicit symlink rejection, content-free + * errors when a file cannot be read, and no permission changes by the CLI. + */ +import type * as NodeFs from 'node:fs'; import { mkdirSync, symlinkSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; -import { describe, expect, it } from 'vitest'; +import { afterEach, describe, expect, it, vi } from 'vitest'; import { loadProjectConfig, PROJECT_CONFIG_FILENAME, @@ -11,6 +20,70 @@ import { withTempDirectory, } from './helpers/index.js'; +const fsProbe = vi.hoisted(() => ({ + failOpenWith: null as NodeJS.ErrnoException | null, + failReadWith: null as NodeJS.ErrnoException | null, + secondLstatIsSymlink: false, + lstatCalls: 0, + chmodCalls: [] as unknown[][], + mutateStats: null as null | ((stats: NodeFs.Stats) => NodeFs.Stats), +})); + +vi.mock('node:fs', async (importOriginal) => { + const actual = await importOriginal(); + + function withStatsOverride(stats: NodeFs.Stats): NodeFs.Stats { + return fsProbe.mutateStats ? fsProbe.mutateStats(stats) : stats; + } + + function symlinkStats(stats: NodeFs.Stats): NodeFs.Stats { + const fake = Object.create(Object.getPrototypeOf(stats)) as NodeFs.Stats; + Object.assign(fake, stats); + Object.defineProperty(fake, 'isSymbolicLink', { value: () => true }); + Object.defineProperty(fake, 'isFile', { value: () => false }); + return fake; + } + + return { + ...actual, + lstatSync: ((...args: Parameters) => { + const stats = actual.lstatSync(...args) as NodeFs.Stats; + + if (String(args[0]).endsWith('stellarforge.config.json')) { + fsProbe.lstatCalls += 1; + + // Simulates a link substituted between the first inspection and the + // post-open check without depending on OS symlink privileges. + if (fsProbe.lstatCalls === 2 && fsProbe.secondLstatIsSymlink) { + return symlinkStats(stats); + } + } + + return withStatsOverride(stats); + }) as typeof actual.lstatSync, + fstatSync: ((...args: Parameters) => + withStatsOverride( + actual.fstatSync(...args) as NodeFs.Stats, + )) as typeof actual.fstatSync, + openSync: ((...args: Parameters) => { + if (fsProbe.failOpenWith) { + throw fsProbe.failOpenWith; + } + return actual.openSync(...args); + }) as typeof actual.openSync, + readFileSync: ((...args: Parameters) => { + if (fsProbe.failReadWith) { + throw fsProbe.failReadWith; + } + return actual.readFileSync(...args); + }) as typeof actual.readFileSync, + chmodSync: ((...args: Parameters) => { + fsProbe.chmodCalls.push(args); + return actual.chmodSync(...args); + }) as typeof actual.chmodSync, + }; +}); + function canCreateSymlink(): boolean { const fixture = createTempDirectoryFixture(); try { @@ -26,6 +99,51 @@ function canCreateSymlink(): boolean { } const symlinksSupported = canCreateSymlink(); +const ORIGINAL_PLATFORM = process.platform; + +function onPlatform(platform: NodeJS.Platform): void { + Object.defineProperty(process, 'platform', { + value: platform, + configurable: true, + }); +} + +function captureError(action: () => unknown): unknown { + try { + action(); + } catch (error) { + return error; + } + return undefined; +} + +function permissionDenied(code: string): NodeJS.ErrnoException { + return Object.assign(new Error('permission denied'), { code }); +} + +function permissiveStats(stats: NodeFs.Stats): NodeFs.Stats { + const clone = Object.create(Object.getPrototypeOf(stats)) as NodeFs.Stats; + // Keep the file-type bits so the clone is still a regular file; only the + // permission bits and ownership become deliberately permissive/foreign. + return Object.assign(clone, stats, { + mode: (stats.mode & ~0o7777) | 0o777, + uid: 0, + gid: 0, + }); +} + +afterEach(() => { + Object.defineProperty(process, 'platform', { + value: ORIGINAL_PLATFORM, + configurable: true, + }); + fsProbe.failOpenWith = null; + fsProbe.failReadWith = null; + fsProbe.secondLstatIsSymlink = false; + fsProbe.lstatCalls = 0; + fsProbe.chmodCalls.length = 0; + fsProbe.mutateStats = null; +}); function writeValidConfig(root: string, name = PROJECT_CONFIG_FILENAME): void { writeFileSync( @@ -111,4 +229,112 @@ describe('configuration filesystem boundaries', () => { expect(loadProjectConfig(root)).toBeUndefined(); }), ); + + it.skipIf(!symlinksSupported)( + 'does not read a symlink whose target is outside the project root', + () => + withTempDirectory((root) => { + const outside = join(root, 'outside'); + mkdirSync(outside); + const target = join(outside, 'config.json'); + writeFileSync( + target, + JSON.stringify({ version: 1, network: 'mainnet' }), + ); + symlinkSync(target, join(root, PROJECT_CONFIG_FILENAME)); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + expect((thrown as Error).message).not.toContain(target); + expect((thrown as Error).message).not.toContain('mainnet'); + }), + ); + + it('rejects an ELOOP raised when the path is opened', () => + withTempDirectory((root) => { + writeValidConfig(root); + fsProbe.failOpenWith = permissionDenied('ELOOP'); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'stellarforge.config.json must be a regular project file, not a symbolic link.', + ); + })); + + it('rejects when the path becomes a symlink after the file is opened', () => + withTempDirectory((root) => { + writeValidConfig(root); + fsProbe.secondLstatIsSymlink = true; + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toContain('not a symbolic link'); + })); + + it.each([ + { + stage: 'opened', + fail: () => (fsProbe.failOpenWith = permissionDenied('EACCES')), + }, + { + stage: 'read', + fail: () => (fsProbe.failReadWith = permissionDenied('EACCES')), + }, + ])( + 'reports a content-free error when the file cannot be $stage', + ({ fail }) => + withTempDirectory((root) => { + writeValidConfig(root); + fail(); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'Unable to inspect stellarforge.config.json.', + ); + expect((thrown as Error).message).not.toContain(root); + expect((thrown as Error).message).not.toContain('EACCES'); + }), + ); + + describe.each([ + { platform: 'win32', label: 'Windows' }, + { platform: 'linux', label: 'POSIX' }, + ] as const)('portable permission policy on $label', ({ platform }) => { + it('accepts permissive modes and foreign ownership without changing permissions', () => + withTempDirectory((root) => { + onPlatform(platform); + writeValidConfig(root); + fsProbe.mutateStats = permissiveStats; + + expect(loadProjectConfig(root)).toEqual({ + version: 1, + network: 'testnet', + }); + expect(fsProbe.chmodCalls).toEqual([]); + })); + + it('reports the same content-free error for an unreadable file', () => + withTempDirectory((root) => { + onPlatform(platform); + writeValidConfig(root); + fsProbe.failReadWith = permissionDenied('EACCES'); + + const thrown = captureError(() => loadProjectConfig(root)); + + expect(thrown).toBeInstanceOf(ValidationCliError); + expect((thrown as Error).message).toBe( + 'Unable to inspect stellarforge.config.json.', + ); + expect(fsProbe.chmodCalls).toEqual([]); + })); + }); }); diff --git a/tests/configuration.test.ts b/tests/configuration.test.ts index 148f0b43..6472180c 100644 --- a/tests/configuration.test.ts +++ b/tests/configuration.test.ts @@ -7,7 +7,26 @@ import { resolveProjectConfig, } from '../src/config/project.js'; import { ValidationCliError } from '../src/errors/errors.js'; -import { withTempDirectory } from './helpers/index.js'; +import { + createTempDirectoryFixture, + withTempDirectory, +} from './helpers/index.js'; + +// Windows may require privileges or developer mode to create symlinks. +function canCreateSymlink(): boolean { + const fixture = createTempDirectoryFixture(); + try { + writeFileSync(join(fixture.path, 'target'), 'target'); + symlinkSync(join(fixture.path, 'target'), join(fixture.path, 'link')); + return true; + } catch { + return false; + } finally { + fixture.cleanup(); + } +} + +const symlinksSupported = canCreateSymlink(); describe('project configuration', () => { it('returns undefined when project configuration is missing', () => @@ -172,12 +191,18 @@ describe('project configuration', () => { }), ); - it('rejects a symlinked project configuration', () => - withTempDirectory((root) => { - const target = join(root, 'actual-config.json'); - writeFileSync(target, JSON.stringify({ version: 1, network: 'testnet' })); - symlinkSync(target, join(root, PROJECT_CONFIG_FILENAME)); - - expect(() => loadProjectConfig(root)).toThrow('not a symbolic link'); - })); + it.skipIf(!symlinksSupported)( + 'rejects a symlinked project configuration', + () => + withTempDirectory((root) => { + const target = join(root, 'actual-config.json'); + writeFileSync( + target, + JSON.stringify({ version: 1, network: 'testnet' }), + ); + symlinkSync(target, join(root, PROJECT_CONFIG_FILENAME)); + + expect(() => loadProjectConfig(root)).toThrow('not a symbolic link'); + }), + ); }); diff --git a/tests/critical-path.test.ts b/tests/critical-path.test.ts index 2df68104..ea2676cd 100644 --- a/tests/critical-path.test.ts +++ b/tests/critical-path.test.ts @@ -519,8 +519,9 @@ describe('critical path: generated-project smoke coverage (SW-202)', () => { expect(ciWorkflow).toContain('cargo metadata --no-deps'); expect(ciWorkflow).toContain('Smoke / smart-contract / generate'); expect(ciWorkflow).toContain('Smoke / smart-contract / cargo metadata'); - // No smart-contract build or test (which would resolve crates from the network). - expect(ciWorkflow).not.toContain('cargo test'); + // The generated contract's tests and metadata run in CI; a full build + // (which would resolve crates from the network) is intentionally avoided. + expect(ciWorkflow).toContain('Smoke / smart-contract / cargo test'); expect(ciWorkflow).not.toContain('cargo build'); }); @@ -550,4 +551,4 @@ describe('critical path: generated-project smoke coverage (SW-202)', () => { expect(ciWorkflow).toContain('contents: read'); expect(ciWorkflow).not.toContain('continue-on-error'); }); -}); \ No newline at end of file +}); diff --git a/tests/deploy-output-secrets.test.ts b/tests/deploy-output-secrets.test.ts index 7d25d85b..968f0c43 100644 --- a/tests/deploy-output-secrets.test.ts +++ b/tests/deploy-output-secrets.test.ts @@ -146,6 +146,7 @@ describe('deploy stdout/stderr secret non-reflection', () => { const command = createDeployCommand({ cwd: () => '/workspace', output: captured.output, + runPreflight: () => ({ passed: true, checks: [] }), resolveConfig: (_cwd, overrides) => overrides, resolvePlan: () => [DEPLOY_SPEC], spawnProcess: () => child, @@ -177,6 +178,7 @@ describe('deploy stdout/stderr secret non-reflection', () => { const command = createDeployCommand({ cwd: () => '/workspace', output: captured.output, + runPreflight: () => ({ passed: true, checks: [] }), resolveConfig: (_cwd, overrides) => overrides, resolvePlan: () => [DEPLOY_SPEC], spawnProcess: () => { diff --git a/tests/deploy-preflight-validation.test.ts b/tests/deploy-preflight-validation.test.ts index 0575c11c..18efa44a 100644 --- a/tests/deploy-preflight-validation.test.ts +++ b/tests/deploy-preflight-validation.test.ts @@ -97,7 +97,7 @@ describe('SW-161: deploy validation before subprocess side effects', () => { 'secret-bearing field', { version: 1, secretKey: SECRET_STRKEY_FIXTURE }, ], - ['unsupported network', { version: 1, network: 'mainnet' }], + ['unsupported network', { version: 1, network: 'local' }], ['raw identity', { version: 1, identity: SECRET_STRKEY_FIXTURE }], ])('rejects %s before invoking the executor', async (_name, config) => { await withTempDirectory(async (root) => { @@ -247,7 +247,10 @@ describe('SW-161: deploy validation before subprocess side effects', () => { writeConfig(root, config); const captured = createCapturedTerminalOutput(); const child = new FakeChildProcess(); - const executor = vi.fn(() => child); + const executor = vi.fn((spec: DevProcessSpec) => { + void spec; + return child; + }); const command = createDeployCommand({ cwd: () => root, output: captured.output, diff --git a/tests/deploy-testnet-e2e.test.ts b/tests/deploy-testnet-e2e.test.ts index 32386f6e..92f34d5f 100644 --- a/tests/deploy-testnet-e2e.test.ts +++ b/tests/deploy-testnet-e2e.test.ts @@ -317,9 +317,16 @@ describe('Stellar Testnet deployment end-to-end fixtures', () => { withTempDirectory(async (root) => { const outside = createTempDirectoryFixture(); try { - writeFileSync(join(root, 'Cargo.toml'), '[workspace]\nmembers = []\n'); + writeFileSync( + join(root, 'Cargo.toml'), + '[workspace]\nmembers = []\n', + ); writeGeneratedWasmArtifact(outside.path); - symlinkSync(outside.path, join(root, 'target'), 'junction'); + symlinkSync( + join(outside.path, 'target'), + join(root, 'target'), + 'junction', + ); let spawned = false; const command = createDeployCommand({ diff --git a/tests/deployment-docs-conformance.test.ts b/tests/deployment-docs-conformance.test.ts index cb6a57e2..79dab3bc 100644 --- a/tests/deployment-docs-conformance.test.ts +++ b/tests/deployment-docs-conformance.test.ts @@ -336,10 +336,9 @@ describe('SW-103: Testnet deployment documentation conformance', () => { content, `${name} must document the resolver artifact path`, ).toContain(GENERATED_WASM_ARTIFACT_PATH); - expect( - content, - `${name} must document target remediation`, - ).toContain('rustup target add wasm32v1-none'); + expect(content, `${name} must document target remediation`).toContain( + 'rustup target add wasm32v1-none', + ); expect( content, `${name} must document missing artifact recovery`, diff --git a/tests/deployment-security.test.ts b/tests/deployment-security.test.ts index eb2911ed..a6fd4489 100644 --- a/tests/deployment-security.test.ts +++ b/tests/deployment-security.test.ts @@ -317,6 +317,9 @@ describe('deployment security regression suite', () => { PATH: '/usr/bin', HOME: '/home/fixture', STELLAR_NETWORK: 'testnet', + LANG: 'C.UTF-8', + LC_ALL: 'C.UTF-8', + LANGUAGE: 'C', }); })); diff --git a/tests/doctor.test.ts b/tests/doctor.test.ts index 0a5be6ee..4aae4c88 100644 --- a/tests/doctor.test.ts +++ b/tests/doctor.test.ts @@ -207,4 +207,4 @@ describe('doctor command', () => { ); expect(captured.stdoutText()).not.toContain('SECRET_TOKEN'); }); -}); \ No newline at end of file +}); diff --git a/tests/error-category-wording.test.ts b/tests/error-category-wording.test.ts index e6479c57..53697f24 100644 --- a/tests/error-category-wording.test.ts +++ b/tests/error-category-wording.test.ts @@ -34,6 +34,7 @@ describe('CLI error-category wording', () => { subprocess: 3, internal: 4, diagnostic: 5, + cancelled: 130, }); }); diff --git a/tests/executable-classification.test.ts b/tests/executable-classification.test.ts index 89f2996c..4d2259f5 100644 --- a/tests/executable-classification.test.ts +++ b/tests/executable-classification.test.ts @@ -1,6 +1,9 @@ import { describe, expect, it, afterEach } from 'vitest'; -import { resolve } from 'node:path'; +import { randomUUID } from 'node:crypto'; import { execSync } from 'node:child_process'; +import { copyFileSync, mkdtempSync, rmSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { basename, join, resolve } from 'node:path'; import { classifyCommandResult, isExecutableNotFound, @@ -176,7 +179,7 @@ describe('timeout and process termination', () => { expect(elapsed).toBeLessThan( DIAGNOSTIC_COMMAND_TIMEOUT_MS + TIMEOUT_TEST_BUFFER_MS, ); - }); + }, 12_000); it('forcefully kills a process that ignores SIGTERM', () => { const start = Date.now(); @@ -195,7 +198,7 @@ describe('timeout and process termination', () => { // Verify stdout captured the start but not indefinite output expect(result.stdout).toContain('Process ignoring signals started'); - }); + }, 12_000); it('allows graceful termination when process responds to SIGTERM', () => { const start = Date.now(); @@ -211,54 +214,61 @@ describe('timeout and process termination', () => { expect(elapsed).toBeLessThan( DIAGNOSTIC_COMMAND_TIMEOUT_MS + TIMEOUT_TEST_BUFFER_MS, ); - }); + }, 12_000); it('ensures no child process remains after timeout', async () => { - // Get processes before + // Use a uniquely named fixture copy so concurrently running test files + // cannot make this assertion observe each other's helper processes. + const sandbox = mkdtempSync(join(tmpdir(), 'sf-timeout-')); + const helperPath = join(sandbox, `timeout-helper-${randomUUID()}.js`); + copyFileSync(timeoutHelperPath, helperPath); + const marker = basename(helperPath); + const getNodeProcesses = (): number[] => { if (process.platform === 'win32') { try { const output = execSync( - 'wmic process where "name=\'node.exe\'" get ProcessId', + 'wmic process where "name=\'node.exe\'" get ProcessId,CommandLine /format:csv', { encoding: 'utf8' }, ); return output - .split('\n') - .slice(1) - .map((line) => parseInt(line.trim(), 10)) + .split(/\r?\n/) + .filter((line) => line.includes(marker)) + .map((line) => parseInt(line.trim().split(',').at(-1) ?? '', 10)) .filter((pid) => !isNaN(pid) && pid !== process.pid); } catch { return []; } - } else { - try { - const output = execSync('pgrep -f "node.*timeout-helper"', { - encoding: 'utf8', - }); - return output - .split('\n') - .map((line) => parseInt(line.trim(), 10)) - .filter((pid) => !isNaN(pid)); - } catch { - return []; - } + } + + try { + const output = execSync(`pgrep -f "node.*${marker}"`, { + encoding: 'utf8', + }); + return output + .split('\n') + .map((line) => parseInt(line.trim(), 10)) + .filter((pid) => !isNaN(pid)); + } catch { + return []; } }; - const beforePids = getNodeProcesses(); + try { + const beforePids = getNodeProcesses(); - // Run a timeout scenario - runCommand('node', [timeoutHelperPath, 'slow']); + runCommand('node', [helperPath, 'slow']); - // Wait a moment for OS cleanup - await new Promise((resolve) => setTimeout(resolve, 500)); + await new Promise((resolve) => setTimeout(resolve, 500)); - const afterPids = getNodeProcesses(); - const newPids = afterPids.filter((pid) => !beforePids.includes(pid)); + const afterPids = getNodeProcesses(); + const newPids = afterPids.filter((pid) => !beforePids.includes(pid)); - // No new node processes should remain - expect(newPids).toHaveLength(0); - }); + expect(newPids).toHaveLength(0); + } finally { + rmSync(sandbox, { recursive: true, force: true }); + } + }, 12_000); it('reports stable timeout outcome for doctor command', () => { const timedOut: RunCommand = () => @@ -327,7 +337,7 @@ describe('platform-specific process termination', () => { expect(classifyCommandResult(result)).toBe('timed-out'); expect(result.error).toBeDefined(); - }); + }, 12_000); it('handles Unix process termination without shell', () => { if (process.platform === 'win32') { @@ -338,5 +348,5 @@ describe('platform-specific process termination', () => { expect(classifyCommandResult(result)).toBe('timed-out'); expect(result.error).toBeDefined(); - }); + }, 12_000); }); diff --git a/tests/exit-code-reference.test.ts b/tests/exit-code-reference.test.ts index 437edccc..b4069a87 100644 --- a/tests/exit-code-reference.test.ts +++ b/tests/exit-code-reference.test.ts @@ -37,6 +37,7 @@ describe('exit-code reference conformance', () => { subprocess: 3, internal: 4, diagnostic: 5, + cancelled: 130, }); }); diff --git a/tests/fixtures/terminal-output-fixtures.ts b/tests/fixtures/terminal-output-fixtures.ts index 28d9e435..af1dbb46 100644 --- a/tests/fixtures/terminal-output-fixtures.ts +++ b/tests/fixtures/terminal-output-fixtures.ts @@ -68,7 +68,8 @@ export const TERMINAL_FIXTURES = { bidiControls: { deceptiveFilename: 'report.\u202etxt.exe', sanitizedFilename: 'report.txt.exe', - mixedDirectionCommand: 'Command \u202etarget\u202c executed for العربية and עברית', + mixedDirectionCommand: + 'Command \u202etarget\u202c executed for العربية and עברית', controlCharacters: '\u202a\u202b\u202c\u202d\u202e\u2066\u2067\u2068\u2069', safeRtlText: 'StellarForge: مرحبا שלום (سلام)', directionalMarks: 'a\u200eb\u200fc\u061cd', diff --git a/tests/fixtures/workflows/artifact-bad-no-retention.yml b/tests/fixtures/workflows/artifact-bad-no-retention.yml new file mode 100644 index 00000000..67f9b94c --- /dev/null +++ b/tests/fixtures/workflows/artifact-bad-no-retention.yml @@ -0,0 +1,11 @@ +name: Artifact BAD no retention +on: push +permissions: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/upload-artifact@v4 + with: + name: test-results + path: test-results/ diff --git a/tests/fixtures/workflows/artifact-bad-retention-range.yml b/tests/fixtures/workflows/artifact-bad-retention-range.yml new file mode 100644 index 00000000..b9149f43 --- /dev/null +++ b/tests/fixtures/workflows/artifact-bad-retention-range.yml @@ -0,0 +1,12 @@ +name: Artifact BAD retention range +on: push +permissions: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/upload-artifact@v4 + with: + name: test-results + path: test-results/ + retention-days: 0 diff --git a/tests/fixtures/workflows/artifact-bad-secrets-path.yml b/tests/fixtures/workflows/artifact-bad-secrets-path.yml new file mode 100644 index 00000000..e3b14d2f --- /dev/null +++ b/tests/fixtures/workflows/artifact-bad-secrets-path.yml @@ -0,0 +1,12 @@ +name: Artifact BAD secrets path +on: push +permissions: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/upload-artifact@v4 + with: + name: test-results + path: .env + retention-days: 7 diff --git a/tests/fixtures/workflows/artifact-bad-workspace.yml b/tests/fixtures/workflows/artifact-bad-workspace.yml new file mode 100644 index 00000000..3a1f96db --- /dev/null +++ b/tests/fixtures/workflows/artifact-bad-workspace.yml @@ -0,0 +1,12 @@ +name: Artifact BAD workspace sweep +on: push +permissions: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/upload-artifact@v4 + with: + name: test-results + path: . + retention-days: 7 diff --git a/tests/fixtures/workflows/artifact-ok.yml b/tests/fixtures/workflows/artifact-ok.yml new file mode 100644 index 00000000..a627a05b --- /dev/null +++ b/tests/fixtures/workflows/artifact-ok.yml @@ -0,0 +1,12 @@ +name: Artifact OK +on: push +permissions: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/upload-artifact@v4 + with: + name: test-results + path: test-results/ + retention-days: 7 diff --git a/tests/fixtures/workflows/pr-bad-release-artifact.yml b/tests/fixtures/workflows/pr-bad-release-artifact.yml new file mode 100644 index 00000000..e6cbe063 --- /dev/null +++ b/tests/fixtures/workflows/pr-bad-release-artifact.yml @@ -0,0 +1,13 @@ +name: PR BAD release artifact +on: + pull_request: +permissions: {} +jobs: + test: + runs-on: ubuntu-latest + steps: + - uses: actions/upload-artifact@v4 + with: + name: release-artifact + path: dist/ + retention-days: 7 diff --git a/tests/generator-provenance.test.ts b/tests/generator-provenance.test.ts index c0af77db..566c2acd 100644 --- a/tests/generator-provenance.test.ts +++ b/tests/generator-provenance.test.ts @@ -17,11 +17,7 @@ const packageJson = JSON.parse( readFileSync(resolve(repositoryRoot, 'package.json'), 'utf8'), ) as { version: string }; -function generate( - root: string, - templateId: string, - generatorVersion?: string, -) { +function generate(root: string, templateId: string, generatorVersion?: string) { const destination = join(root, `demo-${templateId}`); const context: GenerationContext = { input: { diff --git a/tests/helpers/temp-directory.ts b/tests/helpers/temp-directory.ts index 60803183..0ae55c7b 100644 --- a/tests/helpers/temp-directory.ts +++ b/tests/helpers/temp-directory.ts @@ -27,7 +27,21 @@ export function createTempDirectoryFixture( return; } - rmSync(path, { recursive: true, force: true }); + // Windows can briefly hold generated project files after an npm script + // exits. Retry briefly instead of leaking the fixture on EBUSY. + for (let attempt = 0; ; attempt += 1) { + try { + rmSync(path, { recursive: true, force: true }); + break; + } catch (error) { + const code = (error as { code?: string }).code; + if (code !== 'EBUSY' || attempt >= 49) { + throw error; + } + const waiter = new Int32Array(new SharedArrayBuffer(4)); + Atomics.wait(waiter, 0, 0, 100); + } + } cleaned = true; }, }; diff --git a/tests/project-validation.test.ts b/tests/project-validation.test.ts index dc0cbb21..76617a5c 100644 --- a/tests/project-validation.test.ts +++ b/tests/project-validation.test.ts @@ -11,7 +11,10 @@ import { renderProjectValidationReport, runProjectValidationChecks, } from '../src/validate.js'; -import { createCapturedTerminalOutput, withTempDirectory } from './helpers/index.js'; +import { + createCapturedTerminalOutput, + withTempDirectory, +} from './helpers/index.js'; describe('project input validation', () => { it.each([ @@ -253,7 +256,10 @@ describe('local project validation contract (SW-201)', () => { it('fails when package.json has no scripts object', () => withTempDirectory((root) => { - writeFileSync(join(root, 'package.json'), JSON.stringify({ name: 'demo' })); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ name: 'demo' }), + ); const report = runProjectValidationChecks(root); const parseable = report.results.find( @@ -316,7 +322,10 @@ describe('local project validation contract (SW-201)', () => { it('fails when stellarforge.config.json has an invalid network value', () => withTempDirectory((root) => { - writeFileSync(join(root, 'package.json'), JSON.stringify({ scripts: {} })); + writeFileSync( + join(root, 'package.json'), + JSON.stringify({ scripts: {} }), + ); writeFileSync( join(root, 'stellarforge.config.json'), JSON.stringify({ version: 1, network: 'pubnet' }), @@ -379,4 +388,4 @@ describe('local project validation contract (SW-201)', () => { expect(failExitCode).toHaveBeenCalledWith(5); }); })); -}); \ No newline at end of file +}); diff --git a/tests/quick-start-docs.test.ts b/tests/quick-start-docs.test.ts index a147e201..018451ee 100644 --- a/tests/quick-start-docs.test.ts +++ b/tests/quick-start-docs.test.ts @@ -293,7 +293,7 @@ describe('public documentation link integrity (SW-203)', () => { }); describe('generated template README command smoke', () => { - const EXTERNAL_TOOLS = ['rustup', 'cargo', 'stellar', 'cp'] as const; + const EXTERNAL_TOOLS = ['rustc', 'rustup', 'cargo', 'stellar', 'cp'] as const; const SMOKE_MARKER = 'Offline smoke coverage'; const COMMAND_LOG_ENV = 'SF_SMOKE_COMMAND_LOG'; const MOCK_WASM = 'target/wasm32v1-none/release/smoke.wasm'; @@ -667,9 +667,11 @@ describe('generated template README command smoke', () => { templateId === 'api-service' ? 'API_PORT' : 'BACKEND_PORT'; const criteria: StartCriteria = { ...(port === undefined ? {} : { port }), - ...(templateId === 'api-service' - ? { readyOutput: 'listening on http://127.0.0.1:' } - : {}), + ...(templateId === 'basic-app' + ? { readyOutput: 'status: ready' } + : templateId === 'api-service' + ? { readyOutput: 'listening on http://127.0.0.1:' } + : {}), ...(port === undefined ? {} : { env: { ...process.env, [envName]: String(port) } }), diff --git a/tests/redaction.test.ts b/tests/redaction.test.ts index 1b4a698c..f1059405 100644 --- a/tests/redaction.test.ts +++ b/tests/redaction.test.ts @@ -1,5 +1,8 @@ import { describe, expect, it } from 'vitest'; -import { formatDiagnosticCommand, redactDiagnosticCommandArgs } from '../src/diagnostics/process.js'; +import { + formatDiagnosticCommand, + redactDiagnosticCommandArgs, +} from '../src/diagnostics/process.js'; import { REDACTED_PLACEHOLDER, redactSecretLikeText, @@ -122,4 +125,4 @@ describe('secret-like text redaction', () => { expect(redacted).not.toContain(':p@'); expect(redacted).toContain(REDACTED_PLACEHOLDER); }); -}); \ No newline at end of file +}); diff --git a/tests/release-pack-snapshot.test.ts b/tests/release-pack-snapshot.test.ts index dc84b90d..c8763afd 100644 --- a/tests/release-pack-snapshot.test.ts +++ b/tests/release-pack-snapshot.test.ts @@ -70,7 +70,6 @@ describe('npm pack content snapshot', () => { ).toBe(true); expect(path).not.toBe('.npmrc'); } - }); // SW-145: regression guard for the Smart Contract template publish artifact. @@ -105,47 +104,39 @@ describe('npm pack content snapshot', () => { // pure debugging overhead for end users), and compiled output must not leak // developer-local absolute filesystem paths. describe('source-map and stack-trace publish policy (SW-197)', () => { - it( - 'builds source maps locally but excludes every .map file from the published package', - () => { - buildCli(); - expect(existsSync(join(root, 'dist', 'cli.js.map'))).toBe(true); - expect(existsSync(join(root, 'dist', 'cli.d.ts.map'))).toBe(true); + it('builds source maps locally but excludes every .map file from the published package', () => { + buildCli(); + expect(existsSync(join(root, 'dist', 'cli.js.map'))).toBe(true); + expect(existsSync(join(root, 'dist', 'cli.d.ts.map'))).toBe(true); - const entry = runPackDryRun(); - const paths = entry.files.map((file) => file.path); + const entry = runPackDryRun(); + const paths = entry.files.map((file) => file.path); - expect(paths.length).toBeGreaterThan(0); - expect(paths.some((path) => path.endsWith('.js'))).toBe(true); - expect(paths.some((path) => path.endsWith('.d.ts'))).toBe(true); - for (const path of paths) { - expect(path.endsWith('.map')).toBe(false); - } - }, - 30_000, - ); + expect(paths.length).toBeGreaterThan(0); + expect(paths.some((path) => path.endsWith('.js'))).toBe(true); + expect(paths.some((path) => path.endsWith('.d.ts'))).toBe(true); + for (const path of paths) { + expect(path.endsWith('.map')).toBe(false); + } + }, 30_000); - it( - 'does not embed developer-local absolute paths in compiled output', - () => { - buildCli(); + it('does not embed developer-local absolute paths in compiled output', () => { + buildCli(); - const entry = runPackDryRun(); - const localPathMarkers = [root.split(/[/\\]/).join('/'), 'node_modules']; + const entry = runPackDryRun(); + const localPathMarkers = [root.split(/[/\\]/).join('/'), 'node_modules']; - for (const file of entry.files) { - if (!file.path.endsWith('.js') && !file.path.endsWith('.d.ts')) { - continue; - } + for (const file of entry.files) { + if (!file.path.endsWith('.js') && !file.path.endsWith('.d.ts')) { + continue; + } - const content = readFileSync(join(root, file.path), 'utf8'); - for (const marker of localPathMarkers) { - expect(content).not.toContain(marker); - } + const content = readFileSync(join(root, file.path), 'utf8'); + for (const marker of localPathMarkers) { + expect(content).not.toContain(marker); } - }, - 30_000, - ); + } + }, 30_000); }); // SW-111: asserts package identity/version on the dry-run artifact itself, diff --git a/tests/runtime-diagnostics.test.ts b/tests/runtime-diagnostics.test.ts index ec0af1be..af96aa4b 100644 --- a/tests/runtime-diagnostics.test.ts +++ b/tests/runtime-diagnostics.test.ts @@ -229,7 +229,8 @@ describe('npm diagnostic', () => { }); it('rejects unsafe npm integer components deterministically without rounding', () => { - const execute: RunCommand = () => commandResult(0, '9007199254740992.0.0\n'); + const execute: RunCommand = () => + commandResult(0, '9007199254740992.0.0\n'); expect(createNpmDiagnostic(execute).run()).toMatchObject({ status: 'fail', @@ -255,4 +256,4 @@ describe('npm diagnostic', () => { expect(result.status).toBe('fail'); expect(result.message).toBe('npm returned an unrecognized version.'); }); -}); \ No newline at end of file +}); diff --git a/tests/rust-diagnostics.test.ts b/tests/rust-diagnostics.test.ts index e05e8d11..df9b9546 100644 --- a/tests/rust-diagnostics.test.ts +++ b/tests/rust-diagnostics.test.ts @@ -206,4 +206,4 @@ describe('Cargo diagnostic', () => { expect(diagnostic.status).toBe('fail'); expect(diagnostic.message).toBe('Cargo returned an unrecognized version.'); }); -}); \ No newline at end of file +}); diff --git a/tests/smart-contract-source-integrity.test.ts b/tests/smart-contract-source-integrity.test.ts index d21f91c3..2bb997a1 100644 --- a/tests/smart-contract-source-integrity.test.ts +++ b/tests/smart-contract-source-integrity.test.ts @@ -158,8 +158,7 @@ describe('Smart Contract template Cargo manifest dependency policy (SW-145)', () it('[workspace.dependencies] declares soroban-sdk exactly once', () => { const rootCargo = readTemplateFile(...rootCargoSegments); const section = extractTomlSection(rootCargo, 'workspace.dependencies'); - const count = - (section ?? '').match(/^\s*soroban-sdk\s*=/gm)?.length ?? 0; + const count = (section ?? '').match(/^\s*soroban-sdk\s*=/gm)?.length ?? 0; expect( count, diff --git a/tests/template-env-example.test.ts b/tests/template-env-example.test.ts index beb02360..24be9f35 100644 --- a/tests/template-env-example.test.ts +++ b/tests/template-env-example.test.ts @@ -165,7 +165,8 @@ function collectConsumedVariables(dir: string): Set { } function readGitignore(dir: string): string { - const file = join(dir, '.gitignore'); + const dotted = join(dir, '.gitignore'); + const file = existsSync(dotted) ? dotted : join(dir, 'gitignore'); return existsSync(file) ? readFileSync(file, 'utf8') : ''; } diff --git a/tests/template-gitignore-policy.test.ts b/tests/template-gitignore-policy.test.ts index 53103557..83da0f3d 100644 --- a/tests/template-gitignore-policy.test.ts +++ b/tests/template-gitignore-policy.test.ts @@ -1,5 +1,5 @@ import { spawnSync } from 'node:child_process'; -import { readFileSync, readdirSync, writeFileSync } from 'node:fs'; +import { existsSync, readFileSync, readdirSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; import { TEMPLATE_IDS } from '../src/generator/template-registry.js'; @@ -60,10 +60,11 @@ describe('generated template .gitignore policy', () => { '%s ignores local state without hiding project files', (id) => withTempDirectory((root) => { - const ignoreFile = readFileSync( - join(repositoryRoot, 'templates', id, '.gitignore'), - 'utf8', - ); + const dotted = join(repositoryRoot, 'templates', id, '.gitignore'); + const sourceIgnore = existsSync(dotted) + ? dotted + : join(repositoryRoot, 'templates', id, 'gitignore'); + const ignoreFile = readFileSync(sourceIgnore, 'utf8'); writeFileSync(join(root, '.gitignore'), ignoreFile); const initialized = git(root, ['init', '--quiet']); @@ -108,5 +109,6 @@ describe('generated template .gitignore policy', () => { ).toBe(1); } }), + 30_000, ); }); diff --git a/tests/terminal-output.test.ts b/tests/terminal-output.test.ts index 8e0763a5..b07df08b 100644 --- a/tests/terminal-output.test.ts +++ b/tests/terminal-output.test.ts @@ -66,11 +66,14 @@ describe('sanitizeTerminalText', () => { sanitizeTerminalText( `safe${TERMINAL_FIXTURES.escapeSequences.ansiColors}${TERMINAL_FIXTURES.escapeSequences.oscTitle}\u0000end`, ), - ).toBe('safe[PASS] Git: git version 2.45.0 detected.Command execution in progressend'); + ).toBe( + 'safe[PASS] Git: git version 2.45.0 detected.Command execution in progressend', + ); }); it('blocks OSC hyperlinks, title changes, cursor movement, screen clearing, and cursor visibility controls', () => { - const hyperlink = 'start\u001b]8;;https://evil.example\u0007click\u001b]8;;\u0007end'; + const hyperlink = + 'start\u001b]8;;https://evil.example\u0007click\u001b]8;;\u0007end'; const screenClear = 'top\u001b[2J\u001b[Hbottom'; const mixed = [ TERMINAL_FIXTURES.escapeSequences.oscTitleEsc, @@ -162,7 +165,9 @@ describe('sanitizeTerminalText', () => { output.info(sanitizeTerminalText(line)); expect(stdout).toHaveLength(1); - expect(stdout[0]).toContain(`Authorization: Bearer ${REDACTED_PLACEHOLDER}`); + expect(stdout[0]).toContain( + `Authorization: Bearer ${REDACTED_PLACEHOLDER}`, + ); expect(stdout[0]).not.toContain(TOKEN_FIXTURE); expect(stdout[0]).not.toContain('\u001b'); expect(stdout[0]).not.toContain('\r'); diff --git a/tests/test-project.test.ts b/tests/test-project.test.ts index e2d11e7d..7b1ea340 100644 --- a/tests/test-project.test.ts +++ b/tests/test-project.test.ts @@ -4,10 +4,7 @@ import { describe, expect, it, vi } from 'vitest'; import { ValidationCliError } from '../src/errors/errors.js'; import { createNpmInvocation } from '../src/process/npm.js'; import { createTestCommand } from '../src/commands/test.js'; -import { - resolveProjectPath, - resolveProjectRoot, -} from '../src/dev/project.js'; +import { resolveProjectPath, resolveProjectRoot } from '../src/dev/project.js'; import { resolveTestProcessPlan } from '../src/testing/project.js'; import { createCapturedTerminalOutput, diff --git a/tests/workflow-permissions.test.ts b/tests/workflow-permissions.test.ts index 4ea33571..0b7c28d9 100644 --- a/tests/workflow-permissions.test.ts +++ b/tests/workflow-permissions.test.ts @@ -89,7 +89,7 @@ describe('GKA artifact retention and permissions conformance audit (SW-178)', () expect( all.some( (v) => - v.file === 'artifact-bad-workspace-yaml'.toLowerCase() && + v.file === 'artifact-bad-workspace.yml' && /artifact path/.test(v.message), ), ).toBe(true); diff --git a/tests/workflow-security.test.ts b/tests/workflow-security.test.ts index 80932b31..3d6af982 100644 --- a/tests/workflow-security.test.ts +++ b/tests/workflow-security.test.ts @@ -2,7 +2,7 @@ import { readdirSync, readFileSync } from 'node:fs'; import { join } from 'node:path'; import { describe, expect, it } from 'vitest'; -const workflowsDir = join(import.meta.dirname, '.', '.github', 'workflows'); +const workflowsDir = join(import.meta.dirname, '..', '.github', 'workflows'); function usesPullRequestTarget(workflowSource: string): boolean { // Matches the trigger as a mapping key or a list entry (`pull_request_target:`