cornfield 0.21.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/config.js +5 -0
- package/core/theme.js +337 -0
- package/core/validate.js +37 -0
- package/explorer/index.html +9 -2
- package/explorer/plugins.js +2 -0
- 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/server.js +98 -4
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/index.html
CHANGED
|
@@ -8,10 +8,14 @@
|
|
|
8
8
|
<!--@importmap-->
|
|
9
9
|
|
|
10
10
|
<!-- The explorer's own stylesheet and modules (explorer/): no build step, no CDN -->
|
|
11
|
-
<!-- Light or dark on <html data-theme> before the first paint (theme-boot.js; theme.js keeps it after) -->
|
|
12
|
-
<script src="/explorer/theme-boot.js"></script>
|
|
13
11
|
<link rel="stylesheet" href="/explorer/explorer.css" />
|
|
14
12
|
<link rel="stylesheet" href="/explorer/house.css" />
|
|
13
|
+
<!-- The config's theme (server/server.js puts it here, so it comes after cornfield's own CSS): font stylesheets, the repo's theme.css, a named theme -->
|
|
14
|
+
<!--@theme-->
|
|
15
|
+
<!-- Light or dark on <html data-theme>, and the named theme on <html data-theme-name>, before the first paint (theme-boot.js; theme.js
|
|
16
|
+
keeps it after). A classic script in the head, after every stylesheet link: it runs before the body is parsed, so before anything is
|
|
17
|
+
drawn, and the named theme's <link> above already exists when it runs. Keep it the last thing in the head. -->
|
|
18
|
+
<script src="/explorer/theme-boot.js"></script>
|
|
15
19
|
</head>
|
|
16
20
|
<body>
|
|
17
21
|
<!-- Top bar: layers, data-flow preset, search, layout mode, zoom, links -->
|
|
@@ -157,6 +161,9 @@
|
|
|
157
161
|
</svg>
|
|
158
162
|
</button>
|
|
159
163
|
|
|
164
|
+
<!-- The named themes of the config (`theme.names`): filled and shown by explorer/theme-names.js; hidden when there are none -->
|
|
165
|
+
<select id="theme-name-select" class="hx-forge-select" style="width:auto;max-width:9rem" aria-label="Theme" title="Theme" hidden></select>
|
|
166
|
+
|
|
160
167
|
<!-- The config's links (cornfield.config.js `links`), filled by explorer/plugins.js -->
|
|
161
168
|
<span id="cf-links" class="hx-links"></span>
|
|
162
169
|
</div>
|
package/explorer/plugins.js
CHANGED
|
@@ -15,6 +15,7 @@
|
|
|
15
15
|
*/
|
|
16
16
|
|
|
17
17
|
import { escHtml } from './state.js';
|
|
18
|
+
import { initThemePicker } from './theme-names.js';
|
|
18
19
|
|
|
19
20
|
/** What the live layer shows when the repo names no live source */
|
|
20
21
|
export const NO_SOURCE = Object.freeze({
|
|
@@ -43,6 +44,7 @@ export function applyBranding(doc, config) {
|
|
|
43
44
|
if (title && config.title) title.textContent = config.title;
|
|
44
45
|
const heading = doc.getElementById('cf-heading');
|
|
45
46
|
if (heading && config.title) heading.textContent = `${config.title}: the map`;
|
|
47
|
+
initThemePicker(doc, config.theme);
|
|
46
48
|
const links = doc.getElementById('cf-links');
|
|
47
49
|
if (!links) return;
|
|
48
50
|
const html = Array.isArray(config.links) ? config.links
|
package/explorer/theme-boot.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/*
|
|
2
|
-
* Before the first paint (a classic script in the head of explorer/index.html, not a module, so it
|
|
3
|
-
* before the page is drawn): puts the theme on <html data-theme>, so a light page never flashes dark. The
|
|
2
|
+
* Before the first paint (a classic script, the last thing in the head of explorer/index.html, not a module, so it
|
|
3
|
+
* runs before the body is parsed and the page is drawn): puts the theme on <html data-theme>, so a light page never flashes dark. The
|
|
4
4
|
* same rule as theme-model.js `themeChoiceFrom` and `resolveTheme` (a test holds them together); theme.js
|
|
5
5
|
* takes over once the modules load.
|
|
6
6
|
*/
|
|
@@ -14,3 +14,23 @@
|
|
|
14
14
|
|| (choice !== 'dark' && !!(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches));
|
|
15
15
|
document.documentElement.setAttribute('data-theme', light ? 'light' : 'dark');
|
|
16
16
|
})();
|
|
17
|
+
|
|
18
|
+
/*
|
|
19
|
+
* The named themes of the config (`theme.names`, docs/config.md#theme): the server puts them on <html data-theme-names="a b"
|
|
20
|
+
* data-theme-default="a">. This puts the viewer's pick (localStorage, when it is one of them) or the default on
|
|
21
|
+
* <html data-theme-name> before the first paint, and points the named theme's <link id="cf-theme-name-css"> at it (that link comes
|
|
22
|
+
* before this script in the head, so it exists now). Only a plain name (theme-model.js `themeNameHref`) ever reaches the attribute or
|
|
23
|
+
* the URL. The same rule as theme-model.js `themeNameFrom` (a test holds them together).
|
|
24
|
+
*/
|
|
25
|
+
(function () {
|
|
26
|
+
var root = document.documentElement;
|
|
27
|
+
var names = (root.getAttribute('data-theme-names') || '').split(' ').filter(function (n) { return /^[a-z0-9][a-z0-9-]{0,31}$/.test(n); });
|
|
28
|
+
if (!names.length) return;
|
|
29
|
+
var stored = null;
|
|
30
|
+
try { stored = window.localStorage.getItem('cornfield:theme-name'); } catch (e) { stored = null; }
|
|
31
|
+
var fallback = root.getAttribute('data-theme-default');
|
|
32
|
+
var name = stored && names.indexOf(stored) >= 0 ? stored : (fallback && names.indexOf(fallback) >= 0 ? fallback : '');
|
|
33
|
+
if (name) root.setAttribute('data-theme-name', name); else root.removeAttribute('data-theme-name');
|
|
34
|
+
var link = document.getElementById('cf-theme-name-css');
|
|
35
|
+
if (link) { if (name) link.setAttribute('href', '/cornfield/theme/' + name + '.css'); else link.removeAttribute('href'); }
|
|
36
|
+
})();
|
package/explorer/theme-model.js
CHANGED
|
@@ -30,6 +30,25 @@
|
|
|
30
30
|
export const THEME_CHOICES = ['system', 'light', 'dark'];
|
|
31
31
|
/** Where the choice is kept in the browser (theme.js); `?theme=` in the address wins over it, without being kept */
|
|
32
32
|
export const THEME_STORAGE_KEY = 'topology-explorer:theme';
|
|
33
|
+
/** Where a viewer's pick among the config's named themes is kept (theme-names.js); theme-boot.js reads the same key */
|
|
34
|
+
export const THEME_NAME_STORAGE_KEY = 'cornfield:theme-name';
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The named theme in force: the stored pick when it is one of `names`, else the config's default when that is one, else none ('').
|
|
38
|
+
* The same rule as theme-boot.js (a test holds them together).
|
|
39
|
+
* @param {string|null} stored what THEME_NAME_STORAGE_KEY holds
|
|
40
|
+
* @param {string[]} names the config's theme names
|
|
41
|
+
* @param {string|null} fallback the config's default
|
|
42
|
+
* @returns {string}
|
|
43
|
+
*/
|
|
44
|
+
export function themeNameFrom(stored, names, fallback) {
|
|
45
|
+
if (stored && names.includes(stored)) return stored;
|
|
46
|
+
return fallback && names.includes(fallback) ? fallback : '';
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Where a named theme's stylesheet is served (server/server.js); '' for no named theme */
|
|
50
|
+
export const themeNameHref = (name) => (/^[a-z0-9][a-z0-9-]{0,31}$/.test(name) ? `/cornfield/theme/${name}.css` : '');
|
|
51
|
+
|
|
33
52
|
/** The light page's ground (--hx-bg in explorer.css): what the light colours are measured against */
|
|
34
53
|
export const LIGHT_GROUND = '#f4f6fa';
|
|
35
54
|
/** The dark page's ground, for checking what the dark theme already does */
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module explorer/theme-names
|
|
3
|
+
*
|
|
4
|
+
* The named themes of the config (`theme.names`, docs/config.md#theme), the half that touches the page after load. theme-boot.js has
|
|
5
|
+
* already put the pick on <html data-theme-name> before the first paint; this fills the small <select> in the header with the names,
|
|
6
|
+
* and on a change sets the attribute, points the named theme's stylesheet link at it, and keeps the pick in localStorage
|
|
7
|
+
* (THEME_NAME_STORAGE_KEY). A theme is CSS only: nothing here loads anything but a stylesheet from this origin.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { THEME_NAME_STORAGE_KEY, themeNameFrom, themeNameHref } from './theme-model.js';
|
|
11
|
+
|
|
12
|
+
function readStored() {
|
|
13
|
+
try { return window.localStorage.getItem(THEME_NAME_STORAGE_KEY); } catch { return null; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function store(name, fallback) {
|
|
17
|
+
try {
|
|
18
|
+
if (name === fallback) window.localStorage.removeItem(THEME_NAME_STORAGE_KEY);
|
|
19
|
+
else window.localStorage.setItem(THEME_NAME_STORAGE_KEY, name);
|
|
20
|
+
} catch { /* storage blocked: the pick still holds for this visit */ }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Puts a named theme in force on the page ('' for none) */
|
|
24
|
+
export function setThemeName(doc, name) {
|
|
25
|
+
const root = doc.documentElement;
|
|
26
|
+
if (name) root.setAttribute('data-theme-name', name); else root.removeAttribute('data-theme-name');
|
|
27
|
+
const link = doc.getElementById('cf-theme-name-css');
|
|
28
|
+
const href = themeNameHref(name);
|
|
29
|
+
if (link) { if (href) link.setAttribute('href', href); else link.removeAttribute('href'); }
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Fills the header's picker from the config (`{ names, default }`, from /cornfield/config.json) and wires it. Hidden when there are no names.
|
|
34
|
+
* @param {Document} doc
|
|
35
|
+
* @param {{ names?: string[], default?: string | null } | null | undefined} theme
|
|
36
|
+
*/
|
|
37
|
+
export function initThemePicker(doc, theme) {
|
|
38
|
+
const select = doc.getElementById('theme-name-select');
|
|
39
|
+
if (!select) return;
|
|
40
|
+
const names = theme && Array.isArray(theme.names) ? theme.names.filter((n) => themeNameHref(n)) : [];
|
|
41
|
+
if (!names.length) { select.hidden = true; return; }
|
|
42
|
+
const fallback = theme.default && names.includes(theme.default) ? theme.default : '';
|
|
43
|
+
select.textContent = '';
|
|
44
|
+
const add = (value, label) => {
|
|
45
|
+
const o = doc.createElement('option');
|
|
46
|
+
o.value = value;
|
|
47
|
+
o.textContent = label;
|
|
48
|
+
select.appendChild(o);
|
|
49
|
+
};
|
|
50
|
+
if (!fallback) add('', 'Standard');
|
|
51
|
+
for (const n of names) add(n, n);
|
|
52
|
+
const current = themeNameFrom(readStored(), names, fallback);
|
|
53
|
+
setThemeName(doc, current);
|
|
54
|
+
select.value = current;
|
|
55
|
+
select.hidden = false;
|
|
56
|
+
select.onchange = () => {
|
|
57
|
+
const next = names.includes(select.value) ? select.value : '';
|
|
58
|
+
setThemeName(doc, next);
|
|
59
|
+
store(next, fallback);
|
|
60
|
+
};
|
|
61
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.22.0",
|
|
4
4
|
"description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "popcorn245 (https://github.com/popcorn245)",
|
package/server/server.js
CHANGED
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
* GET /cornfield/house.json the repo's house file, when `sources.house` is the built-in house source;
|
|
17
17
|
* Home Assistant's floors, areas and devices, when it is `home-assistant`
|
|
18
18
|
* GET /repo/<path>.js a browser module the config names (and the files in its folder)
|
|
19
|
+
* GET /cornfield/theme.css, /cornfield/theme/<name>.css
|
|
20
|
+
* the stylesheets the config's `theme` names (css, names): those files only, as text/css
|
|
21
|
+
* GET /cornfield/theme/assets/<path> an image or font beside the theme files (png, svg, webp, gif, avif, woff2, woff; 1 MB each)
|
|
19
22
|
* GET /api/forge/… issues, pull requests, their files and checks, release notes: read from the forge (server/forge-routes.js)
|
|
20
23
|
* POST /api/forge/pulls/<n>/merge|rerun land a green pull request, re-run a failed check (server/forge-actions.js)
|
|
21
24
|
* POST /api/forge/issues/<n>/spec, /pulls/<n>/build the pipeline's steps (server/pipeline.js, server/forge-actions.js)
|
|
@@ -50,6 +53,7 @@ import { createHash, randomBytes } from 'node:crypto';
|
|
|
50
53
|
import { fileURLToPath } from 'node:url';
|
|
51
54
|
import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf, DEFAULTS, hookWants, ideaLabel, runnerQuietAfterMs } from '../core/config.js';
|
|
52
55
|
import { CLOUD_FILE } from '../core/cloud.js';
|
|
56
|
+
import { MAX_THEME_ASSET_BYTES, MAX_THEME_BYTES, THEME_ASSET_PREFIX, THEME_NAME, THEME_SVG_CSP, clientTheme, cssProblems, fontOrigins, fontUrl, themeAssetFile, themeAssetPath } from '../core/theme.js';
|
|
53
57
|
import { decodePath, inside, notFound, sendFile } from './files.js';
|
|
54
58
|
import { serveProposals } from './proposals.js';
|
|
55
59
|
import { serveForge } from './forge-routes.js';
|
|
@@ -90,14 +94,96 @@ function importMapOf(config) {
|
|
|
90
94
|
* The Content-Security-Policy of every page: everything from this origin, nothing from anywhere else
|
|
91
95
|
* (the explorer runs offline from any CDN). An import map is inline, so it is allowed by its hash.
|
|
92
96
|
*/
|
|
93
|
-
function cspOf(importMap) {
|
|
97
|
+
function cspOf(importMap, theme) {
|
|
98
|
+
const { style, font } = fontOrigins(theme);
|
|
94
99
|
const hash = importMap ? ` 'sha256-${createHash('sha256').update(importMap).digest('base64')}'` : '';
|
|
95
100
|
return [
|
|
96
|
-
"default-src 'self'", `script-src 'self'${hash}`,
|
|
97
|
-
"connect-src 'self'",
|
|
101
|
+
"default-src 'self'", `script-src 'self'${hash}`, `style-src 'self' 'unsafe-inline'${style.map((o) => ` ${o}`).join('')}`, "img-src 'self' data: blob:",
|
|
102
|
+
"connect-src 'self'", `font-src 'self'${font.map((o) => ` ${o}`).join('')}`, "object-src 'none'", "base-uri 'none'", "frame-ancestors 'none'", "form-action 'self'",
|
|
98
103
|
].join('; ');
|
|
99
104
|
}
|
|
100
105
|
|
|
106
|
+
/** The config's theme names that may reach the page: plain ones only (core/theme.js THEME_NAME), and the default when it is one of them */
|
|
107
|
+
function themeNamesOf(theme) {
|
|
108
|
+
const names = Object.keys(theme.names || {}).filter((n) => THEME_NAME.test(n));
|
|
109
|
+
return { names, fallback: theme.default && names.includes(theme.default) ? theme.default : null };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** `<html>` with the named themes on it, for theme-boot.js to read before the first paint */
|
|
113
|
+
function themeHtmlTag(theme) {
|
|
114
|
+
const { names, fallback } = themeNamesOf(theme);
|
|
115
|
+
return names.length ? `<html lang="en" data-theme-names="${names.join(' ')}"${fallback ? ` data-theme-default="${fallback}"` : ''}>` : '<html lang="en">';
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The links that go after cornfield's own stylesheets, in this order: the allow-listed font stylesheets, the repo's theme.css, and the
|
|
120
|
+
* default named theme. explorer/index.html includes theme-boot.js once, after these, so it points that link at the viewer's choice
|
|
121
|
+
* before the first paint. Always links, never inlined CSS.
|
|
122
|
+
*/
|
|
123
|
+
function themeHead(theme) {
|
|
124
|
+
const out = [];
|
|
125
|
+
for (const f of theme.fonts || []) {
|
|
126
|
+
const u = fontUrl(f);
|
|
127
|
+
if (u) out.push(`<link rel="stylesheet" href="${escapeHtml(u.href)}" referrerpolicy="no-referrer" />`);
|
|
128
|
+
}
|
|
129
|
+
if (theme.css) out.push('<link rel="stylesheet" href="/cornfield/theme.css" data-cf-theme="css" />');
|
|
130
|
+
const { names, fallback } = themeNamesOf(theme);
|
|
131
|
+
if (names.length) out.push(`<link rel="stylesheet" id="cf-theme-name-css"${fallback ? ` href="/cornfield/theme/${fallback}.css"` : ''} data-cf-theme="name" />`);
|
|
132
|
+
return out.join('\n ');
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** The theme files the config names, by the path they are served at: `Map<'/cornfield/theme.css' | '/cornfield/theme/<name>.css', rel>` */
|
|
136
|
+
function themeFilesOf(config) {
|
|
137
|
+
const t = config.theme || {};
|
|
138
|
+
const out = new Map();
|
|
139
|
+
if (t.css) out.set('/cornfield/theme.css', t.css);
|
|
140
|
+
for (const [n, rel] of Object.entries(t.names || {})) if (THEME_NAME.test(n)) out.set(`/cornfield/theme/${n}.css`, rel);
|
|
141
|
+
return out;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* 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
|
|
146
|
+
* (a link out is refused), only up to MAX_THEME_BYTES, and only if it passes the same CSS checks as `cornfield validate`.
|
|
147
|
+
*/
|
|
148
|
+
function sendTheme(req, res, config, rel, reqPath) {
|
|
149
|
+
try {
|
|
150
|
+
const file = inside(config.root, rel);
|
|
151
|
+
const real = file && fs.realpathSync(file);
|
|
152
|
+
const base = fs.realpathSync(config.root);
|
|
153
|
+
if (!real || !real.startsWith(base + path.sep)) return notFound(res, reqPath);
|
|
154
|
+
const stats = fs.statSync(real);
|
|
155
|
+
if (!stats.isFile() || stats.size > MAX_THEME_BYTES) return notFound(res, reqPath);
|
|
156
|
+
const text = fs.readFileSync(real, 'utf8');
|
|
157
|
+
if (cssProblems(text, { fonts: config.theme.fonts }).length) return notFound(res, reqPath);
|
|
158
|
+
res.writeHead(200, { 'Content-Type': 'text/css; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
|
|
159
|
+
return res.end(req.method === 'HEAD' ? undefined : text);
|
|
160
|
+
} catch {
|
|
161
|
+
return notFound(res, reqPath);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Serves one image or font from beside the theme (docs/config.md#theme): only a THEME_ASSET_TYPES file under the theme folder
|
|
167
|
+
* (core/theme.js `themeAssetPath`, `themeAssetFile`: plain names, no dot segments, no link out, at most 1 MB), never a listing,
|
|
168
|
+
* with nosniff; an SVG gets a policy of its own, so opened by itself it runs and loads nothing.
|
|
169
|
+
*/
|
|
170
|
+
function sendThemeAsset(req, res, config, reqPath) {
|
|
171
|
+
try {
|
|
172
|
+
const rel = themeAssetPath(reqPath.slice(THEME_ASSET_PREFIX.length));
|
|
173
|
+
const found = rel && themeAssetFile(config.root, config.theme || {}, rel);
|
|
174
|
+
if (!found || 'problem' in found) return notFound(res, reqPath);
|
|
175
|
+
const body = fs.readFileSync(found.file);
|
|
176
|
+
if (body.length > MAX_THEME_ASSET_BYTES) return notFound(res, reqPath); // it grew since it was looked at
|
|
177
|
+
res.writeHead(200, {
|
|
178
|
+
'Content-Type': found.type, 'Content-Length': body.length, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff',
|
|
179
|
+
...(found.type === 'image/svg+xml' ? { 'Content-Security-Policy': THEME_SVG_CSP } : {}),
|
|
180
|
+
});
|
|
181
|
+
return res.end(req.method === 'HEAD' ? undefined : body);
|
|
182
|
+
} catch {
|
|
183
|
+
return notFound(res, reqPath);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
101
187
|
/** The browser modules the config names from the repo: each one's folder may be served (its .js files only) */
|
|
102
188
|
function repoModuleDirs(config) {
|
|
103
189
|
const dirs = [];
|
|
@@ -120,6 +206,8 @@ export function clientConfig(config, signIn = false) {
|
|
|
120
206
|
version: PKG.version,
|
|
121
207
|
title: config.title,
|
|
122
208
|
links: config.links || [],
|
|
209
|
+
// The theme's names and default, never a file's path (docs/config.md#theme)
|
|
210
|
+
theme: clientTheme(config.theme),
|
|
123
211
|
forge: config.forge ? { type: config.forge.type, url: config.forge.url || (config.forge.type === 'github' ? 'https://github.com' : null), repo: config.forge.repo, mergeMethod: config.forge.mergeMethod || 'merge', ...(config.approveLands ? { approveLands: true } : {}) } : null,
|
|
124
212
|
// Threads (docs/threads.md): the idea label, or false when `threads: false` turns the Threads tab off
|
|
125
213
|
threads: config.threads === false ? false : { label: ideaLabel(config) },
|
|
@@ -167,7 +255,9 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
167
255
|
if (config.approveLands && !auth.enabled) throw new Error('The config says proposals.approveLands, but sign-in is not set up. An approval is a signed-in maintainer\'s, and it lands as them, so without sign-in nothing would ever land: set up sign-in (docs/sign-in.md), or remove approveLands.');
|
|
168
256
|
const root = config.root;
|
|
169
257
|
const importMap = importMapOf(config);
|
|
170
|
-
const
|
|
258
|
+
const theme = config.theme || {};
|
|
259
|
+
const csp = cspOf(importMap, theme);
|
|
260
|
+
const themeFile = themeFilesOf(config);
|
|
171
261
|
const repoModules = repoModuleDirs(config);
|
|
172
262
|
const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
|
|
173
263
|
const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
|
|
@@ -220,6 +310,8 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
220
310
|
const page = () => {
|
|
221
311
|
const html = fs.readFileSync(path.join(EXPLORER_DIR, 'index.html'), 'utf8')
|
|
222
312
|
.replace('<!--@importmap-->', importMap ? `<script type="importmap">${importMap}</script>` : '')
|
|
313
|
+
.replace('<html lang="en">', () => themeHtmlTag(theme))
|
|
314
|
+
.replace('<!--@theme-->', () => themeHead(theme)) // a function, so a `$` in a font URL is not a replacement pattern
|
|
223
315
|
.replace(/<title>[^<]*<\/title>/, `<title>${escapeHtml(config.title)} · cornfield</title>`);
|
|
224
316
|
return html;
|
|
225
317
|
};
|
|
@@ -313,6 +405,8 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
313
405
|
res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-cache' });
|
|
314
406
|
return res.end(req.method === 'HEAD' ? undefined : page());
|
|
315
407
|
}
|
|
408
|
+
if (themeFile.has(reqPath)) return sendTheme(req, res, config, themeFile.get(reqPath), reqPath);
|
|
409
|
+
if (reqPath.startsWith(THEME_ASSET_PREFIX)) return sendThemeAsset(req, res, config, reqPath);
|
|
316
410
|
if (reqPath === '/cornfield/config.json') return sendJson(res, 200, clientConfig(config, signedIn));
|
|
317
411
|
if (reqPath === '/topology.json') {
|
|
318
412
|
const file = inside(root, config.topology);
|