cornfield 0.44.0 → 0.46.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * @module server/embed
3
+ *
4
+ * Letting a listed sibling app in (spec 0011 D9). The config's `embed.origins` (core/config.js `embedOrigin`: exact, canonical origins)
5
+ * names pages that may ask this server for what the map and the review need, with the signed-in maintainer's own session, and decide
6
+ * one review. Nothing here is on by default: with no origin listed `createEmbed(...).headers()` answers `{}`, nothing is answered
7
+ * for a preflight and no write is let in, so every response is what it was before.
8
+ *
9
+ * What it decides (all pure: headers and paths in, headers and booleans out):
10
+ *
11
+ * - **Reads**, on an explicit list of routes (`ROUTES`, default deny): for a request whose `Origin` is exactly a listed origin, the
12
+ * answer carries `Access-Control-Allow-Origin: <that origin>` (never `*`), `Vary: Origin`, and on the routes behind the session also
13
+ * `Access-Control-Allow-Credentials: true` and the headers the explorer reads (`X-Proposal-Sha256`, `X-Proposal-Source`,
14
+ * `X-Proposals-Forge-Error`). The routes that answer without a session (the theme) carry no `Allow-Credentials`: they hold nothing
15
+ * the session decides, and a fetch of them is made without credentials. Every other route, an `/api/*-tokens` and `/api/agent-runs`
16
+ * route and any other `/api/forge/*` route included, gets no CORS header at all.
17
+ * - **The preflight** (`OPTIONS` with `Access-Control-Request-Method`): answered for a listed origin on a route of the list, for the
18
+ * methods and request headers that route needs and no others (`Content-Type` on the two writes, none on a read).
19
+ * - **Writes**: today's same-origin rule stays for every write (server/proposals.js `sameOrigin`). For exactly two writes, the review
20
+ * PUT and the Undo of an approval's hold (`WRITES`), a listed origin is accepted too: its `Origin` must be exactly listed and
21
+ * `Sec-Fetch-Site` must be `same-site`, or missing (a browser too old to send it still sends `Origin` on a cross-origin PUT or POST;
22
+ * and the session cookie is `SameSite=Lax`, so a request that is not same-site arrives with no session to act as). Any other value
23
+ * (`cross-site`, `same-origin`, `none`) is refused. The caller has checked `Host` already (`sameOrigin` does it first).
24
+ * - **Signing in and returning**: `listedReturn` says whether a sign-in may end on an absolute URL: only one whose origin is listed.
25
+ *
26
+ * The session cookie is not touched here (HttpOnly, SameSite=Lax, host-only; server/auth.js). See docs/embedding.md.
27
+ */
28
+
29
+ /** @typedef {{ test: RegExp | string, kind: 'session' | 'open', methods: string[], headers: string[] }} Route */
30
+
31
+ /** The headers the explorer reads from an answer: a page on another origin can read them only if they are exposed */
32
+ const EXPOSED = ['X-Proposal-Sha256', 'X-Proposal-Source', 'X-Proposals-Forge-Error'];
33
+
34
+ const READ = ['GET', 'HEAD'];
35
+ const SLUG = '[^/]+';
36
+
37
+ /**
38
+ * The routes a listed origin may reach, and nothing else. `session`: behind the sign-in guard, so the credentialed form of CORS; `open`:
39
+ * answered before it (the look of the sign-in pages: theme.css, a named theme, and the images and fonts a theme names).
40
+ * `methods` are what a preflight may ask for; `headers` are the request headers it may list (lowercase).
41
+ * @type {readonly Route[]}
42
+ */
43
+ export const ROUTES = Object.freeze([
44
+ { test: '/cornfield/config.json', kind: 'session', methods: READ, headers: [] },
45
+ { test: '/topology.json', kind: 'session', methods: READ, headers: [] },
46
+ { test: '/topology.cloud.json', kind: 'session', methods: READ, headers: [] },
47
+ { test: '/proposals', kind: 'session', methods: READ, headers: [] },
48
+ { test: new RegExp(`^/proposals/${SLUG}\\.json$`), kind: 'session', methods: READ, headers: [] },
49
+ { test: new RegExp(`^/proposals/${SLUG}/decision$`), kind: 'session', methods: READ, headers: [] },
50
+ // The review: read, and the one write a listed origin may make on a proposal (see `WRITES`)
51
+ { test: new RegExp(`^/proposals/${SLUG}/review$`), kind: 'session', methods: [...READ, 'PUT'], headers: ['content-type'] },
52
+ // The list of a proposal's mockups, not the files (`/mockups/<n>`)
53
+ { test: new RegExp(`^/proposals/${SLUG}/mockups$`), kind: 'session', methods: READ, headers: [] },
54
+ // One pull request: the proposal bar reads it
55
+ { test: /^\/api\/forge\/pulls\/[1-9]\d{0,8}$/, kind: 'session', methods: READ, headers: [] },
56
+ // The Undo of an approval's hold
57
+ { test: /^\/api\/forge\/pulls\/[1-9]\d{0,8}\/landing\/cancel$/, kind: 'session', methods: ['POST'], headers: ['content-type'] },
58
+ { test: '/cornfield/theme.css', kind: 'open', methods: READ, headers: [] },
59
+ { test: /^\/cornfield\/theme\/[^/]+\.css$/, kind: 'open', methods: READ, headers: [] },
60
+ { test: /^\/cornfield\/theme\/assets\/.+$/, kind: 'open', methods: READ, headers: [] },
61
+ ]);
62
+
63
+ /**
64
+ * The two writes a listed origin may make, as `[method, route]`. Every other write from a listed origin is refused exactly as a stranger's is.
65
+ * (Which code path asks is decided where the write is handled: server/proposals.js `putPullReview`, server/lander.js `serveLanding`.)
66
+ */
67
+ export const WRITES = Object.freeze(['PUT /proposals/<slug>/review', 'POST /api/forge/pulls/<n>/landing/cancel']);
68
+
69
+ /** @param {string} reqPath @returns {Route | null} */
70
+ export function routeOf(reqPath) {
71
+ for (const r of ROUTES) if (typeof r.test === 'string' ? r.test === reqPath : r.test.test(reqPath)) return r;
72
+ return null;
73
+ }
74
+
75
+ /**
76
+ * Whether a write may come from a listed origin: its `Origin` is exactly one of `origins`, and `Sec-Fetch-Site` is `same-site` or not sent.
77
+ * Only the two routes in `WRITES` ask. `Host` is not looked at here.
78
+ * @param {Record<string, string | string[] | undefined>} headers a request's headers (Node's lowercase names)
79
+ * @param {readonly string[]} origins
80
+ */
81
+ export function listedWrite(headers, origins) {
82
+ const origin = headers.origin;
83
+ if (typeof origin !== 'string' || !origins.includes(origin)) return false;
84
+ const site = headers['sec-fetch-site'];
85
+ return site === undefined || site === 'same-site';
86
+ }
87
+
88
+ /** What an absolute way back may not hold: a control character, a space, or a backslash (browsers read `\` as `/`) */
89
+ const RETURN_BAD = /[\u0000- \u007f\\]/;
90
+ /** The longest absolute way back a sign-in keeps (it rides in the state cookie) */
91
+ export const RETURN_MAX = 1024;
92
+
93
+ /**
94
+ * An absolute http(s) URL as the URL parser reads it, or null: with an explicit scheme (so `//host`, `javascript:` and a path are not one),
95
+ * no control character, space or backslash, no user name or password, at most RETURN_MAX characters.
96
+ * @param {unknown} raw
97
+ * @returns {URL | null}
98
+ */
99
+ export function absoluteUrl(raw) {
100
+ if (typeof raw !== 'string' || raw === '' || raw.length > RETURN_MAX || RETURN_BAD.test(raw) || !/^https?:\/\/[^/?#]/i.test(raw)) return null;
101
+ let u;
102
+ try { u = new URL(raw); } catch { return null; }
103
+ if ((u.protocol !== 'https:' && u.protocol !== 'http:') || u.username !== '' || u.password !== '') return null;
104
+ return u;
105
+ }
106
+
107
+ /**
108
+ * Where a sign-in may end on another origin: the URL as parsed (`href`, so what is sent in `Location` is what was checked) when its origin
109
+ * is exactly a listed one, else null. A different port, a longer host (`https://tasks.example.com.evil.test`), a user name
110
+ * (`https://tasks.example.com@evil.test`) and a scheme other than the listed one all fail.
111
+ * @param {unknown} raw
112
+ * @param {readonly string[]} origins
113
+ * @returns {string | null}
114
+ */
115
+ export function listedReturn(raw, origins) {
116
+ if (!origins.length) return null;
117
+ const u = absoluteUrl(raw);
118
+ if (!u || !origins.includes(u.origin) || u.href.length > RETURN_MAX) return null;
119
+ return u.href;
120
+ }
121
+
122
+ /**
123
+ * @param {readonly string[]} [origins] the config's `embed.origins`, canonical (core/config.js `embedOrigin`)
124
+ */
125
+ export function createEmbed(origins = []) {
126
+ const list = Object.freeze([...origins]);
127
+ /** The one `Origin` of a request, when it is exactly a listed origin; two `Origin` headers are none */
128
+ const listed = (req) => {
129
+ if (!list.length) return null;
130
+ let n = 0;
131
+ for (let i = 0; i < req.rawHeaders.length; i += 2) if (req.rawHeaders[i].toLowerCase() === 'origin') n++;
132
+ const o = req.headers.origin;
133
+ return n === 1 && typeof o === 'string' && list.includes(o) ? o : null;
134
+ };
135
+ return {
136
+ enabled: list.length > 0,
137
+ origins: list,
138
+ listed,
139
+ /**
140
+ * The headers to put on every answer of this request (the guard's 401 and the route's refusals included, so the page can read why):
141
+ * `{}` unless an origin is listed and the path is on the list. `Vary: Origin` goes on the list's routes for every request, listed or
142
+ * not (the answer differs by `Origin`); the CORS headers only for a listed origin and a method the route has.
143
+ * @returns {Record<string, string>}
144
+ */
145
+ headers(req, reqPath) {
146
+ if (!list.length) return {};
147
+ const route = routeOf(reqPath);
148
+ if (!route) return {};
149
+ const out = { Vary: 'Origin' };
150
+ const origin = listed(req);
151
+ if (!origin || req.method === 'OPTIONS' || !route.methods.includes(req.method)) return out;
152
+ out['Access-Control-Allow-Origin'] = origin;
153
+ if (route.kind === 'session') {
154
+ out['Access-Control-Allow-Credentials'] = 'true';
155
+ out['Access-Control-Expose-Headers'] = EXPOSED.join(', ');
156
+ }
157
+ return out;
158
+ },
159
+ /**
160
+ * The answer to a preflight, or null when it is none of ours (not `OPTIONS`, no `Access-Control-Request-Method`, an origin that is not
161
+ * listed, a route off the list, a method or a request header the route does not take): the request then goes on as any other and
162
+ * gets no CORS header, so the browser refuses it.
163
+ * @returns {{ status: number, headers: Record<string, string> } | null}
164
+ */
165
+ preflight(req, reqPath) {
166
+ if (!list.length || req.method !== 'OPTIONS') return null;
167
+ const origin = listed(req);
168
+ const asked = req.headers['access-control-request-method'];
169
+ const route = routeOf(reqPath);
170
+ if (!origin || !route || typeof asked !== 'string' || !route.methods.includes(asked)) return null;
171
+ const wanted = String(req.headers['access-control-request-headers'] || '').split(',').map((h) => h.trim().toLowerCase()).filter(Boolean);
172
+ if (wanted.some((h) => !route.headers.includes(h))) return null;
173
+ const headers = {
174
+ 'Access-Control-Allow-Origin': origin,
175
+ 'Access-Control-Allow-Methods': route.methods.join(', '),
176
+ 'Access-Control-Max-Age': '600',
177
+ Vary: 'Origin, Access-Control-Request-Method, Access-Control-Request-Headers',
178
+ 'Content-Length': '0',
179
+ };
180
+ if (route.kind === 'session') headers['Access-Control-Allow-Credentials'] = 'true';
181
+ if (route.headers.length) headers['Access-Control-Allow-Headers'] = 'Content-Type';
182
+ return { status: 204, headers };
183
+ },
184
+ };
185
+ }
package/server/lander.js CHANGED
@@ -362,7 +362,7 @@ export function landingOf(reqPath) {
362
362
  * cornfield's own page by a maintainer the forge confirms now, counted like any action.
363
363
  * @param {import('node:http').IncomingMessage} req
364
364
  * @param {{ n: number, cancel: boolean }} what
365
- * @param {{ config: any, session: { login: string, userId: string } | null, auth: any, lander?: Lander | null, now?: () => number, publicHost?: string | null }} ctx
365
+ * @param {{ config: any, session: { login: string, userId: string } | null, auth: any, lander?: Lander | null, now?: () => number, publicHost?: string | null, embedOrigins?: readonly string[] }} ctx
366
366
  * @returns {Promise<{ status: number, body: object, headers?: Record<string, string> }>}
367
367
  */
368
368
  export async function serveLanding(req, what, ctx) {
@@ -377,7 +377,7 @@ export async function serveLanding(req, what, ctx) {
377
377
  try {
378
378
  const flood = countAttempt(ctx, session.userId, now());
379
379
  if (flood) throw flood;
380
- if (!sameOrigin(req, ctx.publicHost ?? null)) throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
380
+ if (!sameOrigin(req, ctx.publicHost ?? null, ctx.embedOrigins ?? [])) throw new Refused(403, 'Do this from cornfield\'s own page.', 'forbidden');
381
381
  if (!lander) throw new Refused(404, 'Landing on approval is not turned on (proposals.approveLands).', 'not-found');
382
382
  const forge = auth.forgeFor(session);
383
383
  const me = await forge.me();
@@ -51,6 +51,7 @@ import { hashPullMockups } from './mockups.js';
51
51
  import { readDecision } from './decision.js';
52
52
  import { findPullProposal, forgeWords, listPullProposals, pullNumber, readPullProposal, reviewStates } from './proposal-pulls.js';
53
53
  import { serveMockups } from './mockups.js';
54
+ import { listedWrite } from './embed.js';
54
55
 
55
56
  // The review's checks live in server/reviews.js; these are re-exported for the callers that always had them here
56
57
  export { REVIEW_LIMIT, MAX_REVIEW_EDITS, MAX_NOTE_CHARS, validateReview } from './reviews.js';
@@ -102,10 +103,13 @@ function ownHostName(host, publicHost) {
102
103
  * another domain that resolves here (DNS rebinding) is no more welcome than any other site.
103
104
  * @param {import('node:http').IncomingMessage} req
104
105
  * @param {string|null} [publicHost] the host of the configured public URL, which is the server's own too
106
+ * @param {readonly string[]} [embedOrigins] the listed sibling origins (config `embed.origins`) a request may also come from; only for the review PUT and the Undo of a landing
105
107
  */
106
- export function sameOrigin(req, publicHost = null) {
108
+ export function sameOrigin(req, publicHost = null, embedOrigins = []) {
107
109
  const host = req.headers.host;
108
110
  if (typeof host !== 'string' || !ownHostName(host, publicHost)) return false;
111
+ // The two writes a listed sibling origin may make pass their list here (server/embed.js `listedWrite`); every other caller passes none
112
+ if (embedOrigins.length && listedWrite(req.headers, embedOrigins)) return true;
109
113
  const origin = req.headers.origin;
110
114
  const site = req.headers['sec-fetch-site'];
111
115
  if (origin === undefined && site === undefined) return false;
@@ -278,7 +282,7 @@ async function getDecision(res, where, forgeFor, signedIn, slug, n, fresh) {
278
282
 
279
283
  /** PUT /proposals/<slug>/review?source=pull/<n>: posts the review as a comment on the PR, as the signed-in maintainer */
280
284
  async function putPullReview(req, res, where, forgeFor, signedIn, slug, n) {
281
- if (!sameOrigin(req, where.publicHost)) {
285
+ if (!sameOrigin(req, where.publicHost, where.embedOrigins ?? [])) {
282
286
  req.resume();
283
287
  return send(res, 403, { error: 'A review is only taken from cornfield\'s own page' });
284
288
  }
package/server/server.js CHANGED
@@ -44,8 +44,9 @@
44
44
  * no session is the sign-in page or a 401, a non-maintainer the "ask a maintainer" page or a 403. Without it, `listen`
45
45
  * only binds to loopback (server/bind.js); with it and an https public URL, it may bind to any address.
46
46
  *
47
- * No CORS headers: the explorer and its sources are all same-origin, so no other site's page has any
48
- * business reading what cornfield serves.
47
+ * No CORS headers, unless the config's `embed.origins` lists a sibling app's origin: then that exact origin may read the routes
48
+ * server/embed.js names, and make two writes, as the signed-in maintainer (docs/embedding.md). The explorer and its sources are
49
+ * all same-origin, so no other site's page has any business reading what cornfield serves.
49
50
  */
50
51
 
51
52
  import fs from 'node:fs';
@@ -73,6 +74,7 @@ import { assertBind, hostAllowed } from './bind.js';
73
74
  import { createAuth, signInSettings } from './auth.js';
74
75
  import { createHooks, hooksSettings } from './hooks.js';
75
76
  import { createLander } from './lander.js';
77
+ import { createEmbed } from './embed.js';
76
78
  import { createSpecPoll } from './spec-poll.js';
77
79
  import { createRunnerWatch, runnerPresence } from './runner-presence.js';
78
80
  import { createTriggers } from './triggers.js';
@@ -308,7 +310,9 @@ export function createCornfieldServer(config, opts = {}) {
308
310
  const brandFile = brandFilesOf(config);
309
311
  const repoModules = repoModuleDirs(config);
310
312
  const publicHost = config.publicUrl ? new URL(config.publicUrl).hostname : null;
311
- const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost };
313
+ // The sibling origins that may read and decide a review as the signed-in maintainer (server/embed.js): none unless `embed.origins` lists some
314
+ const embed = createEmbed(config.embed?.origins ?? []);
315
+ const where = { root, proposals: config.proposals, worktrees: config.worktrees, worktreeMaxAgeDays: config.worktreeMaxAgeDays, topology: config.topology, dataDir: config.dataDir, publicHost, embedOrigins: embed.origins };
312
316
  const fixtureCache = new Map();
313
317
  // What the line above Approve says an approval does besides posting (spec 0007 D1, server/decision.js): landing, and the run a trigger asks for
314
318
  const approvalRun = triggersOf(config).find(([event]) => event === 'spec.approved');
@@ -434,6 +438,16 @@ export function createCornfieldServer(config, opts = {}) {
434
438
  return res.end('400 Bad Request');
435
439
  }
436
440
 
441
+ // A listed sibling origin (config `embed.origins`) reads the routes server/embed.js names: its headers go on the answer whatever the answer is, and its
442
+ // preflight is answered here, before the guard (a preflight carries no cookie). With no origin listed both are nothing
443
+ const preflight = embed.preflight(req, reqPath);
444
+ if (preflight) {
445
+ req.resume();
446
+ res.writeHead(preflight.status, preflight.headers);
447
+ return res.end();
448
+ }
449
+ for (const [name, value] of Object.entries(embed.headers(req, reqPath))) res.setHeader(name, value);
450
+
437
451
  // A runner token is good for the runner routes only: on any other route it is refused here, before anything else is looked at
438
452
  if (presentedScope(req) === 'runner' && !takesTokens(reqPath, { reviews: REVIEWS_PATH })) return serveStrayRunner(req, res, reqPath, { config, auth, now: opts.now });
439
453
 
@@ -464,7 +478,7 @@ export function createCornfieldServer(config, opts = {}) {
464
478
  // Before the proxies: a repo's `/api/` proxy must not swallow the panel's own routes
465
479
  if (await serveTokenRoutes(req, res, reqPath, { config, where, auth, session: gate.session, now: opts.now, publicHost })) return;
466
480
  if (await serveRunRoutes(req, res, reqPath, { config, auth, runs, session: gate.session, now: opts.now, publicHost })) return;
467
- if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, lander, now: opts.now, publicHost })) return;
481
+ if (await serveForge(req, res, reqPath, url, { config, where, session: gate.session, auth, hooks, lander, now: opts.now, publicHost, embedOrigins: embed.origins })) return;
468
482
  for (const [prefix, target] of proxies) if (reqPath.startsWith(prefix)) return proxyTo(req, res, target);
469
483
  const session = gate.session;
470
484
  const forgeFor = session ? () => auth.forgeFor(session) : null;