@popcorn245/cornfield 0.46.0 → 0.46.2

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.
Files changed (62) hide show
  1. package/explorer/capped.js +3 -2
  2. package/explorer/engine/feedback.js +49 -0
  3. package/explorer/engine/flow-ui.js +39 -0
  4. package/explorer/engine/fly.js +54 -0
  5. package/explorer/engine/hint.js +97 -0
  6. package/explorer/engine/keyboard.js +156 -0
  7. package/explorer/engine/layers.js +280 -0
  8. package/explorer/engine/layout.js +378 -0
  9. package/explorer/engine/map-style.js +547 -0
  10. package/explorer/engine/piece.js +142 -0
  11. package/explorer/engine/render.js +331 -0
  12. package/explorer/engine/search-status.js +59 -0
  13. package/explorer/engine/selection.js +42 -0
  14. package/explorer/engine/sheets.js +417 -0
  15. package/explorer/engine/strings.js +63 -0
  16. package/explorer/feedback.js +11 -45
  17. package/explorer/flow-style.js +28 -0
  18. package/explorer/flows.js +10 -51
  19. package/explorer/fly.js +11 -43
  20. package/explorer/hint.js +15 -88
  21. package/explorer/index.html +38 -75
  22. package/explorer/input.js +190 -177
  23. package/explorer/instance-state.js +172 -0
  24. package/explorer/instance.js +267 -0
  25. package/explorer/keyboard.js +14 -206
  26. package/explorer/labels.js +3 -3
  27. package/explorer/layers.js +34 -445
  28. package/explorer/layout.js +14 -372
  29. package/explorer/main.js +4 -226
  30. package/explorer/map-style.js +27 -525
  31. package/explorer/mockups-model.js +3 -3
  32. package/explorer/page-pieces.js +61 -0
  33. package/explorer/page.js +232 -0
  34. package/explorer/panels.js +29 -409
  35. package/explorer/pieces/layers.js +325 -0
  36. package/explorer/pieces/node-panel.js +536 -0
  37. package/explorer/pieces/search.js +454 -0
  38. package/explorer/proposal-model.js +1 -1
  39. package/explorer/proposal.js +1 -0
  40. package/explorer/render.js +37 -267
  41. package/explorer/renderer-canvas2d.js +4 -4
  42. package/explorer/renderer-webgl.js +21 -8
  43. package/explorer/renderer.js +11 -9
  44. package/explorer/scene.js +3 -2
  45. package/explorer/search-status.js +8 -47
  46. package/explorer/search.js +26 -324
  47. package/explorer/selection-view.js +17 -19
  48. package/explorer/sheets.js +31 -379
  49. package/explorer/state.js +38 -173
  50. package/explorer/strings.js +17 -60
  51. package/explorer/view.js +4 -5
  52. package/package.json +1 -1
  53. package/server/agent-api.js +13 -6
  54. package/server/agent-runs.js +2 -1
  55. package/server/auth.js +1 -1
  56. package/server/forge-actions.js +34 -24
  57. package/server/forge-routes.js +3 -3
  58. package/server/lander.js +3 -2
  59. package/server/proposals.js +11 -3
  60. package/server/review-api.js +13 -8
  61. package/server/server.js +5 -4
  62. package/server/throttle.js +27 -0
@@ -1,68 +1,25 @@
1
1
  /**
2
2
  * @module explorer/strings
3
3
  *
4
- * The words a repo may say in its own voice (core/strings.js is the table; `strings` in cornfield.config.js the overrides, which
5
- * `/cornfield/config.json` carries). Every overridable label is read through `t(key)`; the static markup in index.html marks what
6
- * to replace with `data-corn-string` attributes, which `applyStrings` fills once the config is in.
7
- *
8
- * data-corn-string="key" the element's text
9
- * data-corn-string-aria-label="key" its aria-label
10
- * data-corn-string-placeholder="key" its placeholder
11
- *
12
- * The rule for accessible names: a control's name is its visible label. When a key is overridden the visible text and the
13
- * aria-label carry the same words, and where a name adds a fixed target ("Stop run 7") only the label part is replaced
14
- * ("Halt run 7"). So a screen reader says what is on the screen.
15
- *
16
- * Values are only ever set through textContent and attributes, never as HTML, and a value that fails core/strings.js
17
- * `stringProblem` (not text, a line break, too long) is ignored here as well, whatever the server sent.
4
+ * A bridge (spec 0011 D2, step 4): the words now live on the instance (`inst.strings`, read with `t(inst, key)` from engine/strings.js).
5
+ * This file keeps the old names for the modules that are not yet on an instance, bound to the page's voice: `pageStrings`, the object the page
6
+ * instance's `strings` is (state.js hands it over), so the two are one. It imports nothing of the page's state, because pure models read the words
7
+ * through it (waiting-model.js) and the converted modules import those. It goes when the last caller (forge-panel.js, proposal.js, review.js,
8
+ * review-column.js, whatif.js, scenario-ui.js, runs-view.js, waiting-*.js, plugins.js) is converted.
18
9
  */
