spur-board 0.47.1 → 0.48.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/dist/cli.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { $ as configSchema, H as ERRORS, f as roleCanUseOperation, it as SLACK_BOT_SCOPES, o as SYSTEMD_SERVICE_SETTINGS, p as OPERATIONS, r as requestHashOf, tt as requiredSecretKeys } from "./src-DGT9Wspi.mjs";
2
- import { a as CliError, c as escapeTerminalControls, i as requestTokenEnrollment, n as fetchTokenStatus, o as errorExitCode, r as requestOperation, s as renderCliError } from "./client-D8BEfeGz.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-Chv5ZHE8.mjs";
1
+ import { $ as configSchema, H as ERRORS, f as roleCanUseOperation, it as SLACK_BOT_SCOPES, o as SYSTEMD_SERVICE_SETTINGS, p as OPERATIONS, r as requestHashOf, tt as requiredSecretKeys } from "./src-Cj3-z45G.mjs";
2
+ import { a as CliError, c as escapeTerminalControls, i as requestTokenEnrollment, n as fetchTokenStatus, o as errorExitCode, r as requestOperation, s as renderCliError } from "./client-DJ0swpg5.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, d as resolveDaemonAddress, f as tokenInFolder, i as fileVerdictCache, l as loadEnrollmentConfig, n as cliPackageVersion, o as configFile, s as dataDirectory, t as checkCatalog, u as readConfiguredPort } from "./config-BMYEBQfk.mjs";
4
4
  import { createHash, randomBytes, randomUUID } from "node:crypto";
5
5
  import { accessSync, chmodSync, closeSync, constants, cpSync, existsSync, ftruncateSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync, writeSync } from "node:fs";
6
6
  import { homedir, hostname, userInfo } from "node:os";
@@ -319,6 +319,7 @@ const remoteBaseIds = [
319
319
  "spur.api",
320
320
  "spur.send",
321
321
  "operator.path",
322
+ "operator.tokens",
322
323
  "curator.sessions"
323
324
  ];
