cornfield 0.46.2 → 0.48.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/core/contrast.js +6 -6
  2. package/explorer/css/account.css +46 -0
  3. package/explorer/css/base.css +159 -0
  4. package/explorer/css/changes.css +160 -0
  5. package/explorer/css/decision.css +68 -0
  6. package/explorer/css/dialogs.css +50 -0
  7. package/explorer/css/header.css +75 -0
  8. package/explorer/css/layers.css +92 -0
  9. package/explorer/css/live.css +48 -0
  10. package/explorer/css/map.css +43 -0
  11. package/explorer/css/node-panel.css +188 -0
  12. package/explorer/css/page.css +83 -0
  13. package/explorer/css/proposal.css +151 -0
  14. package/explorer/css/search.css +84 -0
  15. package/explorer/css/sheets.css +134 -0
  16. package/explorer/css/whatif.css +55 -0
  17. package/explorer/css/work.css +288 -0
  18. package/explorer/engine/hint.js +1 -0
  19. package/explorer/engine/keyboard.js +2 -2
  20. package/explorer/engine/map-style.js +9 -4
  21. package/explorer/flow-build.js +88 -0
  22. package/explorer/flows.js +1 -81
  23. package/explorer/focus-room.js +1 -1
  24. package/explorer/header-fit.js +3 -3
  25. package/explorer/house.css +1 -1
  26. package/explorer/index.html +20 -10
  27. package/explorer/input.js +8 -1
  28. package/explorer/page-pieces.js +5 -0
  29. package/explorer/page.js +11 -20
  30. package/explorer/pieces/adopt-tokens.js +38 -0
  31. package/explorer/pieces/map-stage.css +14 -0
  32. package/explorer/pieces/map.js +332 -0
  33. package/explorer/renderer.js +1 -0
  34. package/explorer/review.js +1 -1
  35. package/explorer/theme-model.js +1 -1
  36. package/explorer/theme.js +1 -1
  37. package/explorer/tokens.css +2 -2
  38. package/package.json +1 -1
  39. package/server/components.js +144 -0
  40. package/server/embed.js +3 -1
  41. package/server/server.js +9 -1
  42. package/explorer/explorer.css +0 -1512
