@popcorn245/cornfield 0.51.6 → 0.51.8

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.
@@ -26,7 +26,7 @@ import { pathToFileURL } from 'node:url';
26
26
  import { DERIVER_CONTRACT, deriveTopology, deriverProblems } from './derive.js';
27
27
  import { planSync, missingPaths } from './sync.js';
28
28
  import { validateTopology } from './validate.js';
29
- import { repoReader, repoPaths } from './repo.js';
29
+ import { reachable, repoReader, repoPaths } from './repo.js';
30
30
  import { BUILTIN_DERIVERS, CORNFIELD_DIR, DEFAULTS } from './config.js';
31
31
 
32
32
  export { DERIVER_CONTRACT, deriverProblems };
@@ -70,14 +70,15 @@ export { DERIVER_CONTRACT, deriverProblems };
70
70
 
71
71
  /**
72
72
  * The readers a deriver gets, rooted at the repo (core/repo.js). Paths are relative, with forward slashes;
73
- * text is read with LF line ends.
73
+ * text is read with LF line ends. A path whose real path (symlinks followed) is outside the repo is not there: `read` throws,
74
+ * `exists` and `isDir` say no, `list` is empty.
74
75
  * @typedef {object} RepoReader
75
76
  * @property {string} root the repo's absolute folder
76
77
  * @property {(rel: string) => string} read
77
78
  * @property {(rel: string) => boolean} exists
78
79
  * @property {(rel: string) => boolean} isDir
79
80
  * @property {(rel: string) => string[]} list a folder's entries, sorted
80
- * @property {(rel: string, test?: (file: string) => boolean, onSkip?: (rel: string, reason: 'outside' | 'walked' | 'missing') => void, seen?: Set<string>) => string[]} walk every file under a folder that `test` accepts, skipping node_modules, .git and the like; a symlink is followed only while it stays in the repo, and a real folder is walked once (`onSkip` hears of each link left out; walks that share `seen` read a folder once between them)
81
+ * @property {(rel: string, test?: (file: string) => boolean, onSkip?: (rel: string, reason: 'outside' | 'walked' | 'missing') => void, seen?: Set<string>, skipDir?: (name: string) => boolean) => string[]} walk every file under a folder that `test` accepts, skipping node_modules, .git and the like; a symlink is followed only while it stays in the repo, and a real folder is walked once (`onSkip` hears of each link left out; walks that share `seen` read a folder once between them; `skipDir` names more folders to leave out)
81
82
  * @property {(rel: string) => boolean} inside whether a path is in the repo once its symlinks are followed
82
83
  */
83
84
 
