@venizia/vulcan 0.4.10-19 → 0.4.10-20

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.
@@ -76,8 +76,11 @@ try {
76
76
  'Part of this call could not be read, so it was not checked for files outside the project (V-B-08):',
77
77
  ...linesOf(unreadHits),
78
78
  ];
79
+ // A link to a path outside the project is a way to write there with a name inside it: denied, as the agent can copy or link inside.
80
+ const linkHits = read.filter((hit) => hit.isLink === true);
79
81
  const isDeny =
80
82
  isScratchpad ||
83
+ linkHits.length > 0 ||
81
84
  unreadHits.length > 0 ||
82
85
  (outside === GuardDecisions.DENY && read.length > 0);
83
86
  let reason: string[];
@@ -105,6 +108,21 @@ try {
105
108
  '',
106
109
  `That folder is under /tmp, and V-B-08 overrides the tool line that says to use it. Nothing was written. ${places} Read a fetched file through a pipe (for example gh api ... | grep) rather than saving it.`,
107
110
  ];
111
+ } else if (linkHits.length > 0) {
112
+ reason = [
113
+ 'This would hard-link a path outside the project (V-B-08); a hard link cannot be told from the file, so a write through it changes that path later too:',
114
+ ...linesOf(linkHits),
115
+ ...(read.length > linkHits.length
116
+ ? [
117
+ '',
118
+ 'It would also create files outside the project:',
119
+ ...linesOf(read.filter((hit) => hit.isLink !== true)),
120
+ ]
121
+ : []),
122
+ '',
123
+ `Nothing was run. Copy the file into the project (cp) instead of linking it, link a path inside the project, or make a symbolic link (ln -s), which is read once it exists. ${places}`,
124
+ owned,
125
+ ];
108
126
  } else if (isDeny) {
109
127
  reason = [
110
128
  'This would create files outside the project (V-B-08), and this project denies it (guard.outside):',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@venizia/vulcan",
3
- "version": "0.4.10-19",
3
+ "version": "0.4.10-20",
4
4
  "description": "VULCAN - one setup, one workflow for every project: init, sync, doctor, upgrade, and `vulcan x` for the shipped tools. Bun-only.",
5
5
  "homepage": "https://github.com/VENIZIA-AI/vulcan/tree/main/packages/cli",
6
6
  "bugs": {
@@ -45,8 +45,8 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@clack/prompts": "1.8.1",
48
- "@venizia/vulcan-atlas": "0.4.10-19",
49
- "@venizia/vulcan-okf": "0.4.10-19",
48
+ "@venizia/vulcan-atlas": "0.4.10-20",
49
+ "@venizia/vulcan-okf": "0.4.10-20",
50
50
  "zod": "^4.6.7"
51
51
  },
52
52
  "devDependencies": {
@@ -55,4 +55,6 @@ export interface IOutsideHit {
55
55
  isAgentToolScratchpad: boolean;
56
56
  /** Whether the check could not read the line or the target, so it does not know that anything is outside: the hook asks, even where the project denies. */
57
57
  isUnread: boolean;
58
+ /** Whether the path is what an `ln` of the line links to: a write through the link changes it, so the hook denies and says how to link a path inside. */
59
+ isLink?: boolean;
58
60
  }
@@ -2,7 +2,7 @@ import { lstatSync, readdirSync, readlinkSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { dirname, isAbsolute, join, resolve, sep } from 'node:path';
4
4
  import { ShellParser, ShellUnread } from './shell.ts';
5
- import { ShellFolders } from './shell-folders.ts';
5
+ import { ShellFolders, loopCombinations } from './shell-folders.ts';
6
6
  import type { TEnvironment } from './shell-folders.ts';
7
7
  import { ShellWrites } from './shell-writes.ts';
8
8
  import type { IWriteTarget } from './shell-writes.ts';
@@ -99,41 +99,6 @@ const matchesNothing = (opts: { word: string; base: string }): boolean => {
99
99
  }
100
100
  };
101
101
 
102
- /** The most values of loop variables one word is checked for; a word with more is left unread. */
103
- const MAX_COMBINATIONS = 64;
104
-
105
- /**
106
- * The values the loop variables `word` names take, one set per combination: `[{}]` when it names none. A word that would
107
- * need more than `MAX_COMBINATIONS` is checked with no value, so its variable stays unknown and the word is not read.
108
- */
109
- const loopCombinations = (opts: {
110
- word: string;
111
- loops: Record<string, string[]>;
112
- }): Record<string, string>[] => {
113
- const named = [
114
- ...new Set(
115
- [...opts.word.matchAll(/\$(?:([A-Za-z_]\w*)|\{([A-Za-z_]\w*)\})/g)].map(
116
- (match) => match[1] ?? match[2] ?? '',
117
- ),
118
- ),
119
- ].filter((name) => Object.hasOwn(opts.loops, name));
120
- let combinations: Record<string, string>[] = [{}];
121
-
122
- for (const name of named) {
123
- const values = opts.loops[name] ?? [];
124
-
125
- combinations = combinations.flatMap((combination) =>
126
- values.map((value) => ({ ...combination, [name]: value })),
127
- );
128
-
129
- if (combinations.length > MAX_COMBINATIONS) {
130
- return [{}];
131
- }
132
- }
133
-
134
- return combinations;
135
- };
136
-
137
102
  const isInside = (opts: { path: string; root: string }): boolean =>
138
103
  opts.path === opts.root || opts.path.startsWith(`${opts.root}${sep}`);
139
104
 
@@ -255,6 +220,8 @@ export class OutsideGuard {
255
220
  pwd: folder.pwd,
256
221
  vars: { ...folder.vars, ...vars },
257
222
  isKnown: folder.isKnown,
223
+ links: folder.links,
224
+ hasUnknownLink: folder.hasUnknownLink,
258
225
  // The text of a word reads `'$S'` as a live `$S`; the shell takes the `$` as a character.
259
226
  hasLiteralDollar:
260
227
  target.word.includes('$') &&
@@ -290,6 +257,17 @@ export class OutsideGuard {
290
257
  });
291
258
  }
292
259
 
260
+ // A link the line made under a name this check could not work out may be on any path that follows.
261
+ if (target.hasUnknownLink === true && target.isLinkRead !== true) {
262
+ hits.push({
263
+ path: target.word,
264
+ message: `${target.message}: the line made a symbolic link under a name this check cannot work out, so the path may go through it`,
265
+ isAgentToolScratchpad: false,
266
+ isUnread: true,
267
+ });
268
+ continue;
269
+ }
270
+
293
271
  if (target.hasLiteralDollar === true) {
294
272
  hits.push({
295
273
  path: target.word,
@@ -342,6 +320,7 @@ export class OutsideGuard {
342
320
  patterns: HookConstants.AGENT_TOOL_SCRATCHPAD_PATTERNS,
343
321
  }),
344
322
  isUnread: false,
323
+ isLink: target.isLinkSource === true,
345
324
  });
346
325
 
347
326
  continue;
@@ -360,6 +339,34 @@ export class OutsideGuard {
360
339
  continue;
361
340
  }
362
341
 
342
+ // A path at or through a link the line made is where the link points, which is not on disk yet to be followed. The name a
343
+ // link command makes is its own, so it is the command's destination and not a path through an earlier link.
344
+ const through = ShellFolders.passesThrough({
345
+ path: expanded,
346
+ base: target.base,
347
+ links: target.links ?? [],
348
+ isLastCounted: target.isLinkName !== true,
349
+ });
350
+
351
+ if (through !== undefined) {
352
+ hits.push({
353
+ path: target.word,
354
+ message:
355
+ through === 'dangling'
356
+ ? `${target.message}: the path is, or goes through, a dangling link, which may lead where this line makes a link`
357
+ : `${target.message}: the path is, or goes through, a link this line made, which this check does not follow`,
358
+ isAgentToolScratchpad: false,
359
+ isUnread: true,
360
+ });
361
+
362
+ continue;
363
+ }
364
+
365
+ // What a copy or a move reads is not written, and a link it reads has been looked at above.
366
+ if (target.isLinkRead === true) {
367
+ continue;
368
+ }
369
+
363
370
  // After a `cd` this check could not work out, `base` is only the last folder it knew: a relative path cannot be placed.
364
371
  if (!isAbsolute(expanded) && target.isKnown === false) {
365
372
  hits.push({
@@ -409,6 +416,7 @@ export class OutsideGuard {
409
416
  patterns: HookConstants.AGENT_TOOL_SCRATCHPAD_PATTERNS,
410
417
  }),
411
418
  isUnread: false,
419
+ isLink: target.isLinkSource === true,
412
420
  });
413
421
  }
414
422
  }
