@pbuilder/sdk 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,13 +6,13 @@ export { isSniffableText } from "./classify-transport.ts";
6
6
  * Reads a package-local file (relative to the active run's `packageDir`) and returns its
7
7
  * content as the string to use for a `create({ templateFile })` render request.
8
8
  *
9
- * Containment (S-005, verify-in-loop-4 Deviation #1 ruling): the path is validated through
10
- * the SAME `validateSourceContainment` machinery `scaffold`/`copyIn` already use
11
- * (`package-root-containment` REQ-PRC-01..08) BEFORE any content read — a missing/
12
- * outside-package/non-regular/unreadable source surfaces the matching neutral `source-*`
13
- * `AuthoringReason` (REQ-AEC-10/11), never a parallel templateFile-only check. The whole
14
- * containment → stat-size (REQ-CCL-06 posture) → read → sniff (REQ-CCL-01/03) → budget
15
- * (REQ-CCL-02) chain is `classifyTransport`'s — ONE gate engine for both callers. A
9
+ * ADR-0077: the path is screened lexically (`validateSourceLexical`, `ir-path-well-formedness`
10
+ * REQ-IPF-01) then hygiene-checked through the SAME `statSourceForRead` machinery
11
+ * `scaffold`/`copyIn` already use (`package-source-io-hygiene` REQ-PSH-01..03) BEFORE any
12
+ * content read — a missing/non-regular/unreadable source surfaces the matching neutral
13
+ * `source-*` `AuthoringReason` (REQ-AEC-10/11), never a parallel templateFile-only check.
14
+ * The whole hygiene → stat-size (REQ-CCL-06 posture) → read → sniff (REQ-CCL-01/03) →
15
+ * budget (REQ-CCL-02) chain is `classifyTransport`'s — ONE gate engine for both callers. A
16
16
  * `templateFile` REQUESTS a render — unlike `scaffold`'s by-value/by-reference
17
17
  * classification of unmarked files, there is no silent by-reference fallback here
18
18
  * (REQ-FEH-02): invalid UTF-8, a null byte, or an over-budget file all fail loud with
@@ -32,11 +32,12 @@ export declare function readTemplateFile(relPath: string, destPath: string, opti
32
32
  * rendered: a text asset containing `{= =}`-like sequences travels verbatim, the documented
33
33
  * escape from `scaffold`'s by-value classification (`content-classification` REQ-CCL-04).
34
34
  * `from`/`to` are mandatory; a missing one rejects fail-loud before any emission
35
- * (REQ-FEH-04.1/.2). Source containment (existence, in-ceiling, regular-file) is validated
36
- * SDK-side against real disk BEFORE any directive is emitted — a missing/outside-package/
37
- * non-regular source surfaces the matching `source-*` reason
38
- * (`package-root-containment` REQ-PRC-04, `by-reference-copy-wire` REQ-BRC-06); content is
39
- * never read (`copyIn` never classifies, REQ-FEH-03).
35
+ * (REQ-FEH-04.1/.2). The destination is screened lexically FIRST (design §4 Q2 — a
36
+ * both-escape fixture must yield the destination template), then the source is screened
37
+ * lexically and hygiene-checked against real disk BEFORE any directive is emitted — a
38
+ * missing/non-regular source surfaces the matching `source-*` reason
39
+ * (`package-source-io-hygiene` REQ-PSH-01/02, `by-reference-copy-wire` REQ-BRC-06);
40
+ * content is never read (`copyIn` never classifies, REQ-FEH-03).
40
41
  */
41
42
  export declare function runCopyIn(args: {
42
43
  from: string | undefined;
@@ -6,7 +6,7 @@
6
6
  import { currentContext, requirePackageAnchors } from "../core/context.js";
7
7
  import { invalidInput } from "../core/authoring-error.js";
8
8
  import { forceEntry } from "../core/directive-factory.js";
9
- import { validateSourceContainment, validateDestinationLexical } from "./containment.js";
9
+ import { validateSourceLexical, statSourceForRead, validateDestinationLexical } from "./path-guards.js";
10
10
  import { classifyTransport } from "./classify-transport.js";
11
11
  // S-001: the folder-scaffold orchestrator lives in expander.ts (the single owner of the
12
12
  // walk → filename-pipeline → classify → emit fan-out, ADR-0044); re-exported here so
@@ -30,13 +30,13 @@ export { isSniffableText } from "./classify-transport.js";
30
30
  * Reads a package-local file (relative to the active run's `packageDir`) and returns its
31
31
  * content as the string to use for a `create({ templateFile })` render request.
32
32
  *
33
- * Containment (S-005, verify-in-loop-4 Deviation #1 ruling): the path is validated through
34
- * the SAME `validateSourceContainment` machinery `scaffold`/`copyIn` already use
35
- * (`package-root-containment` REQ-PRC-01..08) BEFORE any content read — a missing/
36
- * outside-package/non-regular/unreadable source surfaces the matching neutral `source-*`
37
- * `AuthoringReason` (REQ-AEC-10/11), never a parallel templateFile-only check. The whole
38
- * containment → stat-size (REQ-CCL-06 posture) → read → sniff (REQ-CCL-01/03) → budget
39
- * (REQ-CCL-02) chain is `classifyTransport`'s — ONE gate engine for both callers. A
33
+ * ADR-0077: the path is screened lexically (`validateSourceLexical`, `ir-path-well-formedness`
34
+ * REQ-IPF-01) then hygiene-checked through the SAME `statSourceForRead` machinery
35
+ * `scaffold`/`copyIn` already use (`package-source-io-hygiene` REQ-PSH-01..03) BEFORE any
36
+ * content read — a missing/non-regular/unreadable source surfaces the matching neutral
37
+ * `source-*` `AuthoringReason` (REQ-AEC-10/11), never a parallel templateFile-only check.
38
+ * The whole hygiene → stat-size (REQ-CCL-06 posture) → read → sniff (REQ-CCL-01/03) →
39
+ * budget (REQ-CCL-02) chain is `classifyTransport`'s — ONE gate engine for both callers. A
40
40
  * `templateFile` REQUESTS a render — unlike `scaffold`'s by-value/by-reference
41
41
  * classification of unmarked files, there is no silent by-reference fallback here
42
42
  * (REQ-FEH-02): invalid UTF-8, a null byte, or an over-budget file all fail loud with
@@ -50,10 +50,10 @@ export { isSniffableText } from "./classify-transport.js";
50
50
  * never the template content alone.
51
51
  */
52
52
  export function readTemplateFile(relPath, destPath, options, force) {
53
- const { packageDir, packageRoot } = requirePackageAnchors(noResolutionAnchorMessage(relPath));
53
+ const { packageDir } = requirePackageAnchors(noResolutionAnchorMessage(relPath));
54
+ validateSourceLexical(relPath);
54
55
  return classifyTransport({
55
56
  packageDir,
56
- packageRoot,
57
57
  relPath,
58
58
  isTemplateMarked: false,
59
59
  destPath,
@@ -78,11 +78,12 @@ function noResolutionAnchorForCopyInMessage() {
78
78
  * rendered: a text asset containing `{= =}`-like sequences travels verbatim, the documented
79
79
  * escape from `scaffold`'s by-value classification (`content-classification` REQ-CCL-04).
80
80
  * `from`/`to` are mandatory; a missing one rejects fail-loud before any emission
81
- * (REQ-FEH-04.1/.2). Source containment (existence, in-ceiling, regular-file) is validated
82
- * SDK-side against real disk BEFORE any directive is emitted — a missing/outside-package/
83
- * non-regular source surfaces the matching `source-*` reason
84
- * (`package-root-containment` REQ-PRC-04, `by-reference-copy-wire` REQ-BRC-06); content is
85
- * never read (`copyIn` never classifies, REQ-FEH-03).
81
+ * (REQ-FEH-04.1/.2). The destination is screened lexically FIRST (design §4 Q2 — a
82
+ * both-escape fixture must yield the destination template), then the source is screened
83
+ * lexically and hygiene-checked against real disk BEFORE any directive is emitted — a
84
+ * missing/non-regular source surfaces the matching `source-*` reason
85
+ * (`package-source-io-hygiene` REQ-PSH-01/02, `by-reference-copy-wire` REQ-BRC-06);
86
+ * content is never read (`copyIn` never classifies, REQ-FEH-03).
86
87
  */
87
88
  export function runCopyIn(args) {
88
89
  if (args.from === undefined) {
@@ -92,8 +93,11 @@ export function runCopyIn(args) {
92
93
  throw invalidInput(missingCopyInArgMessage("to"));
93
94
  }
94
95
  const { session, factory } = currentContext();
95
- const { packageDir, packageRoot } = requirePackageAnchors(noResolutionAnchorForCopyInMessage());
96
- validateSourceContainment({ packageDir, packageRoot, relPath: args.from });
96
+ const { packageDir } = requirePackageAnchors(noResolutionAnchorForCopyInMessage());
97
+ // design §4 Q2 — pinned statement order: destination BEFORE source. A both-escape
98
+ // fixture must yield the DESTINATION template, never the source one (REQ-AEC-11.2).
97
99
  validateDestinationLexical(args.to);
100
+ validateSourceLexical(args.from);
101
+ statSourceForRead({ packageDir, relPath: args.from });
98
102
  session.buffer(factory.copyIn({ from: args.from, to: args.to, ...forceEntry(args.force) }));
99
103
  }
@@ -0,0 +1,34 @@
1
+ import { type Stats } from "node:fs";
2
+ import { AuthoringError } from "../core/authoring-error.ts";
3
+ /**
4
+ * Ruling-5 lexical screen (REQ-IPF-01). Segment-aware over `/` and `\`; ANY segment
5
+ * === ".." or an absolute path (POSIX `/` or Windows drive) → `invalid-input`. Zero fs
6
+ * calls. Called at EXACTLY three sites: `readTemplateFile`, `runScaffold` (the walk
7
+ * ROOT `from`), `runCopyIn` (`from`).
8
+ */
9
+ export declare function validateSourceLexical(relPath: string): void;
10
+ type RejectionDetail = "directory" | "permission or I/O error" | "symlink cycle" | "path contains an invalid character";
11
+ export declare function sourceRejection(reason: "source-not-found" | "source-not-regular-file" | "source-unreadable", relPath: string, detail?: RejectionDetail): AuthoringError;
12
+ /**
13
+ * IO hygiene, TOTAL guard (`package-source-io-hygiene` REQ-PSH-01/02/03). `absPath =
14
+ * resolve(join(packageDir, relPath))` — LEXICAL, never disk-canonicalized. `statSync` (follows
15
+ * symlinks) → allow-list `isFile()`. The returned `stat` is reused by
16
+ * `classify-transport.ts` for the CCL-06 size gate. The `try` wraps BOTH the path
17
+ * computation AND the `statSync` call — no raw Node error ever escapes.
18
+ */
19
+ export declare function statSourceForRead(params: {
20
+ packageDir: string;
21
+ relPath: string;
22
+ }): {
23
+ absPath: string;
24
+ stat: Stats;
25
+ };
26
+ /**
27
+ * Validates a FINAL, SDK-computed DESTINATION path (`scaffold`'s computed `to`, or
28
+ * `copyIn`'s `to`) — LEXICAL ONLY, never disk-canonicalized (the destination may not exist yet,
29
+ * `ir-path-well-formedness` REQ-IPF-02). Applied post-rename, post-token-translation,
30
+ * immediately pre-emit. Rejects with the EXISTING `invalid-input` reason (scaffold-family
31
+ * author misuse) — never a `source-*` reason, which is reserved for source READS.
32
+ */
33
+ export declare function validateDestinationLexical(relPath: string): void;
34
+ export {};
@@ -0,0 +1,140 @@
1
+ // src/scaffold/path-guards.ts (ADR-0077): replaces containment.ts. The SDK no longer
2
+ // enforces a containment ceiling — `package-root-containment` is retired wholesale. The
3
+ // SDK's remaining obligation for package-local sources is IO HYGIENE (does this resolve to
4
+ // a readable regular file?) and IR WELL-FORMEDNESS (is the literal path shape emittable?) —
5
+ // never a boundary. Three guards live here (ADR-0077 §G, one shared predicate, ruling 5):
6
+ //
7
+ // 1. `validateSourceLexical` — segment-aware `../`/absolute screen for a SOURCE path
8
+ // (`ir-path-well-formedness` REQ-IPF-01). Zero fs calls. Called at EXACTLY three sites.
9
+ // 2. `statSourceForRead` — IO hygiene, TOTAL guard (`package-source-io-hygiene`
10
+ // REQ-PSH-01/02/03). LEXICAL resolution only — no disk-canonicalization pass, no
11
+ // ceiling.
12
+ // 3. `validateDestinationLexical` — lexical-only guard for a `to` destination
13
+ // (`ir-path-well-formedness` REQ-IPF-02). Reuses the EXISTING `invalid-input` reason.
14
+ import { statSync } from "node:fs";
15
+ import { join, resolve } from "node:path";
16
+ import { AuthoringError, invalidInput } from "../core/authoring-error.js";
17
+ import { isErrnoException } from "../core/fs-errors.js";
18
+ // Lexical `../`/absolute screen shared by BOTH the source guard (REQ-IPF-01) and the
19
+ // destination guard (REQ-IPF-02, symmetric by design): a literal ".." segment or an
20
+ // absolute-looking path (POSIX leading `/` or a Windows drive letter) is rejected
21
+ // lexically — no filesystem touch needed.
22
+ function isLexicallyEscaping(relPath) {
23
+ const isAbsolute = relPath.startsWith("/") || /^[A-Za-z]:[\\/]/.test(relPath);
24
+ const segments = relPath.split(/[\\/]+/);
25
+ return isAbsolute || segments.includes("..");
26
+ }
27
+ function sourceLexicalRejectionMessage(relPath) {
28
+ return (`source path invalid: ${relPath} must not contain a '..' segment or be absolute — ` +
29
+ "everything a schematic reads lives inside its package (packageDir)");
30
+ }
31
+ /**
32
+ * Ruling-5 lexical screen (REQ-IPF-01). Segment-aware over `/` and `\`; ANY segment
33
+ * === ".." or an absolute path (POSIX `/` or Windows drive) → `invalid-input`. Zero fs
34
+ * calls. Called at EXACTLY three sites: `readTemplateFile`, `runScaffold` (the walk
35
+ * ROOT `from`), `runCopyIn` (`from`).
36
+ */
37
+ export function validateSourceLexical(relPath) {
38
+ if (typeof relPath !== "string") {
39
+ throw invalidInput("invalid input: source path must be a string");
40
+ }
41
+ if (isLexicallyEscaping(relPath)) {
42
+ throw invalidInput(sourceLexicalRejectionMessage(relPath));
43
+ }
44
+ }
45
+ const UNPRINTABLE_SOURCE_PATH_PLACEHOLDER = "<unprintable source path>";
46
+ function sourceRejectionMessage(reason, displayPath, detail) {
47
+ switch (reason) {
48
+ case "source-not-found":
49
+ return `source file not found: ${displayPath} does not exist in the package`;
50
+ case "source-not-regular-file":
51
+ return detail === "directory"
52
+ ? `source file invalid: ${displayPath} is a directory, not a regular file — use scaffold() to copy a folder`
53
+ : `source file invalid: ${displayPath} is not a regular file`;
54
+ case "source-unreadable":
55
+ return `source file unreadable: ${displayPath} could not be read (${detail})`;
56
+ }
57
+ }
58
+ // REQ-PSH-02.3: when `relPath` is unrepresentable (embedded NUL), the fixed placeholder
59
+ // substitutes for the WHOLE `{path}` slot in the message — never the literal (possibly
60
+ // unprintable) bytes. The `.path` field on the error still carries the real `relPath`
61
+ // (programmatic access, not the human-readable surface). Exported (judgment-day G4(i)):
62
+ // `classify-transport.ts`'s own post-hygiene read failure mints through this SAME helper
63
+ // rather than constructing a bare, category-less `AuthoringError` — the ONE place a
64
+ // `source-unreadable` message is built, so the failure category (REQ-AEC-11.1) can never
65
+ // be silently dropped at a second call site.
66
+ export function sourceRejection(reason, relPath, detail) {
67
+ const displayPath = detail === "path contains an invalid character" ? UNPRINTABLE_SOURCE_PATH_PLACEHOLDER : relPath;
68
+ return new AuthoringError({
69
+ verb: undefined,
70
+ path: relPath,
71
+ reason,
72
+ appliedCount: 0,
73
+ message: sourceRejectionMessage(reason, displayPath, detail),
74
+ });
75
+ }
76
+ /**
77
+ * IO hygiene, TOTAL guard (`package-source-io-hygiene` REQ-PSH-01/02/03). `absPath =
78
+ * resolve(join(packageDir, relPath))` — LEXICAL, never disk-canonicalized. `statSync` (follows
79
+ * symlinks) → allow-list `isFile()`. The returned `stat` is reused by
80
+ * `classify-transport.ts` for the CCL-06 size gate. The `try` wraps BOTH the path
81
+ * computation AND the `statSync` call — no raw Node error ever escapes.
82
+ */
83
+ export function statSourceForRead(params) {
84
+ const { packageDir, relPath } = params;
85
+ let absPath;
86
+ let stat;
87
+ try {
88
+ absPath = resolve(join(packageDir, relPath));
89
+ stat = statSync(absPath);
90
+ }
91
+ catch (err) {
92
+ if (isErrnoException(err)) {
93
+ // ENOTDIR/ENAMETOOLONG (judgment-day G4(ii)): both mean the path, AS GIVEN, does not
94
+ // exist — a segment along the way turned out to be a regular file, or the resolved
95
+ // string exceeded the filesystem's name-length limit. Neither is a permission/IO
96
+ // failure on an existing path; `source-not-found` is the honest category (the spec's
97
+ // own table scopes it to "does not exist"), same as a plain ENOENT.
98
+ if (err.code === "ENOENT" || err.code === "ENOTDIR" || err.code === "ENAMETOOLONG") {
99
+ throw sourceRejection("source-not-found", relPath);
100
+ }
101
+ if (err.code === "ELOOP") {
102
+ throw sourceRejection("source-unreadable", relPath, "symlink cycle");
103
+ }
104
+ if (err.code === "ERR_INVALID_ARG_VALUE") {
105
+ throw sourceRejection("source-unreadable", relPath, "path contains an invalid character");
106
+ }
107
+ // EACCES/EPERM/EMFILE/ENFILE/EINTR/… — deliberately never interpolates the errno.
108
+ throw sourceRejection("source-unreadable", relPath, "permission or I/O error");
109
+ }
110
+ // No `.code` at all — an unclassifiable failure. Safest generic category, never a
111
+ // raw error message.
112
+ throw sourceRejection("source-unreadable", relPath, "permission or I/O error");
113
+ }
114
+ if (stat.isDirectory()) {
115
+ throw sourceRejection("source-not-regular-file", relPath, "directory");
116
+ }
117
+ if (!stat.isFile()) {
118
+ throw sourceRejection("source-not-regular-file", relPath);
119
+ }
120
+ return { absPath, stat };
121
+ }
122
+ function destinationEscapeMessage(relPath) {
123
+ return (`invalid input: destination "${relPath}" escapes the workspace tree ` +
124
+ '(literal ".." segment or absolute path)');
125
+ }
126
+ /**
127
+ * Validates a FINAL, SDK-computed DESTINATION path (`scaffold`'s computed `to`, or
128
+ * `copyIn`'s `to`) — LEXICAL ONLY, never disk-canonicalized (the destination may not exist yet,
129
+ * `ir-path-well-formedness` REQ-IPF-02). Applied post-rename, post-token-translation,
130
+ * immediately pre-emit. Rejects with the EXISTING `invalid-input` reason (scaffold-family
131
+ * author misuse) — never a `source-*` reason, which is reserved for source READS.
132
+ */
133
+ export function validateDestinationLexical(relPath) {
134
+ if (typeof relPath !== "string") {
135
+ throw invalidInput("invalid input: destination path must be a string");
136
+ }
137
+ if (isLexicallyEscaping(relPath)) {
138
+ throw invalidInput(destinationEscapeMessage(relPath));
139
+ }
140
+ }
@@ -7,19 +7,21 @@ export interface WalkEntry {
7
7
  }
8
8
  /**
9
9
  * Enumerates every file under `fromAbs`, mirroring nested directory structure into
10
- * posix-separated `relPath`s (sorted for deterministic output). Symlinked directories are
11
- * NEVER descended — even when their target resolves inside the containment ceiling
12
- * (REQ-FSC-09.1) — skipped silently, no error. Fails loud, naming the bound, once the
13
- * enumerated entry count exceeds `bound` (REQ-FSC-09.2); `bound` is injectable so a test
14
- * can drive the branch without materializing 10,001 real files.
10
+ * posix-separated `relPath`s (sorted for deterministic output). A NESTED symlinked
11
+ * directory is NEVER descended — even when its target resolves inside the package
12
+ * (REQ-FSC-09.1) — skipped silently, no error. The ROOT is held to a stricter standard
13
+ * (owner ruling 16): a symlinked `from` itself is REJECTED (`AuthoringError`,
14
+ * `invalid-input`) rather than followed or silently skipped — a bare no-op would hide a
15
+ * root that resolves to a real, populated directory. Fails loud, naming the bound, once
16
+ * the enumerated entry count exceeds `bound` (REQ-FSC-09.2); `bound` is injectable so a
17
+ * test can drive the branch without materializing 10,001 real files.
15
18
  *
16
- * `rootRelPath` (judgment-day iteration 2 fix, package-root-containment REQ-PRC-10.3
17
- * amendment): the author-facing, package-relative `from` — threaded through SOLELY to name
18
- * the ROOT in an `AuthoringError` message if the root itself is not a readable directory (a
19
- * regular file, or missing — `runScaffold`'s `validateSourceRootContainment` proves the root
20
- * is in-ceiling but deliberately leaves existence/type to this function, see its own
21
- * doc-comment). Recursive sub-directory reads below are NOT re-guarded — every one of them
22
- * enumerates a directory this walk already lstat'd as a directory, so their behavior for a
23
- * valid tree is unchanged.
19
+ * `rootRelPath` (judgment-day iteration 2 fix, extended by ruling 8 / REQ-FSC-10.4): the
20
+ * author-facing, package-relative `from` — threaded through to name BOTH the ROOT and any
21
+ * RECURSIVE entry in an `AuthoringError` message: the root if it itself is not a readable
22
+ * directory (a regular file, or missing — `runScaffold`'s `validateSourceLexical` only
23
+ * screens the root lexically, deliberately leaving existence/type to this function, see its
24
+ * own doc-comment); a nested entry if a recursive `readdirSync`/`lstatSync` fails mid-walk
25
+ * (the entry vanished, or an EACCES mid-tree, REQ-FSC-10.4).
24
26
  */
25
27
  export declare function walkFolder(fromAbs: string, bound?: number, rootRelPath?: string): WalkEntry[];
@@ -1,42 +1,53 @@
1
1
  // src/scaffold/walk.ts (ADR-0044): folder enumeration for `scaffold` — lstat-based
2
2
  // symlinked-directory non-descent (REQ-FSC-09.1) and a 10 000-entry bound (REQ-FSC-09.2).
3
- // Pure enumeration only: source/destination eligibility, containment, and the by-value/
4
- // by-reference verdict are NOT this module's concern (classify-transport.ts + containment.ts,
5
- // the latter landing in S-002).
3
+ // Pure enumeration only: source/destination eligibility and the by-value/by-reference
4
+ // verdict are NOT this module's concern (classify-transport.ts + path-guards.ts).
6
5
  import { lstatSync, readdirSync, statSync } from "node:fs";
7
- import { join } from "node:path";
6
+ import { join, posix, resolve } from "node:path";
8
7
  import { invalidInput } from "../core/authoring-error.js";
9
8
  import { isErrnoException } from "../core/fs-errors.js";
10
9
  export const DEFAULT_WALK_ENTRY_BOUND = 10_000;
11
10
  function boundExceededMessage(bound) {
12
11
  return `invalid input: scaffold walk exceeded the ${bound}-entry bound`;
13
12
  }
14
- // judgment-day iteration 2 fix: the ROOT `readdirSync` (below) has no per-entry containment
15
- // guard ahead of it the way every recursive sub-directory read does (those enumerate
16
- // directories `validateSourceRootContainment` + this function's own walk already proved
17
- // in-ceiling) — `runScaffold` only proves the root is IN-CEILING, never that it exists or is
18
- // a directory (`validateSourceRootContainment`'s own contract: a legitimately absent root is
19
- // deliberately left for `walkFolder` to answer, package-root-containment REQ-PRC-10.3). A
20
- // `from` that resolves to a regular FILE or does not exist at all therefore used to reach
21
- // `readdirSync` unguarded and throw a raw Node `Error` — never an `AuthoringError` — whose
22
- // message echoes the ABSOLUTE filesystem path (no-echo violation). `rootRelPath` is the
23
- // author-facing, package-relative `from` the caller already has in hand (never re-derived
24
- // from `fromAbs`); a caller that omits it (only the direct-unit-test callers in walk.test.ts
13
+ // judgment-day iteration 2 fix: the ROOT `readdirSync` (below) has no guard the caller
14
+ // already provides — `runScaffold` only lexically screens the root (`validateSourceLexical`,
15
+ // ADR-0077), never that it exists or is a directory (that check is deliberately left for
16
+ // `walkFolder` to answer). A `from` that resolves to a regular FILE or does not exist at
17
+ // all therefore used to reach `readdirSync` unguarded and throw a raw Node `Error` — never
18
+ // an `AuthoringError` — whose message echoes the ABSOLUTE filesystem path (no-echo
19
+ // violation). Ruling 8 (REQ-FSC-10.4) extends the SAME guard shape to every RECURSIVE
20
+ // sub-directory `readdirSync` and per-entry `lstatSync` below — a mid-walk failure (an
21
+ // entry vanishes, or an EACCES mid-tree) is no more entitled to leak a raw Node error than
22
+ // the root is. `rootRelPath` is the author-facing, package-relative `from` the caller
23
+ // already has in hand (never re-derived from `fromAbs`); a caller that omits it (only the
24
+ // direct-unit-test callers in walk.test.ts
25
25
  // do) falls back to a locator-free phrasing rather than ever risking an absolute-path leak.
26
+ /** Every message helper below (root and per-entry alike) shares this shape: a locator-free
27
+ * phrasing when `relPath` is undefined (only the direct unit-test callers in walk.test.ts
28
+ * omit it), the locator-bearing phrasing otherwise — never an absolute path either way. */
29
+ function withOptionalLocator(relPath, plain, withLocator) {
30
+ return relPath === undefined ? plain : withLocator(relPath);
31
+ }
26
32
  function rootNotDirectoryMessage(rootRelPath) {
27
- return rootRelPath === undefined
28
- ? "invalid input: scaffold \"from\" must be a folder — it resolves to a regular file"
29
- : `invalid input: scaffold "from" (${rootRelPath}) must be a folder — it resolves to a regular file`;
33
+ return withOptionalLocator(rootRelPath, "invalid input: scaffold \"from\" must be a folder — it resolves to a regular file", (relPath) => `invalid input: scaffold "from" (${relPath}) must be a folder — it resolves to a regular file`);
30
34
  }
31
35
  function rootNotFoundMessage(rootRelPath) {
32
- return rootRelPath === undefined
33
- ? "invalid input: scaffold \"from\" folder does not exist"
34
- : `invalid input: scaffold "from" folder (${rootRelPath}) does not exist`;
36
+ return withOptionalLocator(rootRelPath, "invalid input: scaffold \"from\" folder does not exist", (relPath) => `invalid input: scaffold "from" folder (${relPath}) does not exist`);
35
37
  }
36
38
  function rootUnreadableMessage(rootRelPath) {
37
- return rootRelPath === undefined
38
- ? "invalid input: scaffold \"from\" folder could not be read"
39
- : `invalid input: scaffold "from" folder (${rootRelPath}) could not be read`;
39
+ return withOptionalLocator(rootRelPath, "invalid input: scaffold \"from\" folder could not be read", (relPath) => `invalid input: scaffold "from" folder (${relPath}) could not be read`);
40
+ }
41
+ // Owner ruling 16 (2026-07-29): REQ-FSC-09 mandates the walk never descend into ANY
42
+ // symlinked directory, but only the NESTED case was implemented — the walk ROOT itself
43
+ // went straight to `readdirSync` with no `lstatSync` ahead of it, so a symlinked `from`
44
+ // was FOLLOWED rather than rejected (probe-proven: enumerates content outside the
45
+ // package). A symlinked root is now an explicit, named rejection — never a silent skip
46
+ // (skipping would make `scaffold` a silent no-op for a root that resolves to a real,
47
+ // populated directory, which is a worse surprise than a nested skip) — reusing the SAME
48
+ // `invalid-input` reason and locator shape every other root-failure message already uses.
49
+ function rootIsSymlinkMessage(rootRelPath) {
50
+ return withOptionalLocator(rootRelPath, "invalid input: scaffold \"from\" must not be a symlinked directory", (relPath) => `invalid input: scaffold "from" (${relPath}) must not be a symlinked directory`);
40
51
  }
41
52
  // Never re-throws the raw Node error (no-echo, REQ-AEC-05/FIT-11 posture already held by
42
53
  // every other scaffold-family rejection): ENOTDIR (the root resolves to a non-directory —
@@ -53,6 +64,28 @@ function rootReadFailure(err, rootRelPath) {
53
64
  }
54
65
  return invalidInput(rootUnreadableMessage(rootRelPath));
55
66
  }
67
+ // REQ-FSC-10.4 (ruling 8, design §4 Q3): the recursive `readdirSync` (a nested directory
68
+ // this walk itself discovered) and the per-entry `lstatSync` had NO guard ahead of them —
69
+ // unlike the ROOT read above — so a mid-walk failure (the entry vanishes, or an EACCES
70
+ // mid-tree) used to reach the caller as a raw Node `Error`, echoing an ABSOLUTE path
71
+ // (no-echo violation). `rootReadFailure`'s SHAPE is reused (AuthoringError, invalid-input,
72
+ // package-relative, no-echo) but its three texts are ROOT-specific and would misname a
73
+ // per-entry failure — these two templates are ENTRY-specific instead. `X` is
74
+ // `posix.join(rootRelPath, entryRelPath)`; when `rootRelPath` is undefined (only the
75
+ // direct unit-test callers in walk.test.ts), both fall back to a locator-free phrasing,
76
+ // exactly as the three root texts already do — never an absolute path.
77
+ function entryUnreadableMessage(entryRelPath) {
78
+ return withOptionalLocator(entryRelPath, "invalid input: scaffold entry could not be read", (relPath) => `invalid input: scaffold entry (${relPath}) could not be read`);
79
+ }
80
+ function entryDisappearedMessage(entryRelPath) {
81
+ return withOptionalLocator(entryRelPath, "invalid input: scaffold entry disappeared during the walk", (relPath) => `invalid input: scaffold entry (${relPath}) disappeared during the walk`);
82
+ }
83
+ function entryReadFailure(err, entryRelPath) {
84
+ if (isErrnoException(err) && err.code === "ENOENT") {
85
+ return invalidInput(entryDisappearedMessage(entryRelPath));
86
+ }
87
+ return invalidInput(entryUnreadableMessage(entryRelPath));
88
+ }
56
89
  // A symlink's OWN type (lstat) is always "symbolic link" — this asks what the link's
57
90
  // TARGET is, via `statSync` (follows the link), ONLY to decide non-descent (REQ-FSC-09.1).
58
91
  // NOT a containment check: a broken symlink (target absent) is treated as a
@@ -67,29 +100,62 @@ function symlinkTargetIsDirectory(absPath) {
67
100
  }
68
101
  /**
69
102
  * Enumerates every file under `fromAbs`, mirroring nested directory structure into
70
- * posix-separated `relPath`s (sorted for deterministic output). Symlinked directories are
71
- * NEVER descended — even when their target resolves inside the containment ceiling
72
- * (REQ-FSC-09.1) — skipped silently, no error. Fails loud, naming the bound, once the
73
- * enumerated entry count exceeds `bound` (REQ-FSC-09.2); `bound` is injectable so a test
74
- * can drive the branch without materializing 10,001 real files.
103
+ * posix-separated `relPath`s (sorted for deterministic output). A NESTED symlinked
104
+ * directory is NEVER descended — even when its target resolves inside the package
105
+ * (REQ-FSC-09.1) — skipped silently, no error. The ROOT is held to a stricter standard
106
+ * (owner ruling 16): a symlinked `from` itself is REJECTED (`AuthoringError`,
107
+ * `invalid-input`) rather than followed or silently skipped — a bare no-op would hide a
108
+ * root that resolves to a real, populated directory. Fails loud, naming the bound, once
109
+ * the enumerated entry count exceeds `bound` (REQ-FSC-09.2); `bound` is injectable so a
110
+ * test can drive the branch without materializing 10,001 real files.
75
111
  *
76
- * `rootRelPath` (judgment-day iteration 2 fix, package-root-containment REQ-PRC-10.3
77
- * amendment): the author-facing, package-relative `from` — threaded through SOLELY to name
78
- * the ROOT in an `AuthoringError` message if the root itself is not a readable directory (a
79
- * regular file, or missing — `runScaffold`'s `validateSourceRootContainment` proves the root
80
- * is in-ceiling but deliberately leaves existence/type to this function, see its own
81
- * doc-comment). Recursive sub-directory reads below are NOT re-guarded — every one of them
82
- * enumerates a directory this walk already lstat'd as a directory, so their behavior for a
83
- * valid tree is unchanged.
112
+ * `rootRelPath` (judgment-day iteration 2 fix, extended by ruling 8 / REQ-FSC-10.4): the
113
+ * author-facing, package-relative `from` — threaded through to name BOTH the ROOT and any
114
+ * RECURSIVE entry in an `AuthoringError` message: the root if it itself is not a readable
115
+ * directory (a regular file, or missing — `runScaffold`'s `validateSourceLexical` only
116
+ * screens the root lexically, deliberately leaving existence/type to this function, see its
117
+ * own doc-comment); a nested entry if a recursive `readdirSync`/`lstatSync` fails mid-walk
118
+ * (the entry vanished, or an EACCES mid-tree, REQ-FSC-10.4).
84
119
  */
85
120
  export function walkFolder(fromAbs, bound = DEFAULT_WALK_ENTRY_BOUND, rootRelPath) {
121
+ // judgment-day round 2 fix (F1): POSIX `lstat` FOLLOWS the final symlink when the path
122
+ // ends with a separator — an un-normalized `fromAbs` (trailing slash, doubled trailing
123
+ // slash, or a literal "./" segment) would resolve THROUGH a symlinked root before the
124
+ // `isSymbolicLink()` check below ever ran, bypassing the ruling-16 rejection entirely
125
+ // (probe-proven leak). `resolve` strips any trailing separator and collapses "./"/".."
126
+ // segments — the SAME normalization every recursive `join(root, relDir)` below now
127
+ // builds on, so a caller passing an un-normalized root is corrected in exactly ONE place.
128
+ const root = resolve(fromAbs);
86
129
  const entries = [];
87
130
  const dirStack = [""];
131
+ // judgment-day round 3 fix (F6): counts EVERY enumerated dirent (files, directories, and
132
+ // skipped symlinked directories alike) — the prior bound only incremented on
133
+ // `entries.push` (files), so a directory-only tree was entirely unbounded regardless of
134
+ // depth or breadth. REQ-FSC-09.2 frames the bound as a loop-safety/DoS guard over
135
+ // "enumerated entries," not "emitted files" — every name a `readdirSync` call returns is
136
+ // one enumerated entry, whatever it turns out to be.
137
+ let enumeratedCount = 0;
88
138
  while (dirStack.length > 0) {
89
139
  const relDir = dirStack.pop();
90
- const absDir = relDir === "" ? fromAbs : join(fromAbs, relDir);
140
+ const absDir = relDir === "" ? root : join(root, relDir);
91
141
  let names;
92
142
  if (relDir === "") {
143
+ // REQ-FSC-09.1 (owner ruling 16): the root gets the SAME non-descent guarantee a
144
+ // nested symlinked directory already has — `lstatSync` first (never `readdirSync`
145
+ // straight off `fromAbs`, which would silently FOLLOW a symlinked root) so a
146
+ // missing/non-directory root still reaches `rootReadFailure` unchanged (lstat fails
147
+ // with the identical errno readdir would have), and a symlinked root rejects
148
+ // explicitly instead of either being followed or silently skipped.
149
+ let rootLst;
150
+ try {
151
+ rootLst = lstatSync(absDir);
152
+ }
153
+ catch (err) {
154
+ throw rootReadFailure(err, rootRelPath);
155
+ }
156
+ if (rootLst.isSymbolicLink()) {
157
+ throw invalidInput(rootIsSymlinkMessage(rootRelPath));
158
+ }
93
159
  try {
94
160
  names = readdirSync(absDir).sort();
95
161
  }
@@ -98,12 +164,32 @@ export function walkFolder(fromAbs, bound = DEFAULT_WALK_ENTRY_BOUND, rootRelPat
98
164
  }
99
165
  }
100
166
  else {
101
- names = readdirSync(absDir).sort();
167
+ try {
168
+ names = readdirSync(absDir).sort();
169
+ }
170
+ catch (err) {
171
+ const entryX = rootRelPath === undefined ? undefined : posix.join(rootRelPath, relDir);
172
+ throw entryReadFailure(err, entryX);
173
+ }
102
174
  }
103
175
  for (const name of names) {
176
+ // F6: incremented for EVERY name `readdirSync` returned, before this entry is
177
+ // classified — a directory that will be pushed onto `dirStack` (never reaching
178
+ // `entries.push` below) still counts against the bound.
179
+ enumeratedCount += 1;
180
+ if (enumeratedCount > bound) {
181
+ throw invalidInput(boundExceededMessage(bound));
182
+ }
104
183
  const relPath = relDir === "" ? name : `${relDir}/${name}`;
105
184
  const absPath = join(absDir, name);
106
- const lst = lstatSync(absPath);
185
+ let lst;
186
+ try {
187
+ lst = lstatSync(absPath);
188
+ }
189
+ catch (err) {
190
+ const entryX = rootRelPath === undefined ? undefined : posix.join(rootRelPath, relPath);
191
+ throw entryReadFailure(err, entryX);
192
+ }
107
193
  if (lst.isSymbolicLink()) {
108
194
  if (symlinkTargetIsDirectory(absPath)) {
109
195
  continue; // REQ-FSC-09.1: never descended, no error for the skip
@@ -115,9 +201,6 @@ export function walkFolder(fromAbs, bound = DEFAULT_WALK_ENTRY_BOUND, rootRelPat
115
201
  continue;
116
202
  }
117
203
  entries.push({ relPath, absPath });
118
- if (entries.length > bound) {
119
- throw invalidInput(boundExceededMessage(bound));
120
- }
121
204
  }
122
205
  }
123
206
  return entries;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pbuilder/sdk",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The public TypeScript/Bun authoring layer for Project Builder schematics. Authors file mutations (create, modify, remove, rename, move, copy, copyIn), lowers them to IR, and talks to the Project Builder engine over framed stdio (see docs/engine-sdk-wire-spec.md).",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -1,54 +0,0 @@
1
- import { type Stats } from "node:fs";
2
- export declare function isWithinCeiling(candidateAbs: string, ceilingAbs: string): boolean;
3
- /**
4
- * The realpath'd form of the containment ceiling — a RUN invariant (`packageRoot` is
5
- * seeded once per run and always exists, so this realpath cannot ENOENT). Loop callers
6
- * (`runScaffold`) compute it once and thread it through `classifyTransport` →
7
- * `validateSourceContainment` instead of re-realpath'ing the same directory per entry.
8
- */
9
- export declare function resolveRealCeiling(packageRoot: string): string;
10
- /**
11
- * Validates ONE package-local SOURCE path against the dual-anchor containment model
12
- * (REQ-PRC-01..08) and returns its realpath'd absolute path plus the `lstat` used to
13
- * prove regular-file eligibility — callers (`classify-transport.ts`) reuse this `Stats`
14
- * for the CCL-06 size gate instead of stat'ing again. Throws one of the four `source-*`
15
- * `AuthoringError`s (REQ-AEC-10) on any failure; never reads file CONTENT.
16
- * `realCeiling` (optional) is the precomputed `resolveRealCeiling(packageRoot)` — passed
17
- * by per-entry loop callers; single-shot callers omit it and it is derived here.
18
- */
19
- export declare function validateSourceContainment(params: {
20
- packageDir: string;
21
- packageRoot: string;
22
- relPath: string;
23
- realCeiling?: string;
24
- }): {
25
- absPath: string;
26
- stat: Stats;
27
- };
28
- /**
29
- * Validates `scaffold`'s walk ROOT (`from`, a DIRECTORY — never file-checked) against the
30
- * SAME lexical + realpath ceiling machinery `validateSourceContainment` uses (steps 1-3,
31
- * via `resolveContainedRealpath` — no parallel check forked for the directory case).
32
- * Rejects `source-outside-package` for an escaping or out-of-ceiling root; a
33
- * legitimately ABSENT in-ceiling root is left alone (no-op) so `walkFolder`'s own
34
- * existing not-found behavior is preserved unchanged — this function only ever narrows
35
- * what `runScaffold` was already going to do, it never invents a new not-found path.
36
- * MUST run before `walkFolder` so the 10k-entry bound can never fire on an out-of-ceiling
37
- * tree (owner-ratified final-verify remediation, package-root-containment domain).
38
- */
39
- export declare function validateSourceRootContainment(params: {
40
- packageDir: string;
41
- packageRoot: string;
42
- relPath: string;
43
- realCeiling?: string;
44
- }): void;
45
- /**
46
- * Validates a FINAL, SDK-computed DESTINATION path (`scaffold`'s computed `to`, or
47
- * `copyIn`'s `to`) — LEXICAL ONLY, no realpath (the destination may not exist yet,
48
- * REQ-PRC-09). Applied post-rename, post-token-translation, immediately pre-emit.
49
- * Rejects with the EXISTING `invalid-input` reason (scaffold-family author misuse,
50
- * REQ-AEC-12) — never a `source-*` reason, which is reserved for source READS. The
51
- * engine's own post-render check (REQ-PRC-06/BRC-08) remains the real control for
52
- * rendered forms the SDK cannot evaluate.
53
- */
54
- export declare function validateDestinationLexical(relPath: string): void;