cornfield 0.35.0 → 0.36.1

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/server/auth.js CHANGED
@@ -6,7 +6,7 @@
6
6
  * runs before every route the server answers:
7
7
  *
8
8
  * no session the sign-in page for a page, 401 for anything else
9
- * a reader, not a maintainer "this is the dev dashboard; ask a maintainer" for a page, 403 for anything else
9
+ * a reader, not a maintainer "this is for the people who look after the project; ask a maintainer" for a page, 403 for anything else
10
10
  * a maintainer the route
11
11
  *
12
12
  * The permission is asked of the forge when the session starts and, for a maintainer, again once it is 15 minutes
@@ -43,6 +43,8 @@ import { createForge as defaultCreateForge, isMaintainer, ForgeError } from './f
43
43
  import { githubApiUrl } from './forge-github.js';
44
44
  import { sameOrigin } from './proposals.js';
45
45
  import { revokeOwnerTokens } from './review-tokens.js';
46
+ import { appNameOf, brandImages } from '../core/brand.js';
47
+ import { brandHead, escapeHtml, themeHead, themeHtmlTag } from './page-head.js';
46
48
 
47
49
  /** How often a session's permission is asked of the forge again */
48
50
  export const RECHECK_MS = 15 * 60 * 1000;
@@ -236,35 +238,57 @@ function cookie(name, value, { maxAge, secure }) {
236
238
  // Pages
237
239
  // ---------------------------------------------------------------------------
238
240
 
239
- const escapeHtml = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
240
-
241
- const STYLE = `
242
- :root { color-scheme: light dark; --bg: #f8fafc; --fg: #0f172a; --muted: #475569; --card: #ffffff; --line: #e2e8f0; --accent: #0f766e; }
243
- @media (prefers-color-scheme: dark) { :root { --bg: #0b1120; --fg: #e2e8f0; --muted: #94a3b8; --card: #111827; --line: #1f2937; --accent: #2dd4bf; } }
244
- * { box-sizing: border-box; }
245
- body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 16px; background: var(--bg); color: var(--fg); font: 16px/1.5 system-ui, -apple-system, "Segoe UI", sans-serif; }
246
- main { width: 100%; max-width: 420px; background: var(--card); border: 1px solid var(--line); border-radius: 12px; padding: 28px 24px; }
247
- h1 { font-size: 20px; margin: 0 0 8px; }
248
- p { margin: 0 0 16px; color: var(--muted); }
249
- .button { display: inline-block; padding: 10px 16px; border-radius: 8px; border: 0; background: var(--accent); color: var(--card); font: inherit; font-weight: 600; text-decoration: none; cursor: pointer; }
250
- .quiet { background: transparent; color: var(--accent); border: 1px solid var(--line); }
251
- form { margin: 0; }
252
- `;
241
+ /**
242
+ * The page chrome of the sign-in, "ask a maintainer", failed and 401 pages: what the explorer's own head carries, so a brand and a theme
243
+ * reach a visitor before they are in. The server's CSP already covers them (the same header on every response: nothing inline but style).
244
+ * `@param config` is the whole config; `appName` is the brand's name for the app, else "cornfield".
245
+ */
246
+ function chromeOf(config) {
247
+ const brand = config.brand;
248
+ const images = Object.fromEntries(brandImages(brand).map((i) => [i.key, i.url]));
249
+ return {
250
+ title: config.title || 'cornfield',
251
+ appName: appNameOf(brand) || 'cornfield',
252
+ htmlTag: themeHtmlTag(config.theme || {}),
253
+ // No manifest link: the manifest is behind the sign-in, and a visitor has no session to fetch it with
254
+ head: [brandHead(brand, { manifest: false }), themeHead(config.theme || {})].filter(Boolean).join('\n'),
255
+ logo: images.logo || null,
256
+ wordmark: images.wordmark || null,
257
+ };
258
+ }
259
+
260
+ /** The brand at the top of the card: the logo (or cornfield's mark), then the wordmark image or the app's name */
261
+ function brandHtml(chrome) {
262
+ const mark = chrome.logo
263
+ ? `<img data-corn="brand-logo" src="${escapeHtml(chrome.logo)}" alt="">`
264
+ : '<svg viewBox="0 0 24 24" width="28" height="28" aria-hidden="true" focusable="false"><rect class="cf-mark-bg" x="3" y="3" width="18" height="18" rx="5" /><circle class="cf-mark-fg" cx="9" cy="10" r="2" /><circle class="cf-mark-fg" cx="15" cy="14" r="2" /><path class="cf-mark-line" d="M9 10l6 4" /></svg>';
265
+ const name = chrome.wordmark
266
+ ? `<img data-corn="brand-wordmark" src="${escapeHtml(chrome.wordmark)}" alt="${escapeHtml(chrome.appName)}">`
267
+ : `<span class="cf-app-name">${escapeHtml(chrome.appName)}</span>`;
268
+ return `<div data-corn="auth-brand">${mark}${name}</div>`;
269
+ }
253
270
 
254
- /** One small page: a heading, words, and what can be done next. No script. */
255
- function pageHtml(title, heading, body) {
271
+ /**
272
+ * One small page: the brand, a heading, words, and what can be done next. No script of its own; theme-boot.js (the explorer's, the same
273
+ * file) puts the viewer's Light, Dark or System choice on <html> before the first paint. `state` is "failure" for a page about a problem.
274
+ */
275
+ function pageHtml(chrome, heading, body, state = '') {
256
276
  return `<!doctype html>
257
- <html lang="en">
277
+ ${chrome.htmlTag}
258
278
  <head>
259
279
  <meta charset="utf-8">
260
280
  <meta name="viewport" content="width=device-width, initial-scale=1">
261
281
  <meta name="robots" content="noindex">
262
- <title>${escapeHtml(title)} · cornfield</title>
263
- <style>${STYLE}</style>
282
+ <title>${escapeHtml(chrome.title === chrome.appName ? chrome.title : `${chrome.title} · ${chrome.appName}`)}</title>
283
+ <link rel="stylesheet" href="/explorer/tokens.css" />
284
+ <link rel="stylesheet" href="/explorer/sign-in.css" />
285
+ ${chrome.head}
286
+ <script src="/explorer/theme-boot.js"></script>
264
287
  </head>
265
- <body>
266
- <main>
267
- <h1>${escapeHtml(heading)}</h1>
288
+ <body data-corn="auth-page">
289
+ <main data-corn="auth-card"${state ? ` data-corn-state="${state}"` : ''}>
290
+ ${brandHtml(chrome)}
291
+ <h1>${heading}</h1>
268
292
  ${body}
269
293
  </main>
270
294
  </body>
@@ -272,7 +296,7 @@ ${body}
272
296
  `;
273
297
  }
274
298
 
275
- const signOutForm = '<form method="post" action="/auth/sign-out"><button class="button quiet" type="submit">Sign out</button></form>';
299
+ const signOutForm = '<form method="post" action="/auth/sign-out"><button class="cf-button" data-corn-kind="quiet" type="submit">Sign out</button></form>';
276
300
 
277
301
  /** The longest way back a sign-in keeps (as it comes out, percent-encoded): it rides in the state cookie, which stays small */
278
302
  const RETURN_MAX = 1024;
@@ -308,26 +332,56 @@ const startHref = (returnTo) => {
308
332
  return `/auth/start${back && back !== '/' ? `?return=${encodeURIComponent(back)}` : ''}`;
309
333
  };
310
334
 
311
- /** The sign-in page; `returnTo` (checked by safeReturn) is where the sign-in ends, so a link followed signed out is followed after */
312
- export const signInPage = (title, forgeName, returnTo = null) => pageHtml(title, `Sign in to ${title}`, `
313
- <p>This is the dev dashboard. Sign in with ${escapeHtml(forgeName)} to see it; it is open to the repo's maintainers.</p>
314
- <a class="button" href="${escapeHtml(startHref(returnTo))}">Sign in with ${escapeHtml(forgeName)}</a>`);
335
+ /** A proposal slug, as `?proposal=` names one (core/proposal.js: kebab case); at most 100 characters */
336
+ const SLUG = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
337
+
338
+ /**
339
+ * The proposal (and pull request) a way back leads to, for the line that says what the sign-in is for: only from a way back that
340
+ * safeReturn accepts, only a slug of the proposal shape and a `source=pull/<n>` of digits. What the page shows is the visitor's own link
341
+ * handed back, never a title read from the repo (a visitor who is not signed in learns nothing from the page they did not bring).
342
+ * @param {string | null} returnTo
343
+ * @returns {{ slug: string, pull: string | null } | null}
344
+ */
345
+ export function proposalOf(returnTo) {
346
+ const back = safeReturn(returnTo);
347
+ if (!back) return null;
348
+ const params = new URL(back, 'http://cornfield.invalid').searchParams;
349
+ const slug = params.get('proposal');
350
+ if (!slug || slug.length > 100 || !SLUG.test(slug)) return null;
351
+ const pull = /^pull\/(\d{1,7})$/.exec(params.get('source') || '');
352
+ return { slug, pull: pull ? pull[1] : null };
353
+ }
354
+
355
+ /**
356
+ * The sign-in page; `returnTo` (checked by safeReturn) is where the sign-in ends, so a link followed signed out is followed after. When
357
+ * it is a proposal's link the page says so ("Sign in to review <slug>"): in words, escaped, and nothing that safeReturn refused.
358
+ */
359
+ export const signInPage = (chrome, forgeName, returnTo = null) => {
360
+ const proposal = proposalOf(returnTo);
361
+ const heading = proposal ? `Sign in to review <code>${escapeHtml(proposal.slug)}</code>` : `Sign in to ${escapeHtml(chrome.title)}`;
362
+ const reason = proposal
363
+ ? `\n<p data-corn="auth-reason">You followed a link to a proposed change${proposal.pull ? ` (pull request #${proposal.pull})` : ''}. After you sign in you land on it.</p>`
364
+ : '';
365
+ return pageHtml(chrome, heading, `${reason}
366
+ <p>${escapeHtml(chrome.title)} is a map of how this project fits together, and the place its changes are looked over before they are built. Sign in with your ${escapeHtml(forgeName)} account to open it; it is open to the people who look after the project.</p>
367
+ <a class="cf-button" data-corn-kind="primary" href="${escapeHtml(startHref(returnTo))}">Sign in with ${escapeHtml(forgeName)}</a>`);
368
+ };
315
369
 
316
370
  /** The one page a signed-in non-maintainer sees */
317
- export const askMaintainerPage = (title, login, repo) => pageHtml(title, 'This is the dev dashboard', `
318
- <p>You are signed in as ${escapeHtml(login)}, who does not maintain ${escapeHtml(repo)}. Only its maintainers can see the dashboard: ask a maintainer if you need something from it.</p>
371
+ export const askMaintainerPage = (chrome, login, repo) => pageHtml(chrome, `${escapeHtml(chrome.title)} is for the people who look after the project`, `
372
+ <p>You are signed in as ${escapeHtml(login)}, who does not maintain ${escapeHtml(repo)}. Only its maintainers can open this: ask one of them if you need something from it.</p>
319
373
  <p>Made a maintainer since? Sign out and sign in again.</p>
320
374
  ${signOutForm}`);
321
375
 
322
376
  /** A sign-in that did not work, and the way to try again (to the same place) */
323
- const failedPage = (title, words, returnTo = null) => pageHtml(title, 'Sign-in did not work', `
377
+ const failedPage = (chrome, words, returnTo = null) => pageHtml(chrome, 'Sign-in did not work', `
324
378
  <p>${escapeHtml(words)}</p>
325
- <a class="button" href="${escapeHtml(startHref(returnTo))}">Try again</a>`);
379
+ <a class="cf-button" data-corn-kind="primary" href="${escapeHtml(startHref(returnTo))}">Try again</a>`, 'failure');
326
380
 
327
381
  /** The forge could not be asked about a session's permission */
328
- const uncheckedPage = (title, words) => pageHtml(title, 'Your access could not be checked', `
382
+ const uncheckedPage = (chrome, words) => pageHtml(chrome, 'Your access could not be checked', `
329
383
  <p>${escapeHtml(words)} Reload in a minute.</p>
330
- ${signOutForm}`);
384
+ ${signOutForm}`, 'failure');
331
385
 
332
386
  // ---------------------------------------------------------------------------
333
387
  // The guard
@@ -379,7 +433,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
379
433
  };
380
434
  }
381
435
 
382
- const title = config.title || 'cornfield';
436
+ const chrome = chromeOf(config);
383
437
  const { forge: forgeConfig, forgeName, clientId, clientSecret, publicUrl, secure } = settings;
384
438
  const sessionMs = settings.sessionDays * DAY_MS;
385
439
  const keys = keysOf(settings.sessionSecret);
@@ -725,7 +779,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
725
779
  // (`/auth/callback?error=x`) cannot cancel one in progress
726
780
  const checked = checkState(req, url);
727
781
  // Try again goes back to the same place: the way back is known only from a state cookie that checked out
728
- const fail = (words, clear = true) => send(res, 400, failedPage(title, words, checked.returnTo), clear ? { 'Set-Cookie': clearState } : {});
782
+ const fail = (words, clear = true) => send(res, 400, failedPage(chrome, words, checked.returnTo), clear ? { 'Set-Cookie': clearState } : {});
729
783
  if (checked.error) return fail(checked.error, false);
730
784
  if (url.searchParams.get('error')) return fail(url.searchParams.get('error') === 'access_denied' ? `The sign-in was cancelled on ${forgeName}.` : `${forgeName} did not sign you in.`);
731
785
  const code = url.searchParams.get('code');
@@ -772,7 +826,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
772
826
  const { session } = await currentSession(req);
773
827
  const back = safeReturn(url.searchParams.get('return'));
774
828
  if (session?.admin) return redirect(res, landAt(back));
775
- return send(res, 200, req.method === 'HEAD' ? '' : signInPage(title, forgeName, back));
829
+ return send(res, 200, req.method === 'HEAD' ? '' : signInPage(chrome, forgeName, back));
776
830
  }
777
831
  if (reqPath === '/auth/start') return start(res, url);
778
832
  if (reqPath === '/auth/callback') return callback(req, res, url);
@@ -809,17 +863,17 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
809
863
  const { session, unchecked } = await currentSession(req);
810
864
  if (!session) {
811
865
  req.resume();
812
- answer(req, res, reqPath, 401, signInPage(title, forgeName, `${url.pathname}${url.search}`), 'Sign in first.');
866
+ answer(req, res, reqPath, 401, signInPage(chrome, forgeName, `${url.pathname}${url.search}`), 'Sign in first.');
813
867
  return { done: true };
814
868
  }
815
869
  if (unchecked) {
816
870
  req.resume();
817
- answer(req, res, reqPath, 503, uncheckedPage(title, unchecked), unchecked);
871
+ answer(req, res, reqPath, 503, uncheckedPage(chrome, unchecked), unchecked);
818
872
  return { done: true };
819
873
  }
820
874
  if (!session.admin) {
821
875
  req.resume();
822
- answer(req, res, reqPath, 403, askMaintainerPage(title, session.login, forgeConfig.repo), 'This is the dev dashboard; ask a maintainer.');
876
+ answer(req, res, reqPath, 403, askMaintainerPage(chrome, session.login, forgeConfig.repo), 'Only maintainers can open this; ask one.');
823
877
  return { done: true };
824
878
  }
825
879
  return { done: false, session };
@@ -0,0 +1,55 @@
1
+ /**
2
+ * @module server/page-head
3
+ *
4
+ * The `<head>` lines a page of cornfield's takes from the config: the brand's favicon and tab colour, the theme's font stylesheets and
5
+ * stylesheets, the named themes on `<html>`. The explorer (server/server.js) and the sign-in pages (server/auth.js) both read them, so a
6
+ * brand and a theme reach the page a signed-out visitor sees as well as the one behind it.
7
+ */
8
+
9
+ import { MANIFEST_PATH, brandImages, colorOf } from '../core/brand.js';
10
+ import { THEME_NAME, fontUrl } from '../core/theme.js';
11
+
12
+ export const escapeHtml = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
13
+
14
+ /** 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 */
15
+ export function themeNamesOf(theme) {
16
+ const names = Object.keys(theme.names || {}).filter((n) => THEME_NAME.test(n));
17
+ return { names, fallback: theme.default && names.includes(theme.default) ? theme.default : null };
18
+ }
19
+
20
+ /** `<html>` with the named themes on it, for theme-boot.js to read before the first paint */
21
+ export function themeHtmlTag(theme) {
22
+ const { names, fallback } = themeNamesOf(theme);
23
+ return names.length ? `<html lang="en" data-theme-names="${names.join(' ')}"${fallback ? ` data-theme-default="${fallback}"` : ''}>` : '<html lang="en">';
24
+ }
25
+
26
+ /**
27
+ * The links that go after cornfield's own stylesheets, in this order: the allow-listed font stylesheets, the repo's theme.css, and the
28
+ * default named theme. explorer/index.html includes theme-boot.js once, after these, so it points that link at the viewer's choice
29
+ * before the first paint. Always links, never inlined CSS.
30
+ */
31
+ export function themeHead(theme) {
32
+ const out = [];
33
+ for (const f of theme.fonts || []) {
34
+ const u = fontUrl(f);
35
+ if (u) out.push(`<link rel="stylesheet" href="${escapeHtml(u.href)}" referrerpolicy="no-referrer" />`);
36
+ }
37
+ if (theme.css) out.push('<link rel="stylesheet" href="/cornfield/theme.css" data-corn-theme="css" />');
38
+ const { names, fallback } = themeNamesOf(theme);
39
+ if (names.length) out.push(`<link rel="stylesheet" id="cf-theme-name-css"${fallback ? ` href="/cornfield/theme/${fallback}.css"` : ''} data-corn-theme="name" />`);
40
+ return out.join('\n ');
41
+ }
42
+
43
+ /**
44
+ * The `<head>` lines of a brand: the favicon, the manifest (always, so any cornfield installs as an app; fetched with the sign-in
45
+ * cookie, since the page is behind it) and the tab colour
46
+ */
47
+ export function brandHead(brand, { manifest = true } = {}) {
48
+ const out = [];
49
+ const favicon = brandImages(brand).find((i) => i.key === 'favicon');
50
+ if (favicon) out.push(`<link rel="icon" href="${escapeHtml(favicon.url)}" type="${favicon.type}" />`);
51
+ if (manifest) out.push(`<link rel="manifest" href="${MANIFEST_PATH}" crossorigin="use-credentials" />`);
52
+ const color = colorOf(brand && brand.color);
53
+ if (color) out.push(`<meta name="theme-color" content="${escapeHtml(color)}" />`);
54
+ return out.join('\n ');
55
+ }
package/server/server.js CHANGED
@@ -55,9 +55,9 @@ import { createHash, randomBytes } from 'node:crypto';
55
55
  import { fileURLToPath } from 'node:url';
56
56
  import { browserSources, BUILTIN_SOURCES, parseDuration, specPollMs, triggersOf, DEFAULTS, hookWants, ideaLabel, runnerQuietAfterMs } from '../core/config.js';
57
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';
58
+ import { BRAND_SVG_CSP, MANIFEST_PATH, appNameOf, brandAssetFile, brandImages, clientBrand, manifestOf } from '../core/brand.js';
59
59
  import { clientStrings } from '../core/strings.js';
60
- 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';
60
+ import { MAX_THEME_ASSET_BYTES, MAX_THEME_BYTES, THEME_ASSET_PREFIX, THEME_NAME, THEME_SVG_CSP, clientTheme, cssProblems, cssUrls, fontOrigins, themeAssetFile, themeAssetPath, themeUrlTarget } from '../core/theme.js';
61
61
  import { decodePath, inside, notFound, sendFile } from './files.js';
62
62
  import { serveProposals } from './proposals.js';
63
63
  import { serveForge } from './forge-routes.js';
@@ -75,19 +75,21 @@ import { createLander } from './lander.js';
75
75
  import { createSpecPoll } from './spec-poll.js';
76
76
  import { createRunnerWatch } from './runner-presence.js';
77
77
  import { createTriggers } from './triggers.js';
78
+ import { brandHead, escapeHtml, themeHead, themeHtmlTag } from './page-head.js';
78
79
  import { compressResponse } from './compress.js';
79
80
 
80
81
  export const CORNFIELD_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
81
82
  const EXPLORER_DIR = path.join(CORNFIELD_DIR, 'explorer');
82
83
  /** The pure core modules the explorer imports (no Node built-ins, no files): the only ones of core/ served */
83
84
  export const BROWSER_CORE = ['schema.js', 'proposal.js', 'personas.js', 'cloud.js', 'text.js', 'mentions.js', 'color.js', 'strings.js'];
85
+ /** The explorer files the sign-in pages load: cornfield's tokens, their own stylesheet and the script that applies Light or Dark. Served without a session. */
86
+ const SIGN_IN_FILES = new Set(['/explorer/tokens.css', '/explorer/sign-in.css', '/explorer/theme-boot.js']);
84
87
  /** cornfield's own browser sources, by request path */
85
88
  const BROWSER_PLUGINS = new Map(Object.values(BUILTIN_SOURCES).map((p) => [p, path.join(CORNFIELD_DIR, p)]));
86
89
  const PKG = JSON.parse(fs.readFileSync(path.join(CORNFIELD_DIR, 'package.json'), 'utf8'));
87
90
 
88
91
  const JSON_HEADERS = { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-cache', 'X-Content-Type-Options': 'nosniff' };
89
92
  const sendJson = (res, status, body) => { res.writeHead(status, JSON_HEADERS); res.end(JSON.stringify(body)); };
90
- const escapeHtml = (v) => String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
91
93
 
92
94
  /** The import map the page carries: the config's (repo-local modules a source needs) */
93
95
  function importMapOf(config) {
@@ -108,35 +110,6 @@ function cspOf(importMap, theme) {
108
110
  ].join('; ');
109
111
  }
110
112
 
111
- /** 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 */
112
- function themeNamesOf(theme) {
113
- const names = Object.keys(theme.names || {}).filter((n) => THEME_NAME.test(n));
114
- return { names, fallback: theme.default && names.includes(theme.default) ? theme.default : null };
115
- }
116
-
117
- /** `<html>` with the named themes on it, for theme-boot.js to read before the first paint */
118
- function themeHtmlTag(theme) {
119
- const { names, fallback } = themeNamesOf(theme);
120
- return names.length ? `<html lang="en" data-theme-names="${names.join(' ')}"${fallback ? ` data-theme-default="${fallback}"` : ''}>` : '<html lang="en">';
121
- }
122
-
123
- /**
124
- * The links that go after cornfield's own stylesheets, in this order: the allow-listed font stylesheets, the repo's theme.css, and the
125
- * default named theme. explorer/index.html includes theme-boot.js once, after these, so it points that link at the viewer's choice
126
- * before the first paint. Always links, never inlined CSS.
127
- */
128
- function themeHead(theme) {
129
- const out = [];
130
- for (const f of theme.fonts || []) {
131
- const u = fontUrl(f);
132
- if (u) out.push(`<link rel="stylesheet" href="${escapeHtml(u.href)}" referrerpolicy="no-referrer" />`);
133
- }
134
- if (theme.css) out.push('<link rel="stylesheet" href="/cornfield/theme.css" data-corn-theme="css" />');
135
- const { names, fallback } = themeNamesOf(theme);
136
- if (names.length) out.push(`<link rel="stylesheet" id="cf-theme-name-css"${fallback ? ` href="/cornfield/theme/${fallback}.css"` : ''} data-corn-theme="name" />`);
137
- return out.join('\n ');
138
- }
139
-
140
113
  /** The theme files the config names, by the path they are served at: `Map<'/cornfield/theme.css' | '/cornfield/theme/<name>.css', rel>` */
141
114
  function themeFilesOf(config) {
142
115
  const t = config.theme || {};
@@ -146,6 +119,29 @@ function themeFilesOf(config) {
146
119
  return out;
147
120
  }
148
121
 
122
+ /**
123
+ * The assets the theme files themselves name in a `url()` (core/theme.js `themeUrlTarget`), as paths under THEME_ASSET_PREFIX: the only
124
+ * ones a visitor with no session is served. The theme's folder may hold other images (screenshots, drafts) that are not the look; those
125
+ * stay behind the sign-in. Read when asked, so an edited theme counts at once; a file that cannot be read names nothing.
126
+ * @param {object} config
127
+ * @param {Map<string, string>} themeFile themeFilesOf(config)
128
+ * @returns {Set<string>}
129
+ */
130
+ function themeAssetsNamed(config, themeFile) {
131
+ const out = new Set();
132
+ for (const [servedAt, rel] of themeFile) {
133
+ try {
134
+ const file = inside(config.root, rel);
135
+ if (!file || fs.statSync(file).size > MAX_THEME_BYTES) continue;
136
+ for (const ref of cssUrls(fs.readFileSync(file, 'utf8'))) {
137
+ const target = themeUrlTarget(ref, servedAt);
138
+ if (target.asset) out.add(target.asset);
139
+ }
140
+ } catch { /* not there: it names nothing */ }
141
+ }
142
+ return out;
143
+ }
144
+
149
145
  /**
150
146
  * 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
151
147
  * (a link out is refused), only up to MAX_THEME_BYTES, and only if it passes the same CSS checks as `cornfield validate`.
@@ -194,20 +190,6 @@ function brandFilesOf(config) {
194
190
  return new Map(brandImages(config.brand).map((i) => [i.url, i.rel]));
195
191
  }
196
192
 
197
- /**
198
- * The `<head>` lines of a brand: the favicon, the manifest (always, so any cornfield installs as an app; fetched with the sign-in
199
- * cookie, since the page is behind it) and the tab colour
200
- */
201
- function brandHead(brand) {
202
- const out = [];
203
- const favicon = brandImages(brand).find((i) => i.key === 'favicon');
204
- if (favicon) out.push(`<link rel="icon" href="${escapeHtml(favicon.url)}" type="${favicon.type}" />`);
205
- out.push(`<link rel="manifest" href="${MANIFEST_PATH}" crossorigin="use-credentials" />`);
206
- const color = colorOf(brand && brand.color);
207
- if (color) out.push(`<meta name="theme-color" content="${escapeHtml(color)}" />`);
208
- return out.join('\n ');
209
- }
210
-
211
193
  /** The page's title: the repo's, then the app's name (cornfield, unless the brand names the app) */
212
194
  function titleOf(config) {
213
195
  const app = appNameOf(config.brand);
@@ -446,6 +428,15 @@ export function createCornfieldServer(config, opts = {}) {
446
428
  const runner = runnerRoute(reqPath);
447
429
  if (runner && !(reqPath === REQUESTS_PATH && req.method !== 'GET' && req.method !== 'HEAD')) return serveRunnerCall(req, res, runner, url, { config, auth, runs, now: opts.now });
448
430
  if (reqPath === REQUESTS_PATH) return serveAgentCall(req, res, { config, auth, runs, now: opts.now });
431
+ // The look of the sign-in pages (cornfield's tokens and its sign-in stylesheet, the repo's theme, fonts and brand images) answers without a
432
+ // session: a visitor sees the brand before they are in. Presentation files only, never data (docs/sign-in.md, "What answers without a session")
433
+ if (auth.enabled && (req.method === 'GET' || req.method === 'HEAD')) {
434
+ if (themeFile.has(reqPath)) return sendTheme(req, res, config, themeFile.get(reqPath), reqPath);
435
+ // Only an asset a theme file names in a url(): anything else beside the theme answers 401, as it would without a theme
436
+ if (reqPath.startsWith(THEME_ASSET_PREFIX) && themeAssetsNamed(config, themeFile).has(reqPath.slice(THEME_ASSET_PREFIX.length))) return sendThemeAsset(req, res, config, reqPath);
437
+ if (brandFile.has(reqPath)) return sendBrand(req, res, config, brandFile.get(reqPath), reqPath);
438
+ if (SIGN_IN_FILES.has(reqPath)) return sendFile(req, res, path.join(EXPLORER_DIR, path.basename(reqPath)), reqPath);
439
+ }
449
440
  const gate = await auth.gate(req, res, reqPath, url);
450
441
  if (gate.done) return;
451
442
  const signedIn = gate.session ? { login: gate.session.login } : false;