324
325
  const remoteSlackIds = [
@@ -1,4 +1,4 @@
1
- import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-DGT9Wspi.mjs";
1
+ import { G as errorEnvelopeSchema, H as ERRORS, W as errorContextSchema, g as renderJsonError, q as successEnvelopeSchema } from "./src-Cj3-z45G.mjs";
2
2
  import { randomUUID } from "node:crypto";
3
3
  import { z } from "zod";
4
4
  import { request } from "node:http";
package/dist/client.mjs CHANGED
@@ -1,2 +1,2 @@
1
- import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-D8BEfeGz.mjs";
1
+ import { i as requestTokenEnrollment, n as fetchTokenStatus, r as requestOperation, t as fetchCatalogVersion } from "./client-DJ0swpg5.mjs";
2
2
  export { fetchCatalogVersion, fetchTokenStatus, requestOperation, requestTokenEnrollment };
@@ -1,5 +1,5 @@
1
- import { $ as configSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, p as OPERATIONS } from "./src-DGT9Wspi.mjs";
2
- import { a as CliError, t as fetchCatalogVersion } from "./client-D8BEfeGz.mjs";
1
+ import { $ as configSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, p as OPERATIONS } from "./src-Cj3-z45G.mjs";
2
+ import { a as CliError, t as fetchCatalogVersion } from "./client-DJ0swpg5.mjs";
3
3
  import { randomUUID } from "node:crypto";
4
4
  import { closeSync, constants, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, renameSync, statSync, unlinkSync, writeFileSync } from "node:fs";
5
5
  import { homedir } from "node:os";
package/dist/daemon.mjs CHANGED
@@ -1,13 +1,14 @@
1
- import { $ as configSchema, A as parseRingMarker, B as parseRef$1, C as userIdSchema, D as SESSION_HEALTH_STATES, E as REVIEW_STATES, F as ticketFactsSchema, H as ERRORS, I as actorIdSchema, K as ok, L as encodeActorId, M as prRefSchema, N as ringMarker, O as SESSION_STATUSES, P as sessionFactsSchema, Q as RESERVED_PROJECT, R as errorCodeOf, S as messageRefSchema, T as eventPayloadSchemas, U as err, V as taskKeySchema, Y as DEFAULT_LINK, Z as DEFAULT_SLACK_COMMAND, a as BOARD_TICK_MS, b as inboundEventSchema, c as batchSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, f as roleCanUseOperation, h as renderHttpProblem, i as tokenRequestSchema, it as SLACK_BOT_SCOPES, j as prFactsSchema, k as isExternalAuthor, l as entityRefSchema, m as turnHandedSchema, n as TOKEN_REQUEST_LIMITS, nt as COLUMN_IDS, p as OPERATIONS, q as successEnvelopeSchema, r as requestHashOf, rt as DISPATCHER_MODES, s as AdapterError, t as assertNever, tt as requiredSecretKeys, u as sourceCursorSchema, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseActorId } from "./src-DGT9Wspi.mjs";
1
+ import { $ as configSchema, A as parseRingMarker, B as parseRef$1, C as userIdSchema, D as SESSION_HEALTH_STATES, E as REVIEW_STATES, F as ticketFactsSchema, H as ERRORS, I as actorIdSchema, K as ok, L as encodeActorId, M as prRefSchema, N as ringMarker, O as SESSION_STATUSES, P as sessionFactsSchema, Q as RESERVED_PROJECT, R as errorCodeOf, S as messageRefSchema, T as eventPayloadSchemas, U as err, V as taskKeySchema, Y as DEFAULT_LINK, Z as DEFAULT_SLACK_COMMAND, a as BOARD_TICK_MS, b as inboundEventSchema, c as batchSchema, d as buildCatalogSnapshot, et as plainHttpAllowed, f as roleCanUseOperation, h as renderHttpProblem, i as tokenRequestSchema, it as SLACK_BOT_SCOPES, j as prFactsSchema, k as isExternalAuthor, l as entityRefSchema, m as turnHandedSchema, n as TOKEN_REQUEST_LIMITS, nt as COLUMN_IDS, p as OPERATIONS, q as successEnvelopeSchema, r as requestHashOf, rt as DISPATCHER_MODES, s as AdapterError, t as assertNever, tt as requiredSecretKeys, u as sourceCursorSchema, v as SPACE_IDS, w as EVENT_KINDS, x as interactionRefSchema, y as conversationRefSchema, z as parseActorId } from "./src-Cj3-z45G.mjs";
2
2
  import { createRequire } from "node:module";
3
3
  import { createHash, randomUUID } from "node:crypto";
4
4
  import { chmodSync, closeSync, existsSync, fchmodSync, fstatSync, fsyncSync, ftruncateSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeSync } from "node:fs";
5
- import { homedir } from "node:os";
5
+ import { homedir, hostname } from "node:os";
6
6
  import path, { basename, dirname, isAbsolute, join, normalize, resolve } from "node:path";
7
7
  import { z } from "zod";
8
8
  import YAML from "yaml";
9
9
  import { spawn, spawnSync } from "node:child_process";
10
10
  import { parseEnv } from "node:util";
11
+ import { lstat } from "node:fs/promises";
11
12
  import Database from "better-sqlite3";
12
13
  import { Kysely, SqliteDialect, sql } from "kysely";
13
14
  import { AsyncLocalStorage } from "node:async_hooks";
@@ -9213,6 +9214,10 @@ const MAX_PENDING_REQUESTS = 10;
9213
9214
  /** Days an expired or denied request stays after its decision before the daily purge drops it. */
9214
9215
  const TOKEN_REQUEST_RETENTION_DAYS = 7;
9215
9216
  const DAY_MS$1 = 864e5;
9217
+ /** An approved token's last use is written at most once per token per this interval. */
9218
+ const TOKEN_USE_INTERVAL_MS = 5 * 6e4;
9219
+ /** The longest attention line; the doctor fix limit is the same. */
9220
+ const ATTENTION_LINE_MAX = 300;
9216
9221
  function effectiveStatus(row, at) {
9217
9222
  return row.status === "pending" && row.expires_at <= at.toISOString() ? "expired" : row.status;
9218
9223
  }
@@ -9309,7 +9314,8 @@ async function decideTokenInTransaction(trx, itemId, decision, at) {
9309
9314
  const next = decision === "approve" ? "approved" : "denied";
9310
9315
  await trx.updateTable("operator_token").set({
9311
9316
  status: next,
9312
- decided_at: at.toISOString()
9317
+ decided_at: at.toISOString(),
9318
+ ...next === "approved" ? { approved_at: at.toISOString() } : {}
9313
9319
  }).where("id", "=", row.id).execute();
9314
9320
  await journalToken(trx, decision === "approve" ? "token_approved" : "token_denied", row.name, at);
9315
9321
  await clearItem(trx, row.item_id, at, "operator");
@@ -9343,11 +9349,27 @@ async function purgeEndedTokenRequests(store, at) {
9343
9349
  return Number(deleted.numDeletedRows);
9344
9350
  });
9345
9351
  }
