cornfield 0.20.0 → 0.22.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.
- package/core/agent-contract.js +7 -2
- package/core/agent-contract.schema.json +4 -0
- package/core/config.js +5 -0
- package/core/theme.js +337 -0
- package/core/validate.js +37 -0
- package/explorer/explorer.css +3 -0
- package/explorer/forge-panel.js +99 -21
- package/explorer/index.html +16 -3
- package/explorer/plugins.js +2 -0
- package/explorer/runs-model.js +47 -11
- package/explorer/runs-view.js +22 -6
- package/explorer/theme-boot.js +22 -2
- package/explorer/theme-model.js +19 -0
- package/explorer/theme-names.js +61 -0
- package/package.json +1 -1
- package/server/agent-api.js +11 -3
- package/server/agent-runs.js +50 -10
- package/server/server.js +98 -4
package/core/agent-contract.js
CHANGED
|
@@ -40,7 +40,7 @@
|
|
|
40
40
|
* @typedef {{ issue?: number, proposal?: string, pull?: number, thread?: number }} RunRefs
|
|
41
41
|
* @typedef {{ minutes?: number, turns?: number, cost?: number, tokens?: number }} RunLimits
|
|
42
42
|
* @typedef {{ version: 1, runId: string, kind: RunKind, profile?: string, refs: RunRefs, branch?: string, brief: string,
|
|
43
|
-
* limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
|
|
43
|
+
* limits?: RunLimits, nodes?: string[], requestedBy: string, requestedAt: string, retryOf?: string, trigger?: { event: 'spec.approved' | 'build.opened' | 'thread.message', by: string, ref: string } }} RunRequest
|
|
44
44
|
* @typedef {'claimed' | 'working' | 'waiting' | 'done' | 'failed' | 'stopped'} ReportState
|
|
45
45
|
* @typedef {{ state: ReportState, note?: string, url?: string, tokens?: number, cost?: number }} RunReport
|
|
46
46
|
* @typedef {{ state: 'stop-requested', note?: string }} StopRequest
|
|
@@ -89,7 +89,7 @@ export const RUN_TAG = 'cornfield-run';
|
|
|
89
89
|
/** The key of the trailer */
|
|
90
90
|
export const TRAILER_KEY = 'Cornfield-Run';
|
|
91
91
|
|
|
92
|
-
const REQUEST_KEYS = ['version', 'runId', 'kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'requestedAt', 'trigger'];
|
|
92
|
+
const REQUEST_KEYS = ['version', 'runId', 'kind', 'profile', 'refs', 'branch', 'brief', 'limits', 'nodes', 'requestedBy', 'requestedAt', 'retryOf', 'trigger'];
|
|
93
93
|
const TRIGGER_KEYS = ['event', 'by', 'ref'];
|
|
94
94
|
/** The events an opt-in trigger may fire on (`agents.on`, spec 0005 D10): each is something a maintainer did */
|
|
95
95
|
export const TRIGGER_EVENTS = Object.freeze(['spec.approved', 'build.opened', 'thread.message']);
|
|
@@ -345,6 +345,10 @@ export function validateRequest(body, { profiles } = {}) {
|
|
|
345
345
|
}
|
|
346
346
|
}
|
|
347
347
|
|
|
348
|
+
if (body.retryOf !== undefined) {
|
|
349
|
+
if (!isRunId(body.retryOf)) return no('"retryOf" is the run id of the run this one starts again, like run-01JC8Z3Q5M7VXK2RT9N4B6HDEF.');
|
|
350
|
+
}
|
|
351
|
+
|
|
348
352
|
if (body.nodes !== undefined) {
|
|
349
353
|
if (!Array.isArray(body.nodes)) return no('"nodes" is a list of node ids.');
|
|
350
354
|
if (body.nodes.length > MAX_NODES) return no(`"nodes" has at most ${MAX_NODES} ids.`);
|
|
@@ -369,6 +373,7 @@ export function validateRequest(body, { profiles } = {}) {
|
|
|
369
373
|
if (body.nodes !== undefined) value.nodes = [...body.nodes];
|
|
370
374
|
value.requestedBy = body.requestedBy;
|
|
371
375
|
value.requestedAt = body.requestedAt;
|
|
376
|
+
if (body.retryOf !== undefined) value.retryOf = body.retryOf;
|
|
372
377
|
if (body.trigger !== undefined) {
|
|
373
378
|
if (!isObject(body.trigger)) return no('"trigger" is { event, by, ref }: what caused an automatic request.');
|
|
374
379
|
const triggerKeys = keyProblem(body.trigger, TRIGGER_KEYS, '"trigger"');
|
|
@@ -190,6 +190,10 @@
|
|
|
190
190
|
"type": "string",
|
|
191
191
|
"pattern": "^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(\\.\\d{1,3})?Z$"
|
|
192
192
|
},
|
|
193
|
+
"retryOf": {
|
|
194
|
+
"description": "Only on a request that starts again on an earlier run that failed or was stopped, or a request a runner refused: that run's id. A record, never an instruction; cornfield checks it names a run of the same repo that failed or was stopped.",
|
|
195
|
+
"$ref": "#/$defs/runId"
|
|
196
|
+
},
|
|
193
197
|
"trigger": {
|
|
194
198
|
"description": "Only on an automatic request (agents.on): what caused it. A maintainer's act, never a run's output.",
|
|
195
199
|
"type": "object",
|
package/core/config.js
CHANGED
|
@@ -26,6 +26,7 @@
|
|
|
26
26
|
* hookPoll: { specs: '5m' }, // how often cornfield looks for ready specs and thread activity on its own, for the spec.ready and thread.* hooks; false turns it off (docs/config.md#hook-poll)
|
|
27
27
|
* threads: { label: 'idea' }, // an idea is an issue with this label, its thread the issue's comments; false turns threads off (docs/threads.md)
|
|
28
28
|
* links: [], // [{ label, href }] shown in the explorer's header
|
|
29
|
+
* theme: {}, // { css, fonts, fontHosts, names, default }: a repo's own look, CSS only (docs/config.md#theme)
|
|
29
30
|
* proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
|
|
30
31
|
* importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
|
|
31
32
|
* dataDir: null, // where cornfield keeps its own state (reviews; the SQLite file in v1)
|
|
@@ -40,6 +41,7 @@ import fs from 'node:fs';
|
|
|
40
41
|
import os from 'node:os';
|
|
41
42
|
import path from 'node:path';
|
|
42
43
|
import { pathToFileURL, fileURLToPath } from 'node:url';
|
|
44
|
+
import { themeProblems } from './theme.js';
|
|
43
45
|
import { PROFILE_SOURCE, MAX_NUMBER, MAX_BRIEF_CHARS, RUN_KINDS, TRIGGER_EVENTS, CREDENTIAL_VALUE_SOURCE } from './agent-contract.js';
|
|
44
46
|
|
|
45
47
|
export { TRIGGER_EVENTS };
|
|
@@ -164,6 +166,7 @@ export const DEFAULTS = Object.freeze({
|
|
|
164
166
|
hookPoll: { specs: '5m' },
|
|
165
167
|
threads: { label: 'idea' },
|
|
166
168
|
links: [],
|
|
169
|
+
theme: { css: null, fonts: [], fontHosts: [], names: {}, default: null },
|
|
167
170
|
proxy: {},
|
|
168
171
|
importMap: {},
|
|
169
172
|
dataDir: null,
|
|
@@ -336,6 +339,7 @@ export function configProblems(c) {
|
|
|
336
339
|
if (!isObject(l) || !isText(l.label) || !/^(https?:\/\/|\/)/.test(String(l.href || ''))) out.push(`links[${i}] is { label, href } with an http(s) or same-origin href.`);
|
|
337
340
|
});
|
|
338
341
|
}
|
|
342
|
+
out.push(...themeProblems(c.theme));
|
|
339
343
|
if (c.proxy !== undefined) {
|
|
340
344
|
if (!isObject(c.proxy)) out.push('"proxy" is { "/path/": "http://upstream" }.');
|
|
341
345
|
else for (const [p, t] of Object.entries(c.proxy)) {
|
|
@@ -522,6 +526,7 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
|
|
|
522
526
|
deploys: { ...DEFAULTS.deploys, ...(raw.deploys || {}) },
|
|
523
527
|
agents: { ...DEFAULTS.agents, ...(raw.agents || {}) },
|
|
524
528
|
};
|
|
529
|
+
config.theme = { ...structuredClone(DEFAULTS.theme), ...(raw.theme || {}) };
|
|
525
530
|
// `threads: false` stays false; an object is read over the default
|
|
526
531
|
config.threads = raw.threads === false ? false : { ...DEFAULTS.threads, ...(raw.threads || {}) };
|
|
527
532
|
// `hookPoll: false` is `{ specs: false }`; an object is read over the default
|
package/core/theme.js
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module core/theme
|
|
3
|
+
*
|
|
4
|
+
* The `theme` key of cornfield.config.js (docs/config.md#theme), and the rules a theme file must keep.
|
|
5
|
+
* No theme file is read here (core/validate.js reads them, server/server.js serves them); `themeAssetFile` alone looks at the disk,
|
|
6
|
+
* so the server and `validate` find an asset beside a theme by the same rule.
|
|
7
|
+
*
|
|
8
|
+
* theme: {
|
|
9
|
+
* css: './tools/cornfield/theme.css', // one repo-local stylesheet, loaded after cornfield's own
|
|
10
|
+
* fonts: ['https://fonts.googleapis.com/css2?family=Nunito'], // an allow-list of https: stylesheet URLs
|
|
11
|
+
* fontHosts: [], // the hosts of the font FILES, when a fonts host is not a known pair
|
|
12
|
+
* names: { day: './tools/cornfield/day.css' }, // named themes: data-theme-name on <html>, a picker in the header
|
|
13
|
+
* default: 'day', // the name used until a viewer picks one
|
|
14
|
+
* }
|
|
15
|
+
*
|
|
16
|
+
* A theme is CSS only: never script, never inlined into the page.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import fs from 'node:fs';
|
|
20
|
+
import path from 'node:path';
|
|
21
|
+
|
|
22
|
+
export const THEME_KEYS = Object.freeze(['css', 'fonts', 'fontHosts', 'names', 'default']);
|
|
23
|
+
/** The largest a theme file may be, in bytes */
|
|
24
|
+
export const MAX_THEME_BYTES = 256 * 1024;
|
|
25
|
+
export const MAX_THEME_NAMES = 12;
|
|
26
|
+
export const MAX_THEME_FONTS = 8;
|
|
27
|
+
/** A theme's name: it is put on <html data-theme-name> and in a URL, so it is plain */
|
|
28
|
+
export const THEME_NAME = /^[a-z0-9][a-z0-9-]{0,31}$/;
|
|
29
|
+
/** Stylesheet hosts whose font files come from a known host (the host itself, when it serves both) */
|
|
30
|
+
export const KNOWN_FONT_PAIRS = Object.freeze({
|
|
31
|
+
'fonts.googleapis.com': ['fonts.gstatic.com'],
|
|
32
|
+
'fonts.bunny.net': ['fonts.bunny.net'],
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
36
|
+
const isText = (v) => typeof v === 'string' && v.trim() !== '';
|
|
37
|
+
const HOST = /^(?=.{1,253}$)(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
|
38
|
+
/** A path inside the repo, relative, ending in .css */
|
|
39
|
+
const cssPathInRepo = (p) => isText(p) && !path.isAbsolute(p) && !/^[a-z]:/i.test(p) && !p.split(/[\\/]/).includes('..') && !p.includes('\0') && /\.css$/i.test(p);
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* A fonts entry as a parsed https URL, or null when it is not an acceptable one: https only, a plain
|
|
43
|
+
* host name (no credentials, no wildcard, no IP address), no fragment.
|
|
44
|
+
* @param {unknown} v
|
|
45
|
+
* @returns {URL | null}
|
|
46
|
+
*/
|
|
47
|
+
export function fontUrl(v) {
|
|
48
|
+
if (typeof v !== 'string' || v !== v.trim() || /[\s"'<>\\`]/.test(v)) return null;
|
|
49
|
+
let u;
|
|
50
|
+
try { u = new URL(v); } catch { return null; }
|
|
51
|
+
if (u.protocol !== 'https:' || u.username || u.password || u.hash || !HOST.test(u.hostname) || /^\d+(?:\.\d+){3}$/.test(u.hostname)) return null;
|
|
52
|
+
return u;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* What is wrong with a `theme` value (as the config file wrote it).
|
|
57
|
+
* @param {unknown} t
|
|
58
|
+
* @returns {string[]}
|
|
59
|
+
*/
|
|
60
|
+
export function themeProblems(t) {
|
|
61
|
+
if (t === undefined) return [];
|
|
62
|
+
if (!isObject(t)) return ['"theme" is { css?, fonts?, fontHosts?, names?, default? }.'];
|
|
63
|
+
const out = [];
|
|
64
|
+
for (const k of Object.keys(t)) if (!THEME_KEYS.includes(k)) out.push(`theme.${k}: the keys are ${THEME_KEYS.join(', ')}.`);
|
|
65
|
+
if (t.css !== undefined && t.css !== null && !cssPathInRepo(t.css)) out.push('theme.css is one stylesheet (a .css file) inside the repo, written relative to it, like "./tools/cornfield/theme.css".');
|
|
66
|
+
let pairsKnown = true;
|
|
67
|
+
let fontCount = 0;
|
|
68
|
+
if (t.fonts !== undefined) {
|
|
69
|
+
if (!Array.isArray(t.fonts) || t.fonts.length > MAX_THEME_FONTS) out.push(`theme.fonts is a list of at most ${MAX_THEME_FONTS} https: stylesheet URLs.`);
|
|
70
|
+
else {
|
|
71
|
+
fontCount = t.fonts.length;
|
|
72
|
+
t.fonts.forEach((f, i) => {
|
|
73
|
+
const u = fontUrl(f);
|
|
74
|
+
if (!u) out.push(`theme.fonts[${i}] must be an https: stylesheet URL with a plain host name (no http:, no data:, no credentials, no IP address).`);
|
|
75
|
+
else if (!KNOWN_FONT_PAIRS[u.hostname]) pairsKnown = false;
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const hosts = t.fontHosts;
|
|
80
|
+
if (hosts !== undefined) {
|
|
81
|
+
if (!Array.isArray(hosts) || hosts.length > MAX_THEME_FONTS || hosts.some((h) => typeof h !== 'string' || !HOST.test(h) || /^\d+(?:\.\d+){3}$/.test(h))) out.push(`theme.fontHosts is a list of at most ${MAX_THEME_FONTS} host names (like "fonts.example.org"): where the font files of theme.fonts come from.`);
|
|
82
|
+
else if (!fontCount) out.push('theme.fontHosts only goes with theme.fonts.');
|
|
83
|
+
}
|
|
84
|
+
if (fontCount && !pairsKnown && !(Array.isArray(hosts) && hosts.length)) out.push(`theme.fonts names a host cornfield does not know the font file host of (known: ${Object.keys(KNOWN_FONT_PAIRS).join(', ')}): list where the font files come from in theme.fontHosts.`);
|
|
85
|
+
let names = [];
|
|
86
|
+
if (t.names !== undefined) {
|
|
87
|
+
if (!isObject(t.names)) out.push('theme.names is { name: "./path.css" }.');
|
|
88
|
+
else {
|
|
89
|
+
names = Object.keys(t.names);
|
|
90
|
+
if (names.length > MAX_THEME_NAMES) out.push(`theme.names lists at most ${MAX_THEME_NAMES} themes.`);
|
|
91
|
+
for (const [n, p] of Object.entries(t.names)) {
|
|
92
|
+
if (!THEME_NAME.test(n)) out.push(`theme.names "${n}": a name is lower-case letters, digits and hyphens, at most 32 characters.`);
|
|
93
|
+
if (!cssPathInRepo(p)) out.push(`theme.names.${n} is a .css file inside the repo, written relative to it.`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
if (t.default !== undefined && t.default !== null) {
|
|
98
|
+
if (!isText(t.default)) out.push('theme.default is the name of one of theme.names.');
|
|
99
|
+
else if (!names.includes(t.default)) out.push(`theme.default "${t.default}" is not one of theme.names (${names.join(', ') || 'none are listed'}).`);
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** The font hosts a theme allows: `{ style, font }`, each a list of origins for the CSP (sorted, no repeats) */
|
|
105
|
+
export function fontOrigins(theme) {
|
|
106
|
+
const style = new Set();
|
|
107
|
+
const font = new Set();
|
|
108
|
+
for (const f of (theme && theme.fonts) || []) {
|
|
109
|
+
const u = fontUrl(f);
|
|
110
|
+
if (!u) continue;
|
|
111
|
+
style.add(u.origin);
|
|
112
|
+
font.add(u.origin);
|
|
113
|
+
for (const h of KNOWN_FONT_PAIRS[u.hostname] || []) font.add(`https://${h}`);
|
|
114
|
+
}
|
|
115
|
+
for (const h of (theme && theme.fontHosts) || []) if (HOST.test(h)) font.add(`https://${h}`);
|
|
116
|
+
return { style: [...style].sort(), font: [...font].sort() };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** The files a theme names, `[{ key, rel }]`: `css` is key "css", a named theme is `names.<name>` */
|
|
120
|
+
export function themeFiles(theme) {
|
|
121
|
+
const out = [];
|
|
122
|
+
if (theme && theme.css) out.push({ key: 'css', rel: theme.css });
|
|
123
|
+
for (const [n, rel] of Object.entries((theme && theme.names) || {})) out.push({ key: `names.${n}`, rel });
|
|
124
|
+
return out;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** CSS escapes undone (`\6a ` and `\j` are both "j"), so a word cannot be hidden by writing it escaped */
|
|
128
|
+
function unescapeCss(s) {
|
|
129
|
+
return s.replace(/\\([0-9a-f]{1,6})\s?|\\([^\n])/gi, (_m, hex, ch) => {
|
|
130
|
+
if (hex) { const cp = parseInt(hex, 16); return cp > 0 && cp <= 0x10ffff ? String.fromCodePoint(cp) : ''; }
|
|
131
|
+
return ch;
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const FORBIDDEN = [
|
|
136
|
+
[/expression\s*\(/i, 'expression('],
|
|
137
|
+
[/javascript\s*:/i, 'javascript:'],
|
|
138
|
+
[/vbscript\s*:/i, 'vbscript:'],
|
|
139
|
+
[/behaviou?r\s*:/i, 'behavior:'],
|
|
140
|
+
[/-moz-binding/i, '-moz-binding'],
|
|
141
|
+
];
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The text with its comments replaced by `gap`, read as a browser tokenizes CSS: a comment marker inside a string is part of the
|
|
145
|
+
* string (so `content: "/*"` cannot hide what follows), an escaped character is never a marker, and an unclosed comment runs to the end.
|
|
146
|
+
* @param {string} text
|
|
147
|
+
* @param {string} gap
|
|
148
|
+
*/
|
|
149
|
+
function withoutComments(text, gap) {
|
|
150
|
+
let out = '';
|
|
151
|
+
let quote = null;
|
|
152
|
+
for (let i = 0; i < text.length; i++) {
|
|
153
|
+
const ch = text[i];
|
|
154
|
+
if (ch === '\\') { out += text.slice(i, i + 2); i++; continue; }
|
|
155
|
+
if (quote) { if (ch === quote || ch === '\n') quote = null; out += ch; continue; }
|
|
156
|
+
if (ch === '"' || ch === "'") { quote = ch; out += ch; continue; }
|
|
157
|
+
if (ch === '/' && text[i + 1] === '*') {
|
|
158
|
+
const end = text.indexOf('*/', i + 2);
|
|
159
|
+
out += gap;
|
|
160
|
+
if (end < 0) break;
|
|
161
|
+
i = end + 1;
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
out += ch;
|
|
165
|
+
}
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* The ways a stylesheet's text is read for the checks, comments taken out as a browser does and CSS escapes undone: with each comment
|
|
171
|
+
* as a space, as a browser reads it (`@import/**/url(…)` is still an import), and with comments removed outright, so a word split by
|
|
172
|
+
* one (`java/**/script:`) is still found. A check that either fails, fails.
|
|
173
|
+
*/
|
|
174
|
+
const readings = (text) => [unescapeCss(withoutComments(text, ' ')), unescapeCss(withoutComments(text, ''))];
|
|
175
|
+
|
|
176
|
+
/** Every `@import` and what it names: `@import "x"`, `@import url(x)`, and an `@import` with nothing after it ('') */
|
|
177
|
+
const IMPORT = /@import\s*(?:url\(\s*)?(?:"([^"]*)"|'([^']*)'|([^\s"');]*))/gi;
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* What is wrong with a theme file's text: it must be plain CSS, and keep out of script. An `@import` is refused
|
|
181
|
+
* unless it is an https: URL that is in the config's `theme.fonts`.
|
|
182
|
+
* @param {string} text
|
|
183
|
+
* @param {{ fonts?: string[] }} [opts] the config's allow-list
|
|
184
|
+
* @returns {string[]}
|
|
185
|
+
*/
|
|
186
|
+
export function cssProblems(text, { fonts = [] } = {}) {
|
|
187
|
+
if (typeof text !== 'string' || text.includes('\0')) return ['is not text (it holds a NUL byte), so it is not CSS.'];
|
|
188
|
+
const out = new Set();
|
|
189
|
+
const views = readings(text);
|
|
190
|
+
if (views.some((v) => /<\s*\/?\s*(?:script|style|html|head|body|!doctype)\b/i.test(v) || /<!--/.test(v))) out.add('looks like HTML, not CSS.');
|
|
191
|
+
for (const [re, word] of FORBIDDEN) if (views.some((v) => re.test(v))) out.add(`uses ${word}, which a theme may not (a theme is CSS only, never script).`);
|
|
192
|
+
const allowed = new Set(fonts);
|
|
193
|
+
for (const v of views) {
|
|
194
|
+
for (const m of v.matchAll(IMPORT)) {
|
|
195
|
+
const target = (m[1] ?? m[2] ?? m[3] ?? '').trim();
|
|
196
|
+
if (!allowed.has(target) || !fontUrl(target)) out.add(`has an @import of "${target.slice(0, 80)}": only an https: URL listed in theme.fonts may be imported.`);
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
// Braces must balance (outside strings, escapes skipped): a quick check that it is a stylesheet and not something else
|
|
200
|
+
const plain = withoutComments(text, '');
|
|
201
|
+
let depth = 0;
|
|
202
|
+
let quote = null;
|
|
203
|
+
for (let i = 0; i < plain.length; i++) {
|
|
204
|
+
const ch = plain[i];
|
|
205
|
+
if (ch === '\\') { i++; continue; }
|
|
206
|
+
if (quote) { if (ch === '\n') quote = null; else if (ch === quote) quote = null; continue; }
|
|
207
|
+
if (ch === '"' || ch === "'") quote = ch;
|
|
208
|
+
else if (ch === '{') depth++;
|
|
209
|
+
else if (ch === '}' && --depth < 0) break;
|
|
210
|
+
}
|
|
211
|
+
if (depth !== 0) out.add('has unbalanced braces, so it is not valid CSS.');
|
|
212
|
+
return [...out];
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
// ---------------------------------------------------------------------------
|
|
216
|
+
// Assets beside a theme: images and fonts a theme's url() names
|
|
217
|
+
// ---------------------------------------------------------------------------
|
|
218
|
+
|
|
219
|
+
/** Where the files beside a theme are served (server/server.js): `/cornfield/theme/assets/<path under the theme folder>` */
|
|
220
|
+
export const THEME_ASSET_PREFIX = '/cornfield/theme/assets/';
|
|
221
|
+
/** The largest a theme asset may be, in bytes */
|
|
222
|
+
export const MAX_THEME_ASSET_BYTES = 1024 * 1024;
|
|
223
|
+
/** The only files served beside a theme, by lower-case extension: images and fonts, never a page or a script */
|
|
224
|
+
export const THEME_ASSET_TYPES = Object.freeze({
|
|
225
|
+
'.png': 'image/png',
|
|
226
|
+
'.svg': 'image/svg+xml',
|
|
227
|
+
'.webp': 'image/webp',
|
|
228
|
+
'.gif': 'image/gif',
|
|
229
|
+
'.avif': 'image/avif',
|
|
230
|
+
'.woff2': 'font/woff2',
|
|
231
|
+
'.woff': 'font/woff',
|
|
232
|
+
});
|
|
233
|
+
/** An SVG is an image here, never a page: if it is opened on its own it may not run or load anything */
|
|
234
|
+
export const THEME_SVG_CSP = "default-src 'none'; style-src 'unsafe-inline'";
|
|
235
|
+
/** A `data:` URL a theme may use in url(): an image */
|
|
236
|
+
const DATA_IMAGE = /^data:image\/(?:png|gif|webp|avif|svg\+xml)[;,]/i;
|
|
237
|
+
const ASSET_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]{0,127}$/;
|
|
238
|
+
|
|
239
|
+
/** The served path of a theme file, by its key from `themeFiles` */
|
|
240
|
+
export const themeFileUrl = (key) => (key === 'css' ? '/cornfield/theme.css' : `/cornfield/theme/${key.slice('names.'.length)}.css`);
|
|
241
|
+
|
|
242
|
+
/**
|
|
243
|
+
* The path under the theme folder that an asset request names (the decoded part after THEME_ASSET_PREFIX), or null when it is not
|
|
244
|
+
* one that may be served: plain ASCII segments (letters, digits, `.`, `_`, `-`), none empty, none starting with a dot (so no `..`,
|
|
245
|
+
* no `.git`), no backslash, at most 8 deep, and a THEME_ASSET_TYPES extension.
|
|
246
|
+
* @param {string} rest
|
|
247
|
+
* @returns {string | null}
|
|
248
|
+
*/
|
|
249
|
+
export function themeAssetPath(rest) {
|
|
250
|
+
if (typeof rest !== 'string' || rest.length > 512) return null;
|
|
251
|
+
const parts = rest.split('/');
|
|
252
|
+
if (parts.length > 8 || !parts.every((p) => ASSET_SEGMENT.test(p))) return null;
|
|
253
|
+
return THEME_ASSET_TYPES[path.posix.extname(rest).toLowerCase()] ? parts.join('/') : null;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* The repo folder whose images and fonts are served beside the theme (relative, with `/`): the folder of the theme files, or the
|
|
258
|
+
* deepest one that holds them all when they sit in different folders. null when there are no theme files or that folder is the
|
|
259
|
+
* repo's top, so a theme at the top of the repo never opens the whole repo's images.
|
|
260
|
+
* @param {object} theme
|
|
261
|
+
* @returns {string | null}
|
|
262
|
+
*/
|
|
263
|
+
export function themeAssetDir(theme) {
|
|
264
|
+
const dirs = themeFiles(theme).map(({ rel }) => path.posix.normalize(String(rel).replace(/\\/g, '/')).split('/').slice(0, -1).filter((p) => p && p !== '.'));
|
|
265
|
+
if (!dirs.length) return null;
|
|
266
|
+
const common = [];
|
|
267
|
+
for (let i = 0; dirs.every((d) => i < d.length && d[i] === dirs[0][i]); i++) common.push(dirs[0][i]);
|
|
268
|
+
return common.length && !common.includes('..') ? common.join('/') : null;
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/**
|
|
272
|
+
* Every url() (and src()) a stylesheet names, as written, escapes undone, comments and @import rules left out (an @import is
|
|
273
|
+
* cssProblems's to check).
|
|
274
|
+
* @param {string} text
|
|
275
|
+
* @returns {string[]}
|
|
276
|
+
*/
|
|
277
|
+
export function cssUrls(text) {
|
|
278
|
+
if (typeof text !== 'string') return [];
|
|
279
|
+
const css = unescapeCss(withoutComments(text, ' ')).replace(/@import\b[^;]*;?/gi, ' ');
|
|
280
|
+
return [...css.matchAll(/(?<![\w-])(?:url|src)\(\s*(?:"([^"]*)"|'([^']*)'|([^)\s]*))\s*\)/gi)].map((m) => (m[1] ?? m[2] ?? m[3] ?? '').trim());
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/**
|
|
284
|
+
* Where a url() in a theme file leads, read as the browser reads it: relative to where that file is served (`/cornfield/theme.css`
|
|
285
|
+
* or `/cornfield/theme/<name>.css`). `{ data: true }` for a data: image, `{ asset }` for a path under THEME_ASSET_PREFIX that may
|
|
286
|
+
* be served (themeAssetPath), else `{ problem }`.
|
|
287
|
+
* @param {string} ref what url() holds
|
|
288
|
+
* @param {string} servedAt the file's served path (themeFileUrl)
|
|
289
|
+
* @returns {{ data?: true, asset?: string, problem?: string }}
|
|
290
|
+
*/
|
|
291
|
+
export function themeUrlTarget(ref, servedAt) {
|
|
292
|
+
if (DATA_IMAGE.test(ref)) return { data: true };
|
|
293
|
+
const why = `url(${ref.slice(0, 80)}) is not an image or font served beside the theme: write it as ${THEME_ASSET_PREFIX}<path> (a png, svg, webp, gif, avif, woff2 or woff file under the theme's folder), or as a data: image.`;
|
|
294
|
+
if (!ref) return { problem: why };
|
|
295
|
+
let u;
|
|
296
|
+
try { u = new URL(ref, `https://cornfield.invalid${servedAt}`); } catch { return { problem: why }; }
|
|
297
|
+
if (u.origin !== 'https://cornfield.invalid' || !u.pathname.startsWith(THEME_ASSET_PREFIX)) return { problem: why };
|
|
298
|
+
let rest;
|
|
299
|
+
try { rest = decodeURIComponent(u.pathname.slice(THEME_ASSET_PREFIX.length)); } catch { return { problem: why }; }
|
|
300
|
+
const asset = themeAssetPath(rest);
|
|
301
|
+
return asset ? { asset } : { problem: why };
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
/** The theme as the browser is told it: names and the default, never a path on this machine */
|
|
305
|
+
export function clientTheme(theme) {
|
|
306
|
+
if (!theme) return null;
|
|
307
|
+
const names = Object.keys(theme.names || {});
|
|
308
|
+
return names.length ? { names, default: theme.default || null } : null;
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
/**
|
|
312
|
+
* The file on disk an asset path names (themeAssetPath's result), or why there is none: it must be a plain file under the theme folder
|
|
313
|
+
* (themeAssetDir) once links are followed (a link that leads out of that folder is refused), at most MAX_THEME_ASSET_BYTES.
|
|
314
|
+
* @param {string} root the repo
|
|
315
|
+
* @param {object} theme the config's theme
|
|
316
|
+
* @param {string} rel the asset path
|
|
317
|
+
* @returns {{ file: string, size: number, type: string } | { problem: string }}
|
|
318
|
+
*/
|
|
319
|
+
export function themeAssetFile(root, theme, rel) {
|
|
320
|
+
const dir = themeAssetDir(theme);
|
|
321
|
+
if (!dir) return { problem: 'no theme folder serves assets (the theme files are at the top of the repo, so nothing beside them is served; put them in a folder).' };
|
|
322
|
+
const type = THEME_ASSET_TYPES[path.posix.extname(rel).toLowerCase()];
|
|
323
|
+
if (!type || themeAssetPath(rel) !== rel) return { problem: 'is not an image or font file name that may be served.' };
|
|
324
|
+
let base;
|
|
325
|
+
let real;
|
|
326
|
+
try {
|
|
327
|
+
const top = fs.realpathSync(root);
|
|
328
|
+
base = fs.realpathSync(path.join(root, ...dir.split('/')));
|
|
329
|
+
if (!base.startsWith(top + path.sep)) return { problem: `the theme folder ${dir} leaves the repo.` };
|
|
330
|
+
} catch { return { problem: `the theme folder ${dir} does not exist.` }; }
|
|
331
|
+
try { real = fs.realpathSync(path.join(base, ...rel.split('/'))); } catch { return { problem: `${dir}/${rel} does not exist.` }; }
|
|
332
|
+
if (!real.startsWith(base + path.sep)) return { problem: `${dir}/${rel} leads out of the theme folder (a link).` };
|
|
333
|
+
const stats = fs.statSync(real);
|
|
334
|
+
if (!stats.isFile()) return { problem: `${dir}/${rel} is not a file.` };
|
|
335
|
+
if (stats.size > MAX_THEME_ASSET_BYTES) return { problem: `${dir}/${rel} is ${Math.ceil(stats.size / 1024)} KB; an asset beside a theme is at most ${MAX_THEME_ASSET_BYTES / 1024 / 1024} MB.` };
|
|
336
|
+
return { file: real, size: stats.size, type };
|
|
337
|
+
}
|
package/core/validate.js
CHANGED
|
@@ -23,6 +23,7 @@ import { CLOUD_FILE, cloudNodeProblems } from './cloud.js';
|
|
|
23
23
|
import { deriveTopology } from './derive.js';
|
|
24
24
|
import { missingPaths, planSync } from './sync.js';
|
|
25
25
|
import { repoPaths, repoReader } from './repo.js';
|
|
26
|
+
import { MAX_THEME_BYTES, cssProblems, cssUrls, themeAssetFile, themeFileUrl, themeFiles, themeUrlTarget } from './theme.js';
|
|
26
27
|
|
|
27
28
|
/** How a page is produced today, and whether it is baked to a file */
|
|
28
29
|
export const RENDER_NOW = ['build', 'request', 'build+request', 'rom'];
|
|
@@ -30,6 +31,41 @@ export const ROM_MODES = ['bake', 'skip'];
|
|
|
30
31
|
|
|
31
32
|
const ONLY_REMOVES_HINT = '(A proposal that adds nothing cannot show it has been built: delete it, or close its spec, in the PR that lands it.)';
|
|
32
33
|
|
|
34
|
+
/**
|
|
35
|
+
* The config's theme files (docs/config.md#theme): each one exists, is a plain file inside the repo (a link out of it is refused),
|
|
36
|
+
* is at most MAX_THEME_BYTES, is CSS that keeps out of script (core/theme.js `cssProblems`), and every url() in it is a data: image
|
|
37
|
+
* or an image or font the server serves beside the theme (core/theme.js `themeUrlTarget`, `themeAssetFile`).
|
|
38
|
+
* @param {{ root: string, theme?: object }} config
|
|
39
|
+
* @returns {string[]}
|
|
40
|
+
*/
|
|
41
|
+
export function validateThemeFiles(config) {
|
|
42
|
+
const errors = [];
|
|
43
|
+
let base;
|
|
44
|
+
try { base = fs.realpathSync(config.root); } catch { return errors; }
|
|
45
|
+
for (const { key, rel } of themeFiles(config.theme)) {
|
|
46
|
+
const where = `theme.${key} (${rel})`;
|
|
47
|
+
const file = path.resolve(config.root, rel);
|
|
48
|
+
let real;
|
|
49
|
+
try { real = fs.realpathSync(file); } catch { errors.push(`${where} does not exist.`); continue; }
|
|
50
|
+
if (!real.startsWith(base + path.sep)) { errors.push(`${where} leaves the repo (a link or a path that resolves outside it).`); continue; }
|
|
51
|
+
const stats = fs.statSync(real);
|
|
52
|
+
if (!stats.isFile()) { errors.push(`${where} is not a file.`); continue; }
|
|
53
|
+
if (stats.size > MAX_THEME_BYTES) { errors.push(`${where} is ${Math.ceil(stats.size / 1024)} KB; a theme file is at most ${MAX_THEME_BYTES / 1024} KB.`); continue; }
|
|
54
|
+
const text = fs.readFileSync(real, 'utf8');
|
|
55
|
+
for (const p of cssProblems(text, { fonts: config.theme.fonts })) errors.push(`${where} ${p}`);
|
|
56
|
+
// Every url() leads to an image or font served beside the theme, or is a data: image (docs/config.md#theme)
|
|
57
|
+
for (const ref of new Set(cssUrls(text))) {
|
|
58
|
+
const target = themeUrlTarget(ref, themeFileUrl(key));
|
|
59
|
+
if (target.problem) { errors.push(`${where} ${target.problem}`); continue; }
|
|
60
|
+
if (target.asset) {
|
|
61
|
+
const found = themeAssetFile(config.root, config.theme, target.asset);
|
|
62
|
+
if ('problem' in found) errors.push(`${where} url(${ref.slice(0, 80)}): ${found.problem}`);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return errors;
|
|
67
|
+
}
|
|
68
|
+
|
|
33
69
|
/**
|
|
34
70
|
* The schema checks: no files, no derivers.
|
|
35
71
|
* @param {{ nodes: any[], edges: any[] }} topology
|
|
@@ -220,6 +256,7 @@ export async function validateRepo({ config, derivers, topology = readTopology(c
|
|
|
220
256
|
errors.push(`Deriving the map from the code failed: ${err.message}`);
|
|
221
257
|
}
|
|
222
258
|
errors.push(...validatePersonasFile(config.root, config.personas.roles));
|
|
259
|
+
errors.push(...validateThemeFiles(config));
|
|
223
260
|
errors.push(...validateCloudNodes(topology, config.root));
|
|
224
261
|
errors.push(...validateProposalFiles(topology, path.join(config.root, config.proposals), config.root));
|
|
225
262
|
const io = repoReader(config.root);
|
package/explorer/explorer.css
CHANGED
|
@@ -825,6 +825,9 @@ button.hx-proposal-item:focus-visible { outline: 2px solid var(--hx-indigo); out
|
|
|
825
825
|
.hx-forge-filters { display: grid; grid-template-columns: 1fr 1fr; gap: 6px 8px; }
|
|
826
826
|
.hx-forge-field { display: flex; flex-direction: column; gap: 2px; min-width: 0; font-size: 10px; font-weight: 700; text-transform: uppercase; letter-spacing: 0.05em; color: var(--hx-slate-400); }
|
|
827
827
|
.hx-forge-field--text { grid-column: 1 / -1; }
|
|
828
|
+
/* The Start dialog's four limits: two a row, under their legend */
|
|
829
|
+
.hx-forge-limits { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 6px 8px; margin: 0; padding: 0; border: 0; }
|
|
830
|
+
.hx-forge-limits > legend { padding: 0 0 4px; }
|
|
828
831
|
.hx-forge-select, .hx-forge-input { width: 100%; min-width: 0; padding: 5px 8px; border-radius: 8px; border: 1px solid var(--hx-line); background: var(--hx-well); color: var(--hx-ink); font: inherit; font-size: 12px; font-weight: 400; text-transform: none; letter-spacing: 0; user-select: text; }
|
|
829
832
|
.hx-forge-input::placeholder { color: var(--hx-slate-500); }
|
|
830
833
|
.hx-forge-input:focus-visible { outline: 2px solid var(--hx-indigo); outline-offset: 2px; }
|