@popcorn245/cornfield 0.51.7 → 0.52.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. package/cli/cornfield.js +7 -0
  2. package/core/config.js +2 -1
  3. package/core/map-tokens.js +2 -4
  4. package/core/repo.js +59 -4
  5. package/core/strings.js +5 -0
  6. package/core/text.js +18 -0
  7. package/core/validate.js +17 -10
  8. package/explorer/engine/flow-legend.js +28 -0
  9. package/explorer/engine/flow-ui.js +3 -22
  10. package/explorer/engine/keyboard.js +28 -15
  11. package/explorer/engine/map-rect.js +2 -2
  12. package/explorer/engine/piece.js +27 -2
  13. package/explorer/engine/render.js +7 -4
  14. package/explorer/engine/roots.js +71 -0
  15. package/explorer/engine/search-status.js +2 -8
  16. package/explorer/flows.js +2 -1
  17. package/explorer/instance.js +39 -10
  18. package/explorer/pieces/around.js +114 -0
  19. package/explorer/pieces/layers.js +28 -14
  20. package/explorer/pieces/map.js +14 -1
  21. package/explorer/pieces/node-panel.js +33 -15
  22. package/explorer/pieces/search.js +43 -12
  23. package/explorer/scene.js +1 -1
  24. package/explorer/search-match.js +53 -0
  25. package/explorer/search-model.js +6 -48
  26. package/package.json +1 -1
  27. package/plugins/cloud/index.js +5 -3
  28. package/plugins/compose/index.js +12 -6
  29. package/plugins/docs/site.js +2 -2
  30. package/plugins/openapi/index.js +10 -5
  31. package/plugins/starter/index.js +2 -2
  32. package/plugins/world/index.js +3 -2
  33. package/server/agent-runs.js +3 -4
  34. package/server/components.js +4 -3
  35. package/server/db.js +7 -0
  36. package/server/files.js +97 -15
  37. package/server/forge-routes.js +8 -6
  38. package/server/proposal-walk.js +25 -6
  39. package/server/proposals.js +5 -3
  40. package/server/reviews.js +9 -2
  41. package/server/server.js +43 -31
  42. package/server/spec-poll.js +2 -2
@@ -0,0 +1,53 @@
1
+ /**
2
+ * @module explorer/search-match
3
+ *
4
+ * Whether a node matches a search, and how well (spec 0008 D3): the half of search-model.js the map itself needs, to halo what a query finds
5
+ * (scene.js `matchIds`). Pure. search-model.js builds the list, its groups and its words on it, and re-exports these.
6
+ */
7
+
8
+ /** The ranks, best first */
9
+ export const RANK = Object.freeze({ labelStart: 0, wordStart: 1, label: 2, idOrFile: 3, typeOrKind: 4 });
10
+
11
+ /**
12
+ * The layer's name for each node type, as the Layers menu says it (layers.js `LAYER_DEFS`; a test keeps the two together).
13
+ * A type not here is its own name with a capital.
14
+ */
15
+ export const TYPE_NAMES = Object.freeze({
16
+ root: 'Root', app: 'Apps', pkg: 'Packages', page: 'Pages & Routes', atom: 'Atoms', molecule: 'Molecules', token: 'Design Tokens',
17
+ tool: 'Dev Tools', core: 'Core', store: 'Stores', table: 'Tables', rom: 'ROM', service: 'Services', external: 'Cloud', stack: 'Infra',
18
+ machine: 'Machines', container: 'Containers', device: 'Devices', floor: 'House', room: 'House', persona: 'People',
19
+ });
20
+
21
+ const capital = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
22
+
23
+ /** The name of the group a node is listed under: its layer's name */
24
+ export const groupName = (node) => TYPE_NAMES[node.type] || capital(String(node.type || ''));
25
+
26
+ const lower = (s) => (typeof s === 'string' ? s.toLowerCase() : '');
27
+ const WORD_BREAK = /[^\p{L}\p{N}]+/u;
28
+
29
+ /**
30
+ * How well `query` (trimmed) matches a node, as a RANK, or -1 for no match
31
+ * @param {{label?: string, id?: string, file?: string, type?: string, kind?: string}} node
32
+ * @param {string} query
33
+ */
34
+ export function rankOf(node, query) {
35
+ const term = String(query || '').toLowerCase();
36
+ if (!term) return -1;
37
+ const label = lower(node.label);
38
+ if (label.startsWith(term)) return RANK.labelStart;
39
+ if (label.split(WORD_BREAK).some((w) => w && w.startsWith(term))) return RANK.wordStart;
40
+ if (label.includes(term)) return RANK.label;
41
+ if (lower(node.id).includes(term) || lower(node.file).includes(term)) return RANK.idOrFile;
42
+ if (lower(node.type).includes(term) || lower(groupName(node)).includes(term) || lower(node.kind).includes(term)) return RANK.typeOrKind;
43
+ return -1;
44
+ }
45
+
46
+ /** The ids a query matches (what the map halos): a Set, empty for no query */
47
+ export function matchIds(nodes, query) {
48
+ const term = String(query || '').trim().toLowerCase();
49
+ const ids = new Set();
50
+ if (!term) return ids;
51
+ for (const node of nodes) if (rankOf(node, term) >= 0) ids.add(node.id);
52
+ return ids;
53
+ }
@@ -12,53 +12,20 @@
12
12
  * - It groups by type, under the layer's name with a count, groups in the order of their best match, and puts the matches