9346
- /** Hash lookup uses the unique index and checks durable state on every call. */
9347
- async function verifyOperatorToken(store, token) {
9352
+ /**
9353
+ * Hash lookup uses the unique index and checks durable state on every call. An approved token's
9354
+ * use at `at` is recorded when its last recorded use is older than `TOKEN_USE_INTERVAL_MS`; a
9355
+ * failed write goes to `onUseError` and never changes the result.
9356
+ */
9357
+ async function verifyOperatorToken(store, token, at, onUseError) {
9348
9358
  const hash = createHash("sha256").update(token).digest("hex");
9349
- const row = await store.db.selectFrom("operator_token").select(["name", "status"]).where("hash", "=", hash).executeTakeFirst();
9350
- return row?.status === "approved" ? { name: row.name } : null;
9359
+ const row = await store.db.selectFrom("operator_token").select([
9360
+ "name",
9361
+ "status",
9362
+ "last_used_at"
9363
+ ]).where("hash", "=", hash).executeTakeFirst();
9364
+ if (row?.status !== "approved") return null;
9365
+ const usedAt = at.toISOString();
9366
+ const staleBy = (/* @__PURE__ */ new Date(at.getTime() - TOKEN_USE_INTERVAL_MS)).toISOString();
9367
+ if (row.last_used_at === null || row.last_used_at <= staleBy) try {
9368
+ await store.transaction((trx) => trx.updateTable("operator_token").set({ last_used_at: usedAt }).where("hash", "=", hash).where("status", "=", "approved").where((eb) => eb.or([eb("last_used_at", "is", null), eb("last_used_at", "<=", staleBy)])).execute());
9369
+ } catch (err) {
9370
+ onUseError(err);
9371
+ }
9372
+ return { name: row.name };
9351
9373
  }
9352
9374
  /** Read-only: an expired pending row is reported as expired but left for the sweep. */
9353
9375
  async function tokenStatusByHash(store, hash, at) {
@@ -9364,7 +9386,10 @@ function tokenListQuery(clock) {
9364
9386
  return { tokens: rows.map((row) => ({
9365
9387
  name: row.name,
9366
9388
  folder: row.folder,
9367
- status: effectiveStatus(row, at)
9389
+ status: effectiveStatus(row, at),
9390
+ createdAt: row.requested_at,
9391
+ approvedAt: row.approved_at,
9392
+ lastUsedAt: row.last_used_at
9368
9393
  })) };
9369
9394
  }
9370
9395
  };
@@ -9390,6 +9415,65 @@ const tokenRevokeMutation = {
9390
9415
  };
9391
9416
  }
9392
9417
  };