@@ -0,0 +1,144 @@
1
+ /**
2
+ * @module server/components
3
+ *
4
+ * The web components (components/, spec 0011 D11) served from this server, at `/cornfield/components/<file>`, so a host app loads them with
5
+ * one `<script type="module" src="https://map.example.com/cornfield/components/corn-map.js">` and always gets the build that matches the server.
6
+ *
7
+ * cornfield has no build step: a checkout has no built components, and then this route answers a plain 404 that says how to get them. The
8
+ * image builds them (Dockerfile) into `components/dist` beside the server, and so does `cd components && npm ci && npm run build`. One rule:
9
+ * the folder is `<cornfield>/components/dist`, and it is served only when `manifest.json` (written last by the build, components/scripts/manifest.mjs)
10
+ * is there.
11
+ *
12
+ * What is served is what the manifest names, looked up by exact name in a map: a request path is never joined into a file path, so there is no
13
+ * traversal to get wrong, no listing, no dotfile, and nothing the build did not produce. Only `.js`, `.css`, `.json`, `.d.ts` and `.map`.
14
+ *
15
+ * The route is open (before the sign-in guard): a browser fetches a module script from another origin with CORS and without the cookie. It holds
16
+ * no secret: it is the published package. server/embed.js adds the CORS headers for a listed origin; with none listed there are none.
17
+ *
18
+ * Headers: the type, `nosniff`, a strong ETag (the content's hash, and the encoding's name when the answer will be compressed, so two encodings
19
+ * are two ETags), and caching: `chunks/<name>-<hash>.js` are named by their content, so cached for a year; everything else (`corn-map.js`,
20
+ * `index.js`, `version.json`, `tokens.css`, the types) is revalidated every time, so a host always gets this server's version.
21
+ */
22
+
23
+ import fs from 'node:fs';
24
+ import path from 'node:path';
25
+ import { createHash } from 'node:crypto';
26
+ import { pickEncoding } from './compress.js';
27
+ import { notFound } from './files.js';
28
+
29
+ export const COMPONENTS_PREFIX = '/cornfield/components/';
30
+
31
+ /** Plain segments, none starting with a dot (the same rule the build holds its manifest to) */
32
+ const SAFE_PATH = /^(?!\.)[A-Za-z0-9_-][A-Za-z0-9._-]*(?:\/(?!\.)[A-Za-z0-9_-][A-Za-z0-9._-]*)*$/;
33
+ const TYPES = [
34
+ [/\.js$/, 'application/javascript; charset=utf-8'],
35
+ [/\.css$/, 'text/css; charset=utf-8'],
36
+ [/\.json$/, 'application/json; charset=utf-8'],
37
+ [/\.map$/, 'application/json; charset=utf-8'],
38
+ [/\.d\.ts$/, 'text/plain; charset=utf-8'],
39
+ ];
40
+ /** A chunk the build named by its content */
41
+ const HASHED = /^chunks\/[A-Za-z0-9_-]+-[A-Za-z0-9_-]{8,}\.js$/;
42
+ const MAX_BYTES = 4 * 1024 * 1024;
43
+ /** server/compress.js does not compress below this */
44
+ const MIN_COMPRESSED = 512;
45
+
46
+ const NOT_BUILT = 'The web components are not built here: this cornfield runs from a checkout, which has no build step.\n'
47
+ + 'Build them with `cd components && npm ci && npm run build`, or run the Docker image (it builds them), or install @popcorn245/cornfield-components from npm.\n';
48
+
49
+ /** @param {{ dir: string }} opts the folder the build wrote (`components/dist`) */
50
+ export function createComponents({ dir }) {
51
+ const root = path.resolve(dir);
52
+ /** @type {{ stamp: string, names: Set<string> } | null} */
53
+ let listed = null;
54
+ /** @type {Map<string, { stamp: string, body: Buffer, etag: string }>} */
55
+ const bodies = new Map();
56
+
57
+ /** The names the manifest lists, read again when it changes; null when nothing is built (or the manifest is not one) */
58
+ function names() {
59
+ const file = path.join(root, 'manifest.json');
60
+ let stats;
61
+ try { stats = fs.lstatSync(file); } catch { return (listed = null); }
62
+ if (!stats.isFile() || stats.size > MAX_BYTES) return (listed = null);
63
+ const stamp = `${stats.size}:${stats.mtimeMs}`;
64
+ if (listed?.stamp === stamp) return listed.names;
65
+ try {
66
+ const manifest = JSON.parse(fs.readFileSync(file, 'utf8'));
67
+ const out = new Set();
68
+ for (const f of Array.isArray(manifest.files) ? manifest.files : []) {
69
+ const p = f && typeof f.path === 'string' ? f.path : '';
70
+ if (SAFE_PATH.test(p) && TYPES.some(([re]) => re.test(p))) out.add(p);
71
+ }
72
+ bodies.clear();
73
+ listed = { stamp, names: out };
74
+ return out;
75
+ } catch {
76
+ return (listed = null);
77
+ }
78
+ }
79
+
80
+ /** The bytes of a listed file and their ETag; null when it is not a plain file there */
81
+ function load(name) {
82
+ const file = path.join(root, ...name.split('/'));
83
+ let stats;
84
+ try { stats = fs.lstatSync(file); } catch { return null; }
85
+ if (!stats.isFile() || stats.size > MAX_BYTES) return null;
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
+ // itself may be a link; what is served is what lies, really, inside it
88
+ try {
89
+ const real = fs.realpathSync(file);
90
+ const realRoot = fs.realpathSync(root);
91
+ if (real !== path.join(realRoot, ...name.split('/'))) return null;
92
+ } catch { return null; }
93
+ const stamp = `${stats.size}:${stats.mtimeMs}`;
94
+ const known = bodies.get(name);
95
+ if (known?.stamp === stamp) return known;
96
+ try {
97
+ const body = fs.readFileSync(file);
98
+ const entry = { stamp, body, etag: createHash('sha256').update(body).digest('base64url').slice(0, 27) };
99
+ bodies.set(name, entry);
100
+ return entry;
101
+ } catch {
102
+ return null;
103
+ }
104
+ }
105
+
106
+ return {
107
+ dir: root,
108
+ /** Whether the folder holds a build (a manifest) */
109
+ built: () => names() !== null,
110
+ /**
111
+ * Answers a GET or HEAD under COMPONENTS_PREFIX.
112
+ * @param {import('node:http').IncomingMessage} req
113
+ * @param {import('node:http').ServerResponse} res
114
+ * @param {string} reqPath the decoded path
115
+ */
116
+ serve(req, res, reqPath) {
117
+ const listing = names();
118
+ if (!listing) {
119
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8', 'X-Content-Type-Options': 'nosniff' });
120
+ return res.end(`404 Not Found: ${reqPath}\n${NOT_BUILT}`);
121
+ }
122
+ const name = reqPath.slice(COMPONENTS_PREFIX.length);
123
+ const found = listing.has(name) ? load(name) : null;
124
+ if (!found) return notFound(res, reqPath);
125
+ const type = TYPES.find(([re]) => re.test(name))[1];
126
+ // The compressor (server/compress.js) will encode this answer when it is long enough and the browser accepts one: the ETag names the encoding
127
+ const encoding = found.body.length >= MIN_COMPRESSED && /^(?:text\/|application\/(?:javascript|json))/.test(type) ? pickEncoding(req.headers['accept-encoding']) : null;
128
+ const etag = `"${found.etag}${encoding ? `-${encoding}` : ''}"`;
129
+ const headers = {
130
+ 'Content-Type': type,
131
+ 'X-Content-Type-Options': 'nosniff',
132
+ 'Cache-Control': HASHED.test(name) ? 'public, max-age=31536000, immutable' : 'no-cache',
133
+ ETag: etag,
134
+ };
135
+ const asked = req.headers['if-none-match'];
136
+ if (asked && (asked.trim() === '*' || asked.split(',').some((t) => t.trim().replace(/^W\//, '') === etag))) {
137
+ res.writeHead(304, headers);
138
+ return res.end();
139
+ }
140
+ res.writeHead(200, { ...headers, 'Content-Length': found.body.length });
141
+ return res.end(req.method === 'HEAD' ? undefined : found.body);
142
+ },
143
+ };
144
+ }
package/server/embed.js CHANGED
@@ -36,7 +36,7 @@ const SLUG = '[^/]+';
36
36
 
37
37
  /**
38
38
  * The routes a listed origin may reach, and nothing else. `session`: behind the sign-in guard, so the credentialed form of CORS; `open`:
39
- * answered before it (the look of the sign-in pages: theme.css, a named theme, and the images and fonts a theme names).
39
+ * answered before it (the look of the sign-in pages: theme.css, a named theme, and the images and fonts a theme names; and the web components, which a browser loads without the cookie).
40
40
  * `methods` are what a preflight may ask for; `headers` are the request headers it may list (lowercase).
41
41
  * @type {readonly Route[]}
42
42
  */
@@ -58,6 +58,8 @@ export const ROUTES = Object.freeze([
58
58
  { test: '/cornfield/theme.css', kind: 'open', methods: READ, headers: [] },
59
59
  { test: /^\/cornfield\/theme\/[^/]+\.css$/, kind: 'open', methods: READ, headers: [] },
60
60
  { test: /^\/cornfield\/theme\/assets\/.+$/, kind: 'open', methods: READ, headers: [] },
61
+ // The web components (server/components.js): a host loads them as module scripts, which a browser fetches with CORS and without the cookie
62
+ { test: /^\/cornfield\/components\/.+$/, kind: 'open', methods: READ, headers: [] },
61
63
  ]);
62
64
 
63
65
  /**
package/server/server.js CHANGED
@@ -19,6 +19,8 @@
19
19
  * GET /cornfield/theme.css, /cornfield/theme/<name>.css
20
20
  * the stylesheets the config's `theme` names (css, names): those files only, as text/css
21
21
  * GET /cornfield/theme/assets/<path> an image or font beside the theme files (png, svg, webp, gif, avif, woff2, woff; 1 MB each)
22
+ * GET /cornfield/components/<file> the built web components (components/dist, listed by its manifest.json), open without a session; a plain 404
23
+ * that says how to build them when this checkout has none (server/components.js)
22
24
  * GET /cornfield/brand/<key>.<ext> a brand image the config's `brand` names (logo, wordmark, favicon; svg or png, 512 KB each): those files only
23
25
  * GET /manifest.webmanifest the web app manifest: the repo's title, or built from `brand` when the config sets one
24
26
  * GET /api/forge/… issues, pull requests, their files and checks, release notes: read from the forge (server/forge-routes.js)
@@ -75,6 +77,7 @@ import { createAuth, signInSettings } from './auth.js';
75
77
  import { createHooks, hooksSettings } from './hooks.js';
76
78
  import { createLander } from './lander.js';
77
79
  import { createEmbed } from './embed.js';
80
+ import { COMPONENTS_PREFIX, createComponents } from './components.js';
78
81
  import { createSpecPoll } from './spec-poll.js';
79
82
  import { createRunnerWatch, runnerPresence } from './runner-presence.js';
80
83
  import { createTriggers } from './triggers.js';
@@ -280,7 +283,7 @@ export const HA_CACHE_MS = 30_000;
280
283
  /**
281
284
  * The server for one repo. It does not listen: `listen(config)` does, where server/bind.js allows.
282
285
  * @param {object} config a loaded config (core/config.js `loadConfig`)
283
- * @param {Parameters<typeof createAuth>[1] & { homeAssistant?: object, hookFetch?: typeof fetch, hookTimer?: { setTimeout: Function, clearTimeout: Function }, landTimer?: { setTimeout: Function, clearTimeout: Function }, specPollTimer?: { setTimeout: Function, clearTimeout: Function } }} [opts] what sign-in reads (`env`, and tests' fakes;
286
+ * @param {Parameters<typeof createAuth>[1] & { componentsDir?: string, homeAssistant?: object, hookFetch?: typeof fetch, hookTimer?: { setTimeout: Function, clearTimeout: Function }, landTimer?: { setTimeout: Function, clearTimeout: Function }, specPollTimer?: { setTimeout: Function, clearTimeout: Function } }} [opts] what sign-in reads (`env`, and tests' fakes;
284
287
  * see server/auth.js); the Home Assistant URL and token are read from the same `env`, and `homeAssistant` is what
285
288
  * `homeAssistantHouse` is handed besides them (the tests' fake WebSocket); `hookFetch` and `hookTimer` are the
286
289
  * tests' fake network and clock for the event hooks (server/hooks.js); `landTimer` is the clock of landing on approval (server/lander.js); `specPollTimer` is the clock of the `spec.ready` poll (server/spec-poll.js)
@@ -313,6 +316,8 @@ export function createCornfieldServer(config, opts = {}) {
313
316
  const publicOrigin = config.publicUrl ? new URL(config.publicUrl).origin : null;
314
317
  // The sibling origins that may read and decide a review as the signed-in maintainer (server/embed.js): none unless `embed.origins` lists some
315
318
  const embed = createEmbed(config.embed?.origins ?? []);
319
+ // The web components, when built (components/dist; the image builds them, a checkout does not): served at /cornfield/components/, open (server/components.js)
320
+ const components = createComponents({ dir: opts.componentsDir ?? path.join(CORNFIELD_DIR, 'components', 'dist') });
316
321
  const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost, publicOrigin, embedOrigins: embed.origins };
317
322
  const fixtureCache = new Map();
318
323
  // What the line above Approve says an approval does besides posting (spec 0007 D1, server/decision.js): landing, and the run a trigger asks for
@@ -463,6 +468,9 @@ export function createCornfieldServer(config, opts = {}) {
463
468
  const runner = runnerRoute(reqPath);
464
469
  if (runner && !(reqPath === REQUESTS_PATH && req.method !== 'GET' && req.method !== 'HEAD')) return serveRunnerCall(req, res, runner, url, { config, auth, runs, now: opts.now });
465
470
  if (reqPath === REQUESTS_PATH) return serveAgentCall(req, res, { config, auth, runs, now: opts.now });
471
+ // The web components answer without a session: a browser fetches a module script from another origin without the cookie, and holds nothing secret
472
+ // (it is the published package). The CORS headers for a listed origin are already on the answer; a write to this prefix goes on to the guard as before
473
+ if ((req.method === 'GET' || req.method === 'HEAD') && reqPath.startsWith(COMPONENTS_PREFIX)) return components.serve(req, res, reqPath);
466
474
  // The look of the sign-in pages (cornfield's tokens and its sign-in stylesheet, the repo's theme, fonts and brand images) answers without a
467
475
  // session: a visitor sees the brand before they are in. Presentation files only, never data (docs/sign-in.md, "What answers without a session")
468
476
  if (auth.enabled && (req.method === 'GET' || req.method === 'HEAD')) {