cornfield 0.23.0 → 0.24.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/brand.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * @module core/brand
3
+ *
4
+ * The `brand` key of cornfield.config.js (docs/config.md#brand), and the rules a brand asset must keep.
5
+ * `brandAssetFile` is the one place that looks at an asset on disk, so the server and `cornfield validate` judge a file by the same rule.
6
+ *
7
+ * brand: {
8
+ * logo: './tools/cornfield/logo.svg', // replaces the brand mark in the header
9
+ * wordmark: './tools/cornfield/word.svg', // replaces the title text in the header
10
+ * favicon: './tools/cornfield/favicon.png', // <link rel="icon">
11
+ * appName: 'Acme', // replaces "cornfield" where cornfield names itself (tab title, heading, manifest)
12
+ * color: '#e53e3e', // the manifest's theme_color (and the tab's theme-color)
13
+ * background: '#ffffff', // the manifest's background_color
14
+ * }
15
+ *
16
+ * Images only, from the repo only, served same-origin and never inlined into the page.
17
+ */
18
+
19
+ import fs from 'node:fs';
20
+ import path from 'node:path';
21
+
22
+ export const BRAND_KEYS = Object.freeze(['logo', 'wordmark', 'favicon', 'appName', 'color', 'background']);
23
+ /** The keys that name an image file */
24
+ export const BRAND_IMAGE_KEYS = Object.freeze(['logo', 'wordmark', 'favicon']);
25
+ /** The largest a brand asset may be, in bytes */
26
+ export const MAX_BRAND_BYTES = 512 * 1024;
27
+ export const MAX_APP_NAME = 64;
28
+ /** Where the brand images are served (server/server.js): `/cornfield/brand/<key>.<ext>`, only for a key the config sets */
29
+ export const BRAND_PREFIX = '/cornfield/brand/';
30
+ export const MANIFEST_PATH = '/manifest.webmanifest';
31
+ /** The only brand image types, by lower-case extension */
32
+ export const BRAND_TYPES = Object.freeze({ '.svg': 'image/svg+xml', '.png': 'image/png' });
33
+ /** An SVG is an image here, never a page: opened on its own it may not run or load anything */
34
+ export const BRAND_SVG_CSP = "default-src 'none'; style-src 'unsafe-inline'";
35
+ const PNG_MAGIC = Buffer.from('89504e470d0a1a0a', 'hex');
36
+ const HEX_COLOR = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
37
+
38
+ const isObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
39
+ const isText = (v) => typeof v === 'string' && v.trim() !== '';
40
+ const unset = (v) => v === undefined || v === null;
41
+ /** A path inside the repo, relative, ending in .svg or .png */
42
+ const imagePathInRepo = (p) => isText(p) && !path.isAbsolute(p) && !/^[a-z]:/i.test(p) && !p.split(/[\\/]/).includes('..') && !p.includes('\0') && Boolean(BRAND_TYPES[path.extname(p).toLowerCase()]);
43
+
44
+ /**
45
+ * What is wrong with a `brand` value (as the config file wrote it).
46
+ * @param {unknown} b
47
+ * @returns {string[]}
48
+ */
49
+ export function brandProblems(b) {
50
+ if (b === undefined) return [];
51
+ if (!isObject(b)) return ['"brand" is { logo?, wordmark?, favicon?, appName?, color?, background? }.'];
52
+ const out = [];
53
+ for (const k of Object.keys(b)) if (!BRAND_KEYS.includes(k)) out.push(`brand.${k}: the keys are ${BRAND_KEYS.join(', ')}.`);
54
+ for (const k of BRAND_IMAGE_KEYS) {
55
+ if (!unset(b[k]) && !imagePathInRepo(b[k])) out.push(`brand.${k} is one image (an .svg or .png file) inside the repo, written relative to it, like "./tools/cornfield/${k}.svg".`);
56
+ }
57
+ if (!unset(b.appName) && (typeof b.appName !== 'string' || !b.appName.trim() || b.appName.length > MAX_APP_NAME || /[\u0000-\u001f\u007f]/.test(b.appName))) {
58
+ out.push(`brand.appName is text of at most ${MAX_APP_NAME} characters, on one line.`);
59
+ }
60
+ for (const k of ['color', 'background']) {
61
+ if (!unset(b[k]) && !(typeof b[k] === 'string' && HEX_COLOR.test(b[k]))) out.push(`brand.${k} is a hex colour, like "#e53e3e" or "#e33".`);
62
+ }
63
+ return out;
64
+ }
65
+
66
+ /** A brand colour as it may reach the page and the manifest: a hex colour, else null (configProblems refuses anything else; this is the second lock) */
67
+ export const colorOf = (v) => (typeof v === 'string' && HEX_COLOR.test(v) ? v : null);
68
+
69
+ /** Whether the brand sets anything at all */
70
+ export const brandOn = (brand) => Boolean(brand) && BRAND_KEYS.some((k) => !unset(brand[k]));
71
+
72
+ /** The name chrome shows: the brand's `appName`, else null (the caller falls back to the repo's title or "cornfield") */
73
+ export const appNameOf = (brand) => (brand && typeof brand.appName === 'string' && brand.appName.trim() ? brand.appName.trim() : null);
74
+
75
+ /**
76
+ * The images a brand names, `[{ key, rel, url, type }]`: the url is where the server serves it (`/cornfield/brand/<key>.<ext>`).
77
+ * @param {object} brand
78
+ */
79
+ export function brandImages(brand) {
80
+ const out = [];
81
+ for (const key of BRAND_IMAGE_KEYS) {
82
+ const rel = brand && brand[key];
83
+ if (!imagePathInRepo(rel)) continue;
84
+ const ext = path.extname(rel).toLowerCase();
85
+ out.push({ key, rel, url: `${BRAND_PREFIX}${key}${ext}`, type: BRAND_TYPES[ext] });
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * The brand as the browser is told it: URLs and the name, never a path on this machine. null when nothing is set.
92
+ * @param {object} brand
93
+ * @param {string} poweredBy where "powered by cornfield" leads
94
+ */
95
+ export function clientBrand(brand, poweredBy) {
96
+ if (!brandOn(brand)) return null;
97
+ const urls = Object.fromEntries(brandImages(brand).map((i) => [i.key, i.url]));
98
+ return { logo: urls.logo || null, wordmark: urls.wordmark || null, favicon: urls.favicon || null, appName: appNameOf(brand), poweredBy };
99
+ }
100
+
101
+ /** Whether the first bytes of an SVG file are an SVG document: optional BOM, space, an xml declaration, comments and a doctype, then `<svg` */
102
+ function looksLikeSvg(buf) {
103
+ let s = buf.toString('utf8').replace(/^/, '');
104
+ for (;;) {
105
+ s = s.replace(/^\s+/, '');
106
+ const skip = /^(?:<\?xml[\s\S]*?\?>|<!--[\s\S]*?-->|<!DOCTYPE[^>[]*(?:\[[\s\S]*?\])?\s*>)/i.exec(s);
107
+ if (!skip) break;
108
+ s = s.slice(skip[0].length);
109
+ }
110
+ return /^<svg[\s>/]/.test(s);
111
+ }
112
+
113
+ /** Whether a file's bytes are what its extension says (`.png`: the PNG signature, then the IHDR chunk a PNG must start with; `.svg`: an SVG document) */
114
+ export function magicMatches(ext, buf) {
115
+ if (ext === '.png') return buf.length >= 33 && buf.subarray(0, PNG_MAGIC.length).equals(PNG_MAGIC) && buf.readUInt32BE(8) === 13 && buf.toString('latin1', 12, 16) === 'IHDR';
116
+ if (ext === '.svg') return !buf.includes(0) && looksLikeSvg(buf);
117
+ return false;
118
+ }
119
+
120
+ /** A PNG's width and height from its header, or null */
121
+ export function pngSize(buf) {
122
+ if (!magicMatches('.png', buf)) return null;
123
+ const w = buf.readUInt32BE(16);
124
+ const h = buf.readUInt32BE(20);
125
+ return w > 0 && h > 0 ? { width: w, height: h } : null;
126
+ }
127
+
128
+ /**
129
+ * The file on disk a brand image names, or why there is none: a plain file whose real path is inside the repo (a link out is
130
+ * refused), with an allowed extension and bytes that match it, at most MAX_BRAND_BYTES.
131
+ * @param {string} root the repo
132
+ * @param {string} rel the path as the config wrote it
133
+ * @returns {{ file: string, size: number, type: string, ext: string, body: Buffer } | { problem: string }}
134
+ */
135
+ export function brandAssetFile(root, rel) {
136
+ const ext = typeof rel === 'string' ? path.extname(rel).toLowerCase() : '';
137
+ const type = BRAND_TYPES[ext];
138
+ if (!type) return { problem: 'is not an .svg or .png file.' };
139
+ let base;
140
+ let real;
141
+ try { base = fs.realpathSync(root); } catch { return { problem: 'the repo does not exist.' }; }
142
+ try { real = fs.realpathSync(path.resolve(root, rel)); } catch { return { problem: 'does not exist.' }; }
143
+ if (!real.startsWith(base + path.sep)) return { problem: 'leaves the repo (a link or a path that resolves outside it).' };
144
+ const stats = fs.statSync(real);
145
+ if (!stats.isFile()) return { problem: 'is not a file.' };
146
+ if (stats.size > MAX_BRAND_BYTES) return { problem: `is ${Math.ceil(stats.size / 1024)} KB; a brand image is at most ${MAX_BRAND_BYTES / 1024} KB.` };
147
+ const body = fs.readFileSync(real);
148
+ if (body.length > MAX_BRAND_BYTES) return { problem: `is over ${MAX_BRAND_BYTES / 1024} KB; a brand image is at most that.` };
149
+ if (!magicMatches(ext, body)) return { problem: `is not really ${ext === '.png' ? 'a PNG' : 'an SVG'} (its first bytes do not match its ${ext} extension).` };
150
+ return { file: real, size: body.length, type, ext, body };
151
+ }
152
+
153
+ /**
154
+ * The web app manifest (served at MANIFEST_PATH, with or without a brand, so any cornfield can be installed on a phone): name and
155
+ * short name from `appName` or the repo's title, the favicon and the logo as icons, the colours when the config sets them,
156
+ * standalone, starting at `/`. Without a brand: the repo's title and no icons (cornfield ships no favicon of its own).
157
+ * @param {object | null | undefined} brand
158
+ * @param {string} title the repo's title
159
+ * @param {(rel: string) => { body: Buffer } | { problem: string }} readImage
160
+ */
161
+ export function manifestOf(brand, title, readImage) {
162
+ const name = appNameOf(brand) || title;
163
+ const icons = [];
164
+ const seen = new Set();
165
+ for (const img of brandImages(brand).filter((i) => i.key !== 'wordmark').sort((a, b) => a.key.localeCompare(b.key))) { // favicon, then logo
166
+ if (seen.has(img.rel)) continue;
167
+ seen.add(img.rel);
168
+ const found = readImage(img.rel);
169
+ if ('problem' in found) continue;
170
+ const size = img.type === 'image/png' ? pngSize(found.body) : null;
171
+ icons.push({ src: img.url, type: img.type, sizes: img.type === 'image/png' ? (size ? `${size.width}x${size.height}` : '') : 'any', purpose: 'any' });
172
+ }
173
+ return {
174
+ name,
175
+ short_name: [...name].slice(0, 12).join(''),
176
+ start_url: '/',
177
+ display: 'standalone',
178
+ ...(colorOf(brand && brand.color) ? { theme_color: brand.color } : {}),
179
+ ...(colorOf(brand && brand.background) ? { background_color: brand.background } : {}),
180
+ icons: icons.map((i) => (i.sizes ? i : { src: i.src, type: i.type, purpose: i.purpose })),
181
+ };
182
+ }
package/core/config.js CHANGED
@@ -27,6 +27,7 @@
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
29
  * theme: {}, // { css, fonts, fontHosts, names, default }: a repo's own look, CSS only (docs/config.md#theme)
30
+ * brand: {}, // { logo, wordmark, favicon, appName, color, background }: a repo's own logo and name, images from the repo (docs/config.md#brand)
30
31
  * proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
31
32
  * importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
32
33
  * dataDir: null, // where cornfield keeps its own state (reviews; the SQLite file in v1)
@@ -42,6 +43,7 @@ import os from 'node:os';
42
43
  import path from 'node:path';
43
44
  import { pathToFileURL, fileURLToPath } from 'node:url';
44
45
  import { themeProblems } from './theme.js';
46
+ import { brandProblems } from './brand.js';
45
47
  import { PROFILE_SOURCE, MAX_NUMBER, MAX_BRIEF_CHARS, RUN_KINDS, TRIGGER_EVENTS, CREDENTIAL_VALUE_SOURCE } from './agent-contract.js';
46
48
 
47
49
  export { TRIGGER_EVENTS };
@@ -167,6 +169,7 @@ export const DEFAULTS = Object.freeze({
167
169
  threads: { label: 'idea' },
168
170
  links: [],
169
171
  theme: { css: null, fonts: [], fontHosts: [], names: {}, default: null },
172
+ brand: { logo: null, wordmark: null, favicon: null, appName: null, color: null, background: null },
170
173
  proxy: {},
171
174
  importMap: {},
172
175
  dataDir: null,
@@ -340,6 +343,7 @@ export function configProblems(c) {
340
343
  });
341
344
  }
342
345
  out.push(...themeProblems(c.theme));
346
+ out.push(...brandProblems(c.brand));
343
347
  if (c.proxy !== undefined) {
344
348
  if (!isObject(c.proxy)) out.push('"proxy" is { "/path/": "http://upstream" }.');
345
349
  else for (const [p, t] of Object.entries(c.proxy)) {
@@ -527,6 +531,7 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
527
531
  agents: { ...DEFAULTS.agents, ...(raw.agents || {}) },
528
532
  };
529
533
  config.theme = { ...structuredClone(DEFAULTS.theme), ...(raw.theme || {}) };
534
+ config.brand = { ...DEFAULTS.brand, ...(raw.brand || {}) };
530
535
  // `threads: false` stays false; an object is read over the default
531
536
  config.threads = raw.threads === false ? false : { ...DEFAULTS.threads, ...(raw.threads || {}) };
532
537
  // `hookPoll: false` is `{ specs: false }`; an object is read over the default
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 { BRAND_IMAGE_KEYS, brandAssetFile } from './brand.js';
26
27
  import { MAX_THEME_BYTES, cssProblems, cssUrls, themeAssetFile, themeFileUrl, themeFiles, themeUrlTarget } from './theme.js';
27
28
 
28
29
  /** How a page is produced today, and whether it is baked to a file */
@@ -66,6 +67,23 @@ export function validateThemeFiles(config) {
66
67
  return errors;
67
68
  }
68
69
 
70
+ /**
71
+ * The config's brand images (docs/config.md#brand): each one exists, is a plain file inside the repo (a link out of it is refused),
72
+ * has an allowed extension (.svg, .png) and first bytes that match it, and is at most MAX_BRAND_BYTES (core/brand.js `brandAssetFile`).
73
+ * @param {{ root: string, brand?: object }} config
74
+ * @returns {string[]}
75
+ */
76
+ export function validateBrandFiles(config) {
77
+ const errors = [];
78
+ for (const key of BRAND_IMAGE_KEYS) {
79
+ const rel = config.brand && config.brand[key];
80
+ if (typeof rel !== 'string') continue;
81
+ const found = brandAssetFile(config.root, rel);
82
+ if ('problem' in found) errors.push(`brand.${key} (${rel}) ${found.problem}`);
83
+ }
84
+ return errors;
85
+ }
86
+
69
87
  /**
70
88
  * The schema checks: no files, no derivers.
71
89
  * @param {{ nodes: any[], edges: any[] }} topology
@@ -257,6 +275,7 @@ export async function validateRepo({ config, derivers, topology = readTopology(c
257
275
  }
258
276
  errors.push(...validatePersonasFile(config.root, config.personas.roles));
259
277
  errors.push(...validateThemeFiles(config));
278
+ errors.push(...validateBrandFiles(config));
260
279
  errors.push(...validateCloudNodes(topology, config.root));
261
280
  errors.push(...validateProposalFiles(topology, path.join(config.root, config.proposals), config.root));
262
281
  const io = repoReader(config.root);
@@ -11,6 +11,8 @@
11
11
  <link rel="stylesheet" href="/explorer/tokens.css" />
12
12
  <link rel="stylesheet" href="/explorer/explorer.css" />
13
13
  <link rel="stylesheet" href="/explorer/house.css" />
14
+ <!-- The config's brand (server/server.js puts it here): the favicon, the web app manifest and the tab colour -->
15
+ <!--@brand-->
14
16
  <!-- 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 -->
15
17
  <!--@theme-->
16
18
  <!-- 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
@@ -24,8 +26,8 @@
24
26
  <!-- The page's one heading, for a screen reader's list of headings (plugins.js puts the config's title in it) -->
25
27
  <h1 id="cf-heading" class="hx-sr-only">cornfield: the map</h1>
26
28
  <div class="hx-header-left">
27
- <button type="button" class="hx-brand" data-action="reset-view" title="Reset View" aria-label="cornfield: reset the view">
28
- <span class="hx-live-dot"></span>
29
+ <button type="button" id="cf-brand" class="hx-brand" data-action="reset-view" title="Reset View" aria-label="cornfield: reset the view">
30
+ <span id="cf-mark" class="hx-live-dot"></span>
29
31
  <span id="cf-title" class="hx-title gradient-text">cornfield</span>
30
32
  </button>
31
33
 
@@ -37,13 +37,51 @@ export async function loadClientConfig(fetcher = (...a) => globalThis.fetch(...a
37
37
  }
38
38
  }
39
39
 
40
- /** Puts the repo's title and links in the header, and Sign out when the server says who is signed in */
40
+ /** An <img> for a brand image (the server's same-origin URL): decorative, the button it sits in carries the name; `alt` only shows if it fails to load */
41
+ function brandImage(doc, src, kind, alt = '') {
42
+ const img = doc.createElement('img');
43
+ img.setAttribute('src', src);
44
+ img.setAttribute('alt', alt);
45
+ img.setAttribute('data-corn', `brand-${kind}`);
46
+ img.setAttribute('style', `height:${kind === 'logo' ? 22 : 18}px;width:auto;max-width:${kind === 'logo' ? 48 : 160}px;display:block`);
47
+ return img;
48
+ }
49
+
50
+ /**
51
+ * The repo's brand in the header (docs/config.md#brand): the logo takes the brand mark's place and the wordmark the title text, inside
52
+ * the same button, so its accessible name stays. The header text stays the repo's own title; `appName` replaces "cornfield" where
53
+ * cornfield names itself: the button's accessible name and the page's heading (the tab title and the manifest are the server's).
54
+ */
55
+ function applyBrand(doc, brand, title) {
56
+ const button = doc.getElementById('cf-brand');
57
+ if (button && brand.appName) button.setAttribute('aria-label', `${brand.appName}: reset the view`);
58
+ const text = doc.getElementById('cf-title');
59
+ if (brand.logo && typeof doc.createElement === 'function') {
60
+ const mark = doc.getElementById('cf-mark');
61
+ if (mark) mark.replaceWith(brandImage(doc, brand.logo, 'logo'));
62
+ }
63
+ if (brand.wordmark && text && typeof doc.createElement === 'function') {
64
+ text.textContent = '';
65
+ text.appendChild(brandImage(doc, brand.wordmark, 'wordmark', title || brand.appName || ''));
66
+ }
67
+ const heading = doc.getElementById('cf-heading');
68
+ if (heading && brand.appName) heading.textContent = `${brand.appName}: the map`;
69
+ }
70
+
71
+ /** The small "powered by cornfield" link that stays in the header when a repo brands cornfield */
72
+ function poweredBy(brand) {
73
+ if (!brand || typeof brand.poweredBy !== 'string' || !/^https:\/\//.test(brand.poweredBy)) return '';
74
+ return `<a class="hx-btn hx-btn--quiet" data-corn="powered-by" href="${escHtml(brand.poweredBy)}" target="_blank" rel="noreferrer">powered by cornfield</a>`;
75
+ }
76
+
77
+ /** Puts the repo's title, brand and links in the header, and Sign out when the server says who is signed in */
41
78
  export function applyBranding(doc, config) {
42
79
  if (!config || !doc) return;
43
80
  const title = doc.getElementById('cf-title');
44
81
  if (title && config.title) title.textContent = config.title;
45
82
  const heading = doc.getElementById('cf-heading');
46
83
  if (heading && config.title) heading.textContent = `${config.title}: the map`;
84
+ if (config.brand) applyBrand(doc, config.brand, config.title);
47
85
  initThemePicker(doc, config.theme);
48
86
  const links = doc.getElementById('cf-links');
49
87
  if (!links) return;
@@ -56,7 +94,8 @@ export function applyBranding(doc, config) {
56
94
  const signOut = config.signIn && typeof config.signIn.login === 'string'
57
95
  ? `<form class="cf-sign-out" method="post" action="/auth/sign-out"><button type="submit" class="hx-btn hx-btn--quiet" title="Signed in as ${escHtml(config.signIn.login)}"><span class="cf-sign-out-icon" aria-hidden="true">⎋</span><span class="cf-sign-out-text">Sign out</span></button></form>`
58
96
  : '';
59
- if (html || signOut) links.innerHTML = html + signOut;
97
+ const powered = poweredBy(config.brand);
98
+ if (html || powered || signOut) links.innerHTML = html + powered + signOut;
60
99
  }
61
100
 
62
101
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.23.0",
3
+ "version": "0.24.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
@@ -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/brand/<key>.<ext> a brand image the config's `brand` names (logo, wordmark, favicon; svg or png, 512 KB each): those files only
23
+ * GET /manifest.webmanifest the web app manifest: the repo's title, or built from `brand` when the config sets one
22
24
  * GET /api/forge/… issues, pull requests, their files and checks, release notes: read from the forge (server/forge-routes.js)
23
25
  * POST /api/forge/pulls/<n>/merge|rerun land a green pull request, re-run a failed check (server/forge-actions.js)
24
26
  * POST /api/forge/issues/<n>/spec, /pulls/<n>/build the pipeline's steps (server/pipeline.js, server/forge-actions.js)
@@ -53,6 +55,7 @@ import { createHash, randomBytes } from 'node:crypto';
53
55
  import { fileURLToPath } from 'node:url';
54
56
  import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf, DEFAULTS, hookWants, ideaLabel, runnerQuietAfterMs } from '../core/config.js';
55
57
  import { CLOUD_FILE } from '../core/cloud.js';
58
+ import { BRAND_SVG_CSP, MANIFEST_PATH, appNameOf, brandAssetFile, brandImages, clientBrand, colorOf, manifestOf } from '../core/brand.js';
56
59
  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';
57
60
  import { decodePath, inside, notFound, sendFile } from './files.js';
58
61
  import { serveProposals } from './proposals.js';
@@ -184,6 +187,57 @@ function sendThemeAsset(req, res, config, reqPath) {
184
187
  }
185
188
  }
186
189
 
190
+ /** The brand images the config names, by the path they are served at: `Map<'/cornfield/brand/<key>.<ext>', rel>` */
191
+ function brandFilesOf(config) {
192
+ return new Map(brandImages(config.brand).map((i) => [i.url, i.rel]));
193
+ }
194
+
195
+ /**
196
+ * The `<head>` lines of a brand: the favicon, the manifest (always, so any cornfield installs as an app; fetched with the sign-in
197
+ * cookie, since the page is behind it) and the tab colour
198
+ */
199
+ function brandHead(brand) {
200
+ const out = [];
201
+ const favicon = brandImages(brand).find((i) => i.key === 'favicon');
202
+ if (favicon) out.push(`<link rel="icon" href="${escapeHtml(favicon.url)}" type="${favicon.type}" />`);
203
+ out.push(`<link rel="manifest" href="${MANIFEST_PATH}" crossorigin="use-credentials" />`);
204
+ const color = colorOf(brand && brand.color);
205
+ if (color) out.push(`<meta name="theme-color" content="${escapeHtml(color)}" />`);
206
+ return out.join('\n ');
207
+ }
208
+
209
+ /** The page's title: the repo's, then the app's name (cornfield, unless the brand names the app) */
210
+ function titleOf(config) {
211
+ const app = appNameOf(config.brand);
212
+ return app && app === config.title ? app : `${config.title} · ${app || 'cornfield'}`;
213
+ }
214
+
215
+ /**
216
+ * Serves one brand image: only a file the config names (`brand.logo`, `wordmark`, `favicon`), a plain svg or png file whose real path
217
+ * is inside the repo, whose bytes match its extension, at most 512 KB (core/brand.js `brandAssetFile`, the check `cornfield validate`
218
+ * makes). nosniff always; an SVG gets a policy of its own and is never inlined into the page.
219
+ */
220
+ function sendBrand(req, res, config, rel, reqPath) {
221
+ try {
222
+ const found = brandAssetFile(config.root, rel);
223
+ if ('problem' in found) return notFound(res, reqPath);
224
+ res.writeHead(200, {
225
+ 'Content-Type': found.type, 'Content-Length': found.body.length, 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff',
226
+ ...(found.type === 'image/svg+xml' ? { 'Content-Security-Policy': BRAND_SVG_CSP } : {}),
227
+ });
228
+ return res.end(req.method === 'HEAD' ? undefined : found.body);
229
+ } catch {
230
+ return notFound(res, reqPath);
231
+ }
232
+ }
233
+
234
+ /** The web app manifest (core/brand.js `manifestOf`), as application/manifest+json: served with or without a brand */
235
+ function sendManifest(req, res, config) {
236
+ const body = JSON.stringify(manifestOf(config.brand, config.title, (rel) => brandAssetFile(config.root, rel)));
237
+ res.writeHead(200, { 'Content-Type': 'application/manifest+json; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' });
238
+ return res.end(req.method === 'HEAD' ? undefined : body);
239
+ }
240
+
187
241
  /** The browser modules the config names from the repo: each one's folder may be served (its .js files only) */
188
242
  function repoModuleDirs(config) {
189
243
  const dirs = [];
@@ -208,6 +262,8 @@ export function clientConfig(config, signIn = false) {
208
262
  links: config.links || [],
209
263
  // The theme's names and default, never a file's path (docs/config.md#theme)
210
264
  theme: clientTheme(config.theme),
265
+ // The brand's image URLs and name, never a file's path (docs/config.md#brand)
266
+ brand: clientBrand(config.brand, PKG.homepage),
211
267
  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,
212
268
  // Threads (docs/threads.md): the idea label, or false when `threads: false` turns the Threads tab off
213
269
  threads: config.threads === false ? false : { label: ideaLabel(config) },
@@ -258,6 +314,7 @@ export function createCornfieldServer(config, opts = {}) {
258
314
  const theme = config.theme || {};
259
315
  const csp = cspOf(importMap, theme);
260
316
  const themeFile = themeFilesOf(config);
317
+ const brandFile = brandFilesOf(config);
261
318
  const repoModules = repoModuleDirs(config);
262
319
  const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
263
320
  const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
@@ -312,7 +369,8 @@ export function createCornfieldServer(config, opts = {}) {
312
369
  .replace('<!--@importmap-->', importMap ? `<script type="importmap">${importMap}</script>` : '')
313
370
  .replace('<html lang="en">', () => themeHtmlTag(theme))
314
371
  .replace('<!--@theme-->', () => themeHead(theme)) // a function, so a `$` in a font URL is not a replacement pattern
315
- .replace(/<title>[^<]*<\/title>/, `<title>${escapeHtml(config.title)} · cornfield</title>`);
372
+ .replace('<!--@brand-->', () => brandHead(config.brand))
373
+ .replace(/<title>[^<]*<\/title>/, () => `<title>${escapeHtml(titleOf(config))}</title>`); // a function: a `$` in a name is not a pattern
316
374
  return html;
317
375
  };
318
376
 
@@ -407,6 +465,8 @@ export function createCornfieldServer(config, opts = {}) {
407
465
  }
408
466
  if (themeFile.has(reqPath)) return sendTheme(req, res, config, themeFile.get(reqPath), reqPath);
409
467
  if (reqPath.startsWith(THEME_ASSET_PREFIX)) return sendThemeAsset(req, res, config, reqPath);
468
+ if (brandFile.has(reqPath)) return sendBrand(req, res, config, brandFile.get(reqPath), reqPath);
469
+ if (reqPath === MANIFEST_PATH) return sendManifest(req, res, config);
410
470
  if (reqPath === '/cornfield/config.json') return sendJson(res, 200, clientConfig(config, signedIn));
411
471
  if (reqPath === '/topology.json') {
412
472
  const file = inside(root, config.topology);