@join-pantheon/cli 0.34.0 → 0.34.1

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/dist/relay.js CHANGED
@@ -12,7 +12,7 @@ import { installerLine } from "./managed.js";
12
12
  import { Ledger, SpaceFull } from "./ledger.js";
13
13
  import { fingerprint, newNonce, verifyChallenge, verifyActivity, verifyAccount, verifyRead, actPayload, goalPayload, verifyBytes, verifyDelegate, canonicalJson } from "./identity.js";
14
14
  import { ADMIN_SESSION_MS, Accounts, normalizeEmail, normalizeUsername, validEmail, validUsername, VIEWER_DEFAULT_DAYS, VIEWER_MAX_DAYS, VIEWER_SESSION_MAX_MS } from "./accounts.js";
15
- import { renderViewerBusy, renderViewerUnreadable, renderViewerEnded, renderViewerHome, renderViewerNeedsHttps, renderViewerSignin, renderViewerTeam } from "./viewer-pages.js";
15
+ import { renderViewerBusy, renderViewerUnreadable, renderViewerEnded, renderViewerGoal, renderViewerHome, renderViewerNeedsHttps, renderViewerSignin, renderViewerTeam } from "./viewer-pages.js";
16
16
  import { emailSenderFromEnv, maskEmail } from "./email.js";
17
17
  import { Allowlist, RosterUnreadable } from "./roster-file.js";
18
18
  import { StateStore, ensurePrivateDir, setWaitForDisk, takeSlowestDiskWait, waitsForDisk } from "./store.js";
@@ -20,8 +20,11 @@ import { countGoal, countMessage, emptyUsage, parseUsage, usageAnswer, USAGE_KEE
20
20
  import { busyWriter, DiskBusy, flushWrites, onWriteError, pendingView, recordWrites, whenLanded, writerFor } from "./disk-writer.js";
21
21
  import { feed, noteRefusal, spaceHealth, fleetReport, isMessage, stuckBehind, versionBehind, MESSAGE_ACTS, DAY } from "./admin-stats.js";
22
22
  import { flowIndexAsync, flowOf, flowOfAsync, seriesOf, toFlowGoals, toFlowObligations, toFlowRecords } from "./flow-stats.js";
23
+ import { relayComposed } from "./verify-act.js";
24
+ import { goalFlowOf, GOAL_NODE_CAP } from "./goal-flow.js";
25
+ import { founderView, teamWeeksOfAsync, weekBounds, WEEKS } from "./founder-stats.js";
23
26
  import { newNonce as newUiNonce, pageHeaders, rangeOf } from "./admin-ui.js";
24
- import { renderAdminLogin, renderAudit, renderOverview, renderPeople, renderPlans, renderSecurity, renderTeam, renderTeamUnreadable } from "./admin-pages.js";
27
+ import { renderAdminLogin, renderAudit, renderGoal, renderOverview, renderPeople, renderPlans, renderSecurity, renderTeam, renderTeamUnreadable } from "./admin-pages.js";
25
28
  import { fmtLimit, inviteLimit, parseLimits, planLimits, PLAN_NAME } from "./plans.js";
26
29
  import { FEEDBACK_ADDRESS } from "./feedback.js";
27
30
  import { relayShellArg, teamNameProblem } from "./team-name.js";
@@ -134,6 +137,43 @@ function secretEq(a, b) {
134
137
  const x = createHash("sha256").update(a).digest(), y = createHash("sha256").update(b).digest();
135
138
  return timingSafeEqualBuf(x, y);
136
139
  }
140
+ export function sameOriginRequest(req) {
141
+ const site = req.headers["sec-fetch-site"];
142
+ if (site !== undefined && site !== "same-origin")
143
+ return false;
144
+ const origin = req.headers["origin"];
145
+ if (origin === undefined || origin === "null")
146
+ return site === "same-origin";
147
+ if (typeof origin !== "string")
148
+ return false;
149
+ let host;
150
+ try {
151
+ host = new URL(origin).host.toLowerCase();
152
+ }
153
+ catch {
154
+ return false;
155
+ }
156
+ const own = [req.headers["host"], ...(process.env.PANTHEON_TRUSTED_HOPS?.trim() === "0" ? [] : [req.headers["x-forwarded-host"]])]
157
+ .flatMap((h) => (Array.isArray(h) ? h : [h])).filter((h) => typeof h === "string" && !!h)
158
+ .map((h) => h.split(",").pop().trim().toLowerCase());
159
+ return own.includes(host);
160
+ }
161
+ function fullMessage(rec, goalTitles) {
162
+ const meta = (rec.meta ?? {});
163
+ const kv = [["Message ID", rec.id]];
164
+ if (rec.ref)
165
+ kv.push(["Reply to", rec.ref]);
166
+ if (rec.goal)
167
+ kv.push(["Goal", `${goalTitles.get(rec.goal) ?? ""} (${rec.goal})`]);
168
+ if (rec.role)
169
+ kv.push(["Session role", rec.role]);
170
+ if (rec.summary)
171
+ kv.push(["Summary", rec.summary]);
172
+ for (const k of ["branch", "commit", "remote", "base", "repo_origin", "decision_domains", "defers_to", "affects", "authority", "unverified_domains"])
173
+ if (meta[k] !== undefined)
174
+ kv.push([k.replace(/_/g, " "), typeof meta[k] === "string" ? meta[k] : JSON.stringify(meta[k])]);
175
+ return { id: rec.id, body: rec.body, kv };
176
+ }
137
177
  const clipText = (v, max) => { const t = v.replace(/\s+/g, " ").trim(); if (t.length <= max)
138
178
  return t; const cut = t.slice(0, max - 1); const sp = cut.lastIndexOf(" "); return `${(sp > max * 0.6 ? cut.slice(0, sp) : cut).trimEnd()}…`; };
139
179
  const escHtml = (v) => String(v ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }[c]));
