farna-bootstrapper 0.0.0-stage → 0.1.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.
Files changed (80) hide show
  1. package/CHANGELOG.md +91 -0
  2. package/LICENSE +30 -0
  3. package/NOTICE +42 -0
  4. package/README.md +1079 -2
  5. package/SECURITY.md +65 -0
  6. package/dist/cli/commands/check.d.ts +58 -0
  7. package/dist/cli/commands/check.js +198 -0
  8. package/dist/cli/commands/generate.d.ts +75 -0
  9. package/dist/cli/commands/generate.js +218 -0
  10. package/dist/cli/commands/init.d.ts +52 -0
  11. package/dist/cli/commands/init.js +271 -0
  12. package/dist/cli/main.d.ts +2 -0
  13. package/dist/cli/main.js +51 -0
  14. package/dist/cli/program.d.ts +23 -0
  15. package/dist/cli/program.js +183 -0
  16. package/dist/compose/resolve.d.ts +154 -0
  17. package/dist/compose/resolve.js +545 -0
  18. package/dist/config/load.d.ts +4 -0
  19. package/dist/config/load.js +45 -0
  20. package/dist/config/schema.d.ts +22 -0
  21. package/dist/config/schema.js +46 -0
  22. package/dist/core/constants.d.ts +268 -0
  23. package/dist/core/constants.js +336 -0
  24. package/dist/core/errors.d.ts +44 -0
  25. package/dist/core/errors.js +75 -0
  26. package/dist/core/fs.d.ts +31 -0
  27. package/dist/core/fs.js +169 -0
  28. package/dist/core/json.d.ts +22 -0
  29. package/dist/core/json.js +174 -0
  30. package/dist/core/paths.d.ts +45 -0
  31. package/dist/core/paths.js +110 -0
  32. package/dist/core/text.d.ts +10 -0
  33. package/dist/core/text.js +27 -0
  34. package/dist/index.d.ts +10 -0
  35. package/dist/index.js +1 -0
  36. package/dist/lock/lockfile.d.ts +229 -0
  37. package/dist/lock/lockfile.js +333 -0
  38. package/dist/materialise/source-tree.d.ts +77 -0
  39. package/dist/materialise/source-tree.js +264 -0
  40. package/dist/permissions/permissions.d.ts +128 -0
  41. package/dist/permissions/permissions.js +452 -0
  42. package/dist/render/commit.d.ts +59 -0
  43. package/dist/render/commit.js +279 -0
  44. package/dist/render/generate-lock.d.ts +9 -0
  45. package/dist/render/generate-lock.js +203 -0
  46. package/dist/render/identity.d.ts +23 -0
  47. package/dist/render/identity.js +396 -0
  48. package/dist/render/orphans.d.ts +59 -0
  49. package/dist/render/orphans.js +234 -0
  50. package/dist/render/port.d.ts +96 -0
  51. package/dist/render/port.js +1 -0
  52. package/dist/render/prepare.d.ts +33 -0
  53. package/dist/render/prepare.js +139 -0
  54. package/dist/render/root-cleanliness.d.ts +28 -0
  55. package/dist/render/root-cleanliness.js +76 -0
  56. package/dist/render/stage.d.ts +36 -0
  57. package/dist/render/stage.js +92 -0
  58. package/dist/render/staging.d.ts +16 -0
  59. package/dist/render/staging.js +94 -0
  60. package/dist/render/structured.d.ts +35 -0
  61. package/dist/render/structured.js +258 -0
  62. package/dist/render/upstream.d.ts +41 -0
  63. package/dist/render/upstream.js +179 -0
  64. package/dist/report/format.d.ts +7 -0
  65. package/dist/report/format.js +97 -0
  66. package/dist/report/warnings.d.ts +21 -0
  67. package/dist/report/warnings.js +24 -0
  68. package/dist/source/digest.d.ts +18 -0
  69. package/dist/source/digest.js +77 -0
  70. package/dist/source/frontmatter.d.ts +12 -0
  71. package/dist/source/frontmatter.js +29 -0
  72. package/dist/source/load.d.ts +103 -0
  73. package/dist/source/load.js +676 -0
  74. package/dist/source/schema.d.ts +149 -0
  75. package/dist/source/schema.js +283 -0
  76. package/dist/source/yaml.d.ts +10 -0
  77. package/dist/source/yaml.js +49 -0
  78. package/dist/verify/containment.d.ts +22 -0
  79. package/dist/verify/containment.js +753 -0
  80. package/package.json +79 -4