10
+ import * as S from './engine/strings.js';
19
11
 
20
- import { STRINGS, isStringKey, stringProblem } from '../core/strings.js';
21
-
22
- /** The overrides in force: key -> text */
23
- let overrides = {};
24
-
25
- /**
26
- * Takes the overrides the config carries (`config.strings`). Anything that is not a known key with good text is left out.
27
- * @param {unknown} strings
28
- */
29
- export function setStrings(strings) {
30
- overrides = {};
31
- if (!strings || typeof strings !== 'object' || Array.isArray(strings)) return;
32
- for (const [key, value] of Object.entries(strings)) if (isStringKey(key) && !stringProblem(value)) overrides[key] = value;
33
- }
12
+ /** The overrides in force on cornfield's page: key -> text */
13
+ export const pageStrings = {};
14
+ const voice = { strings: pageStrings, root: null };
34
15
 
16
+ /** Takes the overrides the config carries (`config.strings`) */
17
+ export const setStrings = (strings) => S.setStrings(voice, strings);
35
18
  /** Whether the config overrides this key */
36
- export const isOverridden = (key) => Object.hasOwn(overrides, key);
37
-
38
- /** The words for a key: the override, else the default. A key that is not in the table gives the key itself (a test keeps the code to the table). */
39
- export function t(key) {
40
- if (Object.hasOwn(overrides, key)) return overrides[key];
41
- return isStringKey(key) ? STRINGS[key] : String(key);
42
- }
43
-
44
- const TARGETS = [
45
- ['data-corn-string', (el, text) => { el.textContent = text; }],
46
- ['data-corn-string-aria-label', (el, text) => el.setAttribute('aria-label', text)],
47
- ['data-corn-string-placeholder', (el, text) => el.setAttribute('placeholder', text)],
48
- ];
49
-
50
- /**
51
- * Puts the overrides in the static markup. Only an overridden key touches its element, so what index.html says is what shows
52
- * without one.
53
- * @param {ParentNode} root
54
- */
55
- export function applyStrings(root) {
56
- if (!root || typeof root.querySelectorAll !== 'function') return;
57
- for (const [attr, set] of TARGETS) {
58
- for (const el of root.querySelectorAll(`[${attr}]`)) {
59
- const key = el.getAttribute(attr);
60
- if (isOverridden(key)) set(el, overrides[key]);
61
- }
62
- }
63
- }
64
-
19
+ export const isOverridden = (key) => S.isOverridden(voice, key);
20
+ /** The words for a key: the override, else the default */
21
+ export const t = (key) => S.t(voice, key);
22
+ /** Puts the overrides in the static markup under `root` */
23
+ export const applyStrings = (root) => S.applyStrings(voice, root);
65
24
  /** For tests: forget the overrides */
66
- export function resetStringsForTests() {
67
- overrides = {};
68
- }
25
+ export const resetStringsForTests = () => S.setStrings(voice, {});
package/explorer/view.js CHANGED
@@ -5,7 +5,7 @@
5
5
  * preset. A failed load is an error state on the page, with a retry, never a blank canvas.
6
6
  */
7
7
 
8
- import { state, touchScene } from './state.js';
8
+ import { state, touchScene, pageInstance } from './state.js';
9
9
  import { computeDegreeCentrality, layoutOrbit, computeLaneLayout } from './layout.js';
10
10
  import { buildDataFlow } from './flows.js';
11
11
  import { render, fitGraphToViewport, fitPadding, ensureFlowLoop } from './render.js';
@@ -16,6 +16,7 @@ import { measureParams } from './bench.js';
16
16
  import { mergeLive, placeLiveNodes } from './live-model.js';
17
17
  import { applyHouseLayout } from './house-model.js';
18
18
  import { syncHint } from './hint.js';
19
+ import { ensurePagePieces } from './page-pieces.js';
19
20
 
20
21
  const $ = (id) => document.getElementById(id);
21
22
 
