@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
@@ -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 [];