@@ -961,7 +1001,7 @@ export class Relay {
961
1001
  onAuthHttp(req, res, url, ip) {
962
1002
  if (url.pathname === "/")
963
1003
  return this.landingPage(req, res);
964
- if (url.pathname === "/admin" || url.pathname === "/admin/space" || url.pathname === "/admin/export" || url.pathname === "/admin/backup" || url.pathname === "/admin/action" || url.pathname === "/admin/login" || url.pathname === "/admin/logout" || url.pathname === "/admin/report" || url.pathname === "/admin/leftovers") {
1004
+ if (url.pathname === "/admin" || url.pathname === "/admin/space" || url.pathname === "/admin/export" || url.pathname === "/admin/backup" || url.pathname === "/admin/action" || url.pathname === "/admin/login" || url.pathname === "/admin/logout" || url.pathname === "/admin/report" || url.pathname === "/admin/leftovers" || url.pathname === "/admin/message" || url.pathname === "/admin/goal") {
965
1005
  const A0 = this.accounts;
966
1006
  if (!A0 || !this.adminToken)
967
1007
  return this.json(res, 404, { error: "not found" });
@@ -1052,6 +1092,27 @@ export class Relay {
1052
1092
  return this.json(res, 403, { error: "sign in at /admin" });
1053
1093
  return this.readForm(req, res, (body) => this.adminAction(res, A0, body, ip, csrf));
1054
1094
  }
1095
+ if (url.pathname === "/admin/message") {
1096
+ if (req.method !== "POST") {
1097
+ res.writeHead(405, { allow: "POST", "content-type": "application/json", "cache-control": "no-store" });
1098
+ return void res.end(JSON.stringify({ error: "POST only" }));
1099
+ }
1100
+ if (!bySession)
1101
+ return this.json(res, 403, { error: "sign in at /admin" });
1102
+ if (!sameOriginRequest(req))
1103
+ return this.json(res, 403, { error: "only the relay's own pages may ask for a message" });
1104
+ if (!secretEq(String(req.headers["x-pantheon-csrf"] ?? ""), csrf))
1105
+ return this.json(res, 403, { error: "stale page — reload it and try again" });
1106
+ return this.readForm(req, res, (body) => this.adminMessage(res, body.name ?? "", body.id ?? "", A0, ip));
1107
+ }
1108
+ if (url.pathname === "/admin/goal") {
1109
+ if (!authed)
1110
+ return this.adminLoginPage(res, false);
1111
+ const space = url.searchParams.get("space") ?? "", id = url.searchParams.get("id") ?? "";
1112
+ void this.adminGoal(res, space, id, csrf, A0, ip).catch((e) => { this.log(`! goal page failed: ${e.message}`); if (!res.headersSent)
1113
+ this.json(res, 500, { error: "the goal page could not be made" }); });
1114
+ return;
1115
+ }
1055
1116
  if (url.pathname === "/admin/space") {
1056
1117
  if (!authed)
1057
1118
  return this.adminLoginPage(res, false);
@@ -2977,7 +3038,7 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
2977
3038
  return done();
2978
3039
  return this.readForm(req, res, () => done());
2979
3040
  }
2980
- if (path === "/view/team" && req.method === "GET") {
3041
+ if ((path === "/view/team" || path === "/view/goal") && req.method === "GET") {
2981
3042
  if (!session) {
2982
3043
  res.writeHead(303, { location: "/view/signin" });
2983
3044
  return void res.end();
@@ -3006,6 +3067,31 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3006
3067
  }
3007
3068
  const days = rangeOf(url.searchParams.get("range"));
3008
3069
  const now = Date.now();
3070
+ if (path === "/view/goal") {
3071
+ const gid = url.searchParams.get("id") ?? "";
3072
+ void this.goalFlowAsync(grant.space, gid, now).then(async (g) => {
3073
+ await this.renderTurn();
3074
+ if (res.destroyed)
3075
+ return;
3076
+ if (!g || g.flow.goal.state === "CLOSED")
3077
+ return send(404, renderViewerEnded({ nonce, email: session.email, csrf }), nonce);
3078
+ const ak = `${session.idHash}|${spaceKey(grant.space)}|goal`;
3079
+ if (now - (this.viewAudited.get(ak) ?? 0) > 10 * 60_000) {
3080
+ this.viewAudited.set(ak, now);
3081
+ A.audit({ event: "viewer_view", space: grant.space, target: session.email, detail: "how a goal moved", ip });
3082
+ }
3083
+ A.noteViewerView(grant.id);
3084
+ send(200, renderViewerGoal({ nonce, csrf, email: session.email, team: grant.space, flow: g.flow }), nonce);
3085
+ }).catch((e) => {
3086
+ const code = unreadableCode(e);
3087
+ if (code && !res.headersSent)
3088
+ return send(503, renderViewerUnreadable({ nonce, email: session.email, csrf, team: grant.space, code }), nonce, { "retry-after": "30" });
3089
+ this.log(`! viewer goal page failed: ${e.message}`);
3090
+ if (!res.headersSent)
3091
+ this.json(res, 500, { error: "the page could not be made" });
3092
+ });
3093
+ return;
3094
+ }
3009
3095
  const inflight = this.viewInflight.get(session.idHash) ?? 0;
3010
3096
  if (inflight >= this.readBounds.viewInflight) {
3011
3097
  const tries = Math.max(0, Math.min(99, Math.floor(Number(url.searchParams.get("busy")) || 0)));
@@ -3453,6 +3539,159 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3453
3539
  this.teamViews.set(key, { sig, at: now, view }, estimateViewBytes(view));
3454
3540
  return view;
3455
3541
  }
3542
+ teamWeeksCache = new ByteLru(() => Math.max(1, Math.floor(this.readBounds.viewBytes / 4)));
3543
+ teamWeeksFlights = new Map();
3544
+ async teamWeeksAsync(name, now) {
3545
+ const live = this.spaces.get(spaceKey(name));
3546
+ const safe = live ? safeName(live.name) : safeName(name);
3547
+ const key = safe.toLowerCase();
3548
+ const day = new Date(now).toISOString().slice(0, 10);
3549
+ const sig = `${day}|${live ? (() => { const all = live.ledger.all(); return `live:${all.length}:${all.length ? all[all.length - 1].seq : 0}`; })() : await this.teamFilesSig(safe)}`;
3550
+ const hit = this.teamWeeksCache.get(key);
3551
+ if (hit && hit.sig === sig)
3552
+ return hit.v;
3553
+ const flight = `${key}|${sig}`;
3554
+ const running = this.teamWeeksFlights.get(flight);
3555
+ if (running)
3556
+ return running;
3557
+ const p = this.coldSlot(async () => {
3558
+ const again = this.teamWeeksCache.get(key);
3559
+ if (again && again.sig === sig)
3560
+ return again.v;
3561
+ const ts = await this.teamStateAsync(live ? live.name : name);
3562
+ if (!ts) {
3563
+ this.teamWeeksCache.delete(key);
3564
+ return null;
3565
+ }
3566
+ const recs = ts.sp ? ts.records.slice() : ts.records;
3567
+ const from = weekBounds(now, WEEKS - 1).from;
3568
+ let cut = recs.length;
3569
+ for (let i = recs.length - 1, older = 0; i >= 0 && older < 200; i--) {
3570
+ if (recs[i].ts >= from) {
3571
+ cut = i;
3572
+ older = 0;
3573
+ }
3574
+ else
3575
+ older++;
3576
+ }
3577
+ const askers = new Set();
3578
+ let firstAskAt = null, lastActAt = null;
3579
+ for (let i = 0; i < recs.length; i++) {
3580
+ const r = recs[i];
3581
+ if (!relayComposed(r)) {
3582
+ if (r.act === "ASK") {
3583
+ askers.add(r.from);
3584
+ if (firstAskAt === null || r.ts < firstAskAt)
3585
+ firstAskAt = r.ts;
3586
+ }
3587
+ if (lastActAt === null || r.ts > lastActAt)
3588
+ lastActAt = r.ts;
3589
+ }
3590
+ if (i % 10_000 === 9_999)
3591
+ await new Promise((x) => setImmediate(x));
3592
+ }
3593
+ const projected = [];
3594
+ for (let i = cut; i < recs.length; i += 5_000) {
3595
+ for (const r of toFlowRecords(recs.slice(i, Math.min(recs.length, i + 5_000))))
3596
+ projected.push(r);
3597
+ await new Promise((x) => setImmediate(x));
3598
+ }
3599
+ const index = await flowIndexAsync(projected, 10_000);
3600
+ const createdAt = ts.allow.all().reduce((min, e) => (min === null || e.first_seen < min ? e.first_seen : min), null);
3601
+ const v = await teamWeeksOfAsync({ name: ts.name, now, records: projected, usage: ts.usage, compactedThrough: ts.compactedThrough, createdAt, askers: [...askers], firstAskAt, lastActAt, index });
3602
+ let bytes = 2_000 + v.askers.length * 40;
3603
+ for (const w of v.people)
3604
+ bytes += w.length * 40;
3605
+ bytes += (v.value[0].answerMs.length + v.value[1].answerMs.length + v.value[0].decisionMs.length + v.value[1].decisionMs.length) * 16;
3606
+ this.teamWeeksCache.set(key, { sig, v }, bytes);
3607
+ return v;
3608
+ });
3609
+ this.teamWeeksFlights.set(flight, p);
3610
+ try {
3611
+ return await p;
3612
+ }
3613
+ finally {
3614
+ this.teamWeeksFlights.delete(flight);
3615
+ }
3616
+ }
3617
+ goalViews = new ByteLru(() => Math.max(1, Math.floor(this.readBounds.viewBytes / 4)));
3618
+ goalFlights = new Map();
3619
+ async goalFlowAsync(name, goalId, now) {
3620
+ if (!/^[a-z]{1,3}_[A-Za-z0-9_-]{4,64}$/.test(goalId))
3621
+ return null;
3622
+ const live = this.spaces.get(spaceKey(name));
3623
+ const safe = live ? safeName(live.name) : safeName(name);
3624
+ const key = `${safe.toLowerCase()}|${goalId}`;
3625
+ const sig = live ? `live:${live.ledger.all().length}` : await this.teamFilesSig(safe);
3626
+ const hit = this.goalViews.get(key);
3627
+ if (hit && hit.sig === sig && now - hit.at < (live ? 15_000 : 30_000))
3628
+ return hit;
3629
+ const flight = `${key}|${sig}`;
3630
+ const running = this.goalFlights.get(flight);
3631
+ if (running)
3632
+ return running;
3633
+ const p = this.coldSlot(async () => {
3634
+ const ts = await this.teamStateAsync(live ? live.name : name);
3635
+ if (!ts)
3636
+ return null;
3637
+ const g = ts.goals.get(goalId);
3638
+ if (!g)
3639
+ return null;
3640
+ const recs = ts.sp ? ts.records.slice() : ts.records;
3641
+ const mine = [];
3642
+ for (let i = 0; i < recs.length; i++) {
3643
+ if (recs[i].goal === goalId)
3644
+ mine.push(recs[i]);
3645
+ if (i % 20_000 === 19_999)
3646
+ await new Promise((x) => setImmediate(x));
3647
+ }
3648
+ const obligations = toFlowObligations([...ts.obligations.values()].filter((o) => o.goal === goalId));
3649
+ const flow = goalFlowOf({ records: toFlowRecords(mine), goal: toFlowGoals([g])[0], obligations, now: Date.now() });
3650
+ const drawn = new Set(flow.nodes.map((n) => n.id));
3651
+ const firstLine = (t) => t.split("\n").find((l) => l.trim()) ?? "";
3652
+ const gists = new Map();
3653
+ for (const r of mine)
3654
+ if (drawn.has(r.id))
3655
+ gists.set(r.id, clipText(r.summary ?? firstLine(r.body), 150));
3656
+ const v = { sig, at: now, flow, gists };
3657
+ let bytes = 4_000 + flow.nodes.length * 260 + flow.open.length * 200;
3658
+ for (const t of gists.values())
3659
+ bytes += 2 * t.length + 60;
3660
+ this.goalViews.set(key, v, bytes);
3661
+ return v;
3662
+ });
3663
+ this.goalFlights.set(flight, p);
3664
+ try {
3665
+ return await p;
3666
+ }
3667
+ finally {
3668
+ this.goalFlights.delete(flight);
3669
+ }
3670
+ }
3671
+ async adminGoal(res, space, id, csrf, A, ip) {
3672
+ let g;
3673
+ try {
3674
+ g = await this.goalFlowAsync(space, id, Date.now());
3675
+ }
3676
+ catch (e) {
3677
+ const code = unreadableCode(e);
3678
+ if (!code)
3679
+ throw e;
3680
+ const nonce = newUiNonce();
3681
+ res.writeHead(503, { ...pageHeaders(nonce), "retry-after": "30" });
3682
+ return void res.end(renderTeamUnreadable({ nonce, name: space, code }));
3683
+ }
3684
+ await this.renderTurn();
3685
+ if (res.destroyed)
3686
+ return;
3687
+ if (!g)
3688
+ return this.json(res, 404, { error: "no such goal on this relay" });
3689
+ A.audit({ event: "admin_goal_view", space, target: g.flow.goal.id, detail: printableLine(g.flow.goal.title, 80), ip });
3690
+ const nonce = newUiNonce();
3691
+ const team = this.spaces.get(spaceKey(space))?.name ?? space;
3692
+ res.writeHead(200, pageHeaders(nonce, { connect: true }));
3693
+ res.end(renderGoal({ nonce, csrf, team, flow: g.flow, gist: (x) => g.gists.get(x) ?? "", cap: GOAL_NODE_CAP }));
3694
+ }
3456
3695
  async teamRecordsAsync(name) {
3457
3696
  const sp = this.spaces.get(spaceKey(name));
3458
3697
  if (sp)
@@ -3605,6 +3844,23 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3605
3844
  entries.push(e);
3606
3845
  await new Promise((r) => setImmediate(r));
3607
3846
  }
3847
+ const weeks = [];
3848
+ for (const e of entries) {
3849
+ try {
3850
+ const w = await this.teamWeeksAsync(e.summary.name, now);
3851
+ if (w)
3852
+ weeks.push(w);
3853
+ }
3854
+ catch (err) {
3855
+ if (!unreadableCode(err))
3856
+ throw err;
3857
+ }
3858
+ await new Promise((r) => setImmediate(r));
3859
+ }
3860
+ const founder = founderView({
3861
+ now, teams: weeks, accounts: accounts.map((a) => ({ username: a.username, created_at: a.created_at, plan: a.plan, status: a.status })),
3862
+ admitted: new Map(entries.map((e) => [e.summary.name, e.admitted])), teamPlans: new Map(entries.map((e) => [e.summary.name, e.summary.plan])),
3863
+ });
3608
3864
  await this.renderTurn();
3609
3865
  if (res.destroyed)
3610
3866
  return;
@@ -3638,6 +3894,7 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3638
3894
  const counts = A.counts();
3639
3895
  const planCounts = A.planCounts();
3640
3896
  const backupAt = A.auditLog({ limit: 1, event: "admin_backup" })[0]?.ts ?? null;
3897
+ const backupOkAt = A.auditLog({ limit: 1, event: "admin_backup_done" })[0]?.ts ?? null;
3641
3898
  let snapshots = 0;
3642
3899
  try {
3643
3900
  snapshots = readdirSync(join(this.dataDir, "backups")).filter((f) => f.startsWith("accounts-") && f.endsWith(".db")).length;
@@ -3651,8 +3908,10 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3651
3908
  version: VERSION, hold: this.upgradeHold, upMs: now - this.startedAt, loopP99: this.loopDelay ? this.loopStats().p99 : null,
3652
3909
  storage: sf ? sf.where : null, teams: names.length, maxTeams: this.limits.maxSpaces,
3653
3910
  codesHour: this.emailSends.filter((s) => now - s.at < 3_600_000).length, codesCap: Number(process.env.PANTHEON_EMAIL_MAX_PER_HOUR) || 200,
3654
- backupAt, snapshots,
3911
+ backupAt, backupOkAt, snapshots,
3655
3912
  },
3913
+ founder, lastActive: Object.fromEntries(weeks.map((w) => [w.name, w.lastActiveAt])),
3914
+ sort: url?.searchParams.get("sort") ?? null, dir: url?.searchParams.get("dir") ?? null,
3656
3915
  accounts: {
3657
3916
  total: accounts.length, paid: Object.entries(planCounts).filter(([n]) => n !== "free").reduce((s, [, v]) => s + v, 0),
3658
3917
  top: [...accounts].sort((a, b) => (lastSeenOf.get(b.id) ?? 0) - (lastSeenOf.get(a.id) ?? 0)).slice(0, 5).map((a) => ({
@@ -3708,23 +3967,7 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3708
3967
  }
3709
3968
  if (readRec)
3710
3969
  A.audit({ event: "admin_message_read", space: v.name, target: readRec.id, detail: `#${readRec.seq} ${readRec.act} from ${readRec.from}`, ip });
3711
- let read = null;
3712
- if (readRec) {
3713
- const meta = (readRec.meta ?? {});
3714
- const kv = [["Message ID", readRec.id]];
3715
- if (readRec.ref)
3716
- kv.push(["Reply to", readRec.ref]);
3717
- if (readRec.goal)
3718
- kv.push(["Goal", `${v.goalTitles.get(readRec.goal) ?? ""} (${readRec.goal})`]);
3719
- if (readRec.role)
3720
- kv.push(["Session role", readRec.role]);
3721
- if (readRec.summary)
3722
- kv.push(["Summary", readRec.summary]);
3723
- for (const k of ["branch", "commit", "remote", "base", "repo_origin", "decision_domains", "defers_to", "affects", "authority", "unverified_domains"])
3724
- if (meta[k] !== undefined)
3725
- kv.push([k.replace(/_/g, " "), typeof meta[k] === "string" ? meta[k] : JSON.stringify(meta[k])]);
3726
- read = { id: readRec.id, body: readRec.body, kv };
3727
- }
3970
+ const read = readRec ? fullMessage(readRec, v.goalTitles) : null;
3728
3971
  const plan = this.spacePlan(v.name);
3729
3972
  const since = now - days * DAY;
3730
3973
  const byCode = new Map();
@@ -3759,9 +4002,39 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3759
4002
  retained: records.length,
3760
4003
  allOpen: url.searchParams.get("open") === "all",
3761
4004
  });
3762
- res.writeHead(200, pageHeaders(nonce));
4005
+ res.writeHead(200, pageHeaders(nonce, { connect: true }));
3763
4006
  res.end(html);
3764
4007
  }
4008
+ async adminMessage(res, name, id, A, ip) {
4009
+ const out = (code, body) => { const s = JSON.stringify(body); res.writeHead(code, { "content-type": "application/json", "cache-control": "no-store", "x-content-type-options": "nosniff", "content-length": Buffer.byteLength(s) }); res.end(s); };
4010
+ if (!name || !id)
4011
+ return out(400, { error: "name and id are required" });
4012
+ let v, records;
4013
+ try {
4014
+ v = await this.teamViewAsync(name, 7, Date.now());
4015
+ if (!v)
4016
+ return out(404, { error: `no space "${name}" on this relay` });
4017
+ records = await this.teamRecordsAsync(v.live ? v.name : name);
4018
+ }
4019
+ catch (e) {
4020
+ const code = unreadableCode(e);
4021
+ if (!code)
4022
+ throw e;
4023
+ return out(503, { error: `this team's history can't be read right now (${code})` });
4024
+ }
4025
+ if (res.destroyed)
4026
+ return;
4027
+ let rec = null;
4028
+ for (let i = records.length - 1; i >= 0; i--)
4029
+ if (records[i].id === id) {
4030
+ rec = records[i];
4031
+ break;
4032
+ }
4033
+ if (!rec)
4034
+ return out(404, { error: "that message is no longer kept (old acts of closed goals are compacted)" });
4035
+ A.audit({ event: "admin_message_read", space: v.name, target: rec.id, detail: `#${rec.seq} ${rec.act} from ${rec.from}`, ip });
4036
+ out(200, { ...fullMessage(rec, v.goalTitles), seq: rec.seq });
4037
+ }
3765
4038
  adminExport(res, A, url) {
3766
4039
  const table = url.searchParams.get("table") ?? "audit";
3767
4040
  const format = url.searchParams.get("format") === "csv" ? "csv" : "json";
@@ -3810,12 +4083,19 @@ Sign in with a code sent to this address at /view on the relay.`).catch(() => fa
3810
4083
  }
3811
4084
  });
3812
4085
  tar.stdout.pipe(res);
4086
+ let bytes = 0;
4087
+ tar.stdout.on("data", (c) => { bytes += c.length; });
3813
4088
  tar.on("close", (code) => {
3814
4089
  if (code !== 0) {
3815
4090
  this.log(`! backup archive exited ${code}: ${err.trim()}`);
3816
4091
  if (!res.headersSent)
3817
4092
  this.json(res, 500, { error: `tar exited ${code}` });
3818
4093
  }
4094
+ else if (!res.destroyed && res.headersSent)
4095
+ res.once("finish", () => { try {
4096
+ A.audit({ event: "admin_backup_done", detail: `${bytes} bytes` });
4097
+ }
4098
+ catch { } });
3819
4099
  res.end();
3820
4100
  });
3821
4101
  res.on("close", () => { try {
package/dist/spend.js CHANGED
@@ -62,7 +62,7 @@ export function finishRun(id, end, home) {
62
62
  return;
63
63
  }
64
64
  const { started: _s, ...was } = b.runs[i];
65
- b.runs[i] = { ...was, ...end };
65
+ b.runs[i] = { ...was, ...end, ...(typeof was.at === "number" && was.at <= end.at ? { started_at: was.started_at ?? was.at } : {}) };
66
66
  write(b, home);
67
67
  }
68
68
  export function closeStartedRun(id, summary, fallback, home) {
@@ -80,6 +80,29 @@ export function closeStartedRun(id, summary, fallback, home) {
80
80
  b.runs[i] = { ...was, ok: false, summary };
81
81
  write(b, home);
82
82
  }
83
+ export function runsToday(own, o = {}) {
84
+ const now = o.now ?? Date.now();
85
+ const midnight = new Date(now);
86
+ midnight.setHours(0, 0, 0, 0);
87
+ const mine = new Set(own);
88
+ const runs = read(o.home).runs.filter((r) => r.at >= midnight.getTime() && r.at <= now + 60_000 && !mine.has(r.triggeredBy));
89
+ let ms = 0, timed = 0;
90
+ for (const r of runs) {
91
+ if (r.started || typeof r.started_at !== "number" || !Number.isFinite(r.started_at) || r.started_at > r.at)
92
+ continue;
93
+ ms += Math.min(r.at - r.started_at, 24 * 3600_000);
94
+ timed++;
95
+ }
96
+ return { n: runs.length, minutes: timed ? (ms < 60_000 ? 0 : Math.ceil(ms / 60_000)) : null, failed: runs.filter((r) => !r.ok && !r.started).length };
97
+ }
98
+ export function runsTodayLine(r) {
99
+ if (!r || !(r.n > 0))
100
+ return null;
101
+ const what = `Your agent ran ${r.n} teammate request${r.n === 1 ? "" : "s"} today`;
102
+ if (r.minutes === null)
103
+ return what;
104
+ return `${what} (${r.minutes < 1 ? "<1" : r.minutes} min)`;
105
+ }
83
106
  export function since(ms, home) {
84
107
  const from = Date.now() - ms;
85
108
  const runs = read(home).runs.filter((r) => r.at > from);