cornfield 0.13.1 → 0.14.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/explorer/runs-model.js +3 -1
- package/package.json +1 -1
- package/server/agent-runs.js +60 -19
- package/server/review-tokens.js +40 -0
- package/server/runner-api.js +17 -13
- package/server/triggers.js +6 -3
package/explorer/runs-model.js
CHANGED
|
@@ -194,7 +194,9 @@ export function checksWords(run) {
|
|
|
194
194
|
|
|
195
195
|
/** One line of a run's timeline, and the runner's words under it (data for the page to escape) */
|
|
196
196
|
export function timelineWords(entry) {
|
|
197
|
-
|
|
197
|
+
// A runner's act carries `{ kind: 'runner', label, … }`: shown by its label. An older row's actor is the login, shown as it is
|
|
198
|
+
const who = entry.actor && typeof entry.actor === 'object' ? entry.actor.label : entry.actor;
|
|
199
|
+
const by = who ? ` by ${who}` : '';
|
|
198
200
|
switch (entry.kind) {
|
|
199
201
|
case 'requested': return { what: `Requested${by}${entry.ref ? ` under the profile ${entry.ref}` : ''}`, note: '' };
|
|
200
202
|
case 'claimed': return { what: `Claimed${by}`, note: entry.note || '' };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cornfield",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.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/agent-runs.js
CHANGED
|
@@ -82,8 +82,9 @@ import { createRequest, findRunId, formatRunComment, runAuthors, runBlocksOf, ru
|
|
|
82
82
|
import { quietAfterMs } from '../core/config.js';
|
|
83
83
|
import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.js';
|
|
84
84
|
import { readTopology } from '../core/validate.js';
|
|
85
|
-
import { findPullProposal, listPullProposals, readPullProposal } from './proposal-pulls.js';
|
|
85
|
+
import { findPullProposal, listPullProposals, pullProposals, readPullProposal } from './proposal-pulls.js';
|
|
86
86
|
import { Refused, countAttempt, throttle } from './throttle.js';
|
|
87
|
+
import { byFromText, byToText, runnerBy } from './review-tokens.js';
|
|
87
88
|
|
|
88
89
|
/** Requests one person may make in a minute (a ceiling of its own; every other action is counted by `ATTEMPTS_PER_MINUTE` and `PER_MINUTE`) */
|
|
89
90
|
export const AGENT_REQUESTS_PER_MINUTE = 6;
|
|
@@ -156,6 +157,12 @@ export function statusOf(row, nowMs, quietMs) {
|
|
|
156
157
|
return { status, open: !finished && !quiet, finished, quiet };
|
|
157
158
|
}
|
|
158
159
|
|
|
160
|
+
/** Who a stored `by` is for a hook event: `runner:<label>` for a runner, else the login */
|
|
161
|
+
function actorText(text) {
|
|
162
|
+
const by = byFromText(text);
|
|
163
|
+
return by && typeof by === 'object' ? `runner:${by.label}` : by;
|
|
164
|
+
}
|
|
165
|
+
|
|
159
166
|
/** The numbers a run is about, as keys for the one-per-subject rule: an issue and a thread are conversations (numbers are shared by issues and pull requests) */
|
|
160
167
|
function subjectKeys(refs) {
|
|
161
168
|
const out = [];
|
|
@@ -184,7 +191,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
|
|
|
184
191
|
claimedAt: row.claimed_at,
|
|
185
192
|
comment: row.comment_id ? { id: row.comment_id, url: row.comment_url } : null,
|
|
186
193
|
limits,
|
|
187
|
-
report: row.reported_at ? { state: row.state, at: row.reported_at, by: row.reported_by, note: row.note, url: row.url, tokens: row.tokens, cost: row.cost } : null,
|
|
194
|
+
report: row.reported_at ? { state: row.state, at: row.reported_at, by: byFromText(row.reported_by), note: row.note, url: row.url, tokens: row.tokens, cost: row.cost } : null,
|
|
188
195
|
stopRequested: row.stop_requested_at ? { at: row.stop_requested_at, by: row.stop_requested_by } : null,
|
|
189
196
|
pull: row.pull != null ? { number: row.pull, state: row.pull_state, url: row.pull_url, by: row.pull_by, trusted: row.pull_trusted === 1, via: row.linked_via } : null,
|
|
190
197
|
branch: row.branch, headSha: row.head_sha, checks: row.checks, lastActivity: row.last_activity,
|
|
@@ -201,7 +208,7 @@ export function publicRun(row, nowMs, quietMs, extra = {}) {
|
|
|
201
208
|
*/
|
|
202
209
|
export function timelineOf(row, events, now, quietMs) {
|
|
203
210
|
const out = [{ at: row.requested_at, kind: 'requested', actor: row.requested_by, ref: row.profile, note: null, url: row.comment_url }];
|
|
204
|
-
out.push(...events);
|
|
211
|
+
out.push(...events.map((e) => ({ ...e, actor: byFromText(e.actor) })));
|
|
205
212
|
if (now.status === 'quiet') out.push({ at: iso(Date.parse(row.last_activity) + quietMs), kind: 'quiet', actor: null, ref: null, note: null, url: null });
|
|
206
213
|
return out;
|
|
207
214
|
}
|
|
@@ -237,6 +244,8 @@ function requestNodes(request, known) {
|
|
|
237
244
|
* @property {{ auth: object, now?: () => number }} limits what server/throttle.js counts by
|
|
238
245
|
* @property {{ token: { id: number, label: string } } | null} [via] set when the request came through the API: the token it came with
|
|
239
246
|
* @property {() => string | null | Promise<string | null>} [stillAllowed] asked once more just before the cap is taken: null to go on, or why not
|
|
247
|
+
* @property {number} [landed] set only by the `spec.approved` trigger: the spec pull request the approval was on. If no open pull request holds the
|
|
248
|
+
* proposal because that one has since merged, the request is about the proposal as it is on the default branch (no `refs.pull`) and is posted there
|
|
240
249
|
* @property {{ event: string, ref: string }} [trigger] set only by an opt-in trigger (server/triggers.js): what caused this request. It is written into the
|
|
241
250
|
* request (`trigger: { event, by, ref }`, `by` being the maintainer asking) and the audit row, and the run's `via` is 'trigger'. A caller's body can never set it
|
|
242
251
|
*/
|
|
@@ -486,11 +495,16 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
486
495
|
else if (made.refs.proposal != null) {
|
|
487
496
|
const listed = await listPullProposals(forge, folder, { hooks: null });
|
|
488
497
|
entry = listed.entries.find((e) => e.slug === made.refs.proposal) ?? null;
|
|
489
|
-
if (
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
498
|
+
if (entry) {
|
|
499
|
+
number = entry.pull.number;
|
|
500
|
+
made = build(me.login, number);
|
|
501
|
+
runId = made.runId;
|
|
502
|
+
Object.assign(asked, { runId });
|
|
503
|
+
} else if (ctx.landed != null && (entry = await landedEntry(forge, ctx.landed, made.refs.proposal))) {
|
|
504
|
+
// A trigger's approval landed its spec pull request first (proposals.approveLands): the proposal is on the default branch, so
|
|
505
|
+
// the request names no pull request ("an approved proposal already on the default branch has none") and is posted on the merged one
|
|
506
|
+
number = ctx.landed;
|
|
507
|
+
} else throw new Refused(404, listed.problem ? `The open spec pull requests could not be read: ${listed.problem}` : `No open spec pull request holds the proposal ${made.refs.proposal}, so there is nowhere to post the request.`, 'not-found');
|
|
494
508
|
} else number = /** @type {number} */ (made.refs.issue);
|
|
495
509
|
if (made.refs.issue != null) {
|
|
496
510
|
try {
|
|
@@ -721,20 +735,42 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
721
735
|
return following;
|
|
722
736
|
}
|
|
723
737
|
|
|
738
|
+
/**
|
|
739
|
+
* The proposal `slug` as merged pull request `n` held it, or null: not merged, gone, or it never held that proposal. Read of the forge
|
|
740
|
+
* (its files at its head), not taken from the trigger's word, so a request is posted only on a pull request that landed the proposal.
|
|
741
|
+
* @param {import('./forge.js').Forge} forge
|
|
742
|
+
* @param {number} n
|
|
743
|
+
* @param {string} slug
|
|
744
|
+
*/
|
|
745
|
+
async function landedEntry(forge, n, slug) {
|
|
746
|
+
let pull;
|
|
747
|
+
try {
|
|
748
|
+
pull = await forge.pull(n);
|
|
749
|
+
} catch (err) {
|
|
750
|
+
if (err instanceof ForgeError && err.code === 'not-found') return null;
|
|
751
|
+
throw err;
|
|
752
|
+
}
|
|
753
|
+
if (pull.state !== 'merged') return null;
|
|
754
|
+
return (await pullProposals(forge, folder, pull)).find((e) => e.slug === slug) ?? null;
|
|
755
|
+
}
|
|
756
|
+
|
|
724
757
|
/**
|
|
725
758
|
* What a run is about, as references the map resolves (spec 0005 D9: "before the first push, the nodes come from what the request was
|
|
726
759
|
* about: the proposal, or the thread's mentions"): the `[[mentions]]` in the opening post of its thread, issue or spec PR, and for a
|
|
727
760
|
* proposal the ids of every node it touches (what it adds, changes and removes, the parents of what it adds, and the ends of the edges it
|
|
728
|
-
* adds, changes and removes). Asks the forge; throws what it throws. `entry`: the spec PR's listing when the caller has it already.
|
|
761
|
+
* adds, changes and removes). Asks the forge; throws what it throws. `entry`: the spec PR's listing when the caller has it already. A proposal
|
|
762
|
+
* with no `pull` (one a trigger asked about after it landed) is read from the merged pull request `target` the request was posted on.
|
|
729
763
|
* @returns {Promise<string[]>}
|
|
730
764
|
*/
|
|
731
|
-
async function subjectRefs(forge, refs, entry = null) {
|
|
765
|
+
async function subjectRefs(forge, refs, entry = null, target = null) {
|
|
732
766
|
const out = [];
|
|
733
767
|
const add = (r) => { if (typeof r === 'string' && r !== '' && !out.includes(r)) out.push(r); };
|
|
734
|
-
|
|
735
|
-
|
|
768
|
+
// A request about a proposal and a conversation is read as the conversation's when it names no spec pull request
|
|
769
|
+
const at = refs?.pull ?? entry?.pull.number ?? (refs?.thread == null && refs?.issue == null ? target : null);
|
|
770
|
+
if (refs?.proposal != null && at != null) {
|
|
771
|
+
const pull = await forge.pull(at);
|
|
736
772
|
parseMentions(pull.body ?? '').refs.forEach(add);
|
|
737
|
-
const found = entry ?? await findPullProposal(forge, folder, refs.proposal, refs.pull);
|
|
773
|
+
const found = entry ?? (refs.pull != null ? await findPullProposal(forge, folder, refs.proposal, refs.pull) : await landedEntry(forge, at, refs.proposal));
|
|
738
774
|
if (found) {
|
|
739
775
|
let proposal = null;
|
|
740
776
|
try { proposal = JSON.parse(await readPullProposal(forge, folder, found)); } catch (err) { if (!(err instanceof SyntaxError)) throw err; }
|
|
@@ -797,10 +833,10 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
797
833
|
if (mentions >= MAX_MENTION_READS) continue;
|
|
798
834
|
let refs = null;
|
|
799
835
|
try { refs = JSON.parse(row.request).refs; } catch { refs = null; }
|
|
800
|
-
if (!(refs?.proposal != null && refs.pull != null) && refs?.thread == null && refs?.issue == null) continue;
|
|
836
|
+
if (!(refs?.proposal != null && (refs.pull != null || row.target != null)) && refs?.thread == null && refs?.issue == null) continue;
|
|
801
837
|
mentions += 1;
|
|
802
838
|
try {
|
|
803
|
-
save.run(row.run_id, 'mentions', '', JSON.stringify(await subjectRefs(forge, refs)), iso(at));
|
|
839
|
+
save.run(row.run_id, 'mentions', '', JSON.stringify(await subjectRefs(forge, refs, null, row.target)), iso(at));
|
|
804
840
|
} catch (err) {
|
|
805
841
|
log(`what ${row.run_id} is about could not be read for its nodes: ${words(err)}`);
|
|
806
842
|
}
|
|
@@ -1049,7 +1085,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1049
1085
|
// ---- kept first, then announced ------------------------------------------------------------------------------------------------
|
|
1050
1086
|
for (const row of cur.values()) {
|
|
1051
1087
|
const now2 = statusOf(row, at, quietMs);
|
|
1052
|
-
if (now2.finished && !FINISHED.includes(before.get(row.run_id) ?? '')) queue(row, 'run.finished', `ev:finished:${cause.get(row.run_id) ?? now2.status}`, row.reported_by ?? row.pull_by, now2.status);
|
|
1088
|
+
if (now2.finished && !FINISHED.includes(before.get(row.run_id) ?? '')) queue(row, 'run.finished', `ev:finished:${cause.get(row.run_id) ?? now2.status}`, actorText(row.reported_by) ?? row.pull_by, now2.status);
|
|
1053
1089
|
}
|
|
1054
1090
|
/** @type {typeof events} */
|
|
1055
1091
|
const fresh = [];
|
|
@@ -1090,9 +1126,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1090
1126
|
// Runners: pull and push (a runner token, server/runner-api.js; spec 0005 D2, D5)
|
|
1091
1127
|
// -------------------------------------------------------------------------
|
|
1092
1128
|
|
|
1093
|
-
/** @typedef {{ id: number, label: string }} RunnerToken the runner token a call came with */
|
|
1129
|
+
/** @typedef {{ id: number, label: string, mintedBy?: { login: string, userId: string } }} RunnerToken the runner token a call came with */
|
|
1094
1130
|
|
|
1095
1131
|
const runnerActor = (token) => `runner:${token.label}`;
|
|
1132
|
+
/** What a runner's act writes into the timeline: the runner, with the maintainer who minted the token kept in `mintedBy` */
|
|
1133
|
+
const runnerText = (token) => byToText(runnerBy(token));
|
|
1096
1134
|
|
|
1097
1135
|
/** A run for a runner: the state it is in as cornfield derives it, and whether a maintainer asked it to stop. Nothing else about the run, no credential */
|
|
1098
1136
|
function runnerView(row) {
|
|
@@ -1140,7 +1178,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1140
1178
|
const stamp = iso(at);
|
|
1141
1179
|
const won = typeof runId === 'string' ? db.prepare(`UPDATE runs SET claimed_by = ?, claimed_at = ?, state = 'claimed', reported_at = ?, reported_by = ?, note = NULL, last_activity = MAX(last_activity, ?)
|
|
1142
1180
|
WHERE run_id = ? AND repo = ? AND transport = 'pull' AND state = 'requested' AND claimed_by IS NULL AND stop_requested_at IS NULL AND last_activity > ?`)
|
|
1143
|
-
.run(token.id, stamp, stamp, token
|
|
1181
|
+
.run(token.id, stamp, stamp, runnerText(token), stamp, runId, repo, iso(at - quietMs)).changes === 1 : false;
|
|
1144
1182
|
const row = typeof runId === 'string' ? /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo)) : undefined;
|
|
1145
1183
|
if (!row) throw new Refused(404, 'cornfield has no such request.', 'not-found');
|
|
1146
1184
|
if (!won) {
|
|
@@ -1150,6 +1188,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1150
1188
|
if (statusOf(row, at, quietMs).quiet) throw new Refused(409, 'This request has waited past agents.quietAfter and is no longer offered.', 'conflict');
|
|
1151
1189
|
throw new Refused(409, `This request is ${row.state}; there is nothing to claim.`, 'conflict');
|
|
1152
1190
|
}
|
|
1191
|
+
keepEvent(db, row.run_id, { key: `claim:${token.id}:${stamp}`, at: stamp, kind: 'claimed', actor: runnerText(token), ref: 'claimed' });
|
|
1153
1192
|
const checked = validateRequest(safeJson(row.request));
|
|
1154
1193
|
hooks?.emit('run.claimed', { ...runPayload(row, runnerActor(token)), state: 'claimed' });
|
|
1155
1194
|
hooks?.emit('run.state', { ...runPayload(row, runnerActor(token)), state: 'claimed' });
|
|
@@ -1182,9 +1221,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1182
1221
|
const changed = db.prepare(`UPDATE runs SET state = ?, reported_at = ?, reported_by = ?, note = ?, url = ?, tokens = COALESCE(?, tokens), cost = COALESCE(?, cost),
|
|
1183
1222
|
claimed_by = COALESCE(claimed_by, ?), claimed_at = COALESCE(claimed_at, ?), last_activity = MAX(last_activity, ?)
|
|
1184
1223
|
WHERE run_id = ? AND (claimed_by IS NULL OR claimed_by = ?) AND state NOT IN ('done', 'failed', 'stopped')`)
|
|
1185
|
-
.run(r.state, stamp, token
|
|
1224
|
+
.run(r.state, stamp, runnerText(token), r.note ?? null, r.url ?? null, r.tokens ?? null, r.cost ?? null, token.id, stamp, stamp, row.run_id, token.id).changes;
|
|
1186
1225
|
if (changed !== 1) throw new Refused(409, `Run ${row.run_id} changed while the report was being taken; read it again (GET /api/runs/${row.run_id}).`, 'conflict');
|
|
1187
1226
|
const after = /** @type {RunRow} */ (db.prepare('SELECT * FROM runs WHERE run_id = ?').get(row.run_id));
|
|
1227
|
+
// A report of `claimed` on a run the claim route already claimed is a report, not a second "Claimed" line
|
|
1228
|
+
keepEvent(db, row.run_id, { key: `report:runner:${token.id}:${stamp}:${r.state}`, at: stamp, kind: r.state === 'claimed' && row.state !== 'claimed' ? 'claimed' : 'report', actor: runnerText(token), ref: r.state, note: r.note ?? null, url: r.url ?? null });
|
|
1188
1229
|
const actor = runnerActor(token);
|
|
1189
1230
|
if (r.state === 'claimed' && row.state !== 'claimed') hooks?.emit('run.claimed', { ...runPayload(after, actor), state: r.state });
|
|
1190
1231
|
if (r.state !== row.state) hooks?.emit('run.state', { ...runPayload(after, actor), state: r.state });
|
package/server/review-tokens.js
CHANGED
|
@@ -48,6 +48,46 @@ const TOKEN_SHAPE = /^cf_(?:rt|at|nt)_[A-Za-z0-9_-]{43,128}$/;
|
|
|
48
48
|
const LABEL = /^[\p{L}\p{N}][\p{L}\p{N} ._:/()-]*$/u;
|
|
49
49
|
const COLUMNS = 'id, user_id, login, label, scope, created_at, expires_at, revoked_at, last_used';
|
|
50
50
|
|
|
51
|
+
/**
|
|
52
|
+
* Who acted when a runner token did: the runner (the token's label), with the maintainer who minted the token kept apart as `mintedBy`.
|
|
53
|
+
* A runner token does not act as its owner, so the timeline and the audit name the runner (issue #105).
|
|
54
|
+
* @typedef {{ kind: 'runner', label: string, tokenId?: number, mintedBy?: { login: string, userId: string } }} RunnerBy
|
|
55
|
+
* @param {{ id?: number, label: string, mintedBy?: { login: string, userId: string } }} token
|
|
56
|
+
* @returns {RunnerBy}
|
|
57
|
+
*/
|
|
58
|
+
export function runnerBy(token) {
|
|
59
|
+
return { kind: 'runner', label: token.label, ...(token.id !== undefined ? { tokenId: token.id } : {}), ...(token.mintedBy ? { mintedBy: token.mintedBy } : {}) };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** The token a runner call carries from here on: its id and label, and the maintainer who minted it */
|
|
63
|
+
export const runnerTokenOf = (row) => ({ id: row.id, label: row.label, mintedBy: { login: row.login, userId: String(row.user_id) } });
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* `by` as the TEXT columns keep it: a login stays plain text (the shape every older row has), a runner is JSON. A login never starts with `{`.
|
|
67
|
+
* @param {string | RunnerBy | null | undefined} by
|
|
68
|
+
* @returns {string | null}
|
|
69
|
+
*/
|
|
70
|
+
export function byToText(by) {
|
|
71
|
+
if (by == null || by === '') return null;
|
|
72
|
+
return typeof by === 'string' ? by : JSON.stringify(by);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* `by` as it was kept: the runner object, or the plain login of an older row (or null). Text that only looks like JSON is a plain string.
|
|
77
|
+
* @param {string | null | undefined} text
|
|
78
|
+
* @returns {string | RunnerBy | null}
|
|
79
|
+
*/
|
|
80
|
+
export function byFromText(text) {
|
|
81
|
+
if (typeof text !== 'string' || text === '') return null;
|
|
82
|
+
if (text.startsWith('{')) {
|
|
83
|
+
try {
|
|
84
|
+
const v = JSON.parse(text);
|
|
85
|
+
if (v && v.kind === 'runner' && typeof v.label === 'string') return v;
|
|
86
|
+
} catch { /* plain text */ }
|
|
87
|
+
}
|
|
88
|
+
return text;
|
|
89
|
+
}
|
|
90
|
+
|
|
51
91
|
const iso = (ms) => new Date(ms).toISOString();
|
|
52
92
|
|
|
53
93
|
/** The SHA-256 of a token, as hex: what the table keeps */
|
package/server/runner-api.js
CHANGED
|
@@ -46,7 +46,7 @@
|
|
|
46
46
|
|
|
47
47
|
import { readBody } from './proposals.js';
|
|
48
48
|
import { ANONYMOUS_PER_MINUTE, NO_TOKEN_LOGIN } from './review-api.js';
|
|
49
|
-
import { bearerOf, findToken, scopeOfShape, touchToken } from './review-tokens.js';
|
|
49
|
+
import { bearerOf, findToken, runnerBy, runnerTokenOf, scopeOfShape, touchToken } from './review-tokens.js';
|
|
50
50
|
import { QUEUE_LIMIT } from './agent-runs.js';
|
|
51
51
|
import { refusal } from './submit-review.js';
|
|
52
52
|
import { Refused, countAttempt } from './throttle.js';
|
|
@@ -151,13 +151,17 @@ export async function serveRunnerCall(req, res, route, url, ctx) {
|
|
|
151
151
|
}
|
|
152
152
|
|
|
153
153
|
const { row, state } = found;
|
|
154
|
-
const token =
|
|
154
|
+
const token = runnerTokenOf(row);
|
|
155
|
+
// The runner acts, not the maintainer who minted its token: the audit names the runner and keeps the maintainer in `mintedBy` (a token of another scope that was presented here is its owner's act)
|
|
156
|
+
const audited = { id: row.id, label: row.label };
|
|
157
|
+
const actor = state === 'wrong-scope' ? row.login : `runner:${row.label}`;
|
|
158
|
+
const by = state === 'wrong-scope' ? {} : { by: runnerBy(token), mintedBy: token.mintedBy };
|
|
155
159
|
if (state !== 'active') {
|
|
156
160
|
req.resume();
|
|
157
161
|
const flood = countAttempt(ctx, row.user_id, now());
|
|
158
162
|
if (flood) return send(res, flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
|
|
159
163
|
const wrong = state === 'wrong-scope';
|
|
160
|
-
return refuse(
|
|
164
|
+
return refuse(actor, { reason: wrong ? 'wrong-scope' : state, token: audited, ...by, ...(wrong ? { scope: row.scope } : {}) }, 403, {
|
|
161
165
|
error: wrong ? `This is ${row.scope === 'agent' ? 'an' : 'a'} ${row.scope} token. Runners take a runner token; make one in the dashboard.`
|
|
162
166
|
: state === 'revoked' ? 'This runner token was revoked; make a new one in the dashboard.' : 'This runner token has expired; make a new one in the dashboard.',
|
|
163
167
|
code: 'forbidden',
|
|
@@ -174,23 +178,22 @@ export async function serveRunnerCall(req, res, route, url, ctx) {
|
|
|
174
178
|
if (known !== null && !isMaintainer(known)) {
|
|
175
179
|
req.resume();
|
|
176
180
|
await auth.demoted(row.user_id, row.login, known);
|
|
177
|
-
return refuse(
|
|
181
|
+
return refuse(actor, { reason: 'owner-not-maintainer', token: audited, ...by }, 403, { error: `This runner token's owner, ${row.login}, does not maintain ${repo} any more, so it is revoked.`, code: 'forbidden' });
|
|
178
182
|
}
|
|
179
183
|
touchToken(/** @type {import('node:sqlite').DatabaseSync} */ (db), row.id, now());
|
|
180
|
-
const who = row.login;
|
|
181
184
|
|
|
182
185
|
try {
|
|
183
186
|
if (route.action === 'runner-list') {
|
|
184
187
|
req.resume();
|
|
185
188
|
if (url.searchParams.get('state') !== 'queued') throw new Refused(400, 'The only listing is ?state=queued: the requests waiting for a runner.', 'invalid');
|
|
186
189
|
const requests = await runs.queued();
|
|
187
|
-
if (requests.length || emptyReadDue(auth, row.id, now())) await audit(
|
|
190
|
+
if (requests.length || emptyReadDue(auth, row.id, now())) await audit(actor, { token: audited, ...by }, 200, { ok: true, count: requests.length });
|
|
188
191
|
return send(res, 200, { ok: true, requests, limit: QUEUE_LIMIT });
|
|
189
192
|
}
|
|
190
193
|
if (route.action === 'runner-claim') {
|
|
191
194
|
req.resume();
|
|
192
195
|
const claimed = await runs.claim(token, route.runId);
|
|
193
|
-
await audit(
|
|
196
|
+
await audit(actor, { token: audited, ...by }, 200, { ok: true, claimed: true }, `${repo}#${claimed.row.target}`);
|
|
194
197
|
return send(res, 200, { ok: true, request: claimed.request, run: claimed.run });
|
|
195
198
|
}
|
|
196
199
|
if (method === 'POST') {
|
|
@@ -214,21 +217,21 @@ export async function serveRunnerCall(req, res, route, url, ctx) {
|
|
|
214
217
|
try {
|
|
215
218
|
if (problem) throw problem;
|
|
216
219
|
const done = await runs.report(token, route.runId, body);
|
|
217
|
-
await audit(
|
|
220
|
+
await audit(actor, { token: audited, ...by, ...shape }, 200, { ok: true, state: done.row.state }, `${repo}#${done.row.target}`);
|
|
218
221
|
return send(res, 200, { ok: true, run: done.run });
|
|
219
222
|
} catch (err) {
|
|
220
223
|
const out = answerFor(err);
|
|
221
|
-
await audit(
|
|
224
|
+
await audit(actor, { token: audited, ...by, ...shape }, out.status, { error: out.body.error, code: out.body.code });
|
|
222
225
|
return send(res, out.status, { ok: false, ...out.body }, out.headers);
|
|
223
226
|
}
|
|
224
227
|
}
|
|
225
228
|
req.resume();
|
|
226
229
|
const view = await runs.runnerGet(token, route.runId);
|
|
227
|
-
await audit(
|
|
230
|
+
await audit(actor, { token: audited, ...by }, 200, { ok: true, state: view.state });
|
|
228
231
|
return send(res, 200, { ok: true, run: view });
|
|
229
232
|
} catch (err) {
|
|
230
233
|
const out = answerFor(err);
|
|
231
|
-
await audit(
|
|
234
|
+
await audit(actor, { token: audited, ...by }, out.status, { error: out.body.error, code: out.body.code });
|
|
232
235
|
return send(res, out.status, { ok: false, ...out.body }, out.headers);
|
|
233
236
|
}
|
|
234
237
|
}
|
|
@@ -250,9 +253,10 @@ export async function serveStrayRunner(req, res, reqPath, ctx) {
|
|
|
250
253
|
const presented = bearerOf(req.headers.authorization);
|
|
251
254
|
let owner = null;
|
|
252
255
|
let token;
|
|
256
|
+
let by = {};
|
|
253
257
|
if (presented && auth.enabled) {
|
|
254
258
|
const found = findToken(await auth.store(), presented, now(), 'runner');
|
|
255
|
-
if (found && found.state !== 'wrong-scope') { owner = found.row.
|
|
259
|
+
if (found && found.state !== 'wrong-scope') { owner = `runner:${found.row.label}`; token = { id: found.row.id, label: found.row.label }; by = { by: runnerBy(runnerTokenOf(found.row)), mintedBy: runnerTokenOf(found.row).mintedBy }; }
|
|
256
260
|
}
|
|
257
261
|
const flood = owner === null ? countAttempt(ctx, NO_TOKEN_LOGIN, now(), ANONYMOUS_PER_MINUTE) : countAttempt(ctx, `runner|${token.id}`, now(), RUNNER_PER_MINUTE);
|
|
258
262
|
if (flood) return send(res, flood.status, { ok: false, error: flood.message, code: flood.code }, flood.headers);
|
|
@@ -260,7 +264,7 @@ export async function serveStrayRunner(req, res, reqPath, ctx) {
|
|
|
260
264
|
try {
|
|
261
265
|
await auth.record({
|
|
262
266
|
login: owner ?? NO_TOKEN_LOGIN, action: 'runner-call', target: config.forge?.repo ?? '',
|
|
263
|
-
request: { via: 'api', reason: 'wrong-route', method: String(req.method).slice(0, 10), path: reqPath.slice(0, 80), ...(token ? { token } : {}) }, status: 403, answer: { error: body.error, code: body.code },
|
|
267
|
+
request: { via: 'api', reason: 'wrong-route', method: String(req.method).slice(0, 10), path: reqPath.slice(0, 80), ...(token ? { token, ...by } : {}) }, status: 403, answer: { error: body.error, code: body.code },
|
|
264
268
|
});
|
|
265
269
|
} catch (err) {
|
|
266
270
|
console.error(`[cornfield] a runner call could not be written to the audit table: ${err instanceof Error ? err.message : err}`);
|
package/server/triggers.js
CHANGED
|
@@ -38,9 +38,10 @@
|
|
|
38
38
|
* over (finished, or quiet: what the cap counts). While one is open, the trigger is skipped with `run-open` (`trigger-skipped` and the
|
|
39
39
|
* hook), whatever its profile; the one-run-per-subject rule of the request path only clashes within a profile.
|
|
40
40
|
*
|
|
41
|
-
* **approveLands.** With `proposals.approveLands`, an approval may land the spec pull request before the trigger's request reads it
|
|
42
|
-
* request then finds no open proposal and the
|
|
43
|
-
*
|
|
41
|
+
* **approveLands.** With `proposals.approveLands`, an approval may land the spec pull request before the trigger's request reads it. The
|
|
42
|
+
* request then finds no open proposal and asks for the run on the landed one: `refs: { proposal }` with no `pull`, posted on the merged spec
|
|
43
|
+
* pull request, the cause unchanged (`pull:<n>`), once the forge says that pull request merged and its files held the proposal (else
|
|
44
|
+
* `not-found`). Either order works; the cap and the one-run-per-subject rule apply as always.
|
|
44
45
|
*
|
|
45
46
|
* **No live sign-in.** If the maintainer has no live session, the trigger does nothing else (cornfield holds no forge token of its own, and
|
|
46
47
|
* another maintainer's would put words in their name): an audit row (`trigger-skipped`), the hook event `trigger.skipped`
|
|
@@ -257,6 +258,8 @@ export function createTriggers({ config, auth, runs, hooks, now = Date.now }) {
|
|
|
257
258
|
await runs.request({
|
|
258
259
|
forge: () => forge, who: { login: cause.by, userId: String(userId) }, limits: { auth, now },
|
|
259
260
|
trigger: { event: cause.event, ref: cause.ref },
|
|
261
|
+
// An approval that landed its spec pull request first leaves the proposal on the default branch: the request goes on the merged one
|
|
262
|
+
...(event === 'spec.approved' ? { landed: cause.subject } : {}),
|
|
260
263
|
}, { body });
|
|
261
264
|
} catch (err) {
|
|
262
265
|
if (!(err instanceof Refused) && !(err instanceof ForgeError)) log(`a ${event} trigger failed: ${err instanceof Error ? err.stack || err.message : err}`);
|