13
13
  * in layers that are off last, under their own heading.
14
14
  *
15
- * Substring matching only: no fuzzy matching, so a reviewer can always see why a node matched.
15
+ * Substring matching only: no fuzzy matching, so a reviewer can always see why a node matched. The matching itself is search-match.js.
16
16
  */
17
17
 
18
+ // Whether a node matches, and how well: search-match.js (what the map needs to halo the matches); kept as this module's too
19
+ import { RANK, TYPE_NAMES, groupName, rankOf, matchIds } from './search-match.js';
20
+
21
+ export { RANK, TYPE_NAMES, groupName, rankOf, matchIds };
22
+
18
23
  /** The heading of the matches in layers that are off */
19
24
  export const OFF_GROUP = 'In layers that are off';
20
25
 
21
26
  /** Rows the list shows before "and N more" */
22
27
  export const MAX_ROWS = 50;
23
28
 
24
- /** The ranks, best first */
25
- export const RANK = Object.freeze({ labelStart: 0, wordStart: 1, label: 2, idOrFile: 3, typeOrKind: 4 });
26
-
27
- /**
28
- * The layer's name for each node type, as the Layers menu says it (layers.js `LAYER_DEFS`; a test keeps the two together).
29
- * A type not here is its own name with a capital.
30
- */
31
- export const TYPE_NAMES = Object.freeze({
32
- root: 'Root', app: 'Apps', pkg: 'Packages', page: 'Pages & Routes', atom: 'Atoms', molecule: 'Molecules', token: 'Design Tokens',
33
- tool: 'Dev Tools', core: 'Core', store: 'Stores', table: 'Tables', rom: 'ROM', service: 'Services', external: 'Cloud', stack: 'Infra',
34
- machine: 'Machines', container: 'Containers', device: 'Devices', floor: 'House', room: 'House', persona: 'People',
35
- });
36
-
37
- const capital = (s) => (s ? s.charAt(0).toUpperCase() + s.slice(1) : s);
38
-
39
- /** The name of the group a node is listed under: its layer's name */
40
- export const groupName = (node) => TYPE_NAMES[node.type] || capital(String(node.type || ''));
41
-
42
- const lower = (s) => (typeof s === 'string' ? s.toLowerCase() : '');
43
- const WORD_BREAK = /[^\p{L}\p{N}]+/u;
44
-
45
- /**
46
- * How well `query` (trimmed) matches a node, as a RANK, or -1 for no match
47
- * @param {{label?: string, id?: string, file?: string, type?: string, kind?: string}} node
48
- * @param {string} query
49
- */
50
- export function rankOf(node, query) {
51
- const term = String(query || '').toLowerCase();
52
- if (!term) return -1;
53
- const label = lower(node.label);
54
- if (label.startsWith(term)) return RANK.labelStart;
55
- if (label.split(WORD_BREAK).some((w) => w && w.startsWith(term))) return RANK.wordStart;
56
- if (label.includes(term)) return RANK.label;
57
- if (lower(node.id).includes(term) || lower(node.file).includes(term)) return RANK.idOrFile;
58
- if (lower(node.type).includes(term) || lower(groupName(node)).includes(term) || lower(node.kind).includes(term)) return RANK.typeOrKind;
59
- return -1;
60
- }
61
-
62
29
  /**
63
30
  * Every node the query finds, in the order the list shows them.
64
31
  * @param {object[]} nodes the topology nodes
@@ -116,15 +83,6 @@ export function searchNodes(nodes, query, opts = {}) {
116
83
  return out;
117
84
  }
118
85
 
119
- /** The ids a query matches (what the map halos): a Set, empty for no query */
120
- export function matchIds(nodes, query) {
121
- const term = String(query || '').trim().toLowerCase();
122
- const ids = new Set();
123
- if (!term) return ids;
124
- for (const node of nodes) if (rankOf(node, term) >= 0) ids.add(node.id);
125
- return ids;
126
- }
127
-
128
86
  /**
129
87
  * The match `by` steps (+1 or -1) from the one with id `currentId`, wrapping round; the first (or, going back, the last) when
130
88
  * there is no current one or it is not among them.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.51.7",
3
+ "version": "0.52.0",
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,7 +31,8 @@
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
+ import { fileOptionProblem, leavesRepo, outsideProblem } from '../../core/repo.js';
35
+ import { quote } from '../../core/text.js';
35
36
  import { caddyEvidence, dockerfileSources, imageRef, workflowSources } from './sources.js';
36
37
 
37
38
  const WORKFLOW_DIRS = ['.github/workflows', '.forgejo/workflows'];
@@ -152,8 +153,9 @@ export default {
152
153
 
153
154
  // Caddyfiles the config names
154
155
  for (const { file, from } of options.caddyfiles || []) {
155
- if (leavesRepo(ctx, file)) { problems.push(outsideProblem('cloud', file)); continue; }
156
- if (!ctx.exists(file)) { warnings.push(`cloud: caddyfile ${file} does not exist.`); continue; }
156
+ const bad = fileOptionProblem(ctx, 'cloud', 'caddyfiles[].file', file);
157
+ if (bad) { problems.push(bad); continue; }
158
+ if (!ctx.exists(file)) { warnings.push(`cloud: caddyfile ${quote(file)} does not exist.`); continue; }
157
159
  for (const e of caddyEvidence(ctx.read(file))) add({ ...e, from, when: 'renew', file });
158
160
  }
159
161
 
@@ -35,7 +35,8 @@
35
35
  */