9418
+ /**
9419
+ * Approved tokens unused for `unusedAfterDays` days (last use, else approval, else request time)
9420
+ * or whose token file is gone. `probe` answers whether the token file is present, or null when
9421
+ * it cannot tell (another host, an unreadable folder); it runs after the read, outside any
9422
+ * transaction.
9423
+ */
9424
+ async function tokenAttention(store, at, unusedAfterDays, probe) {
9425
+ const rows = await store.db.selectFrom("operator_token").select([
9426
+ "name",
9427
+ "folder",
9428
+ "host",
9429
+ "requested_at",
9430
+ "approved_at",
9431
+ "last_used_at"
9432
+ ]).where("status", "=", "approved").orderBy("id").execute();
9433
+ const cutoff = (/* @__PURE__ */ new Date(at.getTime() - unusedAfterDays * DAY_MS$1)).toISOString();
9434
+ const attention = {
9435
+ fileMissing: [],
9436
+ unused: []
9437
+ };
9438
+ for (const row of rows) if (await probe({
9439
+ folder: row.folder,
9440
+ host: row.host
9441
+ }) === false) attention.fileMissing.push(row.name);
9442
+ else if ((row.last_used_at ?? row.approved_at ?? row.requested_at) <= cutoff) attention.unused.push(row.name);
9443
+ return attention;
9444
+ }
9445
+ /**
9446
+ * One line naming the tokens in `attention`, at most 300 characters, or null when none needs
9447
+ * attention. Shared by `board doctor` and the daily digest. A name enrollment would refuse today
9448
+ * is counted, never printed; trailing names that do not fit become "and N more".
9449
+ */
9450
+ function tokenAttentionLine(attention, unusedAfterDays) {
9451
+ const total = attention.fileMissing.length + attention.unused.length;
9452
+ if (total === 0) return null;
9453
+ const head = `${String(total)} operator ${total === 1 ? "token needs" : "tokens need"} attention (revoke any that nothing uses with \`board token revoke <name>\`)`;
9454
+ const printableNames = (names) => names.filter((name) => tokenRequestSchema.shape.name.safeParse(name).success);
9455
+ const printable = [{
9456
+ label: "no token file",
9457
+ names: printableNames(attention.fileMissing)
9458
+ }, {
9459
+ label: `unused for ${String(unusedAfterDays)}+ days`,
9460
+ names: printableNames(attention.unused)
9461
+ }];
9462
+ const named = printable.reduce((n, group) => n + group.names.length, 0);
9463
+ for (let shown = named; shown > 0; shown -= 1) {
9464
+ let left = shown;
9465
+ const parts = [];
9466
+ for (const { label, names } of printable) {
9467
+ const listed = names.slice(0, left);
9468
+ left -= listed.length;
9469
+ if (listed.length > 0) parts.push(`${label}: ${listed.join(", ")}`);
9470
+ }
9471
+ const more = total - shown;
9472
+ const line = `${head}: ${parts.join("; ")}${more > 0 ? ` and ${String(more)} more` : ""}`;
9473
+ if (line.length <= ATTENTION_LINE_MAX) return line;
9474
+ }
9475
+ return `${head}: ${String(total)} not named`;
9476
+ }
9393
9477
  //#endregion
9394
9478
  //#region ../core/src/api/identity.ts
9395
9479
  function sessionActor(project, session, config) {
@@ -20982,6 +21066,29 @@ function warning(id, fix) {
20982
21066
  fix
20983
21067
  };
20984
21068
  }
