cornfield 0.19.0 → 0.20.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.
@@ -50,7 +50,7 @@
50
50
  * @typedef {{ runId: string, type: 'request', value: RunRequest } | { runId: string, type: 'report', value: RunReport } | { runId: string, type: 'stop-request', value: StopRequest } | { runId: string, type: 'answer', value: RunAnswer }} RunBlock
51
51
  */
52
52
 
53
- import { defuse } from './defuse.js';
53
+ import { defuse, quoteInert } from './defuse.js';
54
54
 
55
55
  /** Ten (or `n`) random bytes, from the Web Crypto API that Node and the browser both have */
56
56
  const randomBytes = (n) => globalThis.crypto.getRandomValues(new Uint8Array(n));
@@ -543,7 +543,7 @@ export function formatRunComment(runId, body, { line, profiles } = {}) {
543
543
  const head = oneLine(line ?? defaultLine(runId, checked.type, checked.value));
544
544
  // An answer's text is the maintainer's words to the runner: it travels in the block only, never quoted beside it
545
545
  const note = checked.type === 'request' || checked.type === 'answer' ? '' : (checked.value.note ?? '').trim();
546
- const quoted = note ? `\n\n${defuse(note).split(/\r?\n/).map((l) => (l ? `> ${l}` : '>')).join('\n')}` : '';
546
+ const quoted = note ? `\n\n${quoteInert(note)}` : '';
547
547
  const out = `${head}${quoted}\n\n${block}`;
548
548
  if (out.length > MAX_COMMENT_CHARS) throw new RangeError(`That is too long for a comment (${out.length} characters, at most ${MAX_COMMENT_CHARS}); shorten the brief or the note.`);
549
549
  return out;
package/core/defuse.js CHANGED
@@ -5,7 +5,8 @@
5
5
  * `#1`, `owner/repo#1`, `GH-1`, and the links the forge would make of `https://…` or `www.…`. A zero-width space after
6
6
  * the character keeps the text as it reads and stops it notifying anyone or linking anything. The pipeline's issues
7
7
  * (server/pipeline.js), a review that came through the review API (server/reviews.js) and the agent contract
8
- * (core/agent-contract.js) use it. It imports nothing, so Node and the browser can both load it.
8
+ * (core/agent-contract.js) use it; `inert` and `quoteInert` also make someone else's words plain Markdown, the way the agent contract
9
+ * and a run's thread (server/run-thread.js) show a runner's note. It imports nothing, so Node and the browser can both load it.
9
10
  */
10
11
 
11
12
  /** A zero-width space: it ends a mention or a reference without showing */
@@ -15,3 +16,20 @@ export const ZW = '​';
15
16
  export function defuse(text) {
16
17
  return String(text).replace(/[@#]/g, (c) => `${c}${ZW}`).replace(/\b(GH)-(?=\d)/gi, `$1${ZW}-`).replace(/:\/\//g, `:${ZW}//`).replace(/\b(www)\./gi, `$1${ZW}.`);
17
18
  }
19
+
20
+ /**
21
+ * Text that makes no Markdown of its own: `\\` escaped first (so no escape of ours is undone), `&` and `<` as entities (no HTML, no
22
+ * character reference), `[` escaped (no link, image or `[[node]]`), backticks made `'` and runs of tildes broken (no code span, no fence).
23
+ * Mentions, references and links are not touched here: `defuse` them first.
24
+ */
25
+ export function inert(text) {
26
+ return String(text).replace(/\\/g, '\\\\').replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\[/g, '\\[').replace(/`/g, "'").replace(/~(?=~)/g, `~${ZW}`);
27
+ }
28
+
29
+ /**
30
+ * Text quoted line by line, defused and inert: every line end Markdown and the agent contract's reader know (`\r\n`, `\r` alone, `\n`)
31
+ * ends a line here, and every line is behind `> ` (an empty one is `>`), so no line escapes the quote and nothing in it opens a fence.
32
+ */
33
+ export function quoteInert(text) {
34
+ return inert(defuse(text)).split(/\r\n?|\n/).map((l) => (l.trim() ? `> ${l}` : '>')).join('\n');
35
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * @module explorer/deep-link
3
+ *
4
+ * Links from chat that land in the right place (issue #103, docs/agents.md "Deep links"):
5
+ *
6
+ * ?run=<runId> the Agents tab, that run lit and in view
7
+ * ?issue=<n> the Issues tab, that issue's Start an agent button focused
8
+ * ?proposal=<slug>&start=1 the proposal opened (proposal.js) and the Start dialog on it
9
+ *
10
+ * On a phone the sheet it opens is expanded. A name that is not there is a line in the panel and said through the live
11
+ * region, never a blank. A link that is followed is taken out of the address (`run`, `issue`, `start`) at once, so a
12
+ * reload does not open it again; `?proposal=` stays, as it always has (it follows the open proposal).
13
+ * Without a live sign-in the server asks for it first and returns here with the same query (server/auth.js).
14
+ */
15
+
16
+ import { announce } from './keyboard.js';
17
+ import { isPhone, expandSheet } from './sheets.js';
18
+ import { parseProposalQuery } from './proposal-model.js';
19
+ import { openRunLink, openIssueLink, openProposalStart } from './forge-panel.js';
20
+
21
+ const RUN_ID = /^run-[0-9A-Za-z]{26}$/;
22
+ const ISSUE = /^[1-9][0-9]{0,8}$/;
23
+ /** The parameters a followed link gives up */
24
+ const SPENT = ['run', 'issue', 'start'];
25
+
26
+ /**
27
+ * What a query asks for, or null. One link asks for one thing: a run before an issue before a proposal. A value that
28
+ * cannot be a name is `{ kind, bad: words }`.
29
+ * @param {string} search
30
+ * @returns {{ kind: 'run', id: string } | { kind: 'issue', n: number } | { kind: 'proposal', slug: string } | { kind: string, bad: string } | null}
31
+ */
32
+ export function parseDeepLink(search) {
33
+ const params = new URLSearchParams(search || '');
34
+ if (params.has('run')) {
35
+ const id = params.get('run');
36
+ return RUN_ID.test(id) ? { kind: 'run', id } : { kind: 'run', bad: `${id ? `"${id.slice(0, 40)}"` : 'That'} is not a run id.` };
37
+ }
38
+ if (params.has('issue')) {
39
+ const n = params.get('issue');
40
+ return ISSUE.test(n) ? { kind: 'issue', n: Number(n) } : { kind: 'issue', bad: `${n ? `"${n.slice(0, 40)}"` : 'That'} is not an issue number.` };
41
+ }
42
+ if (params.get('start') === '1' && params.has('proposal')) {
43
+ const asked = parseProposalQuery(search);
44
+ return asked ? { kind: 'proposal', slug: asked.slug } : { kind: 'proposal', bad: 'That is not a proposal name.' };
45
+ }
46
+ return null;
47
+ }
48
+
49
+ /** Takes the spent parameters out of the address, without a new history entry; the rest stays */
50
+ export function cleanAddress() {
51
+ if (typeof history === 'undefined' || typeof location === 'undefined') return;
52
+ try {
53
+ const params = new URLSearchParams(location.search);
54
+ if (!SPENT.some((k) => params.has(k))) return;
55
+ SPENT.forEach((k) => params.delete(k));
56
+ const query = params.toString();
57
+ history.replaceState(null, '', `${location.pathname}${query ? `?${query}` : ''}${location.hash}`);
58
+ } catch { /* the address is a convenience */ }
59
+ }
60
+
61
+ /** A thing the link names that cannot be shown here at all (no forge in the config): said, so the page is not silent */
62
+ const unavailable = (words) => { announce(words); return false; };
63
+
64
+ /**
65
+ * Follows the link in the address, once. Call it after the forge panel and the proposals are set up.
66
+ * @param {{ search?: string, proposalOpened?: boolean, forgeOn?: boolean }} [opts]
67
+ * `proposalOpened`: what `initProposals()` answered; `forgeOn`: whether `initForgePanel()` found a forge in the config
68
+ * @returns {Promise<boolean>} whether the link was followed to what it names
69
+ */
70
+ export async function followDeepLink({ search = typeof location === 'undefined' ? '' : location.search, proposalOpened = false, forgeOn = true } = {}) {
71
+ const link = parseDeepLink(search);
72
+ if (!link) return false;
73
+ cleanAddress();
74
+ if ('bad' in link) return unavailable(link.bad);
75
+ if (link.kind === 'proposal') {
76
+ if (!proposalOpened) {
77
+ // proposal.js has put the reason in the bar (a status region); it is said here too
78
+ const bar = typeof document !== 'undefined' ? document.getElementById('proposal-message') : null;
79
+ return unavailable((bar && bar.textContent) || `There is no proposal called ${link.slug}.`);
80
+ }
81
+ if (!forgeOn) return unavailable('Start an agent needs a forge in the config.');
82
+ if (isPhone()) expandSheet('proposal');
83
+ return openProposalStart(link.slug);
84
+ }
85
+ if (!forgeOn) return unavailable('Runs and issues need a forge in the config.');
86
+ return link.kind === 'run' ? openRunLink(link.id) : openIssueLink(link.n);
87
+ }
@@ -61,6 +61,8 @@ export const listKeyOf = (kind, state) => (kind === 'deploys' ? 'deploys' : `${k
61
61
  export const threadsUrl = (state) => `/api/forge/threads?state=${state}&limit=${LIST_LIMIT}`;
62
62
  export const threadUrl = (n) => `/api/forge/threads/${n}`;
63
63
  export const IDEAS_URL = '/api/forge/threads';
64
+ /** The address of one issue, whatever its state */
65
+ export const issueUrl = (n) => `/api/forge/issues/${n}`;
64
66
  /** The address of one pull request with its files and checks */
65
67
  export const pullUrl = (n) => `/api/forge/pulls/${n}`;
66
68
 
@@ -79,7 +79,7 @@ import {
79
79
  specBlock, buildOffers, planUrl, confirmSpec, confirmBuild, specBody, buildBody, existingWords,
80
80
  listKeyOf, litForDeploy, nodesForRestarts, deployWords, deployMeta,
81
81
  DRAFTS_URL, notesUrl, sinceChoices, notesSummary, validTag, confirmWords, postedWords, draftRequest,
82
- threadsUrl, threadUrl, IDEAS_URL, threadKindWords, threadMeta, litForThread, mentionsIndex, ideaRequest, ideaWords,
82
+ threadsUrl, threadUrl, issueUrl, IDEAS_URL, threadKindWords, threadMeta, litForThread, mentionsIndex, ideaRequest, ideaWords,
83
83
  } from './forge-panel-model.js';
84
84
 
85
85
  const $ = (id) => document.getElementById(id);
@@ -1616,7 +1616,7 @@ async function answerRun(runId, action) {
1616
1616
  export const isForgeOpen = () => ui.open;
1617
1617
 
1618
1618
  /** Opens the panel with the focus on its title; the first time, loads the pull requests */
1619
- export function openForge() {
1619
+ export function openForge({ load = true } = {}) {
1620
1620
  const panel = $('forge-panel');
1621
1621
  if (!panel || panel.hidden) return;
1622
1622
  ui.open = true;
@@ -1627,10 +1627,93 @@ export function openForge() {
1627
1627
  const title = $('forge-title');
1628
1628
  title.focus();
1629
1629
  announce('Issues and pull requests');
1630
+ if (!load) return; // a deep link loads the list it wants itself (openTab)
1630
1631
  if (ui.kind === 'notes') { if (!ui.notes.data && !ui.notes.loading) loadNotes(); else paint(); return; }
1631
1632
  if (!current()) { paintFilters(); loadList(); } else paint();
1632
1633
  }
1633
1634
 
1635
+ // ---------------------------------------------------------------------------
1636
+ // Deep links (explorer/deep-link.js): a run, an issue, a proposal's Start dialog
1637
+ // ---------------------------------------------------------------------------
1638
+
1639
+ /** Shows `tab` in the panel, opened (and, on a phone, expanded), with its list read; resolves when the list is in */
1640
+ async function openTab(tab) {
1641
+ ui.kind = tab;
1642
+ ui.filters = defaultFilters(tab); // a filter left from before must not hide what the link names
1643
+ ui.actNote = null;
1644
+ paintFilters();
1645
+ if (!ui.open) openForge({ load: false });
1646
+ if (isPhone()) expandSheet('forge');
1647
+ if (current()) paint(); else await loadList();
1648
+ }
1649
+
1650
+ /** What a link names is not there: a line in the panel, said through the live region */
1651
+ function linkMissing(words) {
1652
+ ui.actNote = { ok: false, text: words };
1653
+ paint();
1654
+ announce(words);
1655
+ return false;
1656
+ }
1657
+
1658
+ /** Moves the focus to `el` (made focusable if it is a row) and brings it into view */
1659
+ function bringIntoView(el) {
1660
+ if (!el) return;
1661
+ if (!el.matches('button, a, input, select, textarea')) el.setAttribute('tabindex', '-1');
1662
+ el.focus();
1663
+ if (typeof el.scrollIntoView === 'function') el.scrollIntoView({ block: 'nearest' });
1664
+ }
1665
+
1666
+ /** `?run=<runId>`: the Agents tab with that run lit and in view. A run that is not there is said, never a blank panel. */
1667
+ export async function openRunLink(id) {
1668
+ if (!ui.config) return false;
1669
+ await openTab('work');
1670
+ if (!(ui.runs && ui.runs.data)) await loadRuns(false, { say: false });
1671
+ let run = runById(id);
1672
+ // A run asked for a moment ago may not be in what was read before: ask once more, past the cache
1673
+ if (!run && ui.runs && ui.runs.data) { await loadRuns(true, { say: false }); run = runById(id); }
1674
+ if (!run) return linkMissing(ui.runs && ui.runs.data ? `There is no run ${id}.` : (ui.runs && ui.runs.error) || 'The runs could not be read.');
1675
+ if (ui.runSel !== id) selectRun(id);
1676
+ paint();
1677
+ bringIntoView($('forge-runs-list').querySelector(`[data-run="${id}"]`));
1678
+ announce(`Run ${id}, in the Runs view`);
1679
+ return true;
1680
+ }
1681
+
1682
+ /** `?issue=<n>`: the Issues tab with that issue's Start an agent button in view and focused, ready to press */
1683
+ export async function openIssueLink(n) {
1684
+ if (!ui.config) return false;
1685
+ await openTab('issues');
1686
+ const list = current();
1687
+ if (!list) return linkMissing(ui.error || 'The issues could not be read.');
1688
+ const item = list.items.find((i) => i.number === n);
1689
+ if (!item) return issueNotListed(n);
1690
+ paint();
1691
+ const start = $('forge-list').querySelector(`[data-forge-agent="issue:${n}"]`);
1692
+ bringIntoView(start);
1693
+ announce(`Issue ${n}: ${item.title}. Start an agent is ready`);
1694
+ return true;
1695
+ }
1696
+
1697
+ /** An issue the open list does not hold: asked for once, directly, so a closed one is called closed and a missing one missing */
1698
+ async function issueNotListed(n) {
1699
+ const res = await request(issueUrl(n));
1700
+ if (res.ok && res.body.issue) {
1701
+ const { issue } = res.body;
1702
+ ui.actNote = { ok: false, text: issue.state === 'closed' ? `Issue ${n} is closed: ${issue.title}` : `Issue ${n} is open, but not in the list shown here: ${issue.title}`, url: issue.url };
1703
+ paint();
1704
+ announce(ui.actNote.text);
1705
+ return false;
1706
+ }
1707
+ return linkMissing(res.status === 404 ? `There is no issue ${n}.` : errorWords(res.status, res.body));
1708
+ }
1709
+
1710
+ /** `?proposal=<slug>&start=1`: the Start dialog on that proposal (the proposal itself is opened by proposal.js) */
1711
+ export async function openProposalStart(slug) {
1712
+ if (!ui.config || !agentEl()) return false;
1713
+ await openAgent(`proposal:${slug}`, '#forge-title');
1714
+ return !!ui.agent;
1715
+ }
1716
+
1634
1717
  /** Closes the panel. What a selected pull request lit stays lit (the button says which); Clear lets go of it. */
1635
1718
  export function closeForge({ restoreFocus = true } = {}) {
1636
1719
  const panel = $('forge-panel');
package/explorer/main.js CHANGED
@@ -13,6 +13,7 @@
13
13
  * proposal.js the proposal overlay (picker, Before / Diff / After); proposal-model.js its pure half
14
14
  * whatif.js what-if edits on an open proposal (add, remove, draw, steps, undo); whatif-model.js its pure half
15
15
  * review.js approve a proposal or send it back with a note and the edits; review-model.js its pure half
16
+ * deep-link.js ?run=, ?issue= and ?proposal=…&start=1 land on a run, an issue and a Start dialog
16
17
  * scenario.js the player's pure core scenario-ui.js its bar, keys and camera
17
18
  * bench.js /?bench=1 stopwatch and /?fixture=5k (the generated topology, from the server)
18
19
  * keyboard.js the map by keyboard and the screen reader's announcer; keyboard-model.js its pure half
@@ -33,6 +34,7 @@ import { initSheets } from './sheets.js';
33
34
  import { loadTopology, setView, syncViewUi } from './view.js';
34
35
  import { bindCanvasInput } from './input.js';
35
36
  import { initProposals } from './proposal.js';
37
+ import { followDeepLink } from './deep-link.js';
36
38
  import { initWhatIf } from './whatif.js';
37
39
  import { initReview } from './review.js';
38
40
  import { initMockups } from './mockups.js';
@@ -208,18 +210,20 @@ loadTopology().then(async (ok) => {
208
210
  // The sources the repo's cornfield.config.js names (plugins.js): a live layer, a house, devices, a checker; each optional
209
211
  const config = await configReady;
210
212
  const { liveSource, floorRenderer, checker } = await loadSources(config);
211
- initForgePanel(config); // issues and PRs: only when the config names a forge (forge-panel.js)
213
+ const forgeOn = initForgePanel(config); // issues and PRs: only when the config names a forge (forge-panel.js)
212
214
  initReviewTokens(config); // review tokens for the review API: only for somebody signed in (review-tokens.js)
213
215
  initWhatIf(); // before a proposal can open, so its edits come with it
214
216
  initReview(); // after it: the review controls sit under the edit controls on the bar
215
217
  initMockups(); // a proposal's screens open from the node they name
216
- await initProposals();
218
+ const proposalOpened = await initProposals();
217
219
  // The live layer (live.js): loads only once a live layer goes on in the Layers menu; with no source it stays off
218
220
  initLive({ source: liveSource, onSelectionGone: closeDrawer });
219
221
  // The House view (house.js): a source's floor renderer draws the plan under the map (plain room boxes without one); /?view=house opens it
220
222
  initHouse({ floor: floorRenderer });
221
223
  initChecks({ checker }); // scenarios ask the source's checker, when there is one (check.js)
222
224
  if (new URLSearchParams(window.location.search).get("view") === "dataflow") setView("dataflow");
225
+ // /?run=, /?issue= and /?proposal=…&start=1 land on a run, an issue's Start button and a proposal's Start dialog (deep-link.js)
226
+ followDeepLink({ proposalOpened, forgeOn }).catch((err) => console.error('Following the link failed', err));
223
227
  // /?scenario-demo=1 plays a small scenario over real nodes, to look at the player
224
228
  maybeStartDemo();
225
229
  // /?bench=1 runs the stopwatch (bench.js) once the map is up
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cornfield",
3
- "version": "0.19.0",
3
+ "version": "0.20.0",
4
4
  "description": "A self-hostable dev dashboard with the topology map at its centre: proposals on the map, scenarios, outages and what-if edits, for any repo.",
5
5
  "license": "MIT",
6
6
  "author": "popcorn245 (https://github.com/popcorn245)",
package/server/auth.js CHANGED
@@ -274,10 +274,44 @@ ${body}
274
274
 
275
275
  const signOutForm = '<form method="post" action="/auth/sign-out"><button class="button quiet" type="submit">Sign out</button></form>';
276
276
 
277
- /** The sign-in page */
278
- export const signInPage = (title, forgeName) => pageHtml(title, `Sign in to ${title}`, `
277
+ /** The longest way back a sign-in keeps (as it comes out, percent-encoded): it rides in the state cookie, which stays small */
278
+ const RETURN_MAX = 1024;
279
+ /** What a way back may not hold: a control character or a backslash (browsers read `\\` as `/`) */
280
+ const RETURN_BAD = /[\u0000-\u001f\u007f\\]/;
281
+ /** A path the browser takes as this origin's: one `/`, then not a second `/` or a `\\` (`//x` is another host) */
282
+ const isOwnPath = (p) => p[0] === '/' && p[1] !== '/' && p[1] !== '\\' && !RETURN_BAD.test(p);
283
+
284
+ /**
285
+ * Where a sign-in may send the person back to: a same-origin relative path (with its query), or null. An absolute URL
286
+ * (`https://elsewhere`), a protocol-relative one (`//elsewhere`), a backslash trick (`/\\elsewhere`), a control character
287
+ * and the sign-in routes themselves are refused, so the return is never an open redirect. The path is checked again as
288
+ * the URL parser leaves it: it resolves dot segments, so `/.//elsewhere` and `/%2e//elsewhere` come out as `//elsewhere`.
289
+ * @param {unknown} raw
290
+ * @returns {string | null}
291
+ */
292
+ export function safeReturn(raw) {
293
+ if (typeof raw !== 'string' || raw.length === 0 || raw.length > RETURN_MAX || !isOwnPath(raw)) return null;
294
+ let parsed;
295
+ try { parsed = new URL(raw, 'http://cornfield.invalid'); } catch { return null; }
296
+ if (parsed.origin !== 'http://cornfield.invalid') return null;
297
+ const back = `${parsed.pathname}${parsed.search}`;
298
+ if (back.length > RETURN_MAX || !isOwnPath(back)) return null;
299
+ let path;
300
+ try { path = decodeURIComponent(parsed.pathname); } catch { return null; }
301
+ if (/^\/auth(\/|$)/i.test(path)) return null;
302
+ return back;
303
+ }
304
+
305
+ /** The sign-in start, with the way back (checked by safeReturn) when there is one */
306
+ const startHref = (returnTo) => {
307
+ const back = safeReturn(returnTo);
308
+ return `/auth/start${back && back !== '/' ? `?return=${encodeURIComponent(back)}` : ''}`;
309
+ };
310
+
311
+ /** The sign-in page; `returnTo` (checked by safeReturn) is where the sign-in ends, so a link followed signed out is followed after */
312
+ export const signInPage = (title, forgeName, returnTo = null) => pageHtml(title, `Sign in to ${title}`, `
279
313
  <p>This is the dev dashboard. Sign in with ${escapeHtml(forgeName)} to see it; it is open to the repo's maintainers.</p>
280
- <a class="button" href="/auth/start">Sign in with ${escapeHtml(forgeName)}</a>`);
314
+ <a class="button" href="${escapeHtml(startHref(returnTo))}">Sign in with ${escapeHtml(forgeName)}</a>`);
281
315
 
282
316
  /** The one page a signed-in non-maintainer sees */
283
317
  export const askMaintainerPage = (title, login, repo) => pageHtml(title, 'This is the dev dashboard', `
@@ -285,10 +319,10 @@ export const askMaintainerPage = (title, login, repo) => pageHtml(title, 'This i
285
319
  <p>Made a maintainer since? Sign out and sign in again.</p>
286
320
  ${signOutForm}`);
287
321
 
288
- /** A sign-in that did not work, and the way to try again */
289
- const failedPage = (title, words) => pageHtml(title, 'Sign-in did not work', `
322
+ /** A sign-in that did not work, and the way to try again (to the same place) */
323
+ const failedPage = (title, words, returnTo = null) => pageHtml(title, 'Sign-in did not work', `
290
324
  <p>${escapeHtml(words)}</p>
291
- <a class="button" href="/auth/start">Try again</a>`);
325
+ <a class="button" href="${escapeHtml(startHref(returnTo))}">Try again</a>`);
292
326
 
293
327
  /** The forge could not be asked about a session's permission */
294
328
  const uncheckedPage = (title, words) => pageHtml(title, 'Your access could not be checked', `
@@ -386,6 +420,13 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
386
420
  res.writeHead(303, { Location: location, 'Cache-Control': 'no-store', ...(cookies.length ? { 'Set-Cookie': cookies } : {}) });
387
421
  res.end();
388
422
  };
423
+ /** Where a sign-in ends: the checked way back as an absolute URL on the public origin, or `/` */
424
+ const landAt = (back) => {
425
+ const path = safeReturn(back);
426
+ if (!path) return '/';
427
+ const to = new URL(path, publicUrl);
428
+ return to.origin === publicUrl.origin ? to.href : '/';
429
+ };
389
430
  const clearSession = cookie(SESSION_COOKIE, '', { maxAge: 0, secure });
390
431
  const clearState = cookie(STATE_COOKIE, '', { maxAge: 0, secure });
391
432
 
@@ -481,11 +522,13 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
481
522
 
482
523
  // --- the routes under /auth/ ---
483
524
 
484
- function start(res) {
525
+ function start(res, url) {
485
526
  const state = random();
486
527
  const verifier = random();
487
528
  const expires = now() + STATE_MS;
488
- const payload = `${state}.${verifier}.${expires}`;
529
+ // The way back is signed with the state: a 5th part, base64url (no dots), empty for none
530
+ const back = safeReturn(url.searchParams.get('return'));
531
+ const payload = `${state}.${verifier}.${expires}.${back ? b64url(Buffer.from(back)) : ''}`;
489
532
  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' });
490
533
  if (endpoints.scope) q.set('scope', endpoints.scope);
491
534
  redirect(res, `${endpoints.authorize}?${q}`, [cookie(STATE_COOKIE, `${payload}.${macOf(keys.mac, `state:${payload}`)}`, { maxAge: STATE_MS / 1000, secure })]);
@@ -495,12 +538,14 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
495
538
  function checkState(req, url) {
496
539
  const raw = parseCookies(req.headers.cookie)[STATE_COOKIE];
497
540
  const parts = raw ? raw.split('.') : [];
498
- if (parts.length !== 4) return { error: 'The sign-in was started in another browser, or too long ago.' };
499
- const [state, verifier, expires, mac] = parts;
500
- if (!sameText(mac, macOf(keys.mac, `state:${state}.${verifier}.${expires}`))) return { error: 'The sign-in was started in another browser, or too long ago.' };
541
+ // A sign-in started before the way back was signed with it (4 parts) is not followed: it is started again
542
+ if (parts.length === 4) return { error: 'The sign-in was started before cornfield was updated. Start it again.' };
543
+ if (parts.length !== 5) return { error: 'The sign-in was started in another browser, or too long ago.' };
544
+ const [state, verifier, expires, back, mac] = parts;
545
+ 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.' };
501
546
  if (!(Number(expires) > now())) return { error: 'The sign-in took too long.' };
502
547
  if (!sameText(state, url.searchParams.get('state') || '')) return { error: 'The sign-in came back with an answer to another request.' };
503
- return { verifier };
548
+ return { verifier, returnTo: safeReturn(back ? Buffer.from(back, 'base64url').toString('utf8') : '') };
504
549
  }
505
550
 
506
551
  /**
@@ -678,8 +723,9 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
678
723
  async function callback(req, res, url) {
679
724
  // The state cookie is cleared only by an answer to the sign-in it belongs to: a link from anywhere else
680
725
  // (`/auth/callback?error=x`) cannot cancel one in progress
681
- const fail = (words, clear = true) => send(res, 400, failedPage(title, words), clear ? { 'Set-Cookie': clearState } : {});
682
726
  const checked = checkState(req, url);
727
+ // Try again goes back to the same place: the way back is known only from a state cookie that checked out
728
+ const fail = (words, clear = true) => send(res, 400, failedPage(title, words, checked.returnTo), clear ? { 'Set-Cookie': clearState } : {});
683
729
  if (checked.error) return fail(checked.error, false);
684
730
  if (url.searchParams.get('error')) return fail(url.searchParams.get('error') === 'access_denied' ? `The sign-in was cancelled on ${forgeName}.` : `${forgeName} did not sign you in.`);
685
731
  const code = url.searchParams.get('code');
@@ -711,7 +757,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
711
757
  // Signed in, and not a maintainer: whatever API tokens they made while they were one stop working now
712
758
  await demoted(String(user.id), user.login, permission);
713
759
  }
714
- redirect(res, '/', [cookie(SESSION_COOKIE, value, { maxAge: sessionMs / 1000, secure }), clearState]);
760
+ redirect(res, landAt(checked.returnTo), [cookie(SESSION_COOKIE, value, { maxAge: sessionMs / 1000, secure }), clearState]);
715
761
  }
716
762
 
717
763
  async function authRoute(req, res, reqPath, url) {
@@ -724,10 +770,11 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
724
770
  }
725
771
  if (reqPath === '/auth/sign-in') {
726
772
  const { session } = await currentSession(req);
727
- if (session?.admin) return redirect(res, '/');
728
- return send(res, 200, req.method === 'HEAD' ? '' : signInPage(title, forgeName));
773
+ const back = safeReturn(url.searchParams.get('return'));
774
+ if (session?.admin) return redirect(res, landAt(back));
775
+ return send(res, 200, req.method === 'HEAD' ? '' : signInPage(title, forgeName, back));
729
776
  }
730
- if (reqPath === '/auth/start') return start(res);
777
+ if (reqPath === '/auth/start') return start(res, url);
731
778
  if (reqPath === '/auth/callback') return callback(req, res, url);
732
779
  if (reqPath === '/auth/me') {
733
780
  const { session } = await currentSession(req);
@@ -762,7 +809,7 @@ export function createAuth(config, { env = process.env, now = Date.now, fetch: d
762
809
  const { session, unchecked } = await currentSession(req);
763
810
  if (!session) {
764
811
  req.resume();
765
- answer(req, res, reqPath, 401, signInPage(title, forgeName), 'Sign in first.');
812
+ answer(req, res, reqPath, 401, signInPage(title, forgeName, `${url.pathname}${url.search}`), 'Sign in first.');
766
813
  return { done: true };
767
814
  }
768
815
  if (unchecked) {
@@ -10,6 +10,7 @@
10
10
  * shared by every visitor and no cache-less repeats.
11
11
  *
12
12
  * GET /api/forge/issues?state=open|closed|all&labels=a,b&limit=100 issues, newest first
13
+ * GET /api/forge/issues/<n> one issue, whatever its state (a deep link to a closed one, explorer/deep-link.js)
13
14
  * GET /api/forge/pulls?state=open|closed|all&limit=100 pull requests, newest first
14
15
  * GET /api/forge/pulls/<n> one pull request with its files and the checks on its head
15
16
  * (each check says whether cornfield can re-run it: `canRerun`)
@@ -180,6 +181,11 @@ function routeOf(reqPath, url, config, where, hooks = null) {
180
181
  },
181
182
  };
182
183
  }
184
+ const issue = /^\/api\/forge\/issues\/([1-9]\d{0,8})$/.exec(reqPath);
185
+ if (issue) {
186
+ const n = Number(issue[1]);
187
+ return { key: `issues/${n}`, load: async (forge) => ({ issue: await forge.issue(n) }) };
188
+ }
183
189
  const one = /^\/api\/forge\/pulls\/([1-9]\d{0,8})$/.exec(reqPath);
184
190
  if (one) {
185
191
  const n = Number(one[1]);
@@ -24,7 +24,7 @@
24
24
  * by the id it kept (`run_mirrors`), never by the marker: the marker is not trusted as an address.
25
25
  */
26
26
 
27
- import { defuse, ZW } from '../core/defuse.js';
27
+ import { defuse, inert, quoteInert, ZW } from '../core/defuse.js';
28
28
 
29
29
  /** The marker on the first line (an HTML comment, which the forge does not show). It does not contain the contract's tag, `cornfield-run` */
30
30
  export const MIRROR_TAG = 'cornfield:run-status';
@@ -40,19 +40,16 @@ const STATUS_WORDS = {
40
40
  /** The state of a run as a word, the one the dashboard shows */
41
41
  export const statusWord = (status) => STATUS_WORDS[status] ?? String(status);
42
42
 
43
- /** Markdown that could make a link, an image or HTML of someone else's words, made plain: `<` as an entity, `[` escaped (so `[[` is no node either) */
44
- const inert = (s) => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/\[/g, '\\[');
45
-
46
43
  /** Text for someone else's eyes: mentions, references and links broken, no link, image or HTML made of it, and made one line */
47
- const plain = (s) => inert(defuse(String(s ?? '').replace(/\s+/g, ' ').trim())).replace(/`/g, "'");
44
+ const plain = (s) => inert(defuse(String(s ?? '').replace(/\s+/g, ' ').trim()));
48
45
 
49
46
  /** A run's note, quoted line by line and cut short */
50
47
  function quote(note) {
51
48
  const text = String(note ?? '').trim();
52
49
  if (!text) return '';
53
50
  const cut = text.length > NOTE_SHOWN ? `${text.slice(0, NOTE_SHOWN)} …` : text;
54
- // Every line end Markdown (and readRunBlocks) knows is a line end here, so no line of the note escapes its `> `; no fence opens inside the quote
55
- return inert(defuse(cut)).replace(/`/g, "'").replace(/~(?=~)/g, `~${ZW}`).split(/\r\n?|\n/).map((l) => (l.trim() ? `> ${l}` : '>')).join('\n');
51
+ // Cut before it is made inert, so the cut never lands inside an escape (core/defuse.js)
52
+ return quoteInert(cut);
56
53
  }
57
54
 
58
55
  /** An address the forge gave, safe to put in a link; null for anything else */