@popcorn245/cornfield 0.22.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);