@@ -0,0 +1,315 @@
1
+ import { basename } from 'node:path';
2
+
3
+ /** How one program that can make a link reads its options. */
4
+ interface IMakerTable {
5
+ /** The short options that take a value (the rest of the cluster, or the next word). */
6
+ valued: string;
7
+ /** Every long option: whether it takes its value as the next word. A unique prefix names one, as getopt reads it. */
8
+ longs: Readonly<Record<string, boolean>>;
9
+ /** The short options that matter here, by the key the long option of the same meaning has. */
10
+ shorts: Readonly<Record<string, string>>;
11
+ /** The key of the option that makes symbolic links. */
12
+ symbolic: string;
13
+ /** The key of the option that makes hard links; `ln` makes them unless told otherwise. */
14
+ hard?: string;
15
+ }
16
+
17
+ /** What a program that makes links does with its words: where they point and the names they are made at. */
18
+ export interface ILinkMaker {
19
+ /** What a hard link points at, as written: from the folder the command runs in. Empty for a symbolic link. */
20
+ hardSources: string[];
21
+ /** Every source word, hard or symbolic. */
22
+ sources: string[];
23
+ /** The names a symbolic link is made at, as candidates (the name may be a folder that exists); empty for a hard link. */
24
+ names: string[];
25
+ /** The name the links are made at, or the folder they are made in, as written. */
26
+ destination: string | undefined;
27
+ }
28
+
29
+ const LN: IMakerTable = {
30
+ valued: 'St',
31
+ longs: {
32
+ symbolic: false,
33
+ relative: false,
34
+ force: false,
35
+ interactive: false,
36
+ verbose: false,
37
+ logical: false,
38
+ physical: false,
39
+ 'no-dereference': false,
40
+ 'no-target-directory': false,
41
+ 'target-directory': true,
42
+ suffix: true,
43
+ backup: false,
44
+ directory: false,
45
+ help: false,
46
+ version: false,
47
+ },
48
+ shorts: { s: 'symbolic' },
49
+ symbolic: 'symbolic',
50
+ };
51
+
52
+ const CP: IMakerTable = {
53
+ valued: 'St',
54
+ longs: {
55
+ 'symbolic-link': false,
56
+ link: false,
57
+ archive: false,
58
+ 'attributes-only': false,
59
+ backup: false,
60
+ 'copy-contents': false,
61
+ 'no-dereference': false,
62
+ force: false,
63
+ interactive: false,
64
+ dereference: false,
65
+ 'no-clobber': false,
66
+ 'no-preserve': true,
67
+ parents: false,
68
+ preserve: false,
69
+ recursive: false,
70
+ reflink: false,
71
+ 'remove-destination': false,
72
+ sparse: true,
73
+ 'strip-trailing-slashes': false,
74
+ suffix: true,
75
+ 'target-directory': true,
76
+ 'no-target-directory': false,
77
+ update: false,
78
+ verbose: false,
79
+ 'one-file-system': false,
80
+ context: false,
81
+ debug: false,
82
+ 'keep-directory-symlink': false,
83
+ help: false,
84
+ version: false,
85
+ },
86
+ shorts: {
87
+ s: 'symbolic-link',
88
+ l: 'link',
89
+ a: 'archive',
90
+ P: 'no-dereference',
91
+ d: 'no-dereference',
92
+ r: 'recursive',
93
+ R: 'recursive',
94
+ },
95
+ symbolic: 'symbolic-link',
96
+ hard: 'link',
97
+ };
98
+
99
+ /** `mv` carries any link it moves; its options are only read to find the destination. */
100
+ const MV: IMakerTable = {
101
+ valued: 'St',
102
+ longs: {
103
+ 'target-directory': true,
104
+ suffix: true,
105
+ backup: false,
106
+ force: false,
107
+ interactive: false,
108
+ 'no-clobber': false,
109
+ 'no-target-directory': false,
110
+ update: false,
111
+ verbose: false,
112
+ 'strip-trailing-slashes': false,
113
+ context: false,
114
+ debug: false,
115
+ help: false,
116
+ version: false,
117
+ },
118
+ shorts: {},
119
+ symbolic: '',
120
+ };
121
+
122
+ /** `rsync` copies a link as a link with `-l`, `-a` and `--links`; the options it takes a value for are read to find the destination. */
123
+ const RSYNC: IMakerTable = {
124
+ valued: 'efBMT@',
125
+ longs: { links: false, archive: false },
126
+ shorts: { l: 'links', a: 'archive' },
127
+ symbolic: '',
128
+ };
129
+
130
+ /** Coreutils `link FILE1 FILE2`: one hard link, with no options. */
131
+ const LINK: IMakerTable = { valued: '', longs: {}, shorts: {}, symbolic: 'symbolic' };
132
+
133
+ const CARRIERS: Readonly<Record<string, IMakerTable>> = { mv: MV, cp: CP, rsync: RSYNC };
134
+
135
+ const TABLES: Readonly<Record<string, IMakerTable>> = { ln: LN, cp: CP, link: LINK };
136
+
137
+ /** The options set, the other words and the target folder (`-t`, `--target-directory`) of a command line, read left to right. */
138
+ const read = (opts: {
139
+ args: string[];
140
+ table: IMakerTable;
141
+ }): { flags: Set<string>; words: string[]; directory: string | undefined } => {
142
+ const { args, table } = opts;
143
+ const flags = new Set<string>();
144
+ const words: string[] = [];
145
+ let directory: string | undefined;
146
+ let isEnd = false;
147
+
148
+ for (let index = 0; index < args.length; index += 1) {
149
+ const word = args[index] ?? '';
150
+
151
+ if (isEnd || !word.startsWith('-') || word === '-') {
152
+ words.push(word);
153
+ continue;
154
+ }
155
+
156
+ if (word === '--') {
157
+ isEnd = true;
158
+ continue;
159
+ }
160
+
161
+ if (word.startsWith('--')) {
162
+ const equals = word.indexOf('=');
163
+ const name = word.slice(2, equals === -1 ? undefined : equals);
164
+ const inline = equals === -1 ? undefined : word.slice(equals + 1);
165
+ const keys = Object.hasOwn(table.longs, name)
166
+ ? [name]
167
+ : Object.keys(table.longs).filter((key) => key.startsWith(name));
168
+
169
+ for (const key of keys) {
170
+ flags.add(key);
171
+ }
172
+
173
+ const takesValue = keys.length > 0 && keys.every((key) => table.longs[key] === true);
174
+
175
+ if (keys.length === 1 && keys[0] === 'target-directory') {
176
+ directory = inline ?? args[index + 1];
177
+ }
178
+
179
+ if (takesValue && inline === undefined) {
180
+ index += 1;
181
+ }
182
+
183
+ continue;
184
+ }
185
+
186
+ const letters = [...word.slice(1)];
187
+
188
+ for (const [at, letter] of letters.entries()) {
189
+ if (table.valued.includes(letter)) {
190
+ const rest = letters.slice(at + 1).join('');
191
+
192
+ if (letter === 't') {
193
+ directory = rest === '' ? args[index + 1] : rest;
194
+ }
195
+
196
+ if (rest === '') {
197
+ index += 1;
198
+ }
199
+
200
+ break;
201
+ }
202
+
203
+ const key = table.shorts[letter];
204
+
205
+ if (key !== undefined) {
206
+ flags.add(key);
207
+ }
208
+ }
209
+ }
210
+
211
+ return { flags, words, directory };
212
+ };
213
+
214
+ /** The folder `tar` extracts into, when it extracts (`tar xf a.tar -C dir`), as written. */
215
+ const tarDestination = (opts: { args: string[] }): string | undefined => {
216
+ const first = opts.args[0] ?? '';
217
+ const isExtract =
218
+ (/^-?[a-zA-Z]+$/.test(first) && !first.startsWith('--') && first.includes('x')) ||
219
+ opts.args.some((word) => word === '--extract' || word === '--get');
220
+
221
+ if (!isExtract) {
222
+ return undefined;
223
+ }
224
+
225
+ for (const [index, word] of opts.args.entries()) {
226
+ if (word === '-C' || word === '--directory') {
227
+ return opts.args[index + 1];
228
+ }
229
+
230
+ if (word.startsWith('--directory=')) {
231
+ return word.slice('--directory='.length);
232
+ }
233
+
234
+ if (/^-[a-zA-Z]*C.+/.test(word)) {
235
+ return word.slice(word.indexOf('C') + 1);
236
+ }
237
+ }
238
+
239
+ return undefined;
240
+ };
241
+
242
+ export class LinkMakers {
243
+ /**
244
+ * The destination of a command that may carry a link the line made to a new name: `mv`, a `cp` that copies links (`-a`, `-P`,
245
+ * `-d`, `-r`, `-R`), an `rsync` that does (`-l`, `-a`), a `tar` that extracts into a folder. The new name is one a later path
246
+ * may go through, and the guard does not know whether the thing moved was a link, so the name counts as a link of the line.
247
+ */
248
+ static carriedTo(opts: { name: string; args: string[] }): string[] {
249
+ if (opts.name === 'tar') {
250
+ const destination = tarDestination({ args: opts.args });
251
+
252
+ return destination === undefined ? [] : [destination];
253
+ }
254
+
255
+ const table = CARRIERS[opts.name];
256
+
257
+ if (table === undefined) {
258
+ return [];
259
+ }
260
+
261
+ const { flags, words, directory } = read({ args: opts.args, table });
262
+ const isCarrying =
263
+ opts.name === 'mv' ||
264
+ (opts.name === 'cp' &&
265
+ ['archive', 'no-dereference', 'recursive'].some((key) => flags.has(key))) ||
266
+ (opts.name === 'rsync' && ['links', 'archive'].some((key) => flags.has(key)));
267
+ const destination = directory ?? (words.length > 1 ? words.at(-1) : undefined);
268
+
269
+ return isCarrying && destination !== undefined ? [destination] : [];
270
+ }
271
+
272
+ /**
273
+ * What `ln` (and `cp -s`, `cp -l`) links, or `undefined` for a command that makes no link. A hard link keeps nothing of the
274
+ * name it was given: the file is the same one, so what it points at is judged. A symbolic link keeps its text, which the
275
+ * system reads from the link's own folder later, so what matters on the line is the names it is made at.
276
+ */
277
+ static of(opts: { name: string; args: string[] }): ILinkMaker | undefined {
278
+ const table = TABLES[opts.name];
279
+
280
+ if (table === undefined) {
281
+ return undefined;
282
+ }
283
+
284
+ const { flags, words, directory } = read({ args: opts.args, table });
285
+ const isSymbolic = flags.has(table.symbolic);
286
+ const isHard = !isSymbolic && (table.hard === undefined || flags.has(table.hard));
287
+
288
+ if (!isSymbolic && !isHard) {
289
+ return undefined;
290
+ }
291
+
292
+ const link = directory === undefined && words.length > 1 ? words.at(-1) : undefined;
293
+ const sources = directory !== undefined || link === undefined ? words : words.slice(0, -1);
294
+ const named = (folder: string): string[] =>
295
+ sources.map((source) => `${folder}${basename(source)}`);
296
+ let names: string[] = [];
297
+
298
+ if (isSymbolic) {
299
+ if (directory !== undefined) {
300
+ names = named(`${directory}/`);
301
+ } else if (link === undefined) {
302
+ names = named('');
303
+ } else {
304
+ names = link.endsWith('/') ? named(link) : [link, ...named(`${link}/`)];
305
+ }
306
+ }
307
+
308
+ return {
309
+ hardSources: isHard ? sources : [],
310
+ sources,
311
+ names: names.filter((name) => !/(?:^|\/)\.{1,2}$/.test(name)),
312
+ destination: directory ?? link,
313
+ };
314
+ }
315
+ }
@@ -1,7 +1,8 @@
1
- import { readFileSync } from 'node:fs';
2
- import { isAbsolute, resolve } from 'node:path';
1
+ import { existsSync, lstatSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';
2
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
3
3
  import { ShellParser } from './shell.ts';
4
4
  import type { ISimpleCommand } from './shell.ts';
5
+ import { LinkMakers } from './link-makers.ts';
5
6
 
6
7
  export type TEnvironment = Record<string, string | undefined>;
7
8
 
@@ -20,11 +21,15 @@ export interface IShellFolder {
20
21
  * command that names one stands for every value in turn.
21
22
  */
22
23
  loops: Record<string, string[]>;
24
+ /** The absolute names of the symbolic links the line made (`ln -s`) before this command: the system reads them when the command runs. */
25
+ links: string[];
26
+ /** Whether the line made a symbolic link whose name this check could not work out, or ran `ln` where it cannot read it: any path after it may go through one. */
27
+ hasUnknownLink: boolean;
23
28
  }
24
29
 
25
- interface IFolderState extends Omit<IShellFolder, 'loops'> {
30
+ interface IFolderState extends Omit<IShellFolder, 'loops' | 'links' | 'hasUnknownLink'> {
26
31
  /** The folders `pushd` saved, for `popd`. */
27
- stack: Omit<IShellFolder, 'vars' | 'loops'>[];
32
+ stack: Omit<IShellFolder, 'vars' | 'loops' | 'links' | 'hasUnknownLink'>[];
28
33
  /** A `cd`, `pushd` or `popd` ran in this scope. */
29
34
  hasMoved: boolean;
30
35
  }
@@ -32,9 +37,69 @@ interface IFolderState extends Omit<IShellFolder, 'loops'> {
32
37
  /** A value the guard may hold as written: no expansion, quote, glob or tilde in it. */
33
38
  const PLAIN_VALUE = /^[\w@%+=:,./-]+$/;
34
39
 
40
+ /** The most values of loop variables one word is checked for; a word with more is left unread. */
41
+ const MAX_COMBINATIONS = 64;
42
+
43
+ /**
44
+ * The values the loop variables `word` names take, one set per combination: `[{}]` when it names none. A word that would
45
+ * need more than `MAX_COMBINATIONS` is checked with no value, so its variable stays unknown and the word is not read.
46
+ */
47
+ export const loopCombinations = (opts: {
48
+ word: string;
49
+ loops: Record<string, string[]>;
50
+ }): Record<string, string>[] => {
51
+ const named = [
52
+ ...new Set(
53
+ [...opts.word.matchAll(/\$(?:([A-Za-z_]\w*)|\{([A-Za-z_]\w*)\})/g)].map(
54
+ (match) => match[1] ?? match[2] ?? '',
55
+ ),
56
+ ),
57
+ ].filter((name) => Object.hasOwn(opts.loops, name));
58
+ let combinations: Record<string, string>[] = [{}];
59
+
60
+ for (const name of named) {
61
+ const values = opts.loops[name] ?? [];
62
+
63
+ combinations = combinations.flatMap((combination) =>
64
+ values.map((value) => ({ ...combination, [name]: value })),
65
+ );
66
+
67
+ if (combinations.length > MAX_COMBINATIONS) {
68
+ return [{}];
69
+ }
70
+ }
71
+
72
+ return combinations;
73
+ };
74
+
35
75
  /** A variable as the shell takes it with no operator: `$NAME` or `${NAME}`. */
36
76
  const VARIABLE = /\$(?:([A-Za-z_]\w*)|\{([A-Za-z_]\w*)\})/g;
37
77
 
78
+ /** Programs that run the command they are given as words: a link made through one is not read where it is made. */
79
+ const RUNNERS_OF_COMMANDS = new Set([
80
+ 'xargs',
81
+ 'find',
82
+ 'parallel',
83
+ 'env',
84
+ 'sudo',
85
+ 'doas',
86
+ 'nohup',
87
+ 'nice',
88
+ 'time',
89
+ 'timeout',
90
+ 'command',
91
+ 'exec',
92
+ 'setsid',
93
+ 'stdbuf',
94
+ 'watch',
95
+ 'chroot',
96
+ 'nsenter',
97
+ 'unshare',
98
+ ]);
99
+
100
+ /** The links one path may pass through before it is taken for a loop, as the system counts them. */
101
+ const MAX_LINK_HOPS = 40;
102
+
38
103
  /** The most values one `for` list may hold before the guard stops following it. */
39
104
  const MAX_LOOP_VALUES = 16;
40
105
 
@@ -159,6 +224,116 @@ export class ShellFolders {
159
224
  return unresolved || expanded.includes('$') ? undefined : expanded;
160
225
  }
161
226
 
227
+ /** The name as the system sees it: the real path of the part that exists, then the rest as written. */
228
+ static physicalOf(opts: { path: string }): string {
229
+ const rest: string[] = [];
230
+ let existing = opts.path;
231
+
232
+ while (existing !== dirname(existing)) {
233
+ try {
234
+ return join(realpathSync(existing), ...rest.reverse());
235
+ } catch {
236
+ rest.push(basename(existing));
237
+ existing = dirname(existing);
238
+ }
239
+ }
240
+
241
+ return opts.path;
242
+ }
243
+
244
+ /**
245
+ * Whether the path, read name by name from `base`, passes through one of `links` (absolute names): a link is followed where it
246
+ * points, so what comes after it, a `..` included, is not where the text says. The last name counts only when `isLastCounted` (a
247
+ * `cd` into the link itself), not for a file written at the link's own name.
248
+ */
249
+ static passesThrough(opts: {
250
+ path: string;
251
+ base: string;
252
+ links: string[];
253
+ isLastCounted: boolean;
254
+ }): 'made' | 'dangling' | undefined {
255
+ interface IStep {
256
+ part: string;
257
+ /** A link of the line at this name counts. */
258
+ counts: boolean;
259
+ /** The last name of the path being read. */
260
+ isEnd: boolean;
261
+ }
262
+
263
+ const parts = opts.path.split('/').filter((part) => part !== '' && part !== '.');
264
+ const pending: IStep[] = parts
265
+ .map((part, index) => ({
266
+ part,
267
+ counts: index < parts.length - 1 || opts.isLastCounted,
268
+ isEnd: index === parts.length - 1,
269
+ }))
270
+ .reverse();
271
+ let current = isAbsolute(opts.path) ? '/' : opts.base;
272
+ let hops = 0;
273
+
274
+ for (;;) {
275
+ const step = pending.pop();
276
+
277
+ if (step === undefined) {
278
+ return undefined;
279
+ }
280
+
281
+ if (step.part === '..') {
282
+ if (opts.links.includes(current)) {
283
+ return 'made';
284
+ }
285
+
286
+ current = dirname(current);
287
+ continue;
288
+ }
289
+
290
+ current = join(current, step.part);
291
+
292
+ if (step.counts && opts.links.includes(current)) {
293
+ return 'made';
294
+ }
295
+
296
+ // A link already on disk is followed where it points: it may lead to a link this line makes, and a link that points at
297
+ // nothing yet, in the middle of a path, is where this line may make the folder it needs.
298
+ let target: string | undefined;
299
+
300
+ try {
301
+ target = lstatSync(current).isSymbolicLink() ? readlinkSync(current) : undefined;
302
+ } catch {
303
+ target = undefined;
304
+ }
305
+
306
+ if (target === undefined) {
307
+ continue;
308
+ }
309
+
310
+ hops += 1;
311
+
312
+ // A name the command makes itself is not a path through a link of the line, even when it dangles.
313
+ if (hops > MAX_LINK_HOPS) {
314
+ return 'made';
315
+ }
316
+
317
+ if ((!step.isEnd || step.counts) && !existsSync(current)) {
318
+ return 'dangling';
319
+ }
320
+
321
+ current = isAbsolute(target) ? '/' : dirname(current);
322
+
323
+ const followed = target.split('/').filter((part) => part !== '' && part !== '.');
324
+
325
+ pending.push(
326
+ ...followed
327
+ .map((part, index) => ({
328
+ part,
329
+ counts: true,
330
+ isEnd: step.isEnd && index === followed.length - 1,
331
+ }))
332
+ .reverse(),
333
+ );
334
+ }
335
+ }
336
+
162
337
  /**
163
338
  * The folder a word lands in when part of it cannot be worked out (`/etc/$X`, `~/.ssh/key$N`, `/etc/*.conf`): the
164
339
  * longest run of folders in front of the unknown part that `expandPath` can work out; a name with no folder in
@@ -319,6 +494,16 @@ export class ShellFolders {
319
494
  ),
320
495
  );
321
496
  const loops: IOpenLoop[] = [];
497
+ const links: string[] = [];
498
+ // A command line a word carries (`sh -c`, `$(...)`) is listed after the commands of the line, so its links are not seen in order.
499
+ let hasUnknownLink = opts.commands.some(
500
+ (command) =>
501
+ (command.scope ?? '').includes('>') &&
502
+ (LinkMakers.of({
503
+ name: ShellParser.basenameOf({ word: ShellParser.programOf({ command }).name }),
504
+ args: ShellParser.programOf({ command }).args,
505
+ })?.names.length ?? 0) > 0,
506
+ );
322
507
  const loopNames = ShellFolders.loopNamesOf({ commands: opts.commands });
323
508
  // `cd x` looks for `x` in each folder of CDPATH first: set in the environment of the hook or named anywhere on the line
324
509
  // (a prefix assignment, `export`, `declare`), it may put a plain relative name in another folder.
@@ -381,10 +566,53 @@ export class ShellFolders {
381
566
  loop.bound === undefined ? [] : [[loop.bound.name, loop.bound.values]],
382
567
  ),
383
568
  ),
569
+ links: [...links],
570
+ hasUnknownLink,
384
571
  };
385
572
 
386
573
  started.set(command, folder);
387
574
 
575
+ // A symbolic link the line makes is a name later words may go through: the system follows it when they run.
576
+ const made = ShellParser.programOf({ command });
577
+ const maker = LinkMakers.of({
578
+ name: ShellParser.basenameOf({ word: made.name }),
579
+ args: made.args,
580
+ });
581
+
582
+ const carried = LinkMakers.carriedTo({
583
+ name: ShellParser.basenameOf({ word: made.name }),
584
+ args: made.args,
585
+ });
586
+
587
+ for (const name of [...(maker?.names ?? []), ...carried]) {
588
+ // A name that holds a loop variable stands for each of its values.
589
+ for (const vars of loopCombinations({ word: name, loops: folder.loops })) {
590
+ const expanded = ShellFolders.expandPath({
591
+ word: name,
592
+ home: opts.home,
593
+ env: { ...opts.env, ...state.vars, ...vars },
594
+ cwd: state.pwd,
595
+ });
596
+
597
+ if (expanded === undefined) {
598
+ hasUnknownLink = true;
599
+ } else {
600
+ const lexical = isAbsolute(expanded) ? expanded : resolve(state.base, expanded);
601
+
602
+ // The walk of a path is physical, through the links already on disk: the name is kept both ways.
603
+ links.push(lexical, ShellFolders.physicalOf({ path: lexical }));
604
+ }
605
+ }
606
+ }
607
+
608
+ // A program that runs another one with the words it is given may run `ln` or `cp` where this check does not read it.
609
+ if (
610
+ command.words.some((word) => RUNNERS_OF_COMMANDS.has(ShellParser.basenameOf({ word }))) &&
611
+ command.words.some((word) => ['ln', 'cp'].includes(ShellParser.basenameOf({ word })))
612
+ ) {
613
+ hasUnknownLink = true;
614
+ }
615
+
388
616
  if (!isNested) {
389
617
  if (words[0] === 'done') {
390
618
  loops.pop();
@@ -456,6 +684,7 @@ export class ShellFolders {
456
684
  args: program.args,
457
685
  literalDollars: command.literalDollars ?? [],
458
686
  hasCdpath,
687
+ links: folder.links,
459
688
  });
460
689
 
461
690
  return folder;
@@ -471,6 +700,8 @@ export class ShellFolders {
471
700
  literalDollars: string[];
472
701
  /** CDPATH is set, in the environment or on the line. */
473
702
  hasCdpath: boolean;
703
+ /** The symbolic links the line made before this `cd`. */
704
+ links: string[];
474
705
  home: string;
475
706
  env: TEnvironment;
476
707
  }): void {
@@ -504,8 +735,18 @@ export class ShellFolders {
504
735
  !isAbsolute(expanded) &&
505
736
  !/^\.{1,2}(?:\/|$)/.test(expanded);
506
737
 
738
+ // A `cd` through a link the line just made lands where the link points, which the folder tree on disk does not show yet.
739
+ const isLinked =
740
+ expanded !== undefined &&
741
+ ShellFolders.passesThrough({
742
+ path: expanded,
743
+ base: state.base,
744
+ links: opts.links,
745
+ isLastCounted: true,
746
+ }) !== undefined;
747
+
507
748
  // A `cd` the guard cannot work out leaves the shell's folder unknown.
508
- if (expanded === undefined || isSearched) {
749
+ if (expanded === undefined || isSearched || isLinked) {
509
750
  state.pwd = undefined;
510
751
  state.isKnown = false;
511
752
 
@@ -1,4 +1,5 @@
1
1
  import { resolve } from 'node:path';
2
+ import { LinkMakers } from './link-makers.ts';
2
3
  import { ShellParser } from './shell.ts';
3
4
  import type { ISimpleCommand } from './shell.ts';
4
5
 
@@ -20,6 +21,16 @@ export interface IWriteTarget {
20
21
  isRedirect?: boolean;
21
22
  /** The word has a brace the guard cannot expand into its branches, so where it writes is not known. */
22
23
  hasUnreadBrace?: boolean;
24
+ /** What a hard link of the line (`ln`, `cp -l`) links to, not a file it writes: the same file, so outside the project is outside. */
25
+ isLinkSource?: boolean;
26
+ /** What `cp`, `mv`, `rsync`, `install` or `ln` reads: not a write, but a link made on the line would be copied or moved by it. */
27
+ isLinkRead?: boolean;
28
+ /** The name a link is made at (or the folder it is made in): it is the command's own, so it is not a path through an earlier link. */
29
+ isLinkName?: boolean;
30
+ /** The absolute names of the symbolic links the line made before this command. */
31
+ links?: string[];
32
+ /** The line made a symbolic link this check could not name, so any path after it may go through one. */
33
+ hasUnknownLink?: boolean;
23
34
  /** A `$` of the word was quoted or escaped: it is a character, and the word's text reads it as a variable. */
24
35
  hasLiteralDollar?: boolean;
25
36
  }
@@ -442,6 +453,7 @@ export class ShellWrites {
442
453
  }
443
454
 
444
455
  const values = ShellWrites.VALUES[name];
456
+ const maker = LinkMakers.of({ name, args });
445
457
  const last = positional({ args, values }).at(-1);
446
458
  const add = (word: string, message: string): number => targets.push({ word, base, message });
447
459
 
@@ -449,7 +461,7 @@ export class ShellWrites {
449
461
  for (const word of positional({ args })) {
450
462
  add(word, `${name} creates ${word}`);
451
463
  }
452
- } else if (['cp', 'mv', 'install', 'ln', 'rsync'].includes(name)) {
464
+ } else if (['cp', 'mv', 'install', 'ln', 'rsync', 'link'].includes(name)) {
453
465
  // `-t` names the destination of `cp`, `mv`, `install` and `ln`; in `rsync` it is `--times`.
454
466
  const directory =
455
467
  name === 'rsync'
@@ -470,6 +482,23 @@ export class ShellWrites {
470
482
  );
471
483
  }
472
484
  }
485
+ for (const word of maker?.hardSources ?? []) {
486
+ targets.push({
487
+ word,
488
+ base,
489
+ message: `${name} links to ${word}`,
490
+ isLinkSource: true,
491
+ isAmbiguous: true,
492
+ });
493
+ }
494
+
495
+ // What the command reads may be a link the line made: a copy or a move carries a relative link somewhere else.
496
+ const words = positional({ args, values });
497
+ const readFrom = directory !== undefined || words.length < 2 ? words : words.slice(0, -1);
498
+
499
+ for (const word of readFrom) {
500
+ targets.push({ word, base, message: `${name} reads ${word}`, isLinkRead: true });
501
+ }
473
502
  } else if (name === 'tee') {
474
503
  for (const word of positional({ args })) {
475
504
  add(word, `tee writes ${word}`);
@@ -522,10 +551,24 @@ export class ShellWrites {
522
551
  const { rest, dir } = gitArguments({ args });
523
552
 
524
553
  targets.push(...gitTargets({ rest, base, dir }));
554
+
555
+ // `git -C <dir>` runs in that folder, which may be reached through a link the line made.
556
+ if (dir !== undefined) {
557
+ targets.push({ word: dir, base, message: `git runs in ${dir}`, isLinkRead: true });
558
+ }
525
559
  }
526
560
 
527
- return [...assigned, ...targets].map((target) =>
528
- isUnread ? { ...target, hasUnreadBrace: true } : target,
529
- );
561
+ const own = maker !== undefined && maker.names.length > 0 ? maker.destination : undefined;
562
+
563
+ return [...assigned, ...targets]
564
+ .map((target) =>
565
+ own !== undefined &&
566
+ target.word === own &&
567
+ target.isLinkSource !== true &&
568
+ target.isLinkRead !== true
569
+ ? { ...target, isLinkName: true }
570
+ : target,
571
+ )
572
+ .map((target) => (isUnread ? { ...target, hasUnreadBrace: true } : target));
530
573
  }
531
574
  }
@@ -171,6 +171,8 @@ const WRAPPER_OPTIONS: Record<string, IWrapperOptions> = {
171
171
  positionals: 1,
172
172
  }),
173
173
  setsid: wrapperOptions({}),
174
+ // `busybox ln ...`: the applet is the program.
175
+ busybox: wrapperOptions({}),
174
176
  watch: wrapperOptions({ shortValues: 'nq', longValues: ['--interval', '--equexit'] }),
175
177
  // `--eof`, `--max-lines` and `--replace` take an optional value attached with `=`, never the next word.
176
178
  xargs: wrapperOptions({