cornfield 0.45.0 → 0.46.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/core/config.js +57 -0
- package/package.json +1 -1
- package/server/agent-api.js +13 -6
- package/server/agent-runs.js +2 -1
- package/server/auth.js +33 -8
- package/server/embed.js +185 -0
- package/server/forge-actions.js +34 -24
- package/server/forge-routes.js +3 -3
- package/server/lander.js +3 -2
- package/server/proposals.js +15 -3
- package/server/review-api.js +13 -8
- package/server/server.js +21 -6
- package/server/throttle.js +27 -0
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": "cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.46.1",
|
|
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/agent-api.js
CHANGED
|
@@ -29,7 +29,8 @@
|
|
|
29
29
|
* theirs and is never taken from the body. A body that carries a credential, by key or by value, is 400 and nothing is posted.
|
|
30
30
|
*
|
|
31
31
|
* The `/api/agent-runs` routes are the signed-in maintainer's, behind the sign-in guard like every other action. The POSTs take a request
|
|
32
|
-
* from cornfield's own page only (`sameOrigin
|
|
32
|
+
* from cornfield's own page only (`sameOrigin`, checked first and never counted) with a JSON body and count toward the flood ceiling
|
|
33
|
+
* (server/throttle.js); a token is no way
|
|
33
34
|
* to them (the guard reads cookies, never `Authorization`). They post with the session's own forge token (`auth.forgeFor`).
|
|
34
35
|
*/
|
|
35
36
|
|
|
@@ -38,7 +39,7 @@ import { sameOrigin, readBody } from './proposals.js';
|
|
|
38
39
|
import { ANONYMOUS_PER_MINUTE, NO_TOKEN_LOGIN } from './review-api.js';
|
|
39
40
|
import { bearerOf, findToken, touchToken } from './review-tokens.js';
|
|
40
41
|
import { refusal } from './submit-review.js';
|
|
41
|
-
import { Refused, countAttempt } from './throttle.js';
|
|
42
|
+
import { Refused, countAttempt, noteRefusedOrigin } from './throttle.js';
|
|
42
43
|
import { ForgeError } from './forge.js';
|
|
43
44
|
|
|
44
45
|
export const REQUESTS_PATH = '/api/agent-requests';
|
|
@@ -70,7 +71,7 @@ function parseBody(body, what) {
|
|
|
70
71
|
}
|
|
71
72
|
}
|
|
72
73
|
|
|
73
|
-
/** @typedef {{ config: any, auth: any, runs: import('./agent-runs.js').Runs | null, now?: () => number, publicHost?: string | null }} AgentContext */
|
|
74
|
+
/** @typedef {{ config: any, auth: any, runs: import('./agent-runs.js').Runs | null, now?: () => number, publicHost?: string | null, publicOrigin?: string | null }} AgentContext */
|
|
74
75
|
|
|
75
76
|
/**
|
|
76
77
|
* `POST /api/agent-requests`. The caller has found the path to be this one; this runs before the sign-in guard.
|
|
@@ -204,13 +205,19 @@ export async function serveRunRoutes(req, res, reqPath, ctx) {
|
|
|
204
205
|
return true;
|
|
205
206
|
}
|
|
206
207
|
|
|
207
|
-
// A change: from cornfield's own page, as JSON; the engine counts the flood first and writes a row for everything after
|
|
208
|
+
// A change: from cornfield's own page, as JSON; past the origin, the engine counts the flood first and writes a row for everything after
|
|
208
209
|
const ask = { forge: () => auth.forgeFor(session), who: { login: session.login, userId: session.userId }, limits: { auth, now: ctx.now } };
|
|
209
210
|
let problem;
|
|
210
211
|
let body = {};
|
|
211
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) {
|
|
212
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, [], ctx.publicOrigin ?? null)) {
|
|
213
|
+
// Refused before the engine counts anything: a same-site page's POST rides on the maintainer's cookie, and a refused one must not use up
|
|
214
|
+
// their budget. It is written down at most once a minute (server/throttle.js `noteRefusedOrigin`)
|
|
212
215
|
req.resume();
|
|
213
|
-
|
|
216
|
+
const answer = { ok: false, error: 'Do this from cornfield\'s own page.', code: 'forbidden' };
|
|
217
|
+
const action = m[2] === '/answer' ? 'agent-answer' : runId ? 'agent-stop' : 'agent-request';
|
|
218
|
+
await noteRefusedOrigin({ auth }, req, session, { action, target: ctx.config.forge?.repo ?? '', request: runId ? { runId } : {}, answer }, (ctx.now ?? Date.now)());
|
|
219
|
+
send(res, 403, answer);
|
|
220
|
+
return true;
|
|
214
221
|
} else if (!/^application\/json(?:\s*;|$)/i.test(String(req.headers['content-type'] || ''))) {
|
|
215
222
|
req.resume();
|
|
216
223
|
problem = { status: 415, message: 'Send the request as JSON (Content-Type: application/json).' };
|
package/server/agent-runs.js
CHANGED
|
@@ -615,7 +615,8 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
615
615
|
* `refusal(err)`, server/submit-review.js); resolves with the run and the comment that is the request.
|
|
616
616
|
* @param {RequestContext} ctx
|
|
617
617
|
* @param {{ body: unknown, problem?: { status: number, message: string } }} input `problem`: something already wrong with the request
|
|
618
|
-
* itself (not
|
|
618
|
+
* itself (not JSON, too large): refused here, after the flood count and with a row, like every other refusal. A request not from
|
|
619
|
+
* cornfield's own page never gets here: the route refuses it before anything is counted (server/agent-api.js)
|
|
619
620
|
*/
|
|
620
621
|
async function request(ctx, { body, problem }) {
|
|
621
622
|
const { who, via = null } = ctx;
|
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
|
/**
|
|
@@ -837,7 +862,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
|
|
|
837
862
|
}
|
|
838
863
|
// /auth/sign-out
|
|
839
864
|
req.resume();
|
|
840
|
-
if (!sameOrigin(req, publicHost)) return send(res, 403, { ok: false, error: 'Sign out from cornfield\'s own page.' });
|
|
865
|
+
if (!sameOrigin(req, publicHost, [], publicUrl.origin)) return send(res, 403, { ok: false, error: 'Sign out from cornfield\'s own page.' });
|
|
841
866
|
const row = await rowOf(req);
|
|
842
867
|
if (row) await endRow(row);
|
|
843
868
|
return redirect(res, '/auth/sign-in', [clearSession]);
|
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/forge-actions.js
CHANGED
|
@@ -14,32 +14,35 @@
|
|
|
14
14
|
* plan's `digest`: the server plans again and refuses (409) a plan that is not the one confirmed. They are idempotent: a
|
|
15
15
|
* second ask answers 200 with what the first made (`created: false`) instead of making it again.
|
|
16
16
|
*
|
|
17
|
-
* In this order, each step refusing in words
|
|
17
|
+
* In this order, each step refusing in words:
|
|
18
18
|
*
|
|
19
19
|
* 1. POST only (405 otherwise); a signed-in maintainer only (the guard in front answers 401 and 403; without
|
|
20
20
|
* sign-in there is nobody to act as, 403)
|
|
21
|
-
* 2. same origin only (`sameOrigin`, as the sign-out and the review PUT
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
25
|
-
*
|
|
26
|
-
*
|
|
27
|
-
* 4.
|
|
21
|
+
* 2. same origin only (`sameOrigin`, as the sign-out and the review PUT; with a public URL, its scheme too): a form
|
|
22
|
+
* on another site cannot send it. A page on a sibling subdomain is same-site, so the maintainer's cookie rides
|
|
23
|
+
* along: its refusal (403) is not counted toward their ceiling below, and is written down at most once a minute
|
|
24
|
+
* per person (server/throttle.js `noteRefusedOrigin`), so it can neither use up their budget nor grow the audit table
|
|
25
|
+
* 3. a ceiling on attempts of any kind per person per minute (`ATTEMPTS_PER_MINUTE`, 429 with Retry-After), before
|
|
26
|
+
* a row is written: refused attempts must not grow the audit table without end. From here every refusal is a row
|
|
27
|
+
* 4. a JSON body (here up to 4 KB, the rest not read)
|
|
28
|
+
* 5. not twice: one attempt at a time for the same action on the same target, a few seconds before it is asked
|
|
29
|
+
* again, and a ceiling of actions per person per minute (429 with Retry-After)
|
|
30
|
+
* 6. the permission asked of the forge now, with their own token, never the session's kept copy: someone who has
|
|
28
31
|
* stopped being a maintainer a minute ago is refused (403)
|
|
29
|
-
*
|
|
32
|
+
* 7. the forge's own state, read now: the pull request is open and not a draft, every check on its head is green,
|
|
30
33
|
* and `sha` is that head (409 otherwise: a push since they looked means they look again). `forge.merge` is the
|
|
31
34
|
* only way in, with `onlyIfGreen` and the sha: there is no force and no admin override to ask for. A re-run
|
|
32
35
|
* only takes a check the forge just listed as failed on that head, where `canRerun`. A pipeline step plans
|
|
33
36
|
* again from the forge (the issue is open; the review that approves is a maintainer's and was not edited) and
|
|
34
37
|
* only adds: a branch, a file, a pull request, an issue, never changes or removes one
|
|
35
38
|
*
|
|
36
|
-
* Every attempt under that ceiling, the ones refused and the ones the forge failed, is a row in `actions`
|
|
39
|
+
* Every attempt from cornfield's own page under that ceiling, the ones refused and the ones the forge failed, is a row in `actions`
|
|
37
40
|
* (server/db.js), begun before anything is asked of the forge and finished with the answer after (`auth.begin`,
|
|
38
41
|
* `auth.finish`). Without an audit to write to nothing is done.
|
|
39
42
|
*
|
|
40
43
|
* One more write is not about a pull request: **a new idea** (docs/threads.md), `POST /api/forge/threads { title, body }`, which opens an issue
|
|
41
44
|
* with the threads label as the signed-in maintainer (`serveIdea`, below). It goes through the same doors, in the same order:
|
|
42
|
-
* POST, signed in, the flood ceiling, an audit row begun,
|
|
45
|
+
* POST, signed in, same origin, the flood ceiling, an audit row begun, JSON (here up to 96 KB), not twice, the permission asked of
|
|
43
46
|
* the forge now. The row keeps the title and the text's length, never the text. It only adds: an issue, and on Forgejo the
|
|
44
47
|
* threads label first when the repo lacks it (the answer, and so the row, says `labelsMade`).
|
|
45
48
|
*
|
|
@@ -51,7 +54,7 @@ import { ForgeError, RERUN_STATES, canRerun, isMaintainer, hasAdapter } from './
|
|
|
51
54
|
import { sameOrigin } from './proposals.js';
|
|
52
55
|
import { planSpec, planBuild, startSpec, openBuildIssue } from './pipeline.js';
|
|
53
56
|
import { PROPOSAL_FILE } from './files.js';
|
|
54
|
-
import { Refused, throttle, countAttempt } from './throttle.js';
|
|
57
|
+
import { Refused, throttle, countAttempt, noteRefusedOrigin } from './throttle.js';
|
|
55
58
|
|
|
56
59
|
// The limits live in server/throttle.js (reviews share them); these are re-exported for the callers that always had them here
|
|
57
60
|
export { COOLDOWN_MS, PER_MINUTE, ATTEMPTS_PER_MINUTE, countAttempt } from './throttle.js';
|
|
@@ -160,7 +163,7 @@ export function actionOf(reqPath) {
|
|
|
160
163
|
* @param {import('node:http').IncomingMessage} req
|
|
161
164
|
* @param {import('node:http').ServerResponse} res
|
|
162
165
|
* @param {{ n: number, action: 'merge' | 'rerun' | 'spec' | 'build' }} what
|
|
163
|
-
* @param {{ config: object, where?: { proposals: string }, hooks?: import('./hooks.js').Hooks | null, session: { login: string, userId: string } | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function }, now?: () => number, publicHost?: string | null }} ctx
|
|
166
|
+
* @param {{ config: object, where?: { proposals: string }, hooks?: import('./hooks.js').Hooks | null, session: { login: string, userId: string } | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function, record: Function }, now?: () => number, publicHost?: string | null, publicOrigin?: string | null }} ctx
|
|
164
167
|
* @param {(status: number, body: object, headers?: object) => void} send
|
|
165
168
|
*/
|
|
166
169
|
export async function serveAction(req, res, what, ctx, send) {
|
|
@@ -174,13 +177,21 @@ export async function serveAction(req, res, what, ctx, send) {
|
|
|
174
177
|
req.resume();
|
|
175
178
|
return send(403, { ok: false, error: `${DOING[action]} is done as the signed-in maintainer: set up sign-in first (docs/sign-in.md).`, code: 'forbidden' });
|
|
176
179
|
}
|
|
180
|
+
const target = `${config.forge.repo}#${n}`;
|
|
181
|
+
// The origin first, before the flood count: a same-site page's POST rides on the maintainer's cookie, and a refused one must not use up
|
|
182
|
+
// their budget. It is written down at most once a minute (`noteRefusedOrigin`), so such a page cannot grow the audit table either
|
|
183
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, [], ctx.publicOrigin ?? null)) {
|
|
184
|
+
req.resume();
|
|
185
|
+
const answer = { ok: false, error: 'Do this from cornfield\'s own page.', code: 'forbidden' };
|
|
186
|
+
await noteRefusedOrigin(ctx, req, session, { action, target, request: { action, number: n }, answer }, now());
|
|
187
|
+
return send(403, answer);
|
|
188
|
+
}
|
|
177
189
|
// Past the ceiling nothing is written down: a flood of refused attempts cannot grow the audit table
|
|
178
190
|
const flood = countAttempt(ctx, session.userId, now());
|
|
179
191
|
if (flood) {
|
|
180
192
|
req.resume();
|
|
181
193
|
return send(flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
|
|
182
194
|
}
|
|
183
|
-
const target = `${config.forge.repo}#${n}`;
|
|
184
195
|
/** @type {Record<string, unknown>} */
|
|
185
196
|
const request = { action, number: n };
|
|
186
197
|
let rowTarget = target;
|
|
@@ -198,10 +209,6 @@ export async function serveAction(req, res, what, ctx, send) {
|
|
|
198
209
|
throw new Refused(503, 'cornfield cannot write its audit log, so it will not act on the forge.', 'unavailable');
|
|
199
210
|
}
|
|
200
211
|
|
|
201
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) {
|
|
202
|
-
req.resume();
|
|
203
|
-
throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
204
|
-
}
|
|
205
212
|
let body;
|
|
206
213
|
try {
|
|
207
214
|
body = await readJson(req);
|
|
@@ -304,7 +311,7 @@ export async function serveAction(req, res, what, ctx, send) {
|
|
|
304
311
|
* caller has found the path and the method to be this; every refusal is in words and written down, as in `serveAction`.
|
|
305
312
|
* @param {import('node:http').IncomingMessage} req
|
|
306
313
|
* @param {import('node:http').ServerResponse} res
|
|
307
|
-
* @param {{ config: any, session: { login: string, userId: string } | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function, begin: Function, finish: Function }, now?: () => number, publicHost?: string | null }} ctx
|
|
314
|
+
* @param {{ config: any, session: { login: string, userId: string } | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function, begin: Function, finish: Function, record: Function }, now?: () => number, publicHost?: string | null, publicOrigin?: string | null }} ctx
|
|
308
315
|
* @param {(status: number, body: object, headers?: object) => void} send
|
|
309
316
|
*/
|
|
310
317
|
export async function serveIdea(req, res, ctx, send) {
|
|
@@ -321,12 +328,19 @@ export async function serveIdea(req, res, ctx, send) {
|
|
|
321
328
|
req.resume();
|
|
322
329
|
return send(403, { ok: false, error: `${DOING.idea} is done as the signed-in maintainer: set up sign-in first (docs/sign-in.md).`, code: 'forbidden' });
|
|
323
330
|
}
|
|
331
|
+
const target = config.forge.repo;
|
|
332
|
+
// The origin first, before the flood count, and written down at most once a minute: as in `serveAction`
|
|
333
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, [], ctx.publicOrigin ?? null)) {
|
|
334
|
+
req.resume();
|
|
335
|
+
const answer = { ok: false, error: 'Do this from cornfield\'s own page.', code: 'forbidden' };
|
|
336
|
+
await noteRefusedOrigin(ctx, req, session, { action: 'idea', target, request: { action: 'idea' }, answer }, now());
|
|
337
|
+
return send(403, answer);
|
|
338
|
+
}
|
|
324
339
|
const flood = countAttempt(ctx, session.userId, now());
|
|
325
340
|
if (flood) {
|
|
326
341
|
req.resume();
|
|
327
342
|
return send(flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
|
|
328
343
|
}
|
|
329
|
-
const target = config.forge.repo;
|
|
330
344
|
/** @type {Record<string, unknown>} */
|
|
331
345
|
const request = { action: 'idea' };
|
|
332
346
|
let rowId = null;
|
|
@@ -341,10 +355,6 @@ export async function serveIdea(req, res, ctx, send) {
|
|
|
341
355
|
console.error(`[cornfield] the audit row of idea ${target} could not be written: ${err instanceof Error ? err.message : err}`);
|
|
342
356
|
throw new Refused(503, 'cornfield cannot write its audit log, so it will not act on the forge.', 'unavailable');
|
|
343
357
|
}
|
|
344
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) {
|
|
345
|
-
req.resume();
|
|
346
|
-
throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
347
|
-
}
|
|
348
358
|
let asked;
|
|
349
359
|
try {
|
|
350
360
|
asked = await readJson(req, IDEA_BODY);
|
package/server/forge-routes.js
CHANGED
|
@@ -256,7 +256,7 @@ async function servePlan(req, res, act, url, ctx) {
|
|
|
256
256
|
* @param {import('node:http').ServerResponse} res
|
|
257
257
|
* @param {string} reqPath the decoded path
|
|
258
258
|
* @param {URL} url
|
|
259
|
-
* @param {{ config: object, where?: { proposals: string }, hooks?: import('./hooks.js').Hooks | null, lander?: import('./lander.js').Lander | null, session: { userId: string, login: string } | null, publicHost?: string | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function }, now?: () => number }} ctx
|
|
259
|
+
* @param {{ config: object, where?: { proposals: string }, hooks?: import('./hooks.js').Hooks | null, lander?: import('./lander.js').Lander | null, session: { userId: string, login: string } | null, publicHost?: string | null, publicOrigin?: string | null, auth: { store: null | (() => Promise<import('node:sqlite').DatabaseSync>), forgeFor: Function }, now?: () => number }} ctx
|
|
260
260
|
* `session` is the signed-in maintainer's (null without sign-in)
|
|
261
261
|
* @returns {Promise<boolean>}
|
|
262
262
|
*/
|
|
@@ -366,7 +366,7 @@ export async function serveForge(req, res, reqPath, url, ctx) {
|
|
|
366
366
|
* POST /api/forge/release-drafts: the notes since a tag, kept by the forge as a draft release.
|
|
367
367
|
* @param {import('node:http').IncomingMessage} req
|
|
368
368
|
* @param {import('node:http').ServerResponse} res
|
|
369
|
-
* @param {{ config: any, session: any, auth: any, publicHost?: string | null }} ctx
|
|
369
|
+
* @param {{ config: any, session: any, auth: any, publicHost?: string | null, publicOrigin?: string | null }} ctx
|
|
370
370
|
* @param {string} name the forge's name, for the words
|
|
371
371
|
*/
|
|
372
372
|
async function postDraft(req, res, ctx, name) {
|
|
@@ -376,7 +376,7 @@ async function postDraft(req, res, ctx, name) {
|
|
|
376
376
|
req.resume();
|
|
377
377
|
return say(405, { ok: false, error: 'A release draft is posted with POST.' }, { Allow: 'POST' });
|
|
378
378
|
}
|
|
379
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) {
|
|
379
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, [], ctx.publicOrigin ?? null)) {
|
|
380
380
|
req.resume();
|
|
381
381
|
return say(403, { ok: false, error: 'A release draft is only posted from cornfield\'s own page.', code: 'forbidden' });
|
|
382
382
|
}
|
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, publicOrigin?: 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) {
|
|
@@ -375,9 +375,10 @@ export async function serveLanding(req, what, ctx) {
|
|
|
375
375
|
}
|
|
376
376
|
if (req.method !== 'POST') return { status: 405, body: { ok: false, error: 'Cancelling is done with POST.', code: 'invalid' }, headers: { Allow: 'POST' } };
|
|
377
377
|
try {
|
|
378
|
+
// The origin first: a same-site page's POST carries the maintainer's cookie, and a refused one must not use up their budget
|
|
379
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, ctx.embedOrigins ?? [], ctx.publicOrigin ?? null)) throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
378
380
|
const flood = countAttempt(ctx, session.userId, now());
|
|
379
381
|
if (flood) throw flood;
|
|
380
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
381
382
|
if (!lander) throw new Refused(404, 'Landing on approval is not turned on (proposals.approveLands).', 'not-found');
|
|
382
383
|
const forge = auth.forgeFor(session);
|
|
383
384
|
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,16 +103,27 @@ 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
|
|
107
|
+
* @param {string|null} [publicOrigin] the configured public URL's origin (scheme, host, port). A request that arrives under the public host must carry exactly this
|
|
108
|
+
* `Origin`, scheme included. Without one (loopback, no public URL) only the host is compared: behind a proxy the scheme cannot be known. A request that
|
|
109
|
+
* arrives under another of the machine's own names (`localhost`, an address) keeps the host comparison, as before.
|
|
105
110
|
*/
|
|
106
|
-
export function sameOrigin(req, publicHost = null) {
|
|
111
|
+
export function sameOrigin(req, publicHost = null, embedOrigins = [], publicOrigin = null) {
|
|
107
112
|
const host = req.headers.host;
|
|
108
113
|
if (typeof host !== 'string' || !ownHostName(host, publicHost)) return false;
|
|
114
|
+
// The two writes a listed sibling origin may make pass their list here (server/embed.js `listedWrite`); every other caller passes none
|
|
115
|
+
if (embedOrigins.length && listedWrite(req.headers, embedOrigins)) return true;
|
|
109
116
|
const origin = req.headers.origin;
|
|
110
117
|
const site = req.headers['sec-fetch-site'];
|
|
111
118
|
if (origin === undefined && site === undefined) return false;
|
|
112
119
|
if (origin !== undefined) {
|
|
113
120
|
try {
|
|
114
|
-
|
|
121
|
+
const given = new URL(origin);
|
|
122
|
+
// A proxy may keep the scheme's default port in the Host (`:443`, `:80`), which an Origin never carries; any other difference is another origin
|
|
123
|
+
const sent = host.toLowerCase();
|
|
124
|
+
const port = given.protocol === 'https:' ? '443' : given.protocol === 'http:' ? '80' : null;
|
|
125
|
+
if (given.host !== sent && !(port && sent === `${given.host}:${port}`)) return false;
|
|
126
|
+
if (publicOrigin && publicHost && new URL(`http://${host}`).hostname === String(publicHost).toLowerCase() && given.protocol !== new URL(publicOrigin).protocol) return false; // host and port equal the Host header's (above), so with the public port in it this is the exact origin
|
|
115
127
|
} catch {
|
|
116
128
|
return false; // `null`, or not a URL
|
|
117
129
|
}
|
|
@@ -278,7 +290,7 @@ async function getDecision(res, where, forgeFor, signedIn, slug, n, fresh) {
|
|
|
278
290
|
|
|
279
291
|
/** PUT /proposals/<slug>/review?source=pull/<n>: posts the review as a comment on the PR, as the signed-in maintainer */
|
|
280
292
|
async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
|
|
281
|
-
if (!sameOrigin(req, where.publicHost)) {
|
|
293
|
+
if (!sameOrigin(req, where.publicHost, where.embedOrigins ?? [], where.publicOrigin ?? null)) {
|
|
282
294
|
req.resume();
|
|
283
295
|
return send(res, 403, { error: 'A review is only taken from cornfield\'s own page' });
|
|
284
296
|
}
|
package/server/review-api.js
CHANGED
|
@@ -40,7 +40,7 @@ import { sameOrigin, readBody } from './proposals.js';
|
|
|
40
40
|
import { REVIEW_LIMIT } from './reviews.js';
|
|
41
41
|
import { MAX_ACTIVE, MAX_DAYS, DEFAULT_DAYS, bearerOf, daysOf, findToken, labelProblem, listTokens, mintToken, revokeToken, touchToken } from './review-tokens.js';
|
|
42
42
|
import { refusal, submitReview } from './submit-review.js';
|
|
43
|
-
import { Refused, countAttempt } from './throttle.js';
|
|
43
|
+
import { Refused, countAttempt, noteRefusedOrigin } from './throttle.js';
|
|
44
44
|
|
|
45
45
|
export const REVIEWS_PATH = '/api/reviews';
|
|
46
46
|
export const TOKENS_PATH = '/api/review-tokens';
|
|
@@ -62,7 +62,7 @@ function send(res, status, body, headers = {}) {
|
|
|
62
62
|
|
|
63
63
|
const plainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
64
64
|
|
|
65
|
-
/** @typedef {{ config: any, where: any, auth: any, hooks?: import('./hooks.js').Hooks | null, lander?: import('./lander.js').Lander | null, now?: () => number, publicHost?: string | null }} ApiContext */
|
|
65
|
+
/** @typedef {{ config: any, where: any, auth: any, hooks?: import('./hooks.js').Hooks | null, lander?: import('./lander.js').Lander | null, now?: () => number, publicHost?: string | null, publicOrigin?: string | null }} ApiContext */
|
|
66
66
|
|
|
67
67
|
/**
|
|
68
68
|
* `POST /api/reviews`. The caller has found the path to be this one; this runs before the sign-in guard.
|
|
@@ -209,14 +209,23 @@ export async function serveTokenRoutes(req, res, reqPath, ctx) {
|
|
|
209
209
|
}
|
|
210
210
|
|
|
211
211
|
// A change: from cornfield's own page only, as JSON, counted and written down, and the forge asked who this is now
|
|
212
|
+
const what = revoke ? 'revoke' : 'mint';
|
|
213
|
+
const request = /** @type {Record<string, unknown>} */ ({ op: what, ...(scope !== 'review' ? { scope } : {}), ...(revoke ? { id: Number(revoke[2]) } : {}) });
|
|
214
|
+
// The origin first, before the flood count: a same-site page's POST rides on the maintainer's cookie, and a refused one must not use up
|
|
215
|
+
// their budget. It is written down at most once a minute (server/throttle.js `noteRefusedOrigin`)
|
|
216
|
+
if (!sameOrigin(req, ctx.publicHost ?? null, [], ctx.publicOrigin ?? null)) {
|
|
217
|
+
req.resume();
|
|
218
|
+
const answer = { ok: false, error: 'Do this from cornfield\'s own page.', code: 'forbidden' };
|
|
219
|
+
await noteRefusedOrigin(ctx, req, session, { action: 'review-token', target: config.forge.repo, request, answer }, now());
|
|
220
|
+
send(res, 403, answer);
|
|
221
|
+
return true;
|
|
222
|
+
}
|
|
212
223
|
const flood = countAttempt(ctx, session.userId, now());
|
|
213
224
|
if (flood) {
|
|
214
225
|
req.resume();
|
|
215
226
|
send(res, flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
|
|
216
227
|
return true;
|
|
217
228
|
}
|
|
218
|
-
const what = revoke ? 'revoke' : 'mint';
|
|
219
|
-
const request = /** @type {Record<string, unknown>} */ ({ op: what, ...(scope !== 'review' ? { scope } : {}), ...(revoke ? { id: Number(revoke[2]) } : {}) });
|
|
220
229
|
let rowId = null;
|
|
221
230
|
/** @type {{ status: number, body: object }} */
|
|
222
231
|
let out;
|
|
@@ -227,10 +236,6 @@ export async function serveTokenRoutes(req, res, reqPath, ctx) {
|
|
|
227
236
|
console.error(`[cornfield] the audit row of a review token could not be written: ${err instanceof Error ? err.message : err}`);
|
|
228
237
|
throw new Refused(503, 'cornfield cannot write its audit log, so it will not change review tokens.', 'unavailable');
|
|
229
238
|
}
|
|
230
|
-
if (!sameOrigin(req, ctx.publicHost ?? null)) {
|
|
231
|
-
req.resume();
|
|
232
|
-
throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
|
|
233
|
-
}
|
|
234
239
|
const body = revoke ? {} : await jsonBody(req);
|
|
235
240
|
const forge = auth.forgeFor(session);
|
|
236
241
|
const me = await forge.me();
|
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,10 @@ 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
|
-
const
|
|
313
|
+
const publicOrigin = config.publicUrl ? new URL(config.publicUrl).origin : null;
|
|
314
|
+
// The sibling origins that may read and decide a review as the signed-in maintainer (server/embed.js): none unless `embed.origins` lists some
|
|
315
|
+
const embed = createEmbed(config.embed?.origins ?? []);
|
|
316
|
+
const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost, publicOrigin, embedOrigins: embed.origins };
|
|
312
317
|
const fixtureCache = new Map();
|
|
313
318
|
// 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
319
|
const approvalRun = triggersOf(config).find(([event]) => event === 'spec.approved');
|
|
@@ -434,6 +439,16 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
434
439
|
return res.end('400 Bad Request');
|
|
435
440
|
}
|
|
436
441
|
|
|
442
|
+
// 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
|
|
443
|
+
// preflight is answered here, before the guard (a preflight carries no cookie). With no origin listed both are nothing
|
|
444
|
+
const preflight = embed.preflight(req, reqPath);
|
|
445
|
+
if (preflight) {
|
|
446
|
+
req.resume();
|
|
447
|
+
res.writeHead(preflight.status, preflight.headers);
|
|
448
|
+
return res.end();
|
|
449
|
+
}
|
|
450
|
+
for (const [name, value] of Object.entries(embed.headers(req, reqPath))) res.setHeader(name, value);
|
|
451
|
+
|
|
437
452
|
// 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
453
|
if (presentedScope(req) === 'runner' && !takesTokens(reqPath, { reviews: REVIEWS_PATH })) return serveStrayRunner(req, res, reqPath, { config, auth, now: opts.now });
|
|
439
454
|
|
|
@@ -462,9 +477,9 @@ export function createCornfieldServer(config, opts = {}) {
|
|
|
462
477
|
const signedIn = gate.session ? { login: gate.session.login } : false;
|
|
463
478
|
|
|
464
479
|
// Before the proxies: a repo's `/api/` proxy must not swallow the panel's own routes
|
|
465
|
-
if (await serveTokenRoutes(req, res, reqPath, { config, where, auth, session: gate.session, now: opts.now, publicHost })) return;
|
|
466
|
-
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;
|
|
480
|
+
if (await serveTokenRoutes(req, res, reqPath, { config, where, auth, session: gate.session, now: opts.now, publicHost, publicOrigin })) return;
|
|
481
|
+
if (await serveRunRoutes(req, res, reqPath, { config, auth, runs, session: gate.session, now: opts.now, publicHost, publicOrigin })) return;
|
|
482
|
+
if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, lander, now: opts.now, publicHost, publicOrigin, embedOrigins: embed.origins })) return;
|
|
468
483
|
for (const [prefix, target] of proxies) if (reqPath.startsWith(prefix)) return proxyTo(req, res, target);
|
|
469
484
|
const session = gate.session;
|
|
470
485
|
const forgeFor = session ? () => auth.forgeFor(session) : null;
|
package/server/throttle.js
CHANGED
|
@@ -10,6 +10,8 @@
|
|
|
10
10
|
* anything is written down, so refused attempts cannot grow the audit table without end
|
|
11
11
|
* throttle not twice: one at a time for the same key, `COOLDOWN_MS` before it is asked again, and a ceiling of
|
|
12
12
|
* `PER_MINUTE` actions per person per minute
|
|
13
|
+
* noteRefusedOrigin a write refused for not coming from cornfield's own page, checked before `countAttempt` and never
|
|
14
|
+
* counted by it: written down at most once a minute per person, under a count of its own
|
|
13
15
|
*
|
|
14
16
|
* A refusal is a `Refused`: a status (429, or the action's own), words, a code and the headers to answer with.
|
|
15
17
|
*/
|
|
@@ -91,3 +93,28 @@ export function throttle(ctx, userId, key, at) {
|
|
|
91
93
|
mine.push(at);
|
|
92
94
|
return () => { t.busy.delete(key); };
|
|
93
95
|
}
|
|
96
|
+
|
|
97
|
+
/** How many writes refused for their origin are written down per person per minute; the rest are refused without a row */
|
|
98
|
+
export const REFUSED_ORIGIN_ROWS_PER_MINUTE = 1;
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Writes down a write refused because it did not come from cornfield's own page: a page on a sibling subdomain is same-site,
|
|
102
|
+
* so the maintainer's cookie rides along, and a trace of "a page tried to act as you" is worth keeping. At most
|
|
103
|
+
* `REFUSED_ORIGIN_ROWS_PER_MINUTE` a minute per person, counted under a key of its own, so such a page neither uses up the
|
|
104
|
+
* person's own budget (`ATTEMPTS_PER_MINUTE`) nor grows the audit table faster than that. A row that cannot be written is
|
|
105
|
+
* logged; the refusal stands either way.
|
|
106
|
+
* @param {{ auth: { record: Function } }} ctx
|
|
107
|
+
* @param {import('node:http').IncomingMessage} req
|
|
108
|
+
* @param {{ login: string, userId: string }} who
|
|
109
|
+
* @param {{ action: string, target: string, request?: object, answer: object }} entry the route's own row, as it would have been
|
|
110
|
+
* @param {number} at
|
|
111
|
+
*/
|
|
112
|
+
export async function noteRefusedOrigin(ctx, req, who, { action, target, request = {}, answer }, at) {
|
|
113
|
+
if (countAttempt(ctx, `origin|${who.userId}`, at, REFUSED_ORIGIN_ROWS_PER_MINUTE)) return;
|
|
114
|
+
const header = (name) => (typeof req.headers[name] === 'string' ? String(req.headers[name]).slice(0, 200) : null);
|
|
115
|
+
try {
|
|
116
|
+
await ctx.auth.record({ login: who.login, action, target, request: { ...request, refused: 'origin', origin: header('origin'), site: header('sec-fetch-site') }, status: 403, answer });
|
|
117
|
+
} catch (err) {
|
|
118
|
+
console.error(`[cornfield] a write refused for its origin could not be written down: ${err instanceof Error ? err.message : err}`);
|
|
119
|
+
}
|
|
120
|
+
}
|