cornfield 0.51.7 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.51.7",
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)",
@@ -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 [];