@@ -295,7 +296,7 @@ export async function runDeriver(deriver, { root, files, options = {}, config =
295
296
  topology,
296
297
  changes,
297
298
  schemaProblems: validateTopology(topology),
298
- pathProblems: missingPaths({ nodes: topology.nodes.filter((n) => (own.nodes || []).some((m) => m.id === n.id)), edges: [] }, repoPaths(dir)),
299
+ pathProblems: missingPaths({ nodes: topology.nodes.filter((n) => (own.nodes || []).some((m) => m.id === n.id)), edges: [] }, repoPaths(dir), reachable(repoReader(dir))),
299
300
  validateProblems,
300
301
  driftProblems,
301
302
  unowned,
package/core/repo.js CHANGED
@@ -18,45 +18,81 @@ export const SKIP_DIRS = new Set(['node_modules', '.git', '.claude', '.worktrees
18
18
  */
19
19
  export function repoReader(root) {
20
20
  const abs = (rel) => path.join(root, rel);
21
- const read = (rel) => fs.readFileSync(abs(rel), 'utf8').replace(/\r\n/g, '\n');
22
- const exists = (rel) => fs.existsSync(abs(rel));
23
- const isDir = (rel) => {
24
- try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
25
- };
26
- const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
27
- const realRoot = (() => { try { return fs.realpathSync(root); } catch { return path.resolve(root); } })();
21
+ const realpath = fs.realpathSync.native;
22
+ const realRoot = (() => { try { return realpath(root); } catch { return path.resolve(root); } })();
28
23
  /** Whether real path `real` is `dir` or under it (by whole segments: `/x/repo-other` is not under `/x/repo`) */
29
24
  const under = (dir, real) => { const r = path.relative(dir, real); return r === '' || (r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r)); };
30
25
  const within = (real) => under(realRoot, real);
31
26
  /**
32
- * Whether `rel` lies in the repo once every symlink on its way is followed. A path that is not there is judged by
33
- * the nearest folder on its way that is, with the rest as written (a `..` included): nothing can be read from it.
27
+ * Whether the path `at` (absolute) lies in the repo once every symlink on its way is followed. A path that is not
28
+ * there is judged by the nearest folder on its way that is, with the rest as written (a `..` included): nothing can
29
+ * be read from it.
34
30
  */
35
- const inside = (rel) => {
36
- if (String(rel).includes('\0')) return false;
37
- let at = abs(rel);
31
+ const insideAbs = (at) => {
32
+ if (at.includes('\0')) return false;
38
33
  let rest = '';
39
34
  for (;;) {
40
- try { return within(path.resolve(fs.realpathSync(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
35
+ try { return within(path.resolve(realpath(at), rest)); } catch { /* not there, or a link loop: try its folder */ }
41
36
  const up = path.dirname(at);
42
37
  if (up === at) return false;
43
38
  rest = path.join(path.basename(at), rest);
44
39
  at = up;
45
40
  }
46
41
  };
42
+ const inside = (rel) => insideAbs(abs(String(rel)));
43
+ // The readers below are the one place a path is held to the repo: whatever a deriver is told to read, and whatever a
44
+ // symlink points at, a file whose real path is outside is not there (`read` throws, `exists` and `isDir` say no,
45
+ // `list` is empty). A folder's verdict is kept for the reader's life, so a plain file costs one `lstat`, not a
46
+ // `realpath` walk of its whole way; only a symlink is resolved each time. A file `walk` returned was judged by its
47
+ // real path there, and is read without a second look. Both are kept for the reader's life: make a reader per run, not
48
+ // one that outlives changes to the repo's links.
49
+ const folders = new Map();
50
+ const walked = new Set();
51
+ const pending = []; // what `walk` returned since a read last looked: only a reader of those files pays to list them
52
+ const folderInside = (dir) => {
53
+ let v = folders.get(dir);
54
+ if (v === undefined) { v = insideAbs(dir); folders.set(dir, v); }
55
+ return v;
56
+ };
57
+ // A trailing separator would make `lstat` follow a link it names (`ext/` for `ext`), so a path is looked at without one
58
+ const bare = (p) => { let q = p; while (q.length > 1 && (q.endsWith('/') || q.endsWith(path.sep))) q = q.slice(0, -1); return q; };
59
+ const rootAt = bare(path.join(root));
60
+ /** `null` when there is nothing at `rel`; else whether it is a symlink, whether it lies in the repo, and (not a link) what it is */
61
+ const look = (rel) => {
62
+ const at = bare(abs(rel));
63
+ let st;
64
+ try { st = fs.lstatSync(at); } catch { return null; }
65
+ if (st.isSymbolicLink()) return { link: true, ok: insideAbs(at), st };
66
+ return { link: false, ok: at === rootAt || folderInside(path.dirname(at)), st };
67
+ };
68
+ const outside = (rel) => Object.assign(new Error(`${JSON.stringify(String(rel))} is outside the repo.`), { code: 'EOUTSIDE' });
69
+ const read = (rel) => {
70
+ while (pending.length) for (const f of pending.pop()) walked.add(f);
71
+ if (!walked.has(rel)) {
72
+ const m = look(rel);
73
+ if (m && !m.ok) throw outside(rel);
74
+ }
75
+ return fs.readFileSync(abs(rel), 'utf8').replace(/\r\n/g, '\n');
76
+ };
77
+ const exists = (rel) => { const m = look(rel); return !!m && m.ok && (!m.link || fs.existsSync(abs(rel))); };
78
+ const rawIsDir = (rel) => {
79
+ try { return fs.statSync(abs(rel)).isDirectory(); } catch { return false; }
80
+ };
81
+ const isDir = (rel) => { const m = look(rel); return !!m && m.ok && (m.link ? rawIsDir(rel) : m.st.isDirectory()); };
82
+ const list = (rel) => (isDir(rel) ? fs.readdirSync(abs(rel)).sort() : []);
47
83
  /**
48
84
  * Every file under `rel` that `test` accepts, sorted by folder, skipping SKIP_DIRS. A symlink is followed only while
49
85
  * it stays in the repo, and a real folder is walked once: a link to a folder under `rel` is left to the real folder,
50
86
  * and of two links to one other folder the first wins. `onSkip(path, reason)` hears of each link left out: 'outside'
51
87
  * (out of the repo, to a folder or to a file `test` accepts), 'walked' (to a folder already walked) or 'missing' (to
52
88
  * nothing, or a loop of links, named like a file `test` accepts). Walks that share `seen` (a set of real folders) read
53
- * each folder once between them, a folder two of them name in the repo's own words in silence. Only links pay a
54
- * `realpath`.
89
+ * each folder once between them, a folder two of them name in the repo's own words in silence. `skipDir(name)` leaves
90
+ * out, beside SKIP_DIRS, each folder (or link to one) it accepts. Only links pay a `realpath`.
55
91
  */
56
- const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set()) => {
92
+ const walk = (rel, test = () => true, onSkip = () => {}, seen = new Set(), skipDir = null) => {
57
93
  const start = rel && rel !== '.' ? rel : '';
58
94
  let startReal;
59
- try { startReal = fs.realpathSync(abs(start)); } catch { return []; }
95
+ try { startReal = realpath(abs(start)); } catch { return []; }
60
96
  if (!within(startReal)) { onSkip(start, 'outside'); return []; }
61
97
  const linked = startReal !== path.join(realRoot, start);
62
98
  if (seen.has(startReal)) { if (linked) onSkip(start, 'walked'); return []; }
@@ -71,25 +107,68 @@ export function repoReader(root) {
71
107
  const child = dir ? `${dir}/${e.name}` : e.name;
72
108
  if (!e.isSymbolicLink()) {
73
109
  if (!e.isDirectory()) return test(child) ? [child] : [];
110
+ if (skipDir && skipDir(e.name)) return [];
74
111
  const childReal = path.join(real, e.name);
75
112
  if (seen.has(childReal)) { if (viaLink) onSkip(child, 'walked'); return []; }
76
113
  return go(child, childReal, viaLink);
77
114
  }
78
115
  let target;
79
- try { target = fs.realpathSync(abs(child)); } catch { if (test(child)) onSkip(child, 'missing'); return []; }
80
- const folder = isDir(child);
116
+ try { target = realpath(abs(child)); } catch { if (test(child)) onSkip(child, 'missing'); return []; }
117
+ const folder = rawIsDir(child);
118
+ if (folder && skipDir && skipDir(e.name)) return [];
81
119
  if (!within(target)) { if (folder || test(child)) onSkip(child, 'outside'); return []; }
82
120
  if (!folder) return test(child) ? [child] : [];
83
- const ownRoute = under(startReal, target) && !path.relative(startReal, target).split(path.sep).some((s) => SKIP_DIRS.has(s));
121
+ const ownRoute = under(startReal, target) && !path.relative(startReal, target).split(path.sep).some((s) => SKIP_DIRS.has(s) || (skipDir && skipDir(s)));
84
122
  if (ownRoute || seen.has(target)) { onSkip(child, 'walked'); return []; }
85
123
  return go(child, target, true);
86
124
  });
87
125
  };
88
- return go(start, startReal, linked);
126
+ const found = go(start, startReal, linked);
127
+ pending.push(found.slice()); // a copy: what a caller adds to the list it gets back is not taken for a walked file
128
+ return found;
89
129
  };
90
130
  return { root, read, exists, isDir, list, walk, inside };
91
131
  }
92
132
 
133
+ /**
134
+ * Whether a path a config names (a file or folder option of a deriver) leaves the repo: it is absolute, climbs out
135
+ * with `..`, or a symlink on its way leads out. `io` is a repo reader (`inside`).
136
+ * @param {{ inside: (rel: string) => boolean }} io
137
+ * @param {unknown} p
138
+ */
139
+ export function leavesRepo(io, p) {
140
+ if (typeof p !== 'string') return false;
141
+ const rel = path.posix.normalize(p.replace(/^\.\/+/, '').replace(/\/+$/, '') || '.');
142
+ return path.isAbsolute(p) || path.win32.isAbsolute(p) || rel === '..' || rel.startsWith('../') || !io.inside(rel);
143
+ }
144
+
145
+ /**
146
+ * The problem `validate` fails on for a config path that leaves the repo, naming the path as written (a JSON string, so
147
+ * nothing in it can break the line) and never where it leads.
148
+ * @param {string} who the deriver's name
149
+ * @param {unknown} p
150
+ */
151
+ export const outsideProblem = (who, p) => `${who}: ${JSON.stringify(p)} is outside the repo; only files and folders of the repo are read.`;
152
+
153
+ /**
154
+ * For `missingPaths`: whether a path `repoPaths` does not list is in the repo all the same, because a symlink on its way
155
+ * stays in the repo (`repoPaths` does not follow links; the walk does, and makes nodes at such paths). The path must be
156
+ * written plainly (relative, no empty, `.` or `..` segment, no folder the walks skip), a symlink must be on its way (so a
157
+ * repo without one is checked exactly as `repoPaths` says), and `exists` holds it to its real path.
158
+ * @param {{ root: string, exists: (rel: string) => boolean }} io a repo reader
159
+ * @returns {(p: string) => boolean}
160
+ */
161
+ export const reachable = (io) => (p) => {
162
+ if (typeof p !== 'string' || p === '' || p.includes('\0') || path.posix.isAbsolute(p) || path.win32.isAbsolute(p)) return false;
163
+ const segments = p.split('/');
164
+ if (segments.some((s) => s === '' || s === '.' || s === '..' || SKIP_DIRS.has(s))) return false;
165
+ if (!io.exists(p)) return false; // first, so a path that is not there costs one look
166
+ for (let i = 1; i <= segments.length; i++) {
167
+ try { if (fs.lstatSync(path.join(io.root, ...segments.slice(0, i))).isSymbolicLink()) return true; } catch { return false; }
168
+ }
169
+ return false;
170
+ };
171
+
93
172
  /**
94
173
  * Every file and folder path under the root (relative, forward slashes), for checking the paths a map cites.
95
174
  * @param {string} root
package/core/sync.js CHANGED
@@ -75,11 +75,12 @@ const CITED_PATH = /(?:^|[\s(`'"[])((?:[\w@.-]+\/)+[\w@-]+\.(?:json|js|ts|mjs|md
75
75
  * (`lib/outbox.ts`), so it counts when it is a path suffix of anything in the repo.
76
76
  * @param {{ nodes: any[], edges: any[] }} topology
77
77
  * @param {Set<string>} paths every path in the repo (core/repo.js `repoPaths`)
78
+ * @param {(p: string) => boolean} [reach] whether a path `paths` does not list is still in the repo, by a symlink that stays in it (core/repo.js `reachable`)
78
79
  * @returns {string[]}
79
80
  */
80
- export function missingPaths(topology, paths) {
81
+ export function missingPaths(topology, paths, reach = () => false) {
81
82
  const all = [...paths];
82
- const exists = (p) => paths.has(p) || all.some((q) => q.endsWith(`/${p}`));
83
+ const exists = (p) => paths.has(p) || all.some((q) => q.endsWith(`/${p}`)) || reach(p);
83
84
  const found = [];
84
85
  const check = (where, text) => {
85
86
  for (const m of String(text || '').matchAll(CITED_PATH)) {
@@ -89,7 +90,7 @@ export function missingPaths(topology, paths) {
89
90
  };
90
91
  for (const n of topology.nodes) {
91
92
  for (const f of String(n.file || '').split(/,\s*/).filter(Boolean)) {
92
- if (!paths.has(f)) found.push(`Node "${n.id}" has file "${f}", which is not in the repo`);
93
+ if (!paths.has(f) && !reach(f)) found.push(`Node "${n.id}" has file "${f}", which is not in the repo`);
93
94
  }
94
95
  check(`Node "${n.id}" description`, n.desc);
95
96
  check(`Node "${n.id}" summary`, n.summary);
package/core/validate.js CHANGED
@@ -22,7 +22,7 @@ import { PERSONAS_FILE, validatePersonas } from './personas.js';
22
22
  import { CLOUD_FILE, cloudNodeProblems } from './cloud.js';
23
23
  import { deriveTopology } from './derive.js';
24
24
  import { missingPaths, planSync } from './sync.js';
25
- import { repoPaths, repoReader } from './repo.js';
25
+ import { reachable, repoPaths, repoReader } from './repo.js';
26
26
  import { checkThemeContrast } from './contrast.js';
27
27
  import { layerTokenWarnings, mapTokenWarnings, nodeColorNotes, nodeColorWarnings, quoted } from './map-tokens.js';
28
28
  import { layersMapWarnings } from './layers.js';
@@ -214,11 +214,11 @@ export function validateProposalFiles(topology, dir, root = path.dirname(dir)) {
214
214
  * @returns {string[]}
215
215
  */
216
216
  export function validatePersonasFile(root, roles = null) {
217
- const file = path.join(root, PERSONAS_FILE);
218
- if (!fs.existsSync(file)) return [];
217
+ const io = repoReader(root); // a file that leads out of the repo is not there, as for the personas deriver
218
+ if (!io.exists(PERSONAS_FILE)) return [];
219
219
  let parsed;
220
220
  try {
221
- parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
221
+ parsed = JSON.parse(io.read(PERSONAS_FILE));
222
222
  } catch (err) {
223
223
  return [`${PERSONAS_FILE} is not valid JSON: ${err.message}`];
224
224
  }
@@ -232,11 +232,11 @@ export function validatePersonasFile(root, roles = null) {
232
232
  * @returns {string[]}
233
233
  */
234
234
  export function validateCloudNodes(topology, root) {
235
- const file = path.join(root, CLOUD_FILE);
235
+ const io = repoReader(root); // a file that leads out of the repo is not there, as for the cloud deriver
236
236
  let parsed = null;
237
- if (fs.existsSync(file)) {
237
+ if (io.exists(CLOUD_FILE)) {
238
238
  try {
239
- parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
239
+ parsed = JSON.parse(io.read(CLOUD_FILE));
240
240
  } catch (err) {
241
241
  return [`${CLOUD_FILE} is not valid JSON: ${err.message}`];
242
242
  }
@@ -260,7 +260,7 @@ export async function validateRepo({ config, derivers, topology = readTopology(c
260
260
  if (!topology) return { errors: [`${config.topology} is missing: run cornfield sync to make it.`], warnings: [], derived: null, notes: [] };
261
261
  const errors = validateTopology(topology);
262
262
  try {
263
- errors.push(...missingPaths(topology, repoPaths(config.root)));
263
+ errors.push(...missingPaths(topology, repoPaths(config.root), reachable(repoReader(config.root))));
264
264
  } catch (err) {
265
265
  errors.push(`Checking the paths the map cites failed: ${err.message}`);
266
266
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.51.6",
3
+ "version": "0.51.8",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",
@@ -31,6 +31,7 @@
31
31
 
32
32
  import { CLOUD_FILE, deriveCloud, EVIDENCE_KINDS } from '../../core/cloud.js';
33
33
  import { hostsIn } from './hosts.js';
34
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
34
35
  import { caddyEvidence, dockerfileSources, imageRef, workflowSources } from './sources.js';
35
36
 
36
37
  const WORKFLOW_DIRS = ['.github/workflows', '.forgejo/workflows'];
@@ -75,6 +76,7 @@ export default {
75
76
  const known = [...ctx.nodes, ...((ctx.map && ctx.map.nodes) || []).filter((n) => !ctx.nodes.some((d) => d.id === n.id))];
76
77
  const evidence = [];
77
78
  const warnings = [];
79
+ const problems = [];
78
80
  const nodes = [];
79
81
  const edges = [];
80
82
  const add = (piece) => evidence.push(piece);
@@ -89,7 +91,7 @@ export default {
89
91
  };
90
92
 
91
93
  // Hosts in code and pages
92
- const roots = Array.isArray(options.code) ? options.code
94
+ const roots = Array.isArray(options.code) ? options.code.filter((dir) => !(leavesRepo(ctx, dir) && problems.push(outsideProblem('cloud', dir))))
93
95
  : (ctx.info.starter?.packages || []).map((p) => p.dir);
94
96
  const files = [...new Set(roots.flatMap((dir) => ctx.walk(dir === '.' ? '' : dir, (f) => (CODE_FILE.test(f) || PAGE_FILE.test(f)) && !NOT_SHIPPED.test(f))))].sort();
95
97
  for (const file of files) {
@@ -123,7 +125,12 @@ export default {
123
125
  }
124
126
 
125
127
  // CI workflows
126
- const workflowFiles = WORKFLOW_DIRS.flatMap((dir) => ctx.list(dir).filter((f) => /\.ya?ml$/.test(f)).map((f) => `${dir}/${f}`));
128
+ // A workflow file that is a link out of the repo, or to nothing, is not read (core/repo.js): said, and left out
129
+ const workflowFiles = WORKFLOW_DIRS.flatMap((dir) => ctx.list(dir).filter((f) => /\.ya?ml$/.test(f)).map((f) => `${dir}/${f}`)).filter((file) => {
130
+ if (ctx.exists(file)) return true;
131
+ warnings.push(`cloud: ${file} ${ctx.inside(file) ? 'is a link to nothing' : 'is a link to somewhere outside the repo'}; it is not read.`);
132
+ return false;
133
+ });
127
134
  if (workflowFiles.length) {
128
135
  const yaml = await loadYaml();
129
136
  if (!yaml) warnings.push(`cloud: ${workflowFiles.length} CI workflow file(s) not read: install the optional dependency js-yaml to draw what CI pulls.`);
@@ -145,6 +152,7 @@ export default {
145
152
 
146
153
  // Caddyfiles the config names
147
154
  for (const { file, from } of options.caddyfiles || []) {
155
+ if (leavesRepo(ctx, file)) { problems.push(outsideProblem('cloud', file)); continue; }
148
156
  if (!ctx.exists(file)) { warnings.push(`cloud: caddyfile ${file} does not exist.`); continue; }
149
157
  for (const e of caddyEvidence(ctx.read(file))) add({ ...e, from, when: 'renew', file });
150
158
  }
@@ -152,7 +160,7 @@ export default {
152
160
  if (!ctx.exists(CLOUD_FILE)) {
153
161
  const hosts = new Set(evidence.filter((e) => e.match.kind === 'host').map((e) => e.match.value));
154
162
  if (evidence.length) warnings.push(`cloud: the code reaches ${hosts.size} outside host(s) and ${evidence.length - [...evidence].filter((e) => e.match.kind === 'host').length} other outside source(s); add ${CLOUD_FILE} to draw them (docs/cloud.md).`);
155
- return { nodes: [], edges: [], warnings, evidence: [] };
163
+ return { nodes: [], edges: [], warnings, problems, evidence: [] };
156
164
  }
157
165
  // What the derivers before this one found (a repo's own deriver may add `lib`, `route`, `env` … evidence)
158
166
  const all = [...(ctx.evidence || []), ...evidence];
@@ -170,6 +178,7 @@ export default {
170
178
  nodes: [...nodes, ...cloud.nodes],
171
179
  edges: [...edges, ...cloud.edges],
172
180
  warnings: [...warnings, ...cloud.warnings],
181
+ problems,
173
182
  ownedIds: [...nodes.map((n) => n.id), ...cloud.ownedIds],
174
183
  evidence,
175
184
  info: { unknownPlans: cloud.unknown },
@@ -35,6 +35,7 @@
35
35
  */
36
36
 
37
37
  import { caddyRoutes, labelsOf, traefikRoutes } from './routes.js';
38
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
38
39
 
39
40
  export const COMPOSE_NAMES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
40
41
  const CADDYFILE = /(?:^|\/)(?:Caddyfile|[\w.-]+\.caddyfile)$/i;
@@ -86,10 +87,11 @@ const targetPort = (p) => {
86
87
  };
87
88
 
88
89
  /** The compose files: the config's, else the first compose name in each folder */
89
- function composeFiles(ctx, options) {
90
+ function composeFiles(ctx, options, problems) {
90
91
  if (Array.isArray(options.files)) {
91
- for (const f of options.files) if (!ctx.exists(f)) throw new Error(`compose file ${f} does not exist.`);
92
- return [...options.files];
92
+ const named = options.files.filter((f) => !(leavesRepo(ctx, f) && problems.push(outsideProblem('compose', f))));
93
+ for (const f of named) if (!ctx.exists(f)) throw new Error(`compose file ${f} does not exist.`);
94
+ return named;
93
95
  }
94
96
  const found = ctx.walk('', (f) => COMPOSE_NAMES.includes(f.slice(f.lastIndexOf('/') + 1)));
95
97
  const byDir = new Map();
@@ -109,9 +111,10 @@ const compose = {
109
111
  async derive(ctx) {
110
112
  const options = ctx.options || {};
111
113
  const parent = options.parent || 'root';
112
- const files = composeFiles(ctx, options);
114
+ const problems = [];
115
+ const files = composeFiles(ctx, options, problems);
113
116
  const warnings = [];
114
- if (!files.length) return { nodes: [], edges: [], warnings, info: { stacks: [] } };
117
+ if (!files.length) return { nodes: [], edges: [], warnings, problems, info: { stacks: [] } };
115
118
  const yaml = await loadYaml();
116
119
  if (!yaml) throw new Error(`${files.length} compose file(s) and no YAML reader: install the optional dependency js-yaml (npm install js-yaml).`);
117
120
 
@@ -170,6 +173,7 @@ const compose = {
170
173
  const caddyfiles = Array.isArray(options.caddyfiles) ? options.caddyfiles : ctx.walk('', (f) => CADDYFILE.test(f));
171
174
  const outside = new Set();
172
175
  for (const file of caddyfiles) {
176
+ if (leavesRepo(ctx, file)) { problems.push(outsideProblem('compose', file)); continue; }
173
177
  if (!ctx.exists(file)) { warnings.push(`compose: caddyfile ${file} does not exist.`); continue; }
174
178
  const here = dirOf(file);
175
179
  for (const r of caddyRoutes(ctx.read(file))) {
@@ -217,7 +221,7 @@ const compose = {
217
221
  }
218
222
 
219
223
  return {
220
- nodes, edges, warnings, ownedIds,
224
+ nodes, edges, warnings, problems, ownedIds,
221
225
  info: { stacks: stacks.map((s) => ({ id: s.id, name: s.name, dir: s.dir, file: s.file, containers: s.services.map((x) => containerId(s, x)) })) },
222
226
  };
223
227
  },
@@ -18,6 +18,7 @@
18
18
 
19
19
  import path from 'node:path';
20
20
  import { markdownLinks, renderMarkdown } from './markdown.js';
21
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
21
22
 
22
23
  export const DEFAULT_PATHS = ['README.md', 'docs'];
23
24
 
@@ -44,7 +45,7 @@ export function docFiles(io, paths, refuse = () => {}) {
44
45
  const told = new Set();
45
46
  for (const p of paths) {
46
47
  const rel = path.posix.normalize(p.replace(/^\.\/+/, '').replace(/\/+$/, '') || '.');
47
- if (path.isAbsolute(p) || path.win32.isAbsolute(p) || rel === '..' || rel.startsWith('../') || !inside(rel)) { refuse(`docs: ${JSON.stringify(p)} is outside the repo; only files and folders of the repo are read.`, 'problem'); continue; }
48
+ if (leavesRepo({ inside }, p)) { refuse(outsideProblem('docs', p), 'problem'); continue; }
48
49
  if (io.isDir(rel)) {
49
50
  io.walk(rel, isMarkdown, (f, why) => { const m = `docs: ${f || '.'} ${SKIPPED[why]}.`; if (!told.has(m)) { told.add(m); refuse(m, 'warning'); } }, seen).forEach((f) => out.add(f));
50
51
  } else if (isMarkdown(rel) && io.exists(rel)) out.add(rel);
@@ -25,6 +25,8 @@
25
25
  * hand-written page under that app is removed. YAML needs the optional dependency js-yaml.
26
26
  */
27
27
 
28
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
29
+
28
30
  const SPEC_FILE = /(?:^|\/)(?:openapi|swagger|[\w.-]+\.openapi|opencollection)\.(?:json|ya?ml)$/i;
29
31
  const METHOD_ORDER = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE'];
30
32
  export const DEFAULT_APP = 'app-api';
@@ -127,9 +129,10 @@ export function specKind(doc) {
127
129
  }
128
130
 
129
131
  /** The specs to read: `[{ file, app, prefix }]` */
130
- function specsOf(ctx, options, warnings) {
131
- if (Array.isArray(options.specs)) return options.specs.map((s) => ({ app: DEFAULT_APP, ...s }));
132
- if (typeof options.file === 'string') return [{ file: options.file, app: options.app || DEFAULT_APP, prefix: options.prefix }];
132
+ function specsOf(ctx, options, warnings, problems) {
133
+ const inRepo = (s) => !(leavesRepo(ctx, s.file) && problems.push(outsideProblem('openapi', s.file)));
134
+ if (Array.isArray(options.specs)) return options.specs.map((s) => ({ app: DEFAULT_APP, ...s })).filter(inRepo);
135
+ if (typeof options.file === 'string') return [{ file: options.file, app: options.app || DEFAULT_APP, prefix: options.prefix }].filter(inRepo);
133
136
  const found = ctx.walk('', (f) => SPEC_FILE.test(f));
134
137
  if (found.length > 1) {
135
138
  warnings.push(`openapi: ${found.length} API description files (${found.join(', ')}); name the ones to draw: { use: 'openapi', options: { specs: [{ file, app }] } }.`);
@@ -145,7 +148,8 @@ const openapi = {
145
148
  async derive(ctx) {
146
149
  const options = ctx.options || {};
147
150
  const warnings = [];
148
- const specs = specsOf(ctx, options, warnings);
151
+ const problems = [];
152
+ const specs = specsOf(ctx, options, warnings, problems);
149
153
  const nodes = [];
150
154
  const edges = [];
151
155
  const ownedIds = [];
@@ -191,7 +195,7 @@ const openapi = {
191
195
  }
192
196
  if (!endpoints.length) warnings.push(`openapi: ${spec.file} describes no endpoints.`);
193
197
  }
194
- return { nodes, edges, warnings, ownedIds, pageOwners, info: { specs: specs.map((s) => ({ file: s.file, app: s.app })) } };
198
+ return { nodes, edges, warnings, problems, ownedIds, pageOwners, info: { specs: specs.map((s) => ({ file: s.file, app: s.app })) } };
195
199
  },
196
200
  };
197
201
 
@@ -35,6 +35,7 @@
35
35
  */
36
36
 
37
37
  import { LANGUAGES, TEST_FILES, docSummary, expandMembers, goImports, goManifest, goWorkDirs, manifestLanguage, pyName, pythonImports, pythonManifest, rustManifest, rustName, rustUses } from './languages.js';
38
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
38
39
 
39
40
  const DEFAULT_EXTENSIONS = LANGUAGES.js.extensions;
40
41
  const TEST_DIRS = new Set(['test', 'tests', '__tests__', '__fixtures__', 'fixtures']);
@@ -105,17 +106,10 @@ const readJson = (io, rel) => {
105
106
  };
106
107
  const join = (dir, name) => (dir ? `${dir}/${name}` : name);
107
108
 
108
- /** Every file under `dir` that `test` accepts, not going into the folders `prune` names */
109
- function walkPruned(io, dir, prune, test) {
110
- if (!prune.length) return io.walk(dir, test);
111
- const skip = new Set(prune);
112
- return io.list(dir).flatMap((name) => {
113
- const child = join(dir, name);
114
- if (!io.isDir(child)) return test(child) ? [child] : [];
115
- if (skip.has(name) || name.endsWith('.egg-info')) return [];
116
- return walkPruned(io, child, prune, test);
117
- }).filter((f) => !f.split('/').some((s) => s === 'node_modules' || s === '.git'));
118
- }
109
+ /** Every file under `dir` that `test` accepts, not going into the folders `prune` names: the repo's own walk, so a symlink out of the repo or a loop of links is not followed */
110
+ const walkPruned = (io, dir, prune, test) => (prune.length
111
+ ? io.walk(dir, test, undefined, undefined, (name) => prune.includes(name) || name.endsWith('.egg-info'))
112
+ : io.walk(dir, test));
119
113
 
120
114
  /** The language most of a folder's source files are in (JavaScript when there are none) */
121
115
  function languageOf(io, dir) {
@@ -178,10 +172,13 @@ function uvMembers(io) {
178
172
  }
179
173
 
180
174
  /** The repo's packages: `[{ dir, lang, name, summary, manifest, deps }]` */
181
- function findPackages(io, options) {
175
+ function findPackages(io, options, problems) {
182
176
  const rootManifest = readJson(io, 'package.json') || {};
183
177
  const ws = Array.isArray(rootManifest.workspaces) ? rootManifest.workspaces : rootManifest.workspaces?.packages;
184
- if (Array.isArray(options.packages)) return expandPatterns(options.packages, io).map((dir) => packageAt(io, dir, languageOf(io, dir)));
178
+ if (Array.isArray(options.packages)) {
179
+ const named = options.packages.filter((p) => !(leavesRepo(io, String(p).replace(/\\/g, '/').replace(/\/\*$/, '')) && problems.push(outsideProblem('starter', p))));
180
+ return expandPatterns(named, io).map((dir) => packageAt(io, dir, languageOf(io, dir)));
181
+ }
185
182
  const others = otherPackages(io);
186
183
  let js = [];
187
184
  if (Array.isArray(ws) && ws.length) js = expandPatterns(ws, io);
@@ -248,7 +245,8 @@ const starter = {
248
245
  const isTest = (f, lang) => (TEST_FILES[lang] || TEST_FILES.js).test(f) || TEST_FILES.js.test(f) || f.split('/').some((s) => TEST_DIRS.has(s));
249
246
  const isSourceOf = (lang) => (f) => extOf(lang).some((e) => f.endsWith(e)) && (options.tests || !isTest(f, lang));
250
247
  const rootManifest = readJson(ctx, 'package.json') || {};
251
- const packages = findPackages(ctx, options);
248
+ const problems = [];
249
+ const packages = findPackages(ctx, options, problems);
252
250
  const nodes = [{ id: 'root', label: rootManifest.name || ctx.config?.title || 'repo', type: 'root', ...(ctx.exists('package.json') ? { file: 'package.json' } : {}) }];
253
251
  const edges = [];
254
252
  const warnings = [];
@@ -363,7 +361,7 @@ const starter = {
363
361
  edges.push({ from: moduleId(a), to: moduleId(b), dashed: true, label: 'imports' });
364
362
  }
365
363
  if (!packages.length) warnings.push('starter: no packages found (no npm workspaces, Go modules, Rust crates or Python packages, and no top-level folder with source files). Set derivers: [{ use: "starter", options: { packages: ["src"] } }].');
366
- return { nodes, edges, warnings, info: { packages: packages.map((p) => ({ id: pid(p.dir), dir: p.dir, name: p.name, language: p.lang })) } };
364
+ return { nodes, edges, warnings, problems, info: { packages: packages.map((p) => ({ id: pid(p.dir), dir: p.dir, name: p.name, language: p.lang })) } };
367
365
  },
368
366
  };
369
367
 
@@ -33,6 +33,7 @@
33
33
  */
34
34
 
35
35
  import { slug } from '../compose/index.js';
36
+ import { leavesRepo, outsideProblem } from '../../core/repo.js';
36
37
 
37
38
  export const WORLD_FILE = 'stacks/world.json';
38
39
  const FILE_KEYS = ['version', 'hosts', 'runs'];
@@ -63,6 +64,7 @@ const world = {
63
64
  const options = ctx.options || {};
64
65
  const file = options.file || WORLD_FILE;
65
66
  const parent = options.parent || 'root';
67
+ if (leavesRepo(ctx, file)) return { nodes: [], edges: [], warnings: [], problems: [outsideProblem('world', file)], info: { machines: [] } };
66
68
  if (!ctx.exists(file)) return { nodes: [], edges: [], warnings: [], problems: [], info: { machines: [] } };
67
69
 
68
70
  let doc;
@@ -128,13 +128,12 @@
128
128
 
129
129
  import fs from 'node:fs';
130
130
  import { createHash } from 'node:crypto';
131
- import path from 'node:path';
132
131
  import { ForgeError, isMaintainer } from './forge.js';
133
132
  import { createRequest, findRunId, fencedBlocks, formatRunComment, isRunId, newRunId, runAuthors, runBlocksOf, runIdFromBranch, validateAnswer, validateReport, validateRequest, CONTRACT_VERSION, EDIT_GRACE_MS, MAX_BLOCKS, MAX_BLOCK_CHARS, MAX_NOTE_CHARS, MAX_TEXT_CHARS, RUN_TAG } from '../core/agent-contract.js';
134
133
  import { handWrittenMode, ideaLabel, limitDefaults, quietAfterMs, runnerQuietAfterMs } from '../core/config.js';
135
134
  import { runnerPresence } from './runner-presence.js';
136
135
  import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
137
- import { readTopology } from '../core/validate.js';
136
+ import { inside, readMap } from './files.js';
138
137
  import { findPullProposal, listPullProposals, pullProposals, readPullProposal } from './proposal-pulls.js';
139
138
  import { Refused, countAttempt, throttle } from './throttle.js';
140
139
  import { byFromText, byToText, runnerBy } from './review-tokens.js';
@@ -380,10 +379,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
380
379
  let mapCache = { stamp: '', nodes: /** @type {{ id: string, file?: string }[]} */ ([]), ids: /** @type {Set<string>} */ (new Set()) };
381
380
  function theMap() {
382
381
  let stamp = '';
383
- try { stamp = String(fs.statSync(path.join(config.root, config.topology)).mtimeMs); } catch { stamp = ''; }
382
+ try { const real = inside(config.root, config.topology); stamp = real ? String(fs.statSync(real).mtimeMs) : ''; } catch { stamp = ''; }
384
383
  if (stamp === mapCache.stamp) return mapCache;
385
384
  let nodes = [];
386
- try { nodes = readTopology(config)?.nodes ?? []; } catch { nodes = []; }
385
+ try { nodes = readMap(config)?.nodes ?? []; } catch { nodes = []; }
387
386
  nodes = Array.isArray(nodes) ? nodes.filter((n) => n && typeof n.id === 'string') : [];
388
387
  mapCache = { stamp, nodes, ids: new Set(nodes.map((n) => n.id)) };
389
388
  return mapCache;
@@ -85,16 +85,17 @@ export function createComponents({ dir }) {
85
85
  if (!stats.isFile() || stats.size > MAX_BYTES) return null;
86
86
  // lstat looks at the last segment only: a folder on the way (`chunks`) that is a link out of the build is refused too. The build folder
87
87
  // itself may be a link; what is served is what lies, really, inside it
88
+ let real;
88
89
  try {
89
- const real = fs.realpathSync(file);
90
+ real = fs.realpathSync(file);
90
91
  const realRoot = fs.realpathSync(root);
91
92
  if (real !== path.join(realRoot, ...name.split('/'))) return null;
92
93
  } catch { return null; }
93
- const stamp = `${stats.size}:${stats.mtimeMs}`;
94
+ const stamp = `${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}:${stats.ino}`;
94
95
  const known = bodies.get(name);
95
96
  if (known?.stamp === stamp) return known;
96
97
  try {
97
- const body = fs.readFileSync(file);
98
+ const body = fs.readFileSync(real); // the path that was checked, not the one written
98
99
  const entry = { stamp, body, etag: createHash('sha256').update(body).digest('base64url').slice(0, 27) };
99
100
  bodies.set(name, entry);
100
101
  return entry;
package/server/db.js CHANGED
@@ -402,6 +402,13 @@ export function openStore(dataDir, { file = DB_FILE, migrations = MIGRATIONS } =
402
402
  if (typeof dataDir !== 'string' || dataDir === '') throw new Error('openStore needs the data folder.');
403
403
  fs.mkdirSync(dataDir, { recursive: true, mode: 0o700 });
404
404
  const where = path.join(dataDir, file);
405
+ // The file and the ones SQLite keeps beside it are plain files or not there yet, never a link: SQLite would write through one, and the
406
+ // chmod below would change its target (a data folder put inside a checkout could hold a committed link)
407
+ for (const name of [where, `${where}-wal`, `${where}-shm`, `${where}-journal`]) {
408
+ let stats = null;
409
+ try { stats = fs.lstatSync(name); } catch { /* not there yet */ }
410
+ if (stats && !stats.isFile()) throw new Error(`${name} is not a plain file: cornfield keeps its database only in plain files in the data folder.`);
411
+ }
405
412
  const db = new DatabaseSync(where);
406
413
  try {
407
414
  fs.chmodSync(where, 0o600);
package/server/files.js CHANGED
@@ -6,6 +6,9 @@
6
6
  * repo's map and registry, and the folders of the browser modules its config names. Everything else in
7
7
  * the checkout (.env files, databases, sources) is not reachable.
8
8
  *
9
+ * Every file the server reads or sends for a request, the config or the repo goes through `inside`, which judges its REAL path, symlinks
10
+ * followed, against the real folder it was asked from: a link that leads out is refused as a file that is not there.
11
+ *
9
12
  * Proposals are found here too (server/proposal-walk.js does the walking, asynchronously): `<proposals>/*.json` in the
10
13
  * checkout and the same under each folder of the configured worktrees folder (git worktrees with unpushed drafts, those
11
14
  * that differ from the checkout's). A request can only name one the listing found itself; what it says is never joined
@@ -15,6 +18,7 @@
15
18
  import fs from 'node:fs';
16
19
  import path from 'node:path';
17
20
  import { createHash } from 'node:crypto';
21
+ import { pipeline } from 'node:stream';
18
22
  import { PROPOSAL_FILE, createProposalLister } from './proposal-walk.js';
19
23
 
20
24
  /** Content-Type by lower-case file extension (with the dot) */
@@ -50,29 +54,90 @@ export function decodePath(pathname) {
50
54
  }
51
55
  }
52
56
 
57
+ /** Open flags for a plain read: never follow a link at the last step, never wait on a pipe (undefined where the platform has no such flag) */
58
+ const READ_FLAGS = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0);
59
+
60
+ /** Whether `real` is strictly under `dir`, both real paths, by whole segments: `/x/repo-other` is not under `/x/repo` */
61
+ export function isUnder(dir, real) {
62
+ const r = path.relative(dir, real);
63
+ return r !== '' && r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r);
64
+ }
65
+
53
66
  /**
54
- * The file `rel` names inside `dir`, or null when it would leave it. The path is resolved before it is
55
- * checked, so `..`, an encoded `..%2f` and (on Windows) a backslash all land outside and come back null.
67
+ * The file `rel` names under `dir`, as written: resolved, so `..`, an encoded `..%2f` and (on Windows) a backslash land outside and come
68
+ * back null, but no link is followed. This is the name a route's allowlist is judged by; to read or send, use `inside`.
56
69
  * @param {string} dir an absolute folder
57
70
  * @param {string} rel a path under it, with or without a leading slash
58
71
  */
59
- export function inside(dir, rel) {
72
+ export function named(dir, rel) {
60
73
  if (typeof rel !== 'string' || rel.includes('\0')) return null;
61
74
  const root = path.resolve(dir);
62
75
  const file = path.resolve(root, `.${rel.startsWith('/') ? '' : '/'}${rel}`);
63
76
  return file.startsWith(root + path.sep) ? file : null;
64
77
  }
65
78
 
66
- /** The ETag of each file served, with the size and mtime it was taken at */
79
+ /**
80
+ * The one check every file the server reads or sends goes through: the REAL path of the file `rel` names under `dir`, or null when it is
81
+ * not there, would leave `dir` as written (`..`), or leads out of it through a link. Real path against real path, by whole segments,
82
+ * so a folder that is itself reached through a link (a repo, an install) is judged by where it really is, and `/x/repo-other` is not
83
+ * inside `/x/repo`. A refused file and a missing file are both null: a caller cannot tell them apart, and says the same to a visitor.
84
+ * Read or send the path this returns, never the one written: that is the one that was checked.
85
+ * @param {string} dir an absolute folder
86
+ * @param {string} rel a path under it, with or without a leading slash
87
+ * @returns {string|null}
88
+ */
89
+ export function inside(dir, rel) {
90
+ const file = named(dir, rel);
91
+ if (!file) return null;
92
+ try {
93
+ const real = fs.realpathSync.native(file);
94
+ return isUnder(fs.realpathSync.native(dir), real) ? real : null;
95
+ } catch {
96
+ return null;
97
+ }
98
+ }
99
+
100
+ /**
101
+ * The bytes of a plain file at a path `inside` gave, read through one descriptor opened without following a link, so a link swapped in
102
+ * since the check is not followed and the size checked is the file read. Null when it is not a plain file, is over `maxBytes`, or cannot be read.
103
+ * @param {string} real
104
+ * @param {number} [maxBytes]
105
+ * @returns {{ body: Buffer, stats: import('node:fs').Stats } | null}
106
+ */
107
+ export function readPlain(real, maxBytes = Infinity) {
108
+ let fd;
109
+ try {
110
+ fd = fs.openSync(real, READ_FLAGS);
111
+ const stats = fs.fstatSync(fd);
112
+ if (!stats.isFile() || stats.size > maxBytes) return null;
113
+ return { body: fs.readFileSync(fd), stats };
114
+ } catch {
115
+ return null;
116
+ } finally {
117
+ if (fd !== undefined) try { fs.closeSync(fd); } catch { /* closed */ }
118
+ }
119
+ }
120
+
121
+ /**
122
+ * The repo's map, parsed: null when `config.topology` is not there or does not stay inside the repo. Throws on text that is not JSON.
123
+ * @param {{ root: string, topology: string }} config
124
+ */
125
+ export function readMap(config) {
126
+ const real = inside(config.root, config.topology);
127
+ const got = real && readPlain(real);
128
+ return got ? JSON.parse(got.body.toString('utf8')) : null;
129
+ }
130
+
131
+ /** The ETag of each file served, by the real path served, with the size, mtime, ctime and inode it was taken at */
67
132
  const etags = new Map();
68
133
 
69
- function etagOf(filePath, stats) {
70
- const stamp = `${stats.size}:${stats.mtimeMs}`;
71
- const known = etags.get(filePath);
134
+ function etagOf(real, fd, stats) {
135
+ const stamp = `${stats.size}:${stats.mtimeMs}:${stats.ctimeMs}:${stats.ino}`; // ctime too: a write that puts the mtime back still moves it
136
+ const known = etags.get(real);
72
137
  if (known && known.stamp === stamp) return known.etag;
73
138
  try {
74
- const etag = `W/"${createHash('sha1').update(fs.readFileSync(filePath)).digest('base64url').slice(0, 22)}"`;
75
- etags.set(filePath, { stamp, etag });
139
+ const etag = `W/"${createHash('sha1').update(fs.readFileSync(fd)).digest('base64url').slice(0, 22)}"`;
140
+ etags.set(real, { stamp, etag });
76
141
  return etag;
77
142
  } catch {
78
143
  return null;
@@ -89,25 +154,42 @@ export function notFound(res, reqPath) {
89
154
 
90
155
  /**
91
156
  * Sends one file (it must be a plain file), `no-cache` with an ETag, so the browser asks every time and an
92
- * unchanged file answers 304. A missing file is a 404.
157
+ * unchanged file answers 304. A missing file is a 404. `filePath` is the real path `inside` gave: it is opened once, without following a
158
+ * link, and the type, the ETag and the body all come from that one descriptor. The Content-Type is the file's own, by its real name.
93
159
  * @param {import('node:http').IncomingMessage} req
94
160
  * @param {import('node:http').ServerResponse} res
95
161
  * @param {string|null} filePath
96
162
  * @param {string} reqPath for the 404's text
97
163
  */
98
164
  export function sendFile(req, res, filePath, reqPath) {
165
+ let fd = null;
99
166
  let stats = null;
100
- try { stats = filePath ? fs.statSync(filePath) : null; } catch { stats = null; }
101
- if (!stats || !stats.isFile()) return notFound(res, reqPath);
102
- const etag = etagOf(filePath, stats);
167
+ try {
168
+ if (filePath) {
169
+ fd = fs.openSync(filePath, READ_FLAGS);
170
+ stats = fs.fstatSync(fd);
171
+ }
172
+ } catch { stats = null; }
173
+ if (fd === null || !stats || !stats.isFile()) {
174
+ if (fd !== null) try { fs.closeSync(fd); } catch { /* closed */ }
175
+ return notFound(res, reqPath);
176
+ }
177
+ const etag = etagOf(filePath, fd, stats);
178
+ // Typed by the file sent, not by the name asked for: with nosniff the type is binding, so a `.js` name that is a link to another kind of file
179
+ // in the repo is not run as a script (and a file that is not a link has one name, so the two agree)
103
180
  const headers = { 'Content-Type': mime(filePath), 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff', ...(etag ? { ETag: etag } : {}) };
104
181
  if (etag && matchesEtag(req.headers['if-none-match'], etag)) {
182
+ fs.closeSync(fd);
105
183
  res.writeHead(304, headers);
106
184
  return res.end();
107
185
  }
108
186
  res.writeHead(200, headers);
109
- if (req.method === 'HEAD') return res.end();
110
- fs.createReadStream(filePath).pipe(res);
187
+ if (req.method === 'HEAD') {
188
+ fs.closeSync(fd);
189
+ return res.end();
190
+ }
191
+ // `pipeline` closes the descriptor however the answer ends: sent, failed, the visitor gone mid-body, or gone before this was reached
192
+ pipeline(fs.createReadStream(filePath, { fd, start: 0 }), res, () => {});
111
193
  }
112
194
 
113
195
  // ---------------------------------------------------------------------------
@@ -48,8 +48,6 @@
48
48
  * for up to a day, instead of nothing.
49
49
  */
50
50
 
51
- import fs from 'node:fs';
52
- import path from 'node:path';
53
51
  import { createHash } from 'node:crypto';
54
52
  import { ForgeError, canRerun, hasAdapter, isMaintainer, isTagName, rateLimitWords } from './forge.js';
55
53
  import { actionOf, countAttempt, serveAction, serveIdea } from './forge-actions.js';
@@ -61,7 +59,7 @@ import { listPullProposals } from './proposal-pulls.js';
61
59
  import { deploysOf } from './deploys.js';
62
60
  import { readBody, sameOrigin } from './proposals.js';
63
61
  import { releaseNotes } from './release-notes.js';
64
- import { readTopology } from '../core/validate.js';
62
+ import { inside, readMap, readPlain } from './files.js';
65
63
 
66
64
  /** How long a kept answer is served without asking the forge again */
67
65
  export const FRESH_MS = 60_000;
@@ -109,10 +107,14 @@ function sinceOf(value) {
109
107
  /** The map the notes are grouped by and the package's version, read from the checkout each time (they change with a sync) */
110
108
  function notesInput(config, since) {
111
109
  let topology = null;
112
- try { topology = readTopology(config); } catch { topology = null; }
110
+ try { topology = readMap(config); } catch { topology = null; }
113
111
  if (!topology) throw new ForgeError(`${config.topology} is not there yet: run cornfield sync, so the notes can follow the map.`, { code: 'not-found' });
114
112
  let version = null;
115
- try { version = JSON.parse(fs.readFileSync(path.join(config.root, 'package.json'), 'utf8')).version ?? null; } catch { version = null; }
113
+ try {
114
+ const real = inside(config.root, 'package.json');
115
+ const pkg = real && readPlain(real);
116
+ version = pkg ? JSON.parse(pkg.body.toString('utf8')).version ?? null : null;
117
+ } catch { version = null; }
116
118
  return { topology, since, version, breakingLabel: config.releaseNotes?.breakingLabel };
117
119
  }
118
120
 
@@ -152,7 +154,7 @@ function routeOf(reqPath, url, config, where, hooks = null) {
152
154
  // Whatever a look reads is news to the hooks once (thread.opened, thread.message, thread.linked), as the spec PRs are
153
155
  if (hooks) {
154
156
  let nodes = [];
155
- try { nodes = readTopology(config)?.nodes || []; } catch { nodes = []; }
157
+ try { nodes = readMap(config)?.nodes || []; } catch { nodes = []; }
156
158
  hooks.threadsSeen(forge.repo, snapshotOf(found.gathered, nodes)).catch(() => {});
157
159
  }
158
160
  return { items: found.items, label, problem: found.problem };
@@ -35,6 +35,11 @@ export const MAX_ENTRIES = 20000;
35
35
  const MAX_WALKS = 16;
36
36
  const DAY_MS = 86_400_000;
37
37
 
38
+ /** Whether real path `real` is `dir` or under it, by whole segments (`/x/repo-other` is not under `/x/repo`); server/files.js `inside` holds the same rule for files */
39
+ const under = (dir, real) => {
40
+ const r = path.relative(dir, real);
41
+ return r === '' || (r !== '..' && !r.startsWith(`..${path.sep}`) && !path.isAbsolute(r));
42
+ };
38
43
  const sha256 = (text) => createHash('sha256').update(text).digest('hex');
39
44
  const countNewlines = (text) => { let n = 0; for (let i = text.indexOf('\n'); i !== -1; i = text.indexOf('\n', i + 1)) n++; return n; };
40
45
  const turn = () => new Promise((resolve) => setImmediate(resolve));
@@ -94,13 +99,23 @@ export function createProposalLister({ fs = fsp, concurrency = CONCURRENCY, maxE
94
99
  const { cache } = state;
95
100
  const seen = new Set();
96
101
  const base = path.resolve(where.root);
102
+ // A fake `fs` (a test's) may not have `realpath`: the real one answers then
103
+ const realpath = (p) => (fs.realpath ?? fsp.realpath).call(fs, p);
104
+ let realBase;
105
+ try { realBase = await realpath(base); } catch { return []; }
97
106
  const maxAgeMs = where.worktreeMaxAgeDays > 0 ? where.worktreeMaxAgeDays * DAY_MS : null;
98
107
  const clock = where.now || now;
99
108
 
100
- /** The proposal files directly in `dir`, each with its lstat; a folder that is not there has none */
101
- async function scan(dir) {
109
+ /**
110
+ * The proposal files directly in `dir`, each with its lstat; a folder that is not there has none, nor has one whose real path is not
111
+ * under `within` (a real path: the repo's, or the worktree's). The files are named by the real folder, which is what was checked.
112
+ */
113
+ async function scan(dir, within) {
102
114
  let names;
103
115
  try {
116
+ const real = await io(() => realpath(dir));
117
+ if (!under(within, real)) return [];
118
+ dir = real;
104
119
  names = await io(() => fs.readdir(dir));
105
120
  } catch { return []; }
106
121
  const wanted = names.filter((name) => PROPOSAL_FILE.test(name) && !name.endsWith('.review.json'));
@@ -147,21 +162,25 @@ export function createProposalLister({ fs = fsp, concurrency = CONCURRENCY, maxE
147
162
 
148
163
  const out = [];
149
164
  const proposals = where.proposals;
150
- const checkoutFiles = await scan(path.join(base, proposals));
165
+ const checkoutFiles = await scan(path.join(base, proposals), realBase);
151
166
  const checkoutRecs = new Map();
152
167
  await Promise.all(checkoutFiles.map(async (f) => checkoutRecs.set(f.name, await recordOf(f))));
153
168
  if (!only || only === 'checkout') for (const f of checkoutFiles) out.push({ slug: f.slug, source: 'checkout', file: f.file, parsed: checkoutRecs.get(f.name).parsed });
154
169
 
155
170
  if (where.worktrees && only !== 'checkout') {
156
- const dir = path.join(base, where.worktrees);
171
+ let dir = path.join(base, where.worktrees);
157
172
  let entries = [];
158
173
  try {
159
- entries = await io(() => fs.readdir(dir, { withFileTypes: true }));
174
+ const real = await io(() => realpath(dir));
175
+ if (under(realBase, real)) { // a worktrees folder that is a link out of the repo holds none
176
+ dir = real;
177
+ entries = await io(() => fs.readdir(dir, { withFileTypes: true }));
178
+ }
160
179
  } catch { /* no worktrees here */ }
161
180
  // A worktree called "checkout" would be taken for the checkout itself: not listed
162
181
  const names = entries.filter((w) => w.isDirectory() && w.name !== 'checkout' && (!only || w.name === only)).map((w) => w.name).sort();
163
182
  await Promise.all(names.map(async (name) => {
164
- const files = await scan(path.join(dir, name, proposals));
183
+ const files = await scan(path.join(dir, name, proposals), path.join(dir, name));
165
184
  if (maxAgeMs !== null && files.length && clock() - Math.max(...files.map((f) => f.mtimeMs)) > maxAgeMs) return;
166
185
  await Promise.all(files.map(async (f) => {
167
186
  const rec = await recordOf(f, checkoutRecs.get(f.name) || null);
@@ -41,8 +41,7 @@
41
41
  */
42
42
 
43
43
  import fsp from 'node:fs/promises';
44
- import path from 'node:path';
45
- import { findProposalFile, listProposalFiles } from './files.js';
44
+ import { findProposalFile, inside, listProposalFiles } from './files.js';
46
45
  import { summarize, proposalProblems } from '../core/proposal.js';
47
46
  import { ForgeError } from './forge.js';
48
47
  import { REVIEW_LIMIT, latestReview, migrateStage1Reviews, proposalHash } from './reviews.js';
@@ -65,9 +64,12 @@ function send(res, status, body, extra = {}) {
65
64
 
66
65
  /** The map the proposals are checked against: the checkout's topology.json, or null when it cannot be read */
67
66
  async function readTopology(where) {
68
- const file = path.join(where.root, where.topology || 'topology.json');
67
+ // The real path, inside the repo: a map that is a link out of it is no map (server/files.js `inside`)
68
+ const file = inside(where.root, where.topology || 'topology.json');
69
+ if (!file) return null;
69
70
  try {
70
71
  const st = await fsp.stat(file);
72
+ if (!st.isFile()) return null; // a pipe would hold a reader thread for good
71
73
  const stamp = `${st.mtimeMs}:${st.size}`;
72
74
  const known = topologies.get(file);
73
75
  if (known && known.stamp === stamp) return known.topology;
package/server/reviews.js CHANGED
@@ -48,7 +48,7 @@ import fs from 'node:fs';
48
48
  import { createHash } from 'node:crypto';
49
49
  import path from 'node:path';
50
50
  import { isMaintainer, ForgeError } from './forge.js';
51
- import { PROPOSAL_FILE } from './files.js';
51
+ import { PROPOSAL_FILE, isUnder } from './files.js';
52
52
  import { MAX_MOCKUPS, mockupPathProblem } from '../core/proposal.js';
53
53
  import { defuse } from './defuse.js';
54
54
 
@@ -261,12 +261,18 @@ export async function postNote(forge, n, text) {
261
261
  // Stage 1 reviews, once
262
262
  // ---------------------------------------------------------------------------
263
263
 
264
- /** What Stage 1 left: `<dataDir>/reviews/<source>/<slug>.review.json` files that are plain files */
264
+ /**
265
+ * What Stage 1 left: `<dataDir>/reviews/<source>/<slug>.review.json` files that are plain files, in folders that really lie in the data folder
266
+ * (a `reviews` or `<source>` folder that is a link out of it is not read, and nothing in it is renamed)
267
+ */
265
268
  function stage1Files(dataDir) {
266
269
  const out = [];
267
270
  const base = path.join(dataDir, 'reviews');
268
271
  let sources = [];
272
+ let realData;
269
273
  try {
274
+ realData = fs.realpathSync(dataDir);
275
+ if (!isUnder(realData, fs.realpathSync(base))) return out;
270
276
  sources = fs.readdirSync(base);
271
277
  } catch {
272
278
  return out; // nothing was ever kept here: the usual case
@@ -274,6 +280,7 @@ function stage1Files(dataDir) {
274
280
  for (const dir of sources) {
275
281
  let names = [];
276
282
  try {
283
+ if (!isUnder(realData, fs.realpathSync(path.join(base, dir)))) continue;
277
284
  names = fs.readdirSync(path.join(base, dir));
278
285
  } catch { continue; }
279
286
  for (const name of names) {
package/server/server.js CHANGED
@@ -62,7 +62,7 @@ import { BRAND_SVG_CSP, MANIFEST_PATH, appNameOf, brandAssetFile, brandImages, c
62
62
  import { clientStrings } from '../core/strings.js';
63
63
  import { clientLayers } from '../core/layers.js';
64
64
  import { MAX_THEME_ASSET_BYTES, MAX_THEME_BYTES, THEME_ASSET_PREFIX, THEME_NAME, THEME_SVG_CSP, clientTheme, cssProblems, cssUrls, fontOrigins, themeAssetFile, themeAssetPath, themeUrlTarget } from '../core/theme.js';
65
- import { decodePath, inside, notFound, sendFile } from './files.js';
65
+ import { decodePath, inside, isUnder, named, notFound, readPlain, sendFile } from './files.js';
66
66
  import { serveProposals } from './proposals.js';
67
67
  import { serveForge } from './forge-routes.js';
68
68
  import { hasAdapter } from './forge.js';
@@ -91,7 +91,9 @@ export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.j
91
91
  /** The explorer files the sign-in pages load: cornfield's tokens, their own stylesheet and the script that applies Light or Dark. Served without a session. */
92
92
  const SIGN_IN_FILES = new Set(['/explorer/tokens.css', '/explorer/sign-in.css', '/explorer/theme-boot.js']);
93
93
  /** cornfield's own browser sources, by request path */
94
- const BROWSER_PLUGINS = new Map(Object.values(BUILTIN_SOURCES).map((p) => [p, path.join(CORNFIELD_DIR, p)]));
94
+ const BROWSER_PLUGINS = new Set(Object.values(BUILTIN_SOURCES));
95
+ const CORE_DIR = path.join(CORNFIELD_DIR, 'core');
96
+ const PLUGINS_DIR = path.join(CORNFIELD_DIR, 'plugins');
95
97
  const PKG = JSON.parse(fs.readFileSync(path.join(CORNFIELD_DIR, 'package.json'), 'utf8'));
96
98
 
97
99
  const JSON_HEADERS = { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
@@ -138,8 +140,9 @@ function themeAssetsNamed(config, themeFile) {
138
140
  for (const [servedAt, rel] of themeFile) {
139
141
  try {
140
142
  const file = inside(config.root, rel);
141
- if (!file || fs.statSync(file).size > MAX_THEME_BYTES) continue;
142
- for (const ref of cssUrls(fs.readFileSync(file, 'utf8'))) {
143
+ const got = file && readPlain(file, MAX_THEME_BYTES);
144
+ if (!got) continue;
145
+ for (const ref of cssUrls(got.body.toString('utf8'))) {
143
146
  const target = themeUrlTarget(ref, servedAt);
144
147
  if (target.asset) out.add(target.asset);
145
148
  }
@@ -150,17 +153,14 @@ function themeAssetsNamed(config, themeFile) {
150
153
 
151
154
  /**
152
155
  * Serves one theme file: text/css and nosniff, only a file the config names, only a plain file whose real path is still inside the repo
153
- * (a link out is refused), only up to MAX_THEME_BYTES, and only if it passes the same CSS checks as `cornfield validate`.
156
+ * (server/files.js `inside`: a link out is refused), only up to MAX_THEME_BYTES, and only if it passes the same CSS checks as `cornfield validate`.
154
157
  */
155
158
  function sendTheme(req, res, config, rel, reqPath) {
156
159
  try {
157
- const file = inside(config.root, rel);
158
- const real = file && fs.realpathSync(file);
159
- const base = fs.realpathSync(config.root);
160
- if (!real || !real.startsWith(base + path.sep)) return notFound(res, reqPath);
161
- const stats = fs.statSync(real);
162
- if (!stats.isFile() || stats.size > MAX_THEME_BYTES) return notFound(res, reqPath);
163
- const text = fs.readFileSync(real, 'utf8');
160
+ const real = inside(config.root, rel);
161
+ const got = real && readPlain(real, MAX_THEME_BYTES);
162
+ if (!got) return notFound(res, reqPath);
163
+ const text = got.body.toString('utf8');
164
164
  if (cssProblems(text, { fonts: config.theme.fonts }).length) return notFound(res, reqPath);
165
165
  res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
166
166
  return res.end(req.method === 'HEAD' ? undefined : text);
@@ -364,18 +364,21 @@ export function createCornfieldServer(config, opts = {}) {
364
364
  let serverClosed = false;
365
365
  const proxies = Object.entries(config.proxy || {});
366
366
  const houseSource = config.sources.house && (config.sources.house === 'house' || config.sources.house.use === 'house') ? config.sources.house : null;
367
- const houseFile = houseSource && houseSource.options && houseSource.options.file ? inside(root, houseSource.options.file) : null;
367
+ // Where the file is is looked at when it is asked for (a link may change, and the file may not be there yet), never kept from now
368
+ const houseRel = houseSource && houseSource.options && houseSource.options.file ? houseSource.options.file : null;
368
369
  const haSource = config.sources.house && (config.sources.house === 'home-assistant' || config.sources.house.use === 'home-assistant') ? config.sources.house : null;
369
370
  const haOptions = (haSource && typeof haSource === 'object' && haSource.options) || {};
370
- const haFile = haOptions.file ? inside(root, haOptions.file) : null;
371
+ const haRel = haOptions.file || null;
371
372
  let haCache = null; // { until, promise }
372
373
  /** Home Assistant's house answer, over the house file's plan and other parts when there is one; reused for HA_CACHE_MS */
373
374
  const haHouse = () => {
374
375
  const now = Date.now();
375
376
  if (haCache && haCache.until > now) return haCache.promise;
376
377
  let file = null;
377
- if (haFile && fs.existsSync(haFile)) {
378
- try { file = JSON.parse(fs.readFileSync(haFile, 'utf8')); } catch { file = null; }
378
+ const haFile = haRel && inside(root, haRel);
379
+ const got = haFile && readPlain(haFile);
380
+ if (got) {
381
+ try { file = JSON.parse(got.body.toString('utf8')); } catch { file = null; }
379
382
  }
380
383
  const promise = homeAssistantHouse({ url: haOptions.url || env[HA_ENV.url], token: env[HA_ENV.token], file, ...homeAssistant });
381
384
  haCache = { until: now + HA_CACHE_MS, promise };
@@ -478,7 +481,7 @@ export function createCornfieldServer(config, opts = {}) {
478
481
  // Only an asset a theme file names in a url(): anything else beside the theme answers 401, as it would without a theme
479
482
  if (reqPath.startsWith(THEME_ASSET_PREFIX) && themeAssetsNamed(config, themeFile).has(reqPath.slice(THEME_ASSET_PREFIX.length))) return sendThemeAsset(req, res, config, reqPath);
480
483
  if (brandFile.has(reqPath)) return sendBrand(req, res, config, brandFile.get(reqPath), reqPath);
481
- if (SIGN_IN_FILES.has(reqPath)) return sendFile(req, res, path.join(EXPLORER_DIR, path.basename(reqPath)), reqPath);
484
+ if (SIGN_IN_FILES.has(reqPath)) return sendFile(req, res, inside(EXPLORER_DIR, path.basename(reqPath)), reqPath);
482
485
  }
483
486
  const gate = await auth.gate(req, res, reqPath, url);
484
487
  if (gate.done) return;
@@ -511,25 +514,29 @@ export function createCornfieldServer(config, opts = {}) {
511
514
  if (reqPath === '/cornfield/config.json') return sendJson(res, 200, clientConfig(config, signedIn));
512
515
  if (reqPath === '/topology.json') {
513
516
  const file = inside(root, config.topology);
514
- if (!file || !fs.existsSync(file)) return sendJson(res, 404, { error: `${config.topology} is not there yet: run cornfield sync` });
517
+ if (!file) return sendJson(res, 404, { error: `${config.topology} is not there yet: run cornfield sync` });
515
518
  return sendFile(req, res, file, reqPath);
516
519
  }
517
520
  if (reqPath === '/topology.cloud.json') {
518
521
  const file = inside(root, CLOUD_FILE);
519
- if (!file || !fs.existsSync(file)) return notFound(res, reqPath);
522
+ const got = file && readPlain(file);
523
+ if (!got) return notFound(res, reqPath);
520
524
  try {
525
+ const body = publicRegistry(got.body.toString('utf8'));
521
526
  res.writeHead(200, JSON_HEADERS);
522
- return res.end(req.method === 'HEAD' ? undefined : publicRegistry(fs.readFileSync(file, 'utf8')));
527
+ return res.end(req.method === 'HEAD' ? undefined : body);
523
528
  } catch {
524
529
  return sendJson(res, 422, { error: `${CLOUD_FILE} is not valid JSON` });
525
530
  }
526
531
  }
527
532
  if (reqPath === '/cornfield/house.json' && haSource) return sendJson(res, 200, { ok: true, data: await haHouse() });
528
533
  if (reqPath === '/cornfield/house.json') {
529
- if (!houseFile || !fs.existsSync(houseFile)) return sendJson(res, 404, { ok: false, error: 'No house file is configured (sources.house.options.file)' });
534
+ const houseFile = houseRel && inside(root, houseRel);
535
+ const got = houseFile && readPlain(houseFile);
536
+ if (!got) return sendJson(res, 404, { ok: false, error: 'No house file is configured (sources.house.options.file)' });
530
537
  try {
531
- const data = JSON.parse(fs.readFileSync(houseFile, 'utf8'));
532
- const at = data.at || fs.statSync(houseFile).mtime.toISOString();
538
+ const data = JSON.parse(got.body.toString('utf8'));
539
+ const at = data.at || got.stats.mtime.toISOString();
533
540
  return sendJson(res, 200, { ok: true, data: { ...data, at } });
534
541
  } catch (err) {
535
542
  return sendJson(res, 422, { ok: false, error: `The house file is not valid JSON: ${err.message}` });
@@ -553,21 +560,26 @@ export function createCornfieldServer(config, opts = {}) {
553
560
  return res.end(req.method === 'HEAD' ? undefined : fixtureCache.get(key));
554
561
  }
555
562
  if (reqPath.startsWith('/explorer/')) {
556
- const file = inside(EXPLORER_DIR, reqPath.slice('/explorer'.length));
557
- if (!file || !/\.(?:js|css)$/.test(file)) return notFound(res, reqPath);
558
- return sendFile(req, res, file, reqPath);
563
+ // The name asked for is what must be .js or .css; the file is judged against cornfield's own explorer folder, where that really is
564
+ if (!/\.(?:js|css)$/.test(reqPath)) return notFound(res, reqPath);
565
+ return sendFile(req, res, inside(EXPLORER_DIR, reqPath.slice('/explorer'.length)), reqPath);
559
566
  }
560
567
  if (reqPath.startsWith('/core/')) {
561
568
  const name = reqPath.slice('/core/'.length);
562
- return BROWSER_CORE.includes(name) ? sendFile(req, res, path.join(CORNFIELD_DIR, 'core', name), reqPath) : notFound(res, reqPath);
569
+ return BROWSER_CORE.includes(name) ? sendFile(req, res, inside(CORE_DIR, name), reqPath) : notFound(res, reqPath);
563
570
  }
564
- if (BROWSER_PLUGINS.has(reqPath)) return sendFile(req, res, BROWSER_PLUGINS.get(reqPath), reqPath);
571
+ if (BROWSER_PLUGINS.has(reqPath)) return sendFile(req, res, inside(PLUGINS_DIR, reqPath.slice('/plugins/'.length)), reqPath);
565
572
  if (reqPath.startsWith('/repo/')) {
566
573
  const rel = reqPath.slice('/repo/'.length);
567
- const file = inside(root, rel);
568
- const relNorm = file ? path.relative(root, file).split(path.sep).join('/') : null;
574
+ // The allowlist judges the name asked for, then the file it really is: a .js file, and (unless the import map names it) really inside a listed module folder
575
+ // (each judged by its own real path, so a module folder that is a link inside the repo works). A link in a module folder to anything else in
576
+ // the repo (a .env, a source, a database) is refused like a file that is not there
577
+ const written = named(root, rel);
578
+ const relNorm = written ? path.relative(root, written).split(path.sep).join('/') : null;
569
579
  const allowed = relNorm && relNorm.endsWith('.js') && (repoModules.files.includes(relNorm) || repoModules.dirs.some((d) => relNorm.startsWith(`${d}/`)));
570
- return allowed ? sendFile(req, res, file, reqPath) : notFound(res, reqPath);
580
+ const real = allowed ? inside(root, rel) : null;
581
+ const isModule = real && real.endsWith('.js') && (repoModules.files.includes(relNorm) || repoModules.dirs.some((d) => { const dir = inside(root, d); return !!dir && isUnder(dir, real); }));
582
+ return isModule ? sendFile(req, res, real, reqPath) : notFound(res, reqPath);
571
583
  }
572
584
  return notFound(res, reqPath);
573
585
  }
@@ -41,7 +41,7 @@ import { isMaintainer } from './forge.js';
41
41
  import { listPullProposals } from './proposal-pulls.js';
42
42
  import { gatherThreads, snapshotOf, POLL_LIMIT } from './threads.js';
43
43
  import { hookWants, threadsOn, triggersOf, THREAD_EVENTS } from '../core/config.js';
44
- import { readTopology } from '../core/validate.js';
44
+ import { readMap } from './files.js';
45
45
 
46
46
  /** How long after start the first look is made: soon, so the repo's silent first look is not left to the first interval */
47
47
  export const FIRST_MS = 15_000;
@@ -105,7 +105,7 @@ export function createSpecPoll({ config, where, auth, hooks, runs = null, specs
105
105
  /** The checkout's nodes, for a hook's `nodes` to be the ones a mention resolves to; none when there is no map */
106
106
  function mapNodes() {
107
107
  try {
108
- const topology = readTopology(config);
108
+ const topology = readMap(config); // only a map really inside the repo (server/files.js `inside`)
109
109
  return topology && Array.isArray(topology.nodes) ? topology.nodes : [];
110
110
  } catch {
111
111
  return [];