@@ -0,0 +1,75 @@
1
+ import { DRIFT_CODE, EXIT, EXIT_BY_CODE } from './constants.js';
2
+ import { escapeControlCharacters } from './text.js';
3
+ /**
4
+ * A typed failure. The code selects the exit status; the message is assembled
5
+ * from the record, never by concatenation at a call site.
6
+ */
7
+ export class FarnaError extends Error {
8
+ code;
9
+ exitCode;
10
+ subject;
11
+ action;
12
+ constructor(code, message, options = {}) {
13
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
14
+ this.name = 'FarnaError';
15
+ this.code = code;
16
+ this.exitCode = code === DRIFT_CODE ? EXIT.drift : EXIT_BY_CODE[code];
17
+ if (options.subject !== undefined) {
18
+ this.subject = options.subject;
19
+ }
20
+ if (options.action !== undefined) {
21
+ this.action = options.action;
22
+ }
23
+ }
24
+ /**
25
+ * The one-line form the text reporter prints. The subject, the message and
26
+ * the action are all escaped: each can embed a source filename, a lockfile
27
+ * path or a foreign key from a hand-edited document, and a raw control
28
+ * character would rewrite the terminal lines the diagnostic appears on.
29
+ */
30
+ format() {
31
+ const subject = this.subject === undefined ? '' : ` ${escapeControlCharacters(this.subject)}`;
32
+ const action = this.action === undefined ? '' : `\n ${escapeControlCharacters(this.action)}`;
33
+ return `${this.code}${subject}\n ${escapeControlCharacters(this.message)}${action}`;
34
+ }
35
+ }
36
+ export function invalidConfig(message, options = {}) {
37
+ return new FarnaError('F001_INVALID_CONFIG', message, options);
38
+ }
39
+ /**
40
+ * `generate` refuses to overwrite a managed path it cannot prove it owns. The
41
+ * code is F007 (drift, exit 1), never F008: the path is not a renderer loss, it
42
+ * is a file this tool did not write.
43
+ */
44
+ export function driftRefused(message, options = {}) {
45
+ return new FarnaError(DRIFT_CODE, message, options);
46
+ }
47
+ /** A literal value in a credential position. The message never echoes it. */
48
+ export function secretLiteral(message, options = {}) {
49
+ return new FarnaError('F002_SECRET_LITERAL', message, options);
50
+ }
51
+ export function pathUnsafe(message, options = {}) {
52
+ return new FarnaError('F003_PATH_UNSAFE', message, options);
53
+ }
54
+ export function conflict(message, options = {}) {
55
+ return new FarnaError('F005_CONFLICT', message, options);
56
+ }
57
+ export function declaredNotEmitted(message, options = {}) {
58
+ return new FarnaError('F008_DECLARED_NOT_EMITTED', message, options);
59
+ }
60
+ export function renderFailed(message, options = {}) {
61
+ return new FarnaError('F009_RENDER_FAILED', message, options);
62
+ }
63
+ export function rendererMismatch(message, options = {}) {
64
+ return new FarnaError('F010_RENDERER_MISMATCH', message, options);
65
+ }
66
+ export function permissionUnmapped(message, options = {}) {
67
+ return new FarnaError('F011_PERMISSION_UNMAPPED', message, options);
68
+ }
69
+ /**
70
+ * The verified managed set could not be written. The tree is left as it was;
71
+ * the subject names the path that could not be staged.
72
+ */
73
+ export function writeFailed(message, options = {}) {
74
+ return new FarnaError('F012_WRITE_FAILED', message, options);
75
+ }
@@ -0,0 +1,31 @@
1
+ export type ReadBytesOptions = {
2
+ action?: string;
3
+ maxBytes?: number;
4
+ };
5
+ /**
6
+ * Read a repository-controlled file into bytes, bounded and without following a
7
+ * symlink. The open fd is authoritative: a path swapped for a symlink or a FIFO
8
+ * after the caller's `lstat` is refused rather than followed or blocked on.
9
+ * A file larger than `maxBytes` is a typed refusal naming the repository-relative
10
+ * subject, never an `Invalid string length` from the allocation that would
11
+ * otherwise follow.
12
+ */
13
+ export declare function readBoundedBytes(path: string, subject: string, options?: ReadBytesOptions): Promise<Buffer>;
14
+ /** The first byte offset of an invalid UTF-8 sequence, or `undefined`. */
15
+ export declare function firstInvalidUtf8Offset(bytes: Uint8Array): number | undefined;
16
+ /** Decode strict UTF-8, naming the subject and the first bad byte offset. */
17
+ export declare function decodeUtf8(bytes: Uint8Array, subject: string): string;
18
+ export type ReadUtf8Options = {
19
+ action?: string;
20
+ };
21
+ /**
22
+ * Read a source file as strict UTF-8. A filesystem failure is a typed error with
23
+ * the repository-relative subject, never a raw `EACCES` carrying an absolute
24
+ * path; the CLI's error boundary has one shape for every failure. The read is
25
+ * bounded before any allocation (see `SOURCE_MAX_BYTES`).
26
+ */
27
+ export declare function readUtf8File(path: string, subject: string, options?: ReadUtf8Options): Promise<string>;
28
+ /** A one-line filesystem code, for a message; never the raw absolute path. */
29
+ export declare function describeFsError(error: unknown): string;
30
+ /** Refuse a path the tool cannot inspect, with the repository-relative subject. */
31
+ export declare function inspectionFailed(subject: string, error: unknown): never;
@@ -0,0 +1,169 @@
1
+ import { constants } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { SOURCE_MAX_BYTES } from './constants.js';
4
+ import { invalidConfig, pathUnsafe } from './errors.js';
5
+ import { hasBom } from './json.js';
6
+ /**
7
+ * The one place source bytes become text. `readFile(path, 'utf8')` replaces an
8
+ * invalid byte with U+FFFD silently, which would let a mis-encoded persona or
9
+ * an edited config be compiled as though the bytes were what the author meant.
10
+ * Every source read is strict UTF-8 and refused with the byte offset instead.
11
+ */
12
+ const NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
13
+ const NO_BLOCK = constants.O_NONBLOCK ?? 0;
14
+ function errorCode(error) {
15
+ return error instanceof Error && 'code' in error && typeof error.code === 'string'
16
+ ? error.code
17
+ : undefined;
18
+ }
19
+ /**
20
+ * Read a repository-controlled file into bytes, bounded and without following a
21
+ * symlink. The open fd is authoritative: a path swapped for a symlink or a FIFO
22
+ * after the caller's `lstat` is refused rather than followed or blocked on.
23
+ * A file larger than `maxBytes` is a typed refusal naming the repository-relative
24
+ * subject, never an `Invalid string length` from the allocation that would
25
+ * otherwise follow.
26
+ */
27
+ export async function readBoundedBytes(path, subject, options = {}) {
28
+ const maxBytes = options.maxBytes ?? SOURCE_MAX_BYTES;
29
+ const action = options.action ?? 'make the path readable and re-run';
30
+ let handle;
31
+ try {
32
+ handle = await open(path, constants.O_RDONLY | NO_FOLLOW | NO_BLOCK);
33
+ }
34
+ catch (error) {
35
+ const code = errorCode(error);
36
+ if (code === 'ELOOP') {
37
+ throw pathUnsafe(`symlink not allowed: ${subject}`, {
38
+ subject,
39
+ action: 'replace the symbolic link with a real file',
40
+ });
41
+ }
42
+ throw invalidConfig(`cannot read ${subject} (${describeFsError(error)})`, {
43
+ subject,
44
+ action,
45
+ cause: error,
46
+ });
47
+ }
48
+ try {
49
+ const stats = await handle.stat();
50
+ if (!stats.isFile()) {
51
+ throw pathUnsafe(`${subject} is not a regular file`, {
52
+ subject,
53
+ action: 'replace it with a regular file, or remove it',
54
+ });
55
+ }
56
+ if (stats.size > maxBytes) {
57
+ throw pathUnsafe(`${subject} is larger than ${maxBytes} bytes; refusing to read it`, {
58
+ subject,
59
+ action: 'replace it with a file this tool can inspect, then re-run',
60
+ });
61
+ }
62
+ return await handle.readFile();
63
+ }
64
+ finally {
65
+ await handle.close();
66
+ }
67
+ }
68
+ /** The first byte offset of an invalid UTF-8 sequence, or `undefined`. */
69
+ export function firstInvalidUtf8Offset(bytes) {
70
+ let index = 0;
71
+ while (index < bytes.length) {
72
+ const lead = bytes[index];
73
+ if (lead === undefined) {
74
+ return index;
75
+ }
76
+ if (lead <= 0x7f) {
77
+ index += 1;
78
+ continue;
79
+ }
80
+ let continuation;
81
+ let codepoint;
82
+ let minimum;
83
+ if (lead >= 0xc2 && lead <= 0xdf) {
84
+ continuation = 1;
85
+ codepoint = lead & 0x1f;
86
+ minimum = 0x80;
87
+ }
88
+ else if (lead >= 0xe0 && lead <= 0xef) {
89
+ continuation = 2;
90
+ codepoint = lead & 0x0f;
91
+ minimum = 0x800;
92
+ }
93
+ else if (lead >= 0xf0 && lead <= 0xf4) {
94
+ continuation = 3;
95
+ codepoint = lead & 0x07;
96
+ minimum = 0x10000;
97
+ }
98
+ else {
99
+ return index;
100
+ }
101
+ if (index + continuation >= bytes.length) {
102
+ return index;
103
+ }
104
+ for (let step = 1; step <= continuation; step += 1) {
105
+ const byte = bytes[index + step];
106
+ if (byte === undefined || (byte & 0xc0) !== 0x80) {
107
+ return index + step;
108
+ }
109
+ codepoint = (codepoint << 6) | (byte & 0x3f);
110
+ }
111
+ const surrogate = codepoint >= 0xd800 && codepoint <= 0xdfff;
112
+ if (codepoint < minimum || codepoint > 0x10ffff || surrogate) {
113
+ return index;
114
+ }
115
+ index += continuation + 1;
116
+ }
117
+ return undefined;
118
+ }
119
+ /** Decode strict UTF-8, naming the subject and the first bad byte offset. */
120
+ export function decodeUtf8(bytes, subject) {
121
+ const invalid = firstInvalidUtf8Offset(bytes);
122
+ if (invalid !== undefined) {
123
+ throw invalidConfig(`${subject} is not valid UTF-8 (byte offset ${invalid})`, {
124
+ subject,
125
+ action: 're-save the file as UTF-8; invalid bytes are refused rather than replaced',
126
+ });
127
+ }
128
+ // `ignoreBOM: true` keeps a leading BOM in the text, so the parsers can
129
+ // refuse it explicitly instead of silently accepting a file that some editors
130
+ // then rewrite differently.
131
+ return new TextDecoder('utf-8', { fatal: true, ignoreBOM: true }).decode(bytes);
132
+ }
133
+ /**
134
+ * Read a source file as strict UTF-8. A filesystem failure is a typed error with
135
+ * the repository-relative subject, never a raw `EACCES` carrying an absolute
136
+ * path; the CLI's error boundary has one shape for every failure. The read is
137
+ * bounded before any allocation (see `SOURCE_MAX_BYTES`).
138
+ */
139
+ export async function readUtf8File(path, subject, options = {}) {
140
+ const action = options.action ?? 'make the path readable and re-run';
141
+ const bytes = await readBoundedBytes(path, subject, { action, maxBytes: SOURCE_MAX_BYTES });
142
+ const text = decodeUtf8(bytes, subject);
143
+ // One rule for every source kind: a leading BOM is refused here rather than
144
+ // being accepted by one parser and rejected by another. Personas, rules,
145
+ // permissions, MCP, skills (including every asset), commands, hooks and the
146
+ // config all pass through this function.
147
+ if (hasBom(text)) {
148
+ throw invalidConfig('file starts with a UTF-8 BOM', {
149
+ subject,
150
+ action: 'save the file as UTF-8 without a BOM',
151
+ });
152
+ }
153
+ return text;
154
+ }
155
+ /** A one-line filesystem code, for a message; never the raw absolute path. */
156
+ export function describeFsError(error) {
157
+ if (error instanceof Error && 'code' in error && typeof error.code === 'string') {
158
+ return error.code;
159
+ }
160
+ return error instanceof Error ? error.message : String(error);
161
+ }
162
+ /** Refuse a path the tool cannot inspect, with the repository-relative subject. */
163
+ export function inspectionFailed(subject, error) {
164
+ throw pathUnsafe(`cannot inspect ${subject}`, {
165
+ subject,
166
+ action: 'make the path readable and re-run, or remove it',
167
+ cause: error,
168
+ });
169
+ }
@@ -0,0 +1,22 @@
1
+ /** Codepoint order, never locale order. */
2
+ export declare function compareCodepoints(a: string, b: string): number;
3
+ export declare function sha256Hex(value: string | Uint8Array): string;
4
+ /** Canonical JSON for digests: sorted keys, no whitespace, no trailing newline. */
5
+ export declare function canonicalJson(value: unknown): string;
6
+ /** Canonical JSON for files: sorted keys, two spaces, exactly one trailing newline. */
7
+ export declare function canonicalJsonFile(value: unknown): string;
8
+ export declare function hasBom(text: string): boolean;
9
+ export type JsoncParseOptions = {
10
+ /** The file path or label printed in an error, relative to the repository root. */
11
+ subject: string;
12
+ };
13
+ /**
14
+ * Parse JSONC with comments and trailing commas, rejecting duplicate keys at
15
+ * every depth. CRLF is normalised before parsing.
16
+ *
17
+ * No nesting-depth limit is imposed by the grammar, so a repository-controlled
18
+ * file can be deep enough to exhaust the stack. That surfaces as a `RangeError`
19
+ * from the parser or the duplicate-key walk; it is mapped to the same typed
20
+ * diagnostic as any other invalid input, never allowed to escape untyped.
21
+ */
22
+ export declare function parseJsonc<T = unknown>(text: string, options: JsoncParseOptions): T;
@@ -0,0 +1,174 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { getNodeValue, parseTree, printParseErrorCode, } from 'jsonc-parser';
3
+ import { invalidConfig } from './errors.js';
4
+ /** Codepoint order, never locale order. */
5
+ export function compareCodepoints(a, b) {
6
+ if (a < b) {
7
+ return -1;
8
+ }
9
+ if (a > b) {
10
+ return 1;
11
+ }
12
+ return 0;
13
+ }
14
+ export function sha256Hex(value) {
15
+ return createHash('sha256').update(value).digest('hex');
16
+ }
17
+ function sortValue(value) {
18
+ if (Array.isArray(value)) {
19
+ return value.map(sortValue);
20
+ }
21
+ if (value !== null && typeof value === 'object') {
22
+ const source = value;
23
+ const sorted = {};
24
+ for (const key of Object.keys(source).sort(compareCodepoints)) {
25
+ const entry = source[key];
26
+ if (entry !== undefined) {
27
+ sorted[key] = sortValue(entry);
28
+ }
29
+ }
30
+ return sorted;
31
+ }
32
+ return value;
33
+ }
34
+ /** Canonical JSON for digests: sorted keys, no whitespace, no trailing newline. */
35
+ export function canonicalJson(value) {
36
+ return JSON.stringify(sortValue(value));
37
+ }
38
+ /** Canonical JSON for files: sorted keys, two spaces, exactly one trailing newline. */
39
+ export function canonicalJsonFile(value) {
40
+ return `${JSON.stringify(sortValue(value), null, 2)}\n`;
41
+ }
42
+ export function hasBom(text) {
43
+ return text.charCodeAt(0) === 0xfeff;
44
+ }
45
+ function findForbiddenKey(node, pointer) {
46
+ if (node.type === 'object') {
47
+ for (const property of node.children ?? []) {
48
+ if (property.type !== 'property') {
49
+ continue;
50
+ }
51
+ const [keyNode, valueNode] = property.children ?? [];
52
+ if (keyNode === undefined || valueNode === undefined) {
53
+ continue;
54
+ }
55
+ const key = String(keyNode.value);
56
+ if (key === '__proto__') {
57
+ return pointer === '' ? key : `${pointer}.${key}`;
58
+ }
59
+ const nested = findForbiddenKey(valueNode, pointer === '' ? key : `${pointer}.${key}`);
60
+ if (nested !== undefined) {
61
+ return nested;
62
+ }
63
+ }
64
+ return undefined;
65
+ }
66
+ if (node.type === 'array') {
67
+ const children = node.children ?? [];
68
+ for (let index = 0; index < children.length; index += 1) {
69
+ const child = children[index];
70
+ if (child === undefined) {
71
+ continue;
72
+ }
73
+ const nested = findForbiddenKey(child, `${pointer}[${index}]`);
74
+ if (nested !== undefined) {
75
+ return nested;
76
+ }
77
+ }
78
+ }
79
+ return undefined;
80
+ }
81
+ function findDuplicateKey(node, pointer) {
82
+ if (node.type === 'object') {
83
+ const seen = new Set();
84
+ for (const property of node.children ?? []) {
85
+ if (property.type !== 'property') {
86
+ continue;
87
+ }
88
+ const [keyNode, valueNode] = property.children ?? [];
89
+ if (keyNode === undefined || valueNode === undefined) {
90
+ continue;
91
+ }
92
+ const key = String(keyNode.value);
93
+ if (seen.has(key)) {
94
+ return pointer === '' ? key : `${pointer}.${key}`;
95
+ }
96
+ seen.add(key);
97
+ const nested = findDuplicateKey(valueNode, pointer === '' ? key : `${pointer}.${key}`);
98
+ if (nested !== undefined) {
99
+ return nested;
100
+ }
101
+ }
102
+ return undefined;
103
+ }
104
+ if (node.type === 'array') {
105
+ const children = node.children ?? [];
106
+ for (let index = 0; index < children.length; index += 1) {
107
+ const child = children[index];
108
+ if (child === undefined) {
109
+ continue;
110
+ }
111
+ const nested = findDuplicateKey(child, `${pointer}[${index}]`);
112
+ if (nested !== undefined) {
113
+ return nested;
114
+ }
115
+ }
116
+ }
117
+ return undefined;
118
+ }
119
+ /**
120
+ * Parse JSONC with comments and trailing commas, rejecting duplicate keys at
121
+ * every depth. CRLF is normalised before parsing.
122
+ *
123
+ * No nesting-depth limit is imposed by the grammar, so a repository-controlled
124
+ * file can be deep enough to exhaust the stack. That surfaces as a `RangeError`
125
+ * from the parser or the duplicate-key walk; it is mapped to the same typed
126
+ * diagnostic as any other invalid input, never allowed to escape untyped.
127
+ */
128
+ export function parseJsonc(text, options) {
129
+ if (hasBom(text)) {
130
+ throw invalidConfig('file starts with a UTF-8 BOM', {
131
+ subject: options.subject,
132
+ action: 'save the file as UTF-8 without a BOM',
133
+ });
134
+ }
135
+ const normalised = text.replace(/\r\n/g, '\n');
136
+ try {
137
+ const errors = [];
138
+ const tree = parseTree(normalised, errors, {
139
+ allowTrailingComma: true,
140
+ disallowComments: false,
141
+ });
142
+ if (errors.length > 0 || tree === undefined) {
143
+ const first = errors[0];
144
+ const detail = first === undefined
145
+ ? 'file did not parse'
146
+ : `${printParseErrorCode(first.error)} at offset ${first.offset}`;
147
+ throw invalidConfig(detail, { subject: options.subject });
148
+ }
149
+ const forbidden = findForbiddenKey(tree, '');
150
+ if (forbidden !== undefined) {
151
+ throw invalidConfig(`forbidden key "${forbidden}"`, {
152
+ subject: options.subject,
153
+ action: 'rename the key: "__proto__" is never read or written, and accepting it would silently drop a declaration',
154
+ });
155
+ }
156
+ const duplicate = findDuplicateKey(tree, '');
157
+ if (duplicate !== undefined) {
158
+ throw invalidConfig(`duplicate key "${duplicate}"`, {
159
+ subject: options.subject,
160
+ action: 'remove one of the duplicate keys; the last value is never silently kept',
161
+ });
162
+ }
163
+ return getNodeValue(tree);
164
+ }
165
+ catch (error) {
166
+ if (error instanceof RangeError) {
167
+ throw invalidConfig('file is nested too deeply to parse', {
168
+ subject: options.subject,
169
+ action: 'flatten the structure; a file this deep would exhaust the stack',
170
+ });
171
+ }
172
+ throw error;
173
+ }
174
+ }
@@ -0,0 +1,45 @@
1
+ import type { Stats } from 'node:fs';
2
+ /**
3
+ * Every filesystem path this tool reads for source or writes as output is
4
+ * checked here. A symbolic link is never followed: it is refused, wherever it
5
+ * points, because the product's contract is that the repository it describes
6
+ * is the repository it reads and writes.
7
+ */
8
+ /** A path API, so the containment predicate is testable with Windows paths. */
9
+ export type PathApi = {
10
+ relative: (from: string, to: string) => string;
11
+ isAbsolute: (path: string) => boolean;
12
+ };
13
+ /**
14
+ * True when `candidate` is `root` or lies inside it. Uses `relative` rather
15
+ * than string prefixes: on Windows the separator is `\`, and a prefix check
16
+ * cannot tell `C:\repo\other` from a child of `C:\repo`. The one predicate is
17
+ * shared by the stage cleanup and the managed-output walk.
18
+ */
19
+ export declare function isPathInside(root: string, candidate: string, api?: PathApi): boolean;
20
+ /**
21
+ * `lstat` a path. A missing path is `undefined`; any other failure (a path that
22
+ * cannot be inspected because a parent denies search permission, say) is a
23
+ * typed error naming the repository-relative subject when one is supplied.
24
+ */
25
+ declare function lstatOrUndefined(path: string, subject?: string): Promise<Stats | undefined>;
26
+ /**
27
+ * `lstat` a path and refuse a symbolic link. Returns the stats, or `undefined`
28
+ * when the path does not exist. A missing path is left to the caller, because
29
+ * "optional" means different things to a source directory and an output file.
30
+ */
31
+ export declare function assertNoSymlink(path: string, subject: string): Promise<Stats | undefined>;
32
+ /** A directory that must not be a symbolic link and must be a directory. */
33
+ export declare function assertRealDirectory(path: string, subject: string): Promise<Stats | undefined>;
34
+ /** A file that must not be a symbolic link and must be a regular file. */
35
+ export declare function assertRealFile(path: string, subject: string): Promise<Stats | undefined>;
36
+ /**
37
+ * Resolve one repository-relative managed path to an absolute target, having
38
+ * refused any symbolic link in any existing ancestor. The target itself is not
39
+ * inspected here: a caller that writes refuses a symlinked target, and `check`
40
+ * reports it as drift rather than following it. The canonical repository root
41
+ * is resolved first, so a symlinked `repoRoot` (macOS `/tmp`, for example) is
42
+ * compared canonically rather than by string prefix.
43
+ */
44
+ export declare function containedTarget(repoRoot: string, relativePath: string): Promise<string>;
45
+ export { lstatOrUndefined };
@@ -0,0 +1,110 @@
1
+ import { lstat, realpath } from 'node:fs/promises';
2
+ import { isAbsolute, join, relative } from 'node:path';
3
+ import { invalidConfig, pathUnsafe } from './errors.js';
4
+ import { inspectionFailed } from './fs.js';
5
+ /**
6
+ * True when `candidate` is `root` or lies inside it. Uses `relative` rather
7
+ * than string prefixes: on Windows the separator is `\`, and a prefix check
8
+ * cannot tell `C:\repo\other` from a child of `C:\repo`. The one predicate is
9
+ * shared by the stage cleanup and the managed-output walk.
10
+ */
11
+ export function isPathInside(root, candidate, api = { relative, isAbsolute }) {
12
+ const rel = api.relative(root, candidate);
13
+ if (rel === '') {
14
+ return true;
15
+ }
16
+ if (api.isAbsolute(rel)) {
17
+ return false;
18
+ }
19
+ return rel !== '..' && !rel.startsWith('../') && !rel.startsWith('..\\');
20
+ }
21
+ /**
22
+ * `lstat` a path. A missing path is `undefined`; any other failure (a path that
23
+ * cannot be inspected because a parent denies search permission, say) is a
24
+ * typed error naming the repository-relative subject when one is supplied.
25
+ */
26
+ async function lstatOrUndefined(path, subject) {
27
+ try {
28
+ return await lstat(path);
29
+ }
30
+ catch (error) {
31
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT') {
32
+ return undefined;
33
+ }
34
+ if (subject === undefined) {
35
+ throw error;
36
+ }
37
+ inspectionFailed(subject, error);
38
+ }
39
+ }
40
+ /**
41
+ * `lstat` a path and refuse a symbolic link. Returns the stats, or `undefined`
42
+ * when the path does not exist. A missing path is left to the caller, because
43
+ * "optional" means different things to a source directory and an output file.
44
+ */
45
+ export async function assertNoSymlink(path, subject) {
46
+ const stats = await lstatOrUndefined(path, subject);
47
+ if (stats?.isSymbolicLink() === true) {
48
+ throw pathUnsafe(`symlink not allowed: ${subject}`, {
49
+ subject,
50
+ action: 'replace the symbolic link with a real file or directory',
51
+ });
52
+ }
53
+ return stats;
54
+ }
55
+ /** A directory that must not be a symbolic link and must be a directory. */
56
+ export async function assertRealDirectory(path, subject) {
57
+ const stats = await assertNoSymlink(path, subject);
58
+ if (stats !== undefined && !stats.isDirectory()) {
59
+ throw invalidConfig(`${subject} is not a directory`, {
60
+ subject,
61
+ action: 'replace it with a directory, or remove it',
62
+ });
63
+ }
64
+ return stats;
65
+ }
66
+ /** A file that must not be a symbolic link and must be a regular file. */
67
+ export async function assertRealFile(path, subject) {
68
+ const stats = await assertNoSymlink(path, subject);
69
+ if (stats !== undefined && !stats.isFile()) {
70
+ throw invalidConfig(`${subject} is not a regular file`, {
71
+ subject,
72
+ action: 'replace it with a regular file, or remove it',
73
+ });
74
+ }
75
+ return stats;
76
+ }
77
+ function assertInside(root, candidate, subject) {
78
+ if (!isPathInside(root, candidate)) {
79
+ throw pathUnsafe('path resolves outside the repository root', { subject });
80
+ }
81
+ }
82
+ /**
83
+ * Resolve one repository-relative managed path to an absolute target, having
84
+ * refused any symbolic link in any existing ancestor. The target itself is not
85
+ * inspected here: a caller that writes refuses a symlinked target, and `check`
86
+ * reports it as drift rather than following it. The canonical repository root
87
+ * is resolved first, so a symlinked `repoRoot` (macOS `/tmp`, for example) is
88
+ * compared canonically rather than by string prefix.
89
+ */
90
+ export async function containedTarget(repoRoot, relativePath) {
91
+ const root = await realpath(repoRoot);
92
+ const segments = relativePath.split('/');
93
+ const directorySegments = segments.slice(0, -1);
94
+ let current = root;
95
+ let walked = '';
96
+ for (const segment of directorySegments) {
97
+ current = join(current, segment);
98
+ walked = walked === '' ? segment : `${walked}/${segment}`;
99
+ const stats = await assertNoSymlink(current, walked);
100
+ if (stats === undefined) {
101
+ break;
102
+ }
103
+ if (!stats.isDirectory()) {
104
+ throw pathUnsafe(`${walked} is not a directory`, { subject: walked });
105
+ }
106
+ assertInside(root, await realpath(current), walked);
107
+ }
108
+ return join(root, ...segments);
109
+ }
110
+ export { lstatOrUndefined };
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Text that reaches a human line. A subject can come from a source tree, a
3
+ * lockfile a user can hand-edit, or a renderer, so it is never printed raw: a C0
4
+ * or C1 control character would let a path rewrite the terminal line it is
5
+ * printed on (carriage return, backspace, an ANSI escape introducer).
6
+ */
7
+ /** True when the string contains a C0, DEL or C1 control character. */
8
+ export declare function hasControlCharacters(value: string): boolean;
9
+ /** Escape every control character as a visible `\uXXXX` sequence. */
10
+ export declare function escapeControlCharacters(value: string): string;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Text that reaches a human line. A subject can come from a source tree, a
3
+ * lockfile a user can hand-edit, or a renderer, so it is never printed raw: a C0
4
+ * or C1 control character would let a path rewrite the terminal line it is
5
+ * printed on (carriage return, backspace, an ANSI escape introducer).
6
+ */
7
+ function isControlCode(code) {
8
+ return code < 0x20 || (code >= 0x7f && code <= 0x9f);
9
+ }
10
+ /** True when the string contains a C0, DEL or C1 control character. */
11
+ export function hasControlCharacters(value) {
12
+ for (const character of value) {
13
+ if (isControlCode(character.codePointAt(0) ?? 0)) {
14
+ return true;
15
+ }
16
+ }
17
+ return false;
18
+ }
19
+ /** Escape every control character as a visible `\uXXXX` sequence. */
20
+ export function escapeControlCharacters(value) {
21
+ let escaped = '';
22
+ for (const character of value) {
23
+ const code = character.codePointAt(0) ?? 0;
24
+ escaped += isControlCode(code) ? `\\u${code.toString(16).padStart(4, '0')}` : character;
25
+ }
26
+ return escaped;
27
+ }
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Public types only. The CLI is the product surface in this slice; behaviour
3
+ * lives behind the command modules.
4
+ */
5
+ export type { Config, TargetConfig } from './config/schema.js';
6
+ export type { Severity, WarningCode } from './core/constants.js';
7
+ export type { Lockfile } from './lock/lockfile.js';
8
+ export type { PermissionCategory, PermissionKey, PermissionPatterns, PermissionTools, PermissionValue, } from './permissions/permissions.js';
9
+ export type { RendererIdentity, RenderRequest, RenderResult, RenderTarget } from './render/port.js';
10
+ export type { Warning } from './report/warnings.js';