36
36
 
37
37
  import { caddyRoutes, labelsOf, traefikRoutes } from './routes.js';
38
- import { leavesRepo, outsideProblem } from '../../core/repo.js';
38
+ import { eachPlaceOnce, fileOptionProblem } from '../../core/repo.js';
39
+ import { quote } from '../../core/text.js';
39
40
 
40
41
  export const COMPOSE_NAMES = ['compose.yaml', 'compose.yml', 'docker-compose.yaml', 'docker-compose.yml'];
41
42
  const CADDYFILE = /(?:^|\/)(?:Caddyfile|[\w.-]+\.caddyfile)$/i;
@@ -89,8 +90,12 @@ const targetPort = (p) => {
89
90
  /** The compose files: the config's, else the first compose name in each folder */
90
91
  function composeFiles(ctx, options, problems) {
91
92
  if (Array.isArray(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.`);
93
+ const named = eachPlaceOnce(options.files).filter((f) => {
94
+ const bad = fileOptionProblem(ctx, 'compose', 'files', f);
95
+ if (bad) problems.push(bad);
96
+ return !bad;
97
+ });
98
+ for (const f of named) if (!ctx.exists(f)) throw new Error(`compose file ${quote(f)} does not exist.`);
94
99
  return named;
95
100
  }
96
101
  const found = ctx.walk('', (f) => COMPOSE_NAMES.includes(f.slice(f.lastIndexOf('/') + 1)));
@@ -170,11 +175,12 @@ const compose = {
170
175
  for (const r of traefikRoutes(svc.name, svc.labels, svc.firstPort)) routes.push({ ...r, stack: s, from: s.file });
171
176
  }
172
177
  }
173
- const caddyfiles = Array.isArray(options.caddyfiles) ? options.caddyfiles : ctx.walk('', (f) => CADDYFILE.test(f));
178
+ const caddyfiles = Array.isArray(options.caddyfiles) ? eachPlaceOnce(options.caddyfiles) : ctx.walk('', (f) => CADDYFILE.test(f));
174
179
  const outside = new Set();
175
180
  for (const file of caddyfiles) {
176
- if (leavesRepo(ctx, file)) { problems.push(outsideProblem('compose', file)); continue; }
177
- if (!ctx.exists(file)) { warnings.push(`compose: caddyfile ${file} does not exist.`); continue; }
181
+ const bad = fileOptionProblem(ctx, 'compose', 'caddyfiles', file);
182
+ if (bad) { problems.push(bad); continue; }
183
+ if (!ctx.exists(file)) { warnings.push(`compose: caddyfile ${quote(file)} does not exist.`); continue; }
178
184
  const here = dirOf(file);
179
185
  for (const r of caddyRoutes(ctx.read(file))) {
180
186
  const serving = stacks.filter((s) => s.services.some((x) => x.name === r.service || x.containerName === r.service));
@@ -19,7 +19,7 @@ import { deriveTopology } from '../../core/derive.js';
19
19
  import { readTopology } from '../../core/validate.js';
20
20
  import { renderMarkdown, safeUrl } from './markdown.js';
21
21
  import docsDeriver, { resolveLink, SITE_OUTPUTS } from './index.js';
22
- import { repoReader } from '../../core/repo.js';
22
+ import { outsideError, repoReader } from '../../core/repo.js';
23
23
 
24
24
  /** The file a built site holds, so a rebuild knows the folder is its own */
25
25
  export const SITE_MARKER = SITE_OUTPUTS[2];
@@ -223,7 +223,7 @@ export async function buildSite({ config, derivers, out, sourceUrl = sourceUrlOf
223
223
  // What the site reads is the repo's: a path that leads out of it, by `..` or a symlink, is as if it were not there
224
224
  const io = repoReader(root);
225
225
  const read = (rel) => {
226
- if (!io.inside(rel)) throw new Error(`${rel} is outside the repo.`);
226
+ if (!io.inside(rel)) throw outsideError(rel);
227
227
  return fs.readFileSync(path.join(root, rel), 'utf8');
228
228
  };
229
229
  const exists = (rel) => io.inside(rel) && io.exists(rel);
@@ -25,7 +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';
28
+ import { fileOptionProblem } from '../../core/repo.js';
29
+ import { quote } from '../../core/text.js';
29
30
 
30
31
  const SPEC_FILE = /(?:^|\/)(?:openapi|swagger|[\w.-]+\.openapi|opencollection)\.(?:json|ya?ml)$/i;
31
32
  const METHOD_ORDER = ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS', 'TRACE'];
@@ -130,9 +131,13 @@ export function specKind(doc) {
130
131
 
131
132
  /** The specs to read: `[{ file, app, prefix }]` */
132
133
  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);
134
+ const inRepo = (option) => (s) => {
135
+ const bad = fileOptionProblem(ctx, 'openapi', option, s.file);
136
+ if (bad) problems.push(bad);
137
+ return !bad;
138
+ };
139
+ if (Array.isArray(options.specs)) return options.specs.map((s) => ({ app: DEFAULT_APP, ...s })).filter(inRepo('specs[].file'));
140
+ if (typeof options.file === 'string') return [{ file: options.file, app: options.app || DEFAULT_APP, prefix: options.prefix }].filter(inRepo('file'));
136
141
  const found = ctx.walk('', (f) => SPEC_FILE.test(f));
137
142
  if (found.length > 1) {
138
143
  warnings.push(`openapi: ${found.length} API description files (${found.join(', ')}); name the ones to draw: { use: 'openapi', options: { specs: [{ file, app }] } }.`);
@@ -157,7 +162,7 @@ const openapi = {
157
162
  const mapNodes = (ctx.map && ctx.map.nodes) || [];
158
163
  let yaml;
159
164
  for (const spec of specs) {
160
- if (!spec.file || !ctx.exists(spec.file)) throw new Error(`API description ${spec.file} does not exist.`);
165
+ if (!spec.file || !ctx.exists(spec.file)) throw new Error(`API description ${quote(spec.file)} does not exist.`);
161
166
  const text = ctx.read(spec.file);
162
167
  let doc;
163
168
  if (/\.json$/i.test(spec.file)) {
@@ -35,7 +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
+ import { eachPlaceOnce, leavesRepo, outsideProblem } from '../../core/repo.js';
39
39
 
40
40
  const DEFAULT_EXTENSIONS = LANGUAGES.js.extensions;
41
41
  const TEST_DIRS = new Set(['test', 'tests', '__tests__', '__fixtures__', 'fixtures']);
@@ -97,7 +97,7 @@ function expandPatterns(patterns, io) {
97
97
  for (const name of io.list(base)) if (!name.startsWith('.') && io.isDir(`${base}/${name}`)) dirs.push(`${base}/${name}`);
98
98
  } else if (io.isDir(p)) dirs.push(p);
99
99
  }
100
- return [...new Set(dirs)].sort();
100
+ return eachPlaceOnce(dirs).sort(); // one place once, however it is spelled (`''` and `.` are the repo itself)
101
101
  }
102
102
 
103
103
  const readJson = (io, rel) => {
@@ -33,7 +33,7 @@
33
33
  */
34
34
 
35
35
  import { slug } from '../compose/index.js';
36
- import { leavesRepo, outsideProblem } from '../../core/repo.js';
36
+ import { fileOptionProblem } from '../../core/repo.js';
37
37
 
38
38
  export const WORLD_FILE = 'stacks/world.json';
39
39
  const FILE_KEYS = ['version', 'hosts', 'runs'];
@@ -64,7 +64,8 @@ const world = {
64
64
  const options = ctx.options || {};
65
65
  const file = options.file || WORLD_FILE;
66
66
  const parent = options.parent || 'root';
67
- if (leavesRepo(ctx, file)) return { nodes: [], edges: [], warnings: [], problems: [outsideProblem('world', file)], info: { machines: [] } };
67
+ const refused = fileOptionProblem(ctx, 'world', 'file', file);
68
+ if (refused) return { nodes: [], edges: [], warnings: [], problems: [refused], info: { machines: [] } };
68
69
  if (!ctx.exists(file)) return { nodes: [], edges: [], warnings: [], problems: [], info: { machines: [] } };
69
70
 
70
71
  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);