@@ -162,9 +163,7 @@ export function syncViewUi() {
162
163
  if (map) map.setAttribute('aria-pressed', String(state.view !== 'dataflow' && state.view !== 'house'));
163
164
  const btn = $('preset-dataflow-btn');
164
165
  if (btn) btn.setAttribute('aria-pressed', String(preset));
165
- const layersBtn = $('legend-toggle-btn');
166
- if (layersBtn) layersBtn.classList.toggle('hx-layers-chip--dim', preset);
167
- const note = $('layers-preset-note');
168
- if (note) note.hidden = !preset;
166
+ ensurePagePieces(); // the Layers menu, if the page has its place
167
+ pageInstance().emit('view', state.view); // the Layers chip dims while the data-flow view is on (pieces/layers.js)
169
168
  syncHint(); // the hint's words for this view and pointer, and whether it shows (hint.js)
170
169
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@popcorn245/cornfield",
3
- "version": "0.46.0",
3
+ "version": "0.46.2",
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)",
@@ -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`) with a JSON body and count toward the flood ceiling (server/throttle.js); a token is no way
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
- problem = { status: 403, message: 'Do this from cornfield\'s own page.' };
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).' };
@@ -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 same-origin, not JSON, too large): refused here, after the flood count and with a row, like every other refusal
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
@@ -862,7 +862,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
862
862
  }
863
863
  // /auth/sign-out
864
864
  req.resume();
865
- 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.' });
866
866
  const row = await rowOf(req);
867
867
  if (row) await endRow(row);
868
868
  return redirect(res, '/auth/sign-in', [clearSession]);
@@ -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 and the refusal written down:
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), with a JSON body: a form on another site
22
- * can send neither
23
- * 3. not twice: one attempt at a time for the same action on the same target, a few seconds before it is asked
24
- * again, and a ceiling per person per minute (429 with Retry-After). Before any of this, and before a row is
25
- * written, a ceiling on attempts of any kind per person per minute (`ATTEMPTS_PER_MINUTE`): a page on a sibling
26
- * subdomain is same-site, so the cookie rides along, and refused attempts must not grow the audit table without end
27
- * 4. the permission asked of the forge now, with their own token, never the session's kept copy: someone who has
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
- * 5. the forge's own state, read now: the pull request is open and not a draft, every check on its head is green,
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, same origin, JSON (here up to 32 KB), not twice, the permission asked of
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);
@@ -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, embedOrigins?: readonly string[] }} 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, ctx.embedOrigins ?? [])) 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();
@@ -104,8 +104,11 @@ function ownHostName(host, publicHost) {
104
104
  * @param {import('node:http').IncomingMessage} req
105
105
  * @param {string|null} [publicHost] the host of the configured public URL, which is the server's own too
106
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.
107
110
  */
108
- export function sameOrigin(req, publicHost = null, embedOrigins = []) {
111
+ export function sameOrigin(req, publicHost = null, embedOrigins = [], publicOrigin = null) {
109
112
  const host = req.headers.host;
110
113
  if (typeof host !== 'string' || !ownHostName(host, publicHost)) return false;
111
114
  // The two writes a listed sibling origin may make pass their list here (server/embed.js `listedWrite`); every other caller passes none
@@ -115,7 +118,12 @@ export function sameOrigin(req, publicHost = null, embedOrigins = []) {
115
118
  if (origin === undefined && site === undefined) return false;
116
119
  if (origin !== undefined) {
117
120
  try {
118
- if (new URL(origin).host !== host.toLowerCase()) return false;
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
119
127
  } catch {
120
128
  return false; // `null`, or not a URL
121
129
  }
@@ -282,7 +290,7 @@ async function getDecision(res, where, forgeFor, signedIn, slug, n, fresh) {
282
290
 
283
291
  /** PUT /proposals/<slug>/review?source=pull/<n>: posts the review as a comment on the PR, as the signed-in maintainer */
284
292
  async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
285
- if (!sameOrigin(req, where.publicHost, where.embedOrigins ?? [])) {
293
+ if (!sameOrigin(req, where.publicHost, where.embedOrigins ?? [], where.publicOrigin ?? null)) {
286
294
  req.resume();
287
295
  return send(res, 403, { error: 'A review is only taken from cornfield\'s own page' });
288
296
  }
@@ -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
@@ -310,9 +310,10 @@ export function createCornfieldServer(config, opts = {}) {
310
310
  const brandFile = brandFilesOf(config);
311
311
  const repoModules = repoModuleDirs(config);
312
312
  const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
313
+ const publicOrigin = config.publicUrl ? new URL(config.publicUrl).origin : null;
313
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
314
315
  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 };
316
+ const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost, publicOrigin, embedOrigins: embed.origins };
316
317
  const fixtureCache = new Map();
317
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
318
319
  const approvalRun = triggersOf(config).find(([event]) => event === 'spec.approved');
@@ -476,9 +477,9 @@ export function createCornfieldServer(config, opts = {}) {
476
477
  const signedIn = gate.session ? { login: gate.session.login } : false;
477
478
 
478
479
  // Before the proxies: a repo's `/api/` proxy must not swallow the panel's own routes
479
- if (await serveTokenRoutes(req, res, reqPath, { config, where, auth, session: gate.session, now: opts.now, publicHost })) return;
480
- if (await serveRunRoutes(req, res, reqPath, { config, auth, runs, session: gate.session, 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;
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;
482
483
  for (const [prefix, target] of proxies) if (reqPath.startsWith(prefix)) return proxyTo(req, res, target);
483
484
  const session = gate.session;
484
485
  const forgeFor = session ? () => auth.forgeFor(session) : null;
@@ -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
+ }