@popcorn245/cornfield 0.13.2 → 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 +18 -6
- package/server/review-tokens.js +40 -0
- package/server/runner-api.js +17 -13
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": "@popcorn245/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
|
@@ -84,6 +84,7 @@ import { nodesForFile, parseMentions, resolveMentions } from '../core/mentions.j
|
|
|
84
84
|
import { readTopology } from '../core/validate.js';
|
|
85
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
|
}
|
|
@@ -1078,7 +1085,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1078
1085
|
// ---- kept first, then announced ------------------------------------------------------------------------------------------------
|
|
1079
1086
|
for (const row of cur.values()) {
|
|
1080
1087
|
const now2 = statusOf(row, at, quietMs);
|
|
1081
|
-
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);
|
|
1082
1089
|
}
|
|
1083
1090
|
/** @type {typeof events} */
|
|
1084
1091
|
const fresh = [];
|
|
@@ -1119,9 +1126,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1119
1126
|
// Runners: pull and push (a runner token, server/runner-api.js; spec 0005 D2, D5)
|
|
1120
1127
|
// -------------------------------------------------------------------------
|
|
1121
1128
|
|
|
1122
|
-
/** @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 */
|
|
1123
1130
|
|
|
1124
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));
|
|
1125
1134
|
|
|
1126
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 */
|
|
1127
1136
|
function runnerView(row) {
|
|
@@ -1169,7 +1178,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1169
1178
|
const stamp = iso(at);
|
|
1170
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, ?)
|
|
1171
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 > ?`)
|
|
1172
|
-
.run(token.id, stamp, stamp, token
|
|
1181
|
+
.run(token.id, stamp, stamp, runnerText(token), stamp, runId, repo, iso(at - quietMs)).changes === 1 : false;
|
|
1173
1182
|
const row = typeof runId === 'string' ? /** @type {RunRow | undefined} */ (db.prepare('SELECT * FROM runs WHERE run_id = ? AND repo = ?').get(runId, repo)) : undefined;
|
|
1174
1183
|
if (!row) throw new Refused(404, 'cornfield has no such request.', 'not-found');
|
|
1175
1184
|
if (!won) {
|
|
@@ -1179,6 +1188,7 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1179
1188
|
if (statusOf(row, at, quietMs).quiet) throw new Refused(409, 'This request has waited past agents.quietAfter and is no longer offered.', 'conflict');
|
|
1180
1189
|
throw new Refused(409, `This request is ${row.state}; there is nothing to claim.`, 'conflict');
|
|
1181
1190
|
}
|
|
1191
|
+
keepEvent(db, row.run_id, { key: `claim:${token.id}:${stamp}`, at: stamp, kind: 'claimed', actor: runnerText(token), ref: 'claimed' });
|
|
1182
1192
|
const checked = validateRequest(safeJson(row.request));
|
|
1183
1193
|
hooks?.emit('run.claimed', { ...runPayload(row, runnerActor(token)), state: 'claimed' });
|
|
1184
1194
|
hooks?.emit('run.state', { ...runPayload(row, runnerActor(token)), state: 'claimed' });
|
|
@@ -1211,9 +1221,11 @@ export function createRuns({ config, where, auth, hooks = null, now = Date.now,
|
|
|
1211
1221
|
const changed = db.prepare(`UPDATE runs SET state = ?, reported_at = ?, reported_by = ?, note = ?, url = ?, tokens = COALESCE(?, tokens), cost = COALESCE(?, cost),
|
|
1212
1222
|
claimed_by = COALESCE(claimed_by, ?), claimed_at = COALESCE(claimed_at, ?), last_activity = MAX(last_activity, ?)
|
|
1213
1223
|
WHERE run_id = ? AND (claimed_by IS NULL OR claimed_by = ?) AND state NOT IN ('done', 'failed', 'stopped')`)
|
|
1214
|
-
.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;
|
|
1215
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');
|
|
1216
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 });
|
|
1217
1229
|
const actor = runnerActor(token);
|
|
1218
1230
|
if (r.state === 'claimed' && row.state !== 'claimed') hooks?.emit('run.claimed', { ...runPayload(after, actor), state: r.state });
|
|
1219
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}`);
|