@popcorn245/cornfield 0.45.0 → 0.46.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 +57 -0
- package/package.json +1 -1
- package/server/auth.js +32 -7
- package/server/embed.js +185 -0
- package/server/lander.js +2 -2
- package/server/proposals.js +6 -2
- package/server/server.js +18 -4
package/core/config.js
CHANGED
|
@@ -30,6 +30,7 @@
|
|
|
30
30
|
* brand: {}, // { logo, wordmark, favicon, appName, color, background }: a repo's own logo and name, images from the repo (docs/config.md#brand)
|
|
31
31
|
* layers: {}, // { add: [{ key, label, desc?, match }], off: [keys], order: [keys] }: a repo's own layers in the Layers menu, as data (docs/config.md#layers)
|
|
32
32
|
* strings: {}, // { approve: 'Ship it', … }: a repo's own words for the visible labels, plain text (core/strings.js, docs/theming.md#words)
|
|
33
|
+
* embed: { origins: [] }, // exact origins of sibling apps that may read, and decide a review, as the signed-in maintainer (docs/embedding.md)
|
|
33
34
|
* proxy: {}, // { '/api/': 'http://127.0.0.1:3245' }: same-origin paths for a live source
|
|
34
35
|
* importMap: {}, // bare imports a repo-local browser module needs: { name: '/repo/path.js' }
|
|
35
36
|
* dataDir: null, // where cornfield keeps its own state (reviews; the SQLite file in v1)
|
|
@@ -176,6 +177,7 @@ export const DEFAULTS = Object.freeze({
|
|
|
176
177
|
brand: { logo: null, wordmark: null, favicon: null, appName: null, color: null, background: null },
|
|
177
178
|
strings: {},
|
|
178
179
|
layers: { add: [], off: [], order: [] },
|
|
180
|
+
embed: { origins: [] },
|
|
179
181
|
proxy: {},
|
|
180
182
|
importMap: {},
|
|
181
183
|
dataDir: null,
|
|
@@ -208,6 +210,58 @@ const isForgeOrigin = (url) => {
|
|
|
208
210
|
} catch { return false; }
|
|
209
211
|
};
|
|
210
212
|
|
|
213
|
+
/** The names a plain `http` origin may have: this machine's own (`localhost`, any `*.localhost`, `127.0.0.1`, `[::1]`) */
|
|
214
|
+
const isLoopbackName = (host) => host === 'localhost' || host.endsWith('.localhost') || host === '127.0.0.1' || host === '[::1]';
|
|
215
|
+
const EMBED_ORIGIN = /^(https?):\/\/([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)*|\[[0-9A-Fa-f:.]+\])(?::(\d{1,5}))?$/i;
|
|
216
|
+
/** The most origins `embed.origins` may list: each one is trusted with the maintainer's session, so the list is short on purpose */
|
|
217
|
+
export const MAX_EMBED_ORIGINS = 20;
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* An `embed.origins` entry as one canonical origin (`https://tasks.example.com`, `http://localhost:5173`), or what is wrong with it, in words.
|
|
221
|
+
* Exact only: a scheme, a host and an optional port; no path (not even a trailing slash), query, fragment or user name, and no wildcard.
|
|
222
|
+
* `https` only, except `http` for this machine's own names. The scheme and host are lowercased and a default port is dropped, so the same origin
|
|
223
|
+
* written two ways is one entry. A host the URL parser would rewrite (`https://2130706433`, `https://0x7f.1`) is refused.
|
|
224
|
+
* @param {unknown} value
|
|
225
|
+
* @returns {{ origin: string } | { problem: string }}
|
|
226
|
+
*/
|
|
227
|
+
export function embedOrigin(value) {
|
|
228
|
+
if (typeof value !== 'string' || value === '') return { problem: 'is an origin like https://tasks.example.com, as text.' };
|
|
229
|
+
if (value.includes('*')) return { problem: `"${value}" has a wildcard: list each origin exactly, like https://tasks.example.com.` };
|
|
230
|
+
if (/\s/.test(value) || value.length > 300) return { problem: `"${value.slice(0, 80)}" is not an origin: no spaces, and at most 300 characters.` };
|
|
231
|
+
if (value.includes('\\')) return { problem: `"${value}" has a backslash: write the origin with forward slashes, like https://tasks.example.com.` };
|
|
232
|
+
if (value.includes('@')) return { problem: `"${value}" has a user name: an origin is a scheme, a host and a port, like https://tasks.example.com.` };
|
|
233
|
+
if (!/^https?:\/\//i.test(value)) return { problem: `"${value}" has no https:// in front: write the whole origin, like https://tasks.example.com.` };
|
|
234
|
+
if (/^https?:\/\/[^/?#]*[/?#]/i.test(value)) return { problem: `"${value}" has a path, query or fragment (a trailing slash counts): list the origin only, like https://tasks.example.com.` };
|
|
235
|
+
const m = EMBED_ORIGIN.exec(value);
|
|
236
|
+
if (!m) return { problem: `"${value}" is not an origin: a scheme, a host name (or a bracketed IPv6 address) and an optional port, like https://tasks.example.com.` };
|
|
237
|
+
const [, scheme, host, port] = m;
|
|
238
|
+
if (port !== undefined && (String(Number(port)) !== port || Number(port) < 1 || Number(port) > 65535)) return { problem: `"${value}" has a port that is not a number from 1 to 65535.` };
|
|
239
|
+
let u;
|
|
240
|
+
try { u = new URL(value.toLowerCase()); } catch { return { problem: `"${value}" is not a URL the browser would read as written.` }; }
|
|
241
|
+
if (u.hostname !== host.toLowerCase()) return { problem: `"${value}" would be read as ${u.hostname}: write the host the way a browser shows it.` };
|
|
242
|
+
if (scheme.toLowerCase() === 'http' && !isLoopbackName(u.hostname)) return { problem: `"${value}" is plain http: only https, or http for localhost, a *.localhost name, 127.0.0.1 or [::1], because the maintainer's session would otherwise be offered to a page that travels in the clear.` };
|
|
243
|
+
return { origin: u.origin };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** What is wrong with `embed`, in words: only `origins`, a short list of exact origins, none twice */
|
|
247
|
+
function embedProblems(e) {
|
|
248
|
+
const out = [];
|
|
249
|
+
if (e === undefined || e === null) return out;
|
|
250
|
+
if (!isObject(e)) return ['"embed" is { origins: ["https://tasks.example.com"] }.'];
|
|
251
|
+
for (const k of Object.keys(e)) if (k !== 'origins') out.push(`embed.${k}: the only key is origins.`);
|
|
252
|
+
if (e.origins === undefined) return out;
|
|
253
|
+
if (!Array.isArray(e.origins)) return [...out, 'embed.origins is a list of origins, like ["https://tasks.example.com"].'];
|
|
254
|
+
if (e.origins.length > MAX_EMBED_ORIGINS) out.push(`embed.origins lists ${e.origins.length} origins; at most ${MAX_EMBED_ORIGINS}: each one is trusted with the maintainer's session.`);
|
|
255
|
+
const seen = new Set();
|
|
256
|
+
e.origins.forEach((o, i) => {
|
|
257
|
+
const r = embedOrigin(o);
|
|
258
|
+
if ('problem' in r) out.push(`embed.origins[${i}] ${r.problem}`);
|
|
259
|
+
else if (seen.has(r.origin)) out.push(`embed.origins[${i}] "${o}" is listed twice.`);
|
|
260
|
+
else seen.add(r.origin);
|
|
261
|
+
});
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
|
|
211
265
|
/**
|
|
212
266
|
* What is wrong with a config object (as the file exports it, before defaults).
|
|
213
267
|
* @param {any} c
|
|
@@ -369,6 +423,7 @@ export function configProblems(c) {
|
|
|
369
423
|
out.push(...brandProblems(c.brand));
|
|
370
424
|
out.push(...stringsProblems(c.strings));
|
|
371
425
|
out.push(...layersProblems(c.layers));
|
|
426
|
+
out.push(...embedProblems(c.embed));
|
|
372
427
|
if (c.proxy !== undefined) {
|
|
373
428
|
if (!isObject(c.proxy)) out.push('"proxy" is { "/path/": "http://upstream" }.');
|
|
374
429
|
else for (const [p, t] of Object.entries(c.proxy)) {
|
|
@@ -559,6 +614,8 @@ export async function loadConfig(root, { env = process.env, file } = {}) {
|
|
|
559
614
|
config.brand = { ...DEFAULTS.brand, ...(raw.brand || {}) };
|
|
560
615
|
config.strings = { ...(raw.strings || {}) };
|
|
561
616
|
config.layers = clientLayers(raw.layers); // checked above: only the known keys, as plain data
|
|
617
|
+
// The origins that may embed this server, as canonical origins (checked above): [] unless the file lists some
|
|
618
|
+
config.embed = { origins: (Array.isArray(raw.embed?.origins) ? raw.embed.origins : []).map((o) => /** @type {{ origin: string }} */ (embedOrigin(o)).origin) };
|
|
562
619
|
// `threads: false` stays false; an object is read over the default
|
|
563
620
|
config.threads = raw.threads === false ? false : { ...DEFAULTS.threads, ...(raw.threads || {}) };
|
|
564
621
|
// `hookPoll: false` is `{ specs: false }`; an object is read over the default
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@popcorn245/cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.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/auth.js
CHANGED
|
@@ -42,6 +42,7 @@ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, ran
|
|
|
42
42
|
import { createForge as defaultCreateForge, isMaintainer, ForgeError } from './forge.js';
|
|
43
43
|
import { githubApiUrl } from './forge-github.js';
|
|
44
44
|
import { sameOrigin } from './proposals.js';
|
|
45
|
+
import { absoluteUrl, listedReturn } from './embed.js';
|
|
45
46
|
import { revokeOwnerTokens } from './review-tokens.js';
|
|
46
47
|
import { appNameOf, brandImages } from '../core/brand.js';
|
|
47
48
|
import { brandHead, escapeHtml, themeHead, themeHtmlTag } from './page-head.js';
|
|
@@ -326,10 +327,14 @@ export function safeReturn(raw) {
|
|
|
326
327
|
return back;
|
|
327
328
|
}
|
|
328
329
|
|
|
329
|
-
/**
|
|
330
|
+
/**
|
|
331
|
+
* The sign-in start, with the way back when there is one: a path (checked by safeReturn) as `return`, or an absolute URL the caller has
|
|
332
|
+
* already had checked (it comes from a signed state cookie) as `returnTo`, which /auth/start checks again against the listed origins
|
|
333
|
+
*/
|
|
330
334
|
const startHref = (returnTo) => {
|
|
331
335
|
const back = safeReturn(returnTo);
|
|
332
|
-
return `/auth/start${back
|
|
336
|
+
if (back) return `/auth/start${back !== '/' ? `?return=${encodeURIComponent(back)}` : ''}`;
|
|
337
|
+
return typeof returnTo === 'string' && absoluteUrl(returnTo) ? `/auth/start?returnTo=${encodeURIComponent(returnTo)}` : '/auth/start';
|
|
333
338
|
};
|
|
334
339
|
|
|
335
340
|
/** A proposal slug, as `?proposal=` names one (core/proposal.js: kebab case); at most 100 characters */
|
|
@@ -442,6 +447,24 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
442
447
|
const SESSION_COOKIE = secure ? '__Host-cornfield' : 'cornfield';
|
|
443
448
|
const STATE_COOKIE = secure ? '__Host-cornfield-oauth' : 'cornfield-oauth';
|
|
444
449
|
const publicHost = publicUrl.hostname;
|
|
450
|
+
// The sibling origins a sign-in may end on (config `embed.origins`, server/embed.js)
|
|
451
|
+
const embedOrigins = config.embed?.origins ?? [];
|
|
452
|
+
/**
|
|
453
|
+
* Where a sign-in may end, as it is kept and followed: a same-origin path (safeReturn: its rules are unchanged), or an absolute URL, which is
|
|
454
|
+
* honoured only when its origin is this server's own (it is cut down to its path and query, then checked as a path) or exactly a listed one
|
|
455
|
+
* (kept as the URL parser reads it). Anything else is null, and the sign-in ends where it always has: on `/`. With no origin listed an
|
|
456
|
+
* absolute URL is never one (the sign-in is what it was before `embed.origins`).
|
|
457
|
+
* @param {unknown} raw
|
|
458
|
+
* @returns {string | null}
|
|
459
|
+
*/
|
|
460
|
+
const wayBack = (raw) => {
|
|
461
|
+
const path = safeReturn(raw);
|
|
462
|
+
if (path) return path;
|
|
463
|
+
if (!embedOrigins.length) return null;
|
|
464
|
+
const u = absoluteUrl(raw);
|
|
465
|
+
if (!u) return null;
|
|
466
|
+
return u.origin === publicUrl.origin ? safeReturn(`${u.pathname}${u.search}`) : listedReturn(raw, embedOrigins);
|
|
467
|
+
};
|
|
445
468
|
/** @type {import('node:sqlite').DatabaseSync | null} */
|
|
446
469
|
let db = null;
|
|
447
470
|
/** @type {Promise<import('node:sqlite').DatabaseSync> | null} */
|
|
@@ -476,10 +499,11 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
476
499
|
};
|
|
477
500
|
/** Where a sign-in ends: the checked way back as an absolute URL on the public origin, or `/` */
|
|
478
501
|
const landAt = (back) => {
|
|
479
|
-
const path =
|
|
502
|
+
const path = wayBack(back);
|
|
480
503
|
if (!path) return '/';
|
|
481
504
|
const to = new URL(path, publicUrl);
|
|
482
|
-
|
|
505
|
+
// A listed origin's URL is absolute and stays as checked; a path is made absolute on the public origin
|
|
506
|
+
return to.origin === publicUrl.origin || embedOrigins.includes(to.origin) ? to.href : '/';
|
|
483
507
|
};
|
|
484
508
|
const clearSession = cookie(SESSION_COOKIE, '', { maxAge: 0, secure });
|
|
485
509
|
const clearState = cookie(STATE_COOKIE, '', { maxAge: 0, secure });
|
|
@@ -580,8 +604,9 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
580
604
|
const state = random();
|
|
581
605
|
const verifier = random();
|
|
582
606
|
const expires = now() + STATE_MS;
|
|
583
|
-
// The way back is signed with the state: a 5th part, base64url (no dots), empty for none
|
|
584
|
-
|
|
607
|
+
// The way back is signed with the state: a 5th part, base64url (no dots), empty for none. `returnTo` is an absolute URL (own or a listed
|
|
608
|
+
// origin); when it is none of those, or no origin is listed, the sign-in goes on as if it had not been sent, with `return` (a path) as before
|
|
609
|
+
const back = (embedOrigins.length ? wayBack(url.searchParams.get('returnTo')) : null) ?? safeReturn(url.searchParams.get('return'));
|
|
585
610
|
const payload = `${state}.${verifier}.${expires}.${back ? b64url(Buffer.from(back)) : ''}`;
|
|
586
611
|
const q = new URLSearchParams({ client_id: clientId, redirect_uri: redirectUri, response_type: 'code', state, code_challenge: b64url(createHash('sha256').update(verifier).digest()), code_challenge_method: 'S256' });
|
|
587
612
|
if (endpoints.scope) q.set('scope', endpoints.scope);
|
|
@@ -599,7 +624,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
599
624
|
if (!sameText(mac, macOf(keys.mac, `state:${state}.${verifier}.${expires}.${back}`))) return { error: 'The sign-in was started in another browser, or too long ago.' };
|
|
600
625
|
if (!(Number(expires) > now())) return { error: 'The sign-in took too long.' };
|
|
601
626
|
if (!sameText(state, url.searchParams.get('state') || '')) return { error: 'The sign-in came back with an answer to another request.' };
|
|
602
|
-
return { verifier, returnTo:
|
|
627
|
+
return { verifier, returnTo: wayBack(back ? Buffer.from(back, 'base64url').toString('utf8') : '') };
|
|
603
628
|
}
|
|
604
629
|
|
|
605
630
|
/**
|
package/server/embed.js
ADDED
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @module server/embed
|
|
3
|
+
*
|
|
4
|
+
* Letting a listed sibling app in (spec 0011 D9). The config's `embed.origins` (core/config.js `embedOrigin`: exact, canonical origins)
|
|
5
|
+
* names pages that may ask this server for what the map and the review need, with the signed-in maintainer's own session, and decide
|
|
6
|
+
* one review. Nothing here is on by default: with no origin listed `createEmbed(...).headers()` answers `{}`, nothing is answered
|
|
7
|
+
* for a preflight and no write is let in, so every response is what it was before.
|
|
8
|
+
*
|
|
9
|
+
* What it decides (all pure: headers and paths in, headers and booleans out):
|
|
10
|
+
*
|
|
11
|
+
* - **Reads**, on an explicit list of routes (`ROUTES`, default deny): for a request whose `Origin` is exactly a listed origin, the
|
|
12
|
+
* answer carries `Access-Control-Allow-Origin: <that origin>` (never `*`), `Vary: Origin`, and on the routes behind the session also
|
|
13
|
+
* `Access-Control-Allow-Credentials: true` and the headers the explorer reads (`X-Proposal-Sha256`, `X-Proposal-Source`,
|
|
14
|
+
* `X-Proposals-Forge-Error`). The routes that answer without a session (the theme) carry no `Allow-Credentials`: they hold nothing
|
|
15
|
+
* the session decides, and a fetch of them is made without credentials. Every other route, an `/api/*-tokens` and `/api/agent-runs`
|
|
16
|
+
* route and any other `/api/forge/*` route included, gets no CORS header at all.
|
|
17
|
+
* - **The preflight** (`OPTIONS` with `Access-Control-Request-Method`): answered for a listed origin on a route of the list, for the
|
|
18
|
+
* methods and request headers that route needs and no others (`Content-Type` on the two writes, none on a read).
|
|
19
|
+
* - **Writes**: today's same-origin rule stays for every write (server/proposals.js `sameOrigin`). For exactly two writes, the review
|
|
20
|
+
* PUT and the Undo of an approval's hold (`WRITES`), a listed origin is accepted too: its `Origin` must be exactly listed and
|
|
21
|
+
* `Sec-Fetch-Site` must be `same-site`, or missing (a browser too old to send it still sends `Origin` on a cross-origin PUT or POST;
|
|
22
|
+
* and the session cookie is `SameSite=Lax`, so a request that is not same-site arrives with no session to act as). Any other value
|
|
23
|
+
* (`cross-site`, `same-origin`, `none`) is refused. The caller has checked `Host` already (`sameOrigin` does it first).
|
|
24
|
+
* - **Signing in and returning**: `listedReturn` says whether a sign-in may end on an absolute URL: only one whose origin is listed.
|
|
25
|
+
*
|
|
26
|
+
* The session cookie is not touched here (HttpOnly, SameSite=Lax, host-only; server/auth.js). See docs/embedding.md.
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
/** @typedef {{ test: RegExp | string, kind: 'session' | 'open', methods: string[], headers: string[] }} Route */
|
|
30
|
+
|
|
31
|
+
/** The headers the explorer reads from an answer: a page on another origin can read them only if they are exposed */
|
|
32
|
+
const EXPOSED = ['X-Proposal-Sha256', 'X-Proposal-Source', 'X-Proposals-Forge-Error'];
|
|
33
|
+
|
|
34
|
+
const READ = ['GET', 'HEAD'];
|
|
35
|
+
const SLUG = '[^/]+';
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The routes a listed origin may reach, and nothing else. `session`: behind the sign-in guard, so the credentialed form of CORS; `open`:
|
|
39
|
+
* answered before it (the look of the sign-in pages: theme.css, a named theme, and the images and fonts a theme names).
|
|
40
|
+
* `methods` are what a preflight may ask for; `headers` are the request headers it may list (lowercase).
|
|
41
|
+
* @type {readonly Route[]}
|
|
42
|
+
*/
|
|
43
|
+
export const ROUTES = Object.freeze([
|
|
44
|
+
{ test: '/cornfield/config.json', kind: 'session', methods: READ, headers: [] },
|
|
45
|
+
{ test: '/topology.json', kind: 'session', methods: READ, headers: [] },
|
|
46
|
+
{ test: '/topology.cloud.json', kind: 'session', methods: READ, headers: [] },
|
|
47
|
+
{ test: '/proposals', kind: 'session', methods: READ, headers: [] },
|
|
48
|
+
{ test: new RegExp(`^/proposals/${SLUG}\\.json$`), kind: 'session', methods: READ, headers: [] },
|
|
49
|
+
{ test: new RegExp(`^/proposals/${SLUG}/decision$`), kind: 'session', methods: READ, headers: [] },
|
|
50
|
+
// The review: read, and the one write a listed origin may make on a proposal (see `WRITES`)
|
|
51
|
+
{ test: new RegExp(`^/proposals/${SLUG}/review$`), kind: 'session', methods: [...READ, 'PUT'], headers: ['content-type'] },
|
|
52
|
+
// The list of a proposal's mockups, not the files (`/mockups/<n>`)
|
|
53
|
+
{ test: new RegExp(`^/proposals/${SLUG}/mockups$`), kind: 'session', methods: READ, headers: [] },
|
|
54
|
+
// One pull request: the proposal bar reads it
|
|
55
|
+
{ test: /^\/api\/forge\/pulls\/[1-9]\d{0,8}$/, kind: 'session', methods: READ, headers: [] },
|
|
56
|
+
// The Undo of an approval's hold
|
|
57
|
+
{ test: /^\/api\/forge\/pulls\/[1-9]\d{0,8}\/landing\/cancel$/, kind: 'session', methods: ['POST'], headers: ['content-type'] },
|
|
58
|
+
{ test: '/cornfield/theme.css', kind: 'open', methods: READ, headers: [] },
|
|
59
|
+
{ test: /^\/cornfield\/theme\/[^/]+\.css$/, kind: 'open', methods: READ, headers: [] },
|
|
60
|
+
{ test: /^\/cornfield\/theme\/assets\/.+$/, kind: 'open', methods: READ, headers: [] },
|
|
61
|
+
]);
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* The two writes a listed origin may make, as `[method, route]`. Every other write from a listed origin is refused exactly as a stranger's is.
|
|
65
|
+
* (Which code path asks is decided where the write is handled: server/proposals.js `putPullReview`, server/lander.js `serveLanding`.)
|
|
66
|
+
*/
|
|
67
|
+
export const WRITES = Object.freeze(['PUT /proposals/<slug>/review', 'POST /api/forge/pulls/<n>/landing/cancel']);
|
|
68
|
+
|
|
69
|
+
/** @param {string} reqPath @returns {Route | null} */
|
|
70
|
+
export function routeOf(reqPath) {
|
|
71
|
+
for (const r of ROUTES) if (typeof r.test === 'string' ? r.test === reqPath : r.test.test(reqPath)) return r;
|
|
72
|
+
return null;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Whether a write may come from a listed origin: its `Origin` is exactly one of `origins`, and `Sec-Fetch-Site` is `same-site` or not sent.
|
|
77
|
+
* Only the two routes in `WRITES` ask. `Host` is not looked at here.
|
|
78
|
+
* @param {Record<string, string | string[] | undefined>} headers a request's headers (Node's lowercase names)
|
|
79
|
+
* @param {readonly string[]} origins
|
|
80
|
+
*/
|
|
81
|
+
export function listedWrite(headers, origins) {
|
|
82
|
+
const origin = headers.origin;
|
|
83
|
+
if (typeof origin !== 'string' || !origins.includes(origin)) return false;
|
|
84
|
+
const site = headers['sec-fetch-site'];
|
|
85
|
+
return site === undefined || site === 'same-site';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** What an absolute way back may not hold: a control character, a space, or a backslash (browsers read `\` as `/`) */
|
|
89
|
+
const RETURN_BAD = /[\u0000- \u007f\\]/;
|
|
90
|
+
/** The longest absolute way back a sign-in keeps (it rides in the state cookie) */
|
|
91
|
+
export const RETURN_MAX = 1024;
|
|
92
|
+
|
|
93
|
+
/**
|
|
94
|
+
* An absolute http(s) URL as the URL parser reads it, or null: with an explicit scheme (so `//host`, `javascript:` and a path are not one),
|
|
95
|
+
* no control character, space or backslash, no user name or password, at most RETURN_MAX characters.
|
|
96
|
+
* @param {unknown} raw
|
|
97
|
+
* @returns {URL | null}
|
|
98
|
+
*/
|
|
99
|
+
export function absoluteUrl(raw) {
|
|
100
|
+
if (typeof raw !== 'string' || raw === '' || raw.length > RETURN_MAX || RETURN_BAD.test(raw) || !/^https?:\/\/[^/?#]/i.test(raw)) return null;
|
|
101
|
+
let u;
|
|
102
|
+
try { u = new URL(raw); } catch { return null; }
|
|
103
|
+
if ((u.protocol !== 'https:' && u.protocol !== 'http:') || u.username !== '' || u.password !== '') return null;
|
|
104
|
+
return u;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Where a sign-in may end on another origin: the URL as parsed (`href`, so what is sent in `Location` is what was checked) when its origin
|
|
109
|
+
* is exactly a listed one, else null. A different port, a longer host (`https://tasks.example.com.evil.test`), a user name
|
|
110
|
+
* (`https://tasks.example.com@evil.test`) and a scheme other than the listed one all fail.
|
|
111
|
+
* @param {unknown} raw
|
|
112
|
+
* @param {readonly string[]} origins
|
|
113
|
+
* @returns {string | null}
|
|
114
|
+
*/
|
|
115
|
+
export function listedReturn(raw, origins) {
|
|
116
|
+
if (!origins.length) return null;
|
|
117
|
+
const u = absoluteUrl(raw);
|
|
118
|
+
if (!u || !origins.includes(u.origin) || u.href.length > RETURN_MAX) return null;
|
|
119
|
+
return u.href;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* @param {readonly string[]} [origins] the config's `embed.origins`, canonical (core/config.js `embedOrigin`)
|
|
124
|
+
*/
|
|
125
|
+
export function createEmbed(origins = []) {
|
|
126
|
+
const list = Object.freeze([...origins]);
|
|
127
|
+
/** The one `Origin` of a request, when it is exactly a listed origin; two `Origin` headers are none */
|
|
128
|
+
const listed = (req) => {
|
|
129
|
+
if (!list.length) return null;
|
|
130
|
+
let n = 0;
|
|
131
|
+
for (let i = 0; i < req.rawHeaders.length; i += 2) if (req.rawHeaders[i].toLowerCase() === 'origin') n++;
|
|
132
|
+
const o = req.headers.origin;
|
|
133
|
+
return n === 1 && typeof o === 'string' && list.includes(o) ? o : null;
|
|
134
|
+
};
|
|
135
|
+
return {
|
|
136
|
+
enabled: list.length > 0,
|
|
137
|
+
origins: list,
|
|
138
|
+
listed,
|
|
139
|
+
/**
|
|
140
|
+
* The headers to put on every answer of this request (the guard's 401 and the route's refusals included, so the page can read why):
|
|
141
|
+
* `{}` unless an origin is listed and the path is on the list. `Vary: Origin` goes on the list's routes for every request, listed or
|
|
142
|
+
* not (the answer differs by `Origin`); the CORS headers only for a listed origin and a method the route has.
|
|
143
|
+
* @returns {Record<string, string>}
|
|
144
|
+
*/
|
|
145
|
+
headers(req, reqPath) {
|
|
146
|
+
if (!list.length) return {};
|
|
147
|
+
const route = routeOf(reqPath);
|
|
148
|
+
if (!route) return {};
|
|
149
|
+
const out = { Vary: 'Origin' };
|
|
150
|
+
const origin = listed(req);
|
|
151
|
+
if (!origin || req.method === 'OPTIONS' || !route.methods.includes(req.method)) return out;
|
|
152
|
+
out['Access-Control-Allow-Origin'] = origin;
|
|
153
|
+
if (route.kind === 'session') {
|
|
154
|
+
out['Access-Control-Allow-Credentials'] = 'true';
|
|
155
|
+
out['Access-Control-Expose-Headers'] = EXPOSED.join(', ');
|
|
156
|
+
}
|
|
157
|
+
return out;
|
|
158
|
+
},
|
|
159
|
+
/**
|
|
160
|
+
* The answer to a preflight, or null when it is none of ours (not `OPTIONS`, no `Access-Control-Request-Method`, an origin that is not
|
|
161
|
+
* listed, a route off the list, a method or a request header the route does not take): the request then goes on as any other and
|
|
162
|
+
* gets no CORS header, so the browser refuses it.
|
|
163
|
+
* @returns {{ status: number, headers: Record<string, string> } | null}
|
|
164
|
+
*/
|
|
165
|
+
preflight(req, reqPath) {
|
|
166
|
+
if (!list.length || req.method !== 'OPTIONS') return null;
|
|
167
|
+
const origin = listed(req);
|
|
168
|
+
const asked = req.headers['access-control-request-method'];
|
|
169
|
+
const route = routeOf(reqPath);
|
|
170
|
+
if (!origin || !route || typeof asked !== 'string' || !route.methods.includes(asked)) return null;
|
|
171
|
+
const wanted = String(req.headers['access-control-request-headers'] || '').split(',').map((h) => h.trim().toLowerCase()).filter(Boolean);
|
|
172
|
+
if (wanted.some((h) => !route.headers.includes(h))) return null;
|
|
173
|
+
const headers = {
|
|
174
|
+
'Access-Control-Allow-Origin': origin,
|
|
175
|
+
'Access-Control-Allow-Methods': route.methods.join(', '),
|
|
176
|
+
'Access-Control-Max-Age': '600',
|
|
177
|
+
Vary: 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers',
|
|
178
|
+
'Content-Length': '0',
|
|
179
|
+
};
|
|
180
|
+
if (route.kind === 'session') headers['Access-Control-Allow-Credentials'] = 'true';
|
|
181
|
+
if (route.headers.length) headers['Access-Control-Allow-Headers'] = 'Content-Type';
|
|
182
|
+
return { status: 204, headers };
|
|
183
|
+
},
|
|
184
|
+
};
|
|
185
|
+
}
|
package/server/lander.js
CHANGED
|
@@ -362,7 +362,7 @@ export function landingOf(reqPath) {
|
|
|
362
362
|
* cornfield's own page by a maintainer the forge confirms now, counted like any action.
|
|
363
363
|
* @param {import('node:http').IncomingMessage} req
|
|
364
364
|
* @param {{ n: number, cancel: boolean }} what
|
|
365
|
-
* @param {{ config: any, session: { login: string, userId: string } | null, auth: any, lander?: Lander | null, now?: () => number, publicHost?: string | null }} ctx
|
|
365
|
+
* @param {{ config: any, session: { login: string, userId: string } | null, auth: any, lander?: Lander | null, now?: () => number, publicHost?: string | null, embedOrigins?: readonly string[] }} ctx
|
|
366
366
|
* @returns {Promise<{ status: number, body: object, headers?: Record<string, string> }>}
|
|
367
367
|
*/
|
|
368
368
|
export async function serveLanding(req, what, ctx) {
|
|
@@ -377,7 +377,7 @@ export async function serveLanding(req, what, ctx) {
|
|
|
377
377
|
try {
|
|
378
378
|
const flood = countAttempt(ctx, session.userId, now());
|
|
379
379
|
if (flood) throw flood;
|
|
380
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
380
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, ctx.embedOrigins ?? [])) throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
381
381
|
if (!lander) throw new Refused(404, 'Landing on approval is not turned on (proposals.approveLands).', 'not-found');
|
|
382
382
|
const forge = auth.forgeFor(session);
|
|
383
383
|
const me = await forge.me();
|
package/server/proposals.js
CHANGED
|
@@ -51,6 +51,7 @@ import { hashPullMockups } from './mockups.js';
|
|
|
51
51
|
import { readDecision } from './decision.js';
|
|
52
52
|
import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal, reviewStates } from './proposal-pulls.js';
|
|
53
53
|
import { serveMockups } from './mockups.js';
|
|
54
|
+
import { listedWrite } from './embed.js';
|
|
54
55
|
|
|
55
56
|
// The review's checks live in server/reviews.js; these are re-exported for the callers that always had them here
|
|
56
57
|
export { REVIEW_LIMIT, MAX_REVIEW_EDITS, MAX_NOTE_CHARS, validateReview } from './reviews.js';
|
|
@@ -102,10 +103,13 @@ function ownHostName(host, publicHost) {
|
|
|
102
103
|
* another domain that resolves here (DNS rebinding) is no more welcome than any other site.
|
|
103
104
|
* @param {import('node:http').IncomingMessage} req
|
|
104
105
|
* @param {string|null} [publicHost] the host of the configured public URL, which is the server's own too
|
|
106
|
+
* @param {readonly string[]} [embedOrigins] the listed sibling origins (config `embed.origins`) a request may also come from; only for the review PUT and the Undo of a landing
|
|
105
107
|
*/
|
|
106
|
-
export function sameOrigin(req, publicHost = null) {
|
|
108
|
+
export function sameOrigin(req, publicHost = null, embedOrigins = []) {
|
|
107
109
|
const host = req.headers.host;
|
|
108
110
|
if (typeof host !== 'string' || !ownHostName(host, publicHost)) return false;
|
|
111
|
+
// The two writes a listed sibling origin may make pass their list here (server/embed.js `listedWrite`); every other caller passes none
|
|
112
|
+
if (embedOrigins.length && listedWrite(req.headers, embedOrigins)) return true;
|
|
109
113
|
const origin = req.headers.origin;
|
|
110
114
|
const site = req.headers['sec-fetch-site'];
|
|
111
115
|
if (origin === undefined && site === undefined) return false;
|
|
@@ -278,7 +282,7 @@ async function getDecision(res, where, forgeFor, signedIn, slug, n, fresh) {
|
|
|
278
282
|
|
|
279
283
|
/** PUT /proposals/<slug>/review?source=pull/<n>: posts the review as a comment on the PR, as the signed-in maintainer */
|
|
280
284
|
async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
|
|
281
|
-
if (!sameOrigin(req, where.publicHost)) {
|
|
285
|
+
if (!sameOrigin(req, where.publicHost, where.embedOrigins ?? [])) {
|
|
282
286
|
req.resume();
|
|
283
287
|
return send(res, 403, { error: 'A review is only taken from cornfield\'s own page' });
|
|
284
288
|
}
|
package/server/server.js
CHANGED
|
@@ -44,8 +44,9 @@
|
|
|
44
44
|
* no session is the sign-in page or a 401, a non-maintainer the "ask a maintainer" page or a 403. Without it, `listen`
|
|
45
45
|
* only binds to loopback (server/bind.js); with it and an https public URL, it may bind to any address.
|
|
46
46
|
*
|
|
47
|
-
* No CORS headers
|
|
48
|
-
*
|
|
47
|
+
* No CORS headers, unless the config's `embed.origins` lists a sibling app's origin: then that exact origin may read the routes
|
|
48
|
+
* server/embed.js names, and make two writes, as the signed-in maintainer (docs/embedding.md). The explorer and its sources are
|
|
49
|
+
* all same-origin, so no other site's page has any business reading what cornfield serves.
|
|
49
50
|
*/
|
|
50
51
|
|
|
51
52
|
import fs from 'node:fs';
|
|
@@ -73,6 +74,7 @@ import { assertBind, hostAllowed } from './bind.js';
|
|
|
73
74
|
import { createAuth, signInSettings } from './auth.js';
|
|
74
75
|
import { createHooks, hooksSettings } from './hooks.js';
|
|
75
76
|
import { createLander } from './lander.js';
|
|
77
|
+
import { createEmbed } from './embed.js';
|
|
76
78
|
import { createSpecPoll } from './spec-poll.js';
|
|
77
79
|
import { createRunnerWatch, runnerPresence } from './runner-presence.js';
|
|
78
80
|
import { createTriggers } from './triggers.js';
|
|
@@ -308,7 +310,9 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
308
310
|
const brandFile = brandFilesOf(config);
|
|
309
311
|
const repoModules = repoModuleDirs(config);
|
|
310
312
|
const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
|
|
311
|
-
|
|
313
|
+
// The sibling origins that may read and decide a review as the signed-in maintainer (server/embed.js): none unless `embed.origins` lists some
|
|
314
|
+
const embed = createEmbed(config.embed?.origins ?? []);
|
|
315
|
+
const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost, embedOrigins: embed.origins };
|
|
312
316
|
const fixtureCache = new Map();
|
|
313
317
|
// What the line above Approve says an approval does besides posting (spec 0007 D1, server/decision.js): landing, and the run a trigger asks for
|
|
314
318
|
const approvalRun = triggersOf(config).find(([event]) => event === 'spec.approved');
|
|
@@ -434,6 +438,16 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
434
438
|
return res.end('400 Bad Request');
|
|
435
439
|
}
|
|
436
440
|
|
|
441
|
+
// A listed sibling origin (config `embed.origins`) reads the routes server/embed.js names: its headers go on the answer whatever the answer is, and its
|
|
442
|
+
// preflight is answered here, before the guard (a preflight carries no cookie). With no origin listed both are nothing
|
|
443
|
+
const preflight = embed.preflight(req, reqPath);
|
|
444
|
+
if (preflight) {
|
|
445
|
+
req.resume();
|
|
446
|
+
res.writeHead(preflight.status, preflight.headers);
|
|
447
|
+
return res.end();
|
|
448
|
+
}
|
|
449
|
+
for (const [name, value] of Object.entries(embed.headers(req, reqPath))) res.setHeader(name, value);
|
|
450
|
+
|
|
437
451
|
// A runner token is good for the runner routes only: on any other route it is refused here, before anything else is looked at
|
|
438
452
|
if (presentedScope(req) === 'runner' && !takesTokens(reqPath, { reviews: REVIEWS_PATH })) return serveStrayRunner(req, res, reqPath, { config, auth, now: opts.now });
|
|
439
453
|
|
|
@@ -464,7 +478,7 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
464
478
|
// Before the proxies: a repo's `/api/` proxy must not swallow the panel's own routes
|
|
465
479
|
if (await serveTokenRoutes(req, res, reqPath, { config, where, auth, session: gate.session, now: opts.now, publicHost })) return;
|
|
466
480
|
if (await serveRunRoutes(req, res, reqPath, { config, auth, runs, session: gate.session, now: opts.now, publicHost })) return;
|
|
467
|
-
if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, lander, now: opts.now, publicHost })) return;
|
|
481
|
+
if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, lander, now: opts.now, publicHost, embedOrigins: embed.origins })) return;
|
|
468
482
|
for (const [prefix, target] of proxies) if (reqPath.startsWith(prefix)) return proxyTo(req, res, target);
|
|
469
483
|
const session = gate.session;
|
|
470
484
|
const forgeFor = session ? () => auth.forgeFor(session) : null;
|