21069
+ /**
21070
+ * Whether a token's folder on this host still holds `.spur-board/token` as a regular file. Null
21071
+ * for a token of another host, or when the folder cannot be read for another reason.
21072
+ */
21073
+ async function tokenFilePresent(token) {
21074
+ if (token.host !== hostname()) return null;
21075
+ try {
21076
+ return (await lstat(join(token.folder, ".spur-board", "token"))).isFile();
21077
+ } catch (err) {
21078
+ const code = err instanceof Error && "code" in err ? err.code : void 0;
21079
+ return code === "ENOENT" || code === "ENOTDIR" ? false : null;
21080
+ }
21081
+ }
21082
+ async function operatorTokensCheck(ctx, config) {
21083
+ const days = config.operatorAccess.unusedAfterDays;
21084
+ const line = tokenAttentionLine(await tokenAttention(ctx.store, new Date(ctx.clock.now()), days, tokenFilePresent), days);
21085
+ return line === null ? {
21086
+ id: "operator.tokens",
21087
+ status: "pass",
21088
+ blocking: false,
21089
+ fix: null
21090
+ } : warning("operator.tokens", line);
21091
+ }
20985
21092
  async function request(ctx, fetcher, deadlineMs, id, url, init = {}) {
20986
21093
  try {
20987
21094
  return await ctx.logCall(`doctor.${id}`, () => fetcher(url, {
@@ -21110,6 +21217,7 @@ async function runDaemonDoctor(ctx, productVersion, fetcher = fetch, { deadlineM
21110
21217
  const operatorProject = config.projects.some((project) => project.spurProjects.some((spurProject) => spurProject.role === "operator"));
21111
21218
  const token = operatorProject ? void 0 : await ctx.store.db.selectFrom("operator_token").select("id").where("status", "=", "approved").executeTakeFirst();
21112
21219
  checks.push(check("operator.path", operatorProject || token !== void 0, "Configure a Spur project with the operator role or approve a named operator token."));
21220
+ checks.push(await operatorTokensCheck(ctx, config));
21113
21221
  checks.push(curatorSessionsCheck(await curatorSessions(ctx.store.db, config)));
21114
21222
  return {
21115
21223
  version: productVersion,
@@ -21149,7 +21257,9 @@ function createHttpModule(ctx, options = {}) {
21149
21257
  stopping: () => ctx.state() === "stopping",
21150
21258
  clock: ctx.clock,
21151
21259
  lookupSession: (id) => ctx.logCall("spur.session.lookup", () => lookupLiveSession(ctx.config.adapters.spur.baseUrl, id, options.fetcher)),
21152
- verifyToken: (token) => verifyOperatorToken(ctx.store, token),
21260
+ verifyToken: (token) => verifyOperatorToken(ctx.store, token, new Date(ctx.clock.now()), (err) => {
21261
+ ctx.log.warn({ err }, "token use not recorded");
21262
+ }),
21153
21263
  registry: options.registry ?? {},
21154
21264
  ...options.afterOperation === void 0 ? {} : { afterOperation: options.afterOperation },
21155
21265
  ...options.runOperation === void 0 ? {} : { runOperation: options.runOperation },
package/dist/mcp.mjs CHANGED
@@ -1,6 +1,6 @@
1
- import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-DGT9Wspi.mjs";
2
- import { a as CliError, r as requestOperation } from "./client-D8BEfeGz.mjs";
3
- import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-Chv5ZHE8.mjs";
1
+ import { H as ERRORS, _ as renderMcpError, p as OPERATIONS } from "./src-Cj3-z45G.mjs";
2
+ import { a as CliError, r as requestOperation } from "./client-DJ0swpg5.mjs";
3
+ import { a as memoryVerdictCache, c as loadClientConfig, r as compareCatalogs, t as checkCatalog } from "./config-BMYEBQfk.mjs";
4
4
  import { randomUUID } from "node:crypto";
5
5
  import { readFileSync } from "node:fs";
6
6
  import { z } from "zod";
@@ -0,0 +1,7 @@
1
+ -- When an operator token was approved, and when an authenticated call last used it. Revoke
2
+ -- overwrites `decided_at`, so the backfill sets `approved_at` only for rows still approved: a token
3
+ -- revoked before this migration keeps `approved_at` NULL. `last_used_at` is NULL until the first
4
+ -- call with the token and is written at most once per token per few minutes.
5
+ ALTER TABLE operator_token ADD COLUMN approved_at TEXT;
6
+ ALTER TABLE operator_token ADD COLUMN last_used_at TEXT;
7
+ UPDATE operator_token SET approved_at = decided_at WHERE status = 'approved';
@@ -444,6 +444,7 @@ const configSchema = z.strictObject({
444
444
  archive: z.strictObject({ doneWeekday: z.enum(WEEKDAYS).default("saturday").describe("Weekday whose local midnight, in digest.tz, is the weekly archive slot: tasks done before it are archived then, once their repos have a complete poll since their last change. A slot missed while the daemon was down is applied on the next tick.") }).prefault({}),
445
445
  digest: z.strictObject({ tz: z.string().refine(isTimeZone, "Unknown IANA time zone").describe("IANA time zone, such as Europe/Berlin, for the archive.doneWeekday slot and the times shown in resolved feed lines.") }),
446
446
  commands: z.strictObject({ retentionDays: z.int().min(1).default(7).describe("Days the board keeps each caller's mutation --key with its input and result. In that time the same caller and key with the same input returns the stored result, and with a different input the call is refused. A daily job deletes older keys.") }).prefault({}),
447
+ operatorAccess: z.strictObject({ unusedAfterDays: z.int().min(1).max(3650).default(14).describe("Days an approved operator access key from board token create may go unused before board doctor warns about it.") }).prefault({}),
447
448
  doorbells: z.strictObject({
448
449
  firstRetryMs: durationMs(12e4, "Wait after the first unanswered doorbell"),
449
450
  secondRetryMs: durationMs(3e5, "Wait after the second unanswered doorbell"),
@@ -2586,16 +2587,19 @@ const OPERATIONS = [
2586
2587
  defineOperation({
2587
2588
  id: "token.list",
2588
2589
  kind: "query",
2589
- description: "List named operator tokens and their current status.",
2590
+ description: "List named operator tokens with their status and when each was created, approved and last used.",
2590
2591
  mcp: {
2591
- whenToUse: "Inspect named operator tokens and their current status.",
2592
+ whenToUse: "Inspect named operator tokens, their status, and when each was approved and last used.",
2592
2593
  whenNotToUse: "Use token_revoke to disable a token."
2593
2594
  },
2594
2595
  input: z.strictObject({}),
2595
2596
  output: z.strictObject({ tokens: z.array(z.strictObject({
2596
2597
  name: tokenName,
2597
2598
  folder: z.string().min(1).describe("Folder where the token file was created."),
2598
- status: tokenStatus
2599
+ status: tokenStatus,
2600
+ createdAt: z.iso.datetime().describe("When the token was requested, ISO 8601 UTC."),
2601
+ approvedAt: z.iso.datetime().nullable().describe("When the token was approved, ISO 8601 UTC; null when it never was, or was revoked before approval times were kept."),
2602
+ lastUsedAt: z.iso.datetime().nullable().describe("When a call last authenticated with the token, ISO 8601 UTC, recorded at most once every 5 minutes; null before the first call.")
2599
2603
  })).describe("Named tokens in creation order.") }),
2600
2604
  grants: operatorOnly,
2601
2605
  errors: [],
@@ -2610,7 +2614,10 @@ const OPERATIONS = [
2610
2614
  output: { tokens: [{
2611
2615
  name: "desk",
2612
2616
  folder: "workspace/desk",
2613
- status: "approved"
2617
+ status: "approved",
2618
+ createdAt: "2026-11-04T10:00:00.000Z",
2619
+ approvedAt: "2026-11-04T10:02:00.000Z",
2620
+ lastUsedAt: "2026-11-05T09:30:00.000Z"
2614
2621
  }] }
2615
2622
  }]
2616
2623
  }),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "spur-board",
3
- "version": "0.47.1",
3
+ "version": "0.48.0",
4
4
  "license": "MIT",
5
5
  "engines": {
6
6
  "node": "^24.12.0 || ^26.0.0"