@vercel/board 0.40.0 → 0.42.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.
Files changed (91) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-Bl_k_Hpa.mjs → access-BgBiaCyx.mjs} +2 -2
  3. package/dist/access.d.mts +6 -6
  4. package/dist/access.mjs +5 -5
  5. package/dist/{actors-yBRWTpt5.mjs → actors-DkZsnMgA.mjs} +59 -40
  6. package/dist/{auth-DtmZzlHm.d.mts → auth-Bn8J_1F2.d.mts} +12 -30
  7. package/dist/{auth-C8URZHLx.mjs → auth-Ft4AJptx.mjs} +9 -19
  8. package/dist/{backend-BW5NbBsp.d.mts → backend-DMrK55mU.d.mts} +137 -48
  9. package/dist/backend-local.d.mts +1 -1
  10. package/dist/backend-local.mjs +1 -1
  11. package/dist/{chat-provider-1WKsLEnM.mjs → chat-provider-CPZg2MQb.mjs} +2 -2
  12. package/dist/{chat-provider-Bbb9JguG.d.mts → chat-provider-Cgkh9xJw.d.mts} +2 -2
  13. package/dist/cli-commands.d.mts +1 -1
  14. package/dist/cli-commands.mjs +1 -1
  15. package/dist/cli-embedded.d.mts +10 -5
  16. package/dist/cli-embedded.mjs +8 -6
  17. package/dist/cli.mjs +8 -13
  18. package/dist/{commands-BJLocuXj.d.mts → commands-CrEVjASe.d.mts} +8 -30
  19. package/dist/{commands-D6VWegVY.mjs → commands-QRD0U9AQ.mjs} +30 -101
  20. package/dist/{conformance-BWhZ0k8T.mjs → conformance-BORt5nky.mjs} +139 -109
  21. package/dist/conformance.d.mts +9 -8
  22. package/dist/conformance.mjs +1 -1
  23. package/dist/digest-CKC0Rmy1.mjs +4 -0
  24. package/dist/{engine-Djif8XVk.mjs → engine-BVHSH2Kn.mjs} +11 -12
  25. package/dist/{errors-CNRJqUuL.mjs → errors-DUzpDSrJ.mjs} +112 -30
  26. package/dist/{events-C6HwB046.mjs → events-BT8y_81j.mjs} +2 -2
  27. package/dist/{exports-C2OWIbLU.mjs → exports-BfNXPHN_.mjs} +473 -174
  28. package/dist/exports-Bw_OYNRl.d.mts +4 -0
  29. package/dist/{external-CHDxWIVf.mjs → external-DymyhUzl.mjs} +1 -1
  30. package/dist/{index-Cuxbz_E0.d.mts → index-CydxnBND.d.mts} +2 -2
  31. package/dist/index.d.mts +6 -6
  32. package/dist/index.mjs +6 -5
  33. package/dist/index.node.d.mts +6 -6
  34. package/dist/index.node.mjs +3 -3
  35. package/dist/inspect/app.js +41 -41
  36. package/dist/inspect/engine.js +2 -2
  37. package/dist/{inspect-cGcP8ZO9.mjs → inspect-CniRRiJ2.mjs} +6 -6
  38. package/dist/inspect-HlHh7OXa.mjs +2 -0
  39. package/dist/{local-CsleYuyM.mjs → local-CWLPYoiY.mjs} +130 -359
  40. package/dist/{main-D97xuqWZ.mjs → main-aVEEoc60.mjs} +429 -139
  41. package/dist/{memory-BvVoglGv.mjs → memory-DhduVbUu.mjs} +2 -2
  42. package/dist/{mentions-CT2bN5eP.mjs → mentions-DfZGp3B-.mjs} +1 -1
  43. package/dist/{middleware-BF9vnPPS.mjs → middleware-0DUFrav-.mjs} +2 -2
  44. package/dist/{origin-DLCmrwmE.mjs → origin-DAyYeDuW.mjs} +7 -36
  45. package/dist/{page-6BTCZWGY.mjs → page-BD6ygU49.mjs} +2 -2
  46. package/dist/page-BiJVe-7R.mjs +2 -0
  47. package/dist/{provider-YqkF1E2k.d.mts → provider-dY54GFNz.d.mts} +1 -25
  48. package/dist/{routes-CAjd5ARa.d.mts → routes-By9lmvUD.d.mts} +1 -63
  49. package/dist/{schemas-AZkxk06N.mjs → schemas-DAzSsgWk.mjs} +8 -3
  50. package/dist/{serve-Cs-e0Jke.mjs → serve-BnBqi0sw.mjs} +5 -5
  51. package/dist/{server-CIfMdIt3.mjs → server-Bcpkt6TS.mjs} +79 -131
  52. package/dist/{serving-B4l0nLng.mjs → serving-hcxzaCCO.mjs} +1 -1
  53. package/dist/{sql-Bv-RQu8n.mjs → sql-P9g-rLIF.mjs} +3 -3
  54. package/dist/{sqlite-D4mkYihG.mjs → sqlite-B3rCcIof.mjs} +2 -2
  55. package/dist/{sqlite-db-BraLvHtf.mjs → sqlite-db-D0Fyju-4.mjs} +1 -1
  56. package/dist/sync-chat-sdk.d.mts +2 -2
  57. package/dist/sync-chat-sdk.mjs +2 -2
  58. package/dist/sync-github.d.mts +2 -2
  59. package/dist/sync-github.mjs +2 -2
  60. package/dist/sync-linear.d.mts +3 -3
  61. package/dist/sync-linear.mjs +2 -2
  62. package/dist/sync-slack.d.mts +3 -3
  63. package/dist/sync-slack.mjs +4 -4
  64. package/dist/sync.d.mts +2 -2
  65. package/dist/sync.mjs +2 -2
  66. package/dist/{tokens-CrrXAVGz.mjs → tokens-BSMpTPEe.mjs} +4 -4
  67. package/docs/01-board/01-mounting.md +12 -17
  68. package/docs/01-board/03-identity.md +45 -39
  69. package/docs/01-board/04-messages.md +3 -1
  70. package/docs/01-board/05-reading.md +8 -2
  71. package/docs/01-board/06-watchers.md +15 -10
  72. package/docs/01-board/07-schedules.md +6 -2
  73. package/docs/01-board/09-access.md +59 -111
  74. package/docs/02-sync/01-overview.md +5 -2
  75. package/docs/02-sync/03-slack.md +12 -12
  76. package/docs/03-guides/01-coding-agents.md +18 -22
  77. package/docs/03-guides/02-inspector.md +4 -5
  78. package/docs/03-guides/03-ci.md +7 -26
  79. package/docs/03-guides/04-triage.md +2 -2
  80. package/docs/03-guides/05-agent-factory.md +7 -9
  81. package/docs/03-guides/06-sandboxed-agents.md +149 -0
  82. package/docs/04-reference/01-cli.md +59 -90
  83. package/docs/04-reference/02-board.md +53 -37
  84. package/docs/04-reference/03-http.md +32 -53
  85. package/docs/04-reference/05-conformance.md +37 -18
  86. package/docs/index.md +4 -4
  87. package/package.json +1 -1
  88. package/dist/digest-D32GV_mX.mjs +0 -4
  89. package/dist/exports-FyRBIAMs.d.mts +0 -4
  90. package/dist/inspect-CLy6FrOZ.mjs +0 -2
  91. package/dist/page-BnY8FhPn.mjs +0 -2
@@ -1,17 +1,17 @@
1
- import { a as forbidden$1, c as toErrorResponse, f as duration, g as fileName, h as IMPORT_BYTES_MAX, i as duplicateId, l as unauthorized, m as DIRECT_UPLOAD_BYTES_MAX, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-CNRJqUuL.mjs";
2
- import { _ as actorKind, a as CAN_MAX, c as Handle, d as Labels, g as SeenActorKind, h as RemoteWatcherId, i as Author, l as LabelKey, m as MessageText, n as Attachment, o as ChannelPath, p as MessageId, s as Emoji, t as ActorId, v as platformAvatar, y as storable } from "./schemas-AZkxk06N.mjs";
3
- import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-CHDxWIVf.mjs";
1
+ import { _ as IMPORT_BYTES_MAX, a as forbidden$1, b as mediaType, c as toErrorResponse, f as duration, g as DIRECT_UPLOAD_BYTES_MAX, h as ATTACHMENT_BYTES_MAX, i as duplicateId, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as fileName } from "./errors-DUzpDSrJ.mjs";
2
+ import { _ as actorKind, a as CAN_MAX, b as storable, c as Handle, d as Labels, g as SeenActorKind, h as RemoteWatcherId, i as Author, l as LabelKey, m as MessageText, n as Attachment, o as ChannelPath, p as MessageId, s as Emoji, t as ActorId, v as authorView, y as platformAvatar } from "./schemas-DAzSsgWk.mjs";
3
+ import { a as Link, i as ExternalTarget, n as ExternalEvent, o as Origin } from "./external-DymyhUzl.mjs";
4
4
  import { a as SCHEMA_DESCRIPTION_MAX, c as canonical, d as parseSchemaId, f as schemaId, i as BUILT_IN_SCHEMAS, l as checkDefinition, n as blocksIn, o as SCHEMA_NAME, s as SCHEMA_VERSION_MAX, u as isBuiltInName } from "./blocks-CVoBC7ur.mjs";
5
- import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-DLCmrwmE.mjs";
6
- import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-BF9vnPPS.mjs";
7
- import { a as canText, c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-Bl_k_Hpa.mjs";
8
- import { C as workflowPath, c as checkGrant, f as grantIssuers, h as joined, l as checkPrincipal, m as issuerName, n as DEFAULT_CAN, o as authenticates, r as GITHUB_ISSUER, s as checkCan, t as BOARD_TOKEN_PREFIX, v as removes, w as wroteAs, y as tokenHash } from "./auth-C8URZHLx.mjs";
5
+ import { a as compileWatcher, c as METHODS, h as VERSION, i as runMatch, m as SYNC, n as syncTarget, o as hasCriteria, r as canonicalWatchers, t as SYNC_ACTOR } from "./origin-DAyYeDuW.mjs";
6
+ import { a as waitUntil, c as platformProfile, d as userIdOf, h as isKeyIdOf, l as shownName, m as derivedId, n as MIDDLEWARE_ACTOR, o as actorParts, s as importedHandle, t as DroppedError } from "./middleware-0DUFrav-.mjs";
7
+ import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-BgBiaCyx.mjs";
8
+ import { S as wroteAs, _ as removes, a as authenticates, c as checkPrincipal, d as grantIssuers, m as joined, n as GITHUB_ISSUER, o as checkCan, p as issuerName, s as checkGrant, x as workflowPath } from "./auth-Ft4AJptx.mjs";
9
9
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
10
- import { a as viaOf, n as actorSeen } from "./actors-yBRWTpt5.mjs";
10
+ import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-DkZsnMgA.mjs";
11
11
  import { C as sessionClearedError, a as SOCKET_TIMINGS, c as drainSettledHooks, d as nullProtoRecord, f as runtimeConsumerFactory, g as A2Error, h as stateTailReaders, i as RESERVED_PARTICIPANT_IDS, l as failedPreviousAttempt, m as serverInternals, n as POLL_TIMINGS, o as STATE_CACHE, p as runtimeConsumers, r as PRESENCE_TIMINGS, s as STREAM_TIMINGS, t as DRAIN_TIMINGS, u as markSchedulerSendFailure, v as NonRetriableError, x as isSessionCleared, y as asStoreUnavailable } from "./internal-CvsrprnU-CEPOUpAv.mjs";
12
12
  import { i as streamActivities, n as defaultSleep, t as createStreamActivity } from "./store-polling-BZt2Rf3D-oh3aU_An.mjs";
13
- import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-Bv-RQu8n.mjs";
14
- import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-CT2bN5eP.mjs";
13
+ import { a as foldActors, i as concernedMessageId, o as foldMessages, s as iso, t as TABLES_CONSUMER } from "./sql-P9g-rLIF.mjs";
14
+ import { a as replaceMentions, i as mentionTerms, n as isEmail, r as mentionTerm, t as extractMentions } from "./mentions-DfZGp3B-.mjs";
15
15
  import { z } from "zod";
16
16
  import { createHash, randomBytes } from "node:crypto";
17
17
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -4122,7 +4122,7 @@ const StoredPrincipal = z.object({
4122
4122
  team: z.string().max(200).optional()
4123
4123
  }).optional(),
4124
4124
  scope: z.string().max(CAN_MAX).optional(),
4125
- /** The board token it came with: what it stores stops when the token does. */
4125
+ /** The board token it came with, from when boards issued them: what it stored stopped with them. */
4126
4126
  token: z.string().min(1).max(64).optional()
4127
4127
  });
4128
4128
  /** A watcher as a board on `http()` registers it: its tail. */
@@ -4290,9 +4290,8 @@ const GrantPrincipal = z.discriminatedUnion("kind", [
4290
4290
  /** A grant's `can`, as written: each pattern and `'all'` or its permissions. */
4291
4291
  const GrantCan = z.record(z.string().min(1).max(300), Grant);
4292
4292
  /**
4293
- * Who the board trusts beside its code's rules, outside the board log: grants, and the tokens it
4294
- * issued, of which only a hash is kept. Session `access`. A token's ID is the index of the event
4295
- * that made it; a grant's comes from the fold, counting from the one the board starts with.
4293
+ * Who the board trusts beside its code's rules, outside the board log: its grants. Session
4294
+ * `access`. A grant's ID comes from the fold, counting from the one the board starts with.
4296
4295
  */
4297
4296
  const accessContract = contract({
4298
4297
  name: "board-access",
@@ -4327,27 +4326,10 @@ const accessContract = contract({
4327
4326
  id: z.number().int().positive(),
4328
4327
  by: ActorId
4329
4328
  }),
4330
- "token.minted": z.object({
4331
- /** The secret's SHA-256, hex. */
4332
- hash: z.string().regex(/^[0-9a-f]{64}$/),
4333
- name: z.string().min(1).max(64),
4334
- /** Who it acts as, its scope narrowed to what the token may do. */
4335
- minter: StoredPrincipal,
4336
- profile: z.string().min(1).max(32).nullable(),
4337
- avatar: z.string().max(2048).nullable(),
4338
- session: z.string().min(1).max(128).nullable(),
4339
- /** A person's handle and name when they minted it. */
4340
- handle: Handle.nullable(),
4341
- personName: z.string().min(1).max(128).nullable(),
4342
- expiresAt: Millis,
4343
- /** The token it was minted with, which it stops with. */
4344
- parent: z.number().int().positive().nullable(),
4345
- by: ActorId
4346
- }),
4347
- "token.revoked": z.object({
4348
- id: z.number().int().positive(),
4349
- by: ActorId
4350
- })
4329
+ /** From when boards issued tokens: kept so older logs load, and folded into nothing. */
4330
+ "token.minted": z.object({ by: ActorId }),
4331
+ /** From when boards issued tokens: folded into nothing. */
4332
+ "token.revoked": z.object({ by: ActorId })
4351
4333
  }
4352
4334
  });
4353
4335
  const ACCESS_SESSION = "access";
@@ -4520,6 +4502,7 @@ function view$1(message, actors, reader) {
4520
4502
  const { blind, version, revision, schedule, platformText, mentions: _mentions, ...shown } = message;
4521
4503
  return {
4522
4504
  ...shown,
4505
+ by: authorView(message.by),
4523
4506
  ...blind ? { blind } : {},
4524
4507
  id: ref(message.id),
4525
4508
  re: message.re === null ? null : ref(message.re),
@@ -4550,6 +4533,18 @@ function whoIs(value, actors) {
4550
4533
  };
4551
4534
  }
4552
4535
  /**
4536
+ * Who a `--by` value names. `me` is the caller's own actor and nobody else, as on Vercel's board:
4537
+ * not a person's agents, which their handle covers. It needs no record of them, so it holds for
4538
+ * someone who has yet to post. Anyone else is `whoIs`.
4539
+ */
4540
+ function authorOf(value, context) {
4541
+ if (value === "me" && context.me) return {
4542
+ actors: /* @__PURE__ */ new Set([context.me.id]),
4543
+ principals: /* @__PURE__ */ new Set()
4544
+ };
4545
+ return whoIs(value, context.actors);
4546
+ }
4547
+ /**
4553
4548
  * What a `--mentions` value matches in a message's text (`mentionTerms`): `me` is the caller's handle
4554
4549
  * and ID. Anyone else is the value as written, and what's under it: a person's agents
4555
4550
  * (`@julian/claude`), a project's imports (`@support/malte`), and their IDs. A reader of every
@@ -4596,7 +4591,7 @@ function compileFilter(filters, context) {
4596
4591
  const labels = filters.label ?? [];
4597
4592
  const channel = filters.channel;
4598
4593
  const subtree = channel?.endsWith("/") ? channel.slice(0, -1) : null;
4599
- const by = filters.by === void 0 ? null : whoIs(filters.by, context.actors);
4594
+ const by = filters.by === void 0 ? null : authorOf(filters.by, context);
4600
4595
  const re = filters.re === void 0 ? void 0 : indexOf$1(filters.re) ?? -1;
4601
4596
  const mentions = filters.mentions === void 0 ? null : mentionFilter(filters.mentions, context);
4602
4597
  return (message) => {
@@ -4645,7 +4640,7 @@ function toMessageFilter(filters, context) {
4645
4640
  };
4646
4641
  if (filters.re !== void 0) out.re = indexOf$1(filters.re) ?? -1;
4647
4642
  if (filters.by !== void 0) {
4648
- const who = whoIs(filters.by, context.actors);
4643
+ const who = authorOf(filters.by, context);
4649
4644
  out.by = {
4650
4645
  actors: [...who.actors],
4651
4646
  principals: [...who.principals]
@@ -4730,6 +4725,7 @@ function payloadView(payload, links) {
4730
4725
  "re",
4731
4726
  "replyTo"
4732
4727
  ]) if (typeof shown[key] === "number") shown[key] = ref(shown[key]);
4728
+ if (typeof shown.by === "object" && shown.by !== null) shown.by = authorView(shown.by);
4733
4729
  const schedule = shown.schedule;
4734
4730
  if (schedule) shown.schedule = {
4735
4731
  id: scheduleRef(schedule.id),
@@ -4911,8 +4907,7 @@ function deploymentIdentity(actor, handle) {
4911
4907
  author: {
4912
4908
  actor,
4913
4909
  principal: actor,
4914
- profile: null,
4915
- session: null
4910
+ profile: null
4916
4911
  },
4917
4912
  actor: {
4918
4913
  id: actor,
@@ -4936,17 +4931,17 @@ function seenFor(identity, actors) {
4936
4931
  } : actor, actors, identity.principal.facts?.issuer === "host");
4937
4932
  }
4938
4933
  /**
4939
- * Whether the board checked who a write is by, as it shows them: a principal a credential named
4940
- * (an OIDC token it trusts, a board token, or a host's verifier; never the board's own code), under
4941
- * the handle that credential gave it. An agent shows that principal after `via`, and its profile
4942
- * name is the principal's to choose; a person, deployment, or workflow writing as itself shows the
4943
- * handle as its name, which a display name its client sends replaces. An import says for itself.
4934
+ * Whether the board checked who a write is by, as it shows them: a principal a credential named (an
4935
+ * OIDC token it trusts, or a host's verifier; never the board's own code), shown as
4936
+ * that principal names it: its handle and name, and for an agent, that principal after `via`, its
4937
+ * profile name the principal's to choose. A stored actor that shows otherwise (a schedule's, from
4938
+ * before handles were checked) isn't. An import says for itself.
4944
4939
  */
4945
4940
  function verifiedAs({ principal, author, actor }) {
4946
4941
  if (principal.kind === "external") return actor.verified === true;
4947
4942
  if (principal.id.startsWith("board:")) return false;
4948
- if (author.profile !== null) return actor.via !== void 0 && actor.via.name === viaOf(principal).name;
4949
- return actor.name === principal.handle && actor.handle === principal.handle;
4943
+ const named = ownedActor(principal, author, actor);
4944
+ return named.handle === actor.handle && named.name === actor.name && named.avatar === actor.avatar && named.via?.name === actor.via?.name && named.via?.environment === actor.via?.environment;
4950
4945
  }
4951
4946
  /**
4952
4947
  * Whether `identity` wrote `message`, to change it as its author: its principal did, as itself or
@@ -4972,7 +4967,7 @@ async function authorizeMessage(ctx, access, permission, id) {
4972
4967
  * read, it's yours only if it was posted without reading too: a write-only
4973
4968
  * source fixes what it wrote, but a principal ID it shares with a caller that
4974
4969
  * reads (a repo's workflows share one) doesn't reach that caller's messages.
4975
- * A board token that pins a profile owns only what was written as it (`wroteAs`).
4970
+ * A profile owns only what was written as it; its principal, as no profile, owns all of them (`wroteAs`).
4976
4971
  * Someone else's answers 404 where you can't read it, and 403 where you can.
4977
4972
  */
4978
4973
  async function authorizeOwn(ctx, identity, id, verb) {
@@ -5107,7 +5102,7 @@ async function landedFor(ctx, identity, landed) {
5107
5102
  * import names its own profiles: who those are, `/actors` doesn't show it either.
5108
5103
  */
5109
5104
  const blindText = (text, own) => replaceMentions(text, (token) => token.kind === "actor" && token.actor !== own ? "@…" : null);
5110
- const sameAuthor = (a, b) => a.actor === b.actor && a.principal === b.principal && a.profile === b.profile && a.session === b.session;
5105
+ const sameAuthor = (a, b) => a.actor === b.actor && a.principal === b.principal && a.profile === b.profile;
5111
5106
  async function commitPost(ctx, input, placed) {
5112
5107
  const { identity } = input;
5113
5108
  const { channel, re, replyTo, thread, id, sent } = placed;
@@ -5452,10 +5447,6 @@ const appendIfLast = (session, index, events) => session.append.ifLastIndex(inde
5452
5447
  const headMoved = (error) => error?.code === "LAST_INDEX_MISMATCH";
5453
5448
  //#endregion
5454
5449
  //#region src/server/trust.ts
5455
- /** How long a token lives when its minter doesn't say, and at most: npm caps its write tokens at 90 days. */
5456
- const TOKEN_DEFAULT_MS = 2592e6;
5457
- /** How deep tokens minted with tokens go: each request walks the chain to its root. */
5458
- const TOKEN_DEPTH_MAX = 8;
5459
5450
  /**
5460
5451
  * The grants a board starts with, as a team's board in Vercel's API does: g1, every person may do
5461
5452
  * everything (no team roles cap it here), g2, every project on the board's team, in every
@@ -5507,59 +5498,19 @@ const STARTING_GRANTS = {
5507
5498
  at: null
5508
5499
  }
5509
5500
  };
5510
- /** The access session before its first event: the grants every board starts with, and no tokens. */
5501
+ /** The access session before its first event: the grants every board starts with. */
5511
5502
  const startingAccess = () => ({
5512
5503
  grants: structuredClone(STARTING_GRANTS),
5513
- nextGrant: 4,
5514
- tokens: {},
5515
- hashes: {},
5516
- expiring: {},
5517
- pruned: null
5504
+ nextGrant: 4
5518
5505
  });
5519
- const DAY_MS = 864e5;
5520
- function dropToken(state, id) {
5521
- const row = state.tokens[id];
5522
- if (!row) return;
5523
- delete state.hashes[row.hash];
5524
- delete state.tokens[id];
5525
- }
5526
- /** Whether token `id` is token `ancestor`, or was minted with it at any depth. */
5527
- function mintedWith(state, id, ancestor) {
5528
- let at = id;
5529
- for (let depth = 0; at !== null && depth <= TOKEN_DEPTH_MAX; depth++) {
5530
- if (at === ancestor) return true;
5531
- at = state.tokens[at]?.parent ?? null;
5532
- }
5533
- return false;
5534
- }
5535
- /**
5536
- * Whether `identity` may see and revoke token `row`: anyone's with `manage` in every channel. A
5537
- * token acts as its minter, so its principal alone would hand it every token its minter has: with
5538
- * a token, it's that token and those minted with it; without one, those its principal minted.
5539
- */
5540
- function manages(state, { principal }, row) {
5541
- if (principal.access.everywhere("manage")) return true;
5542
- if (row.minter.id !== principal.id) return false;
5543
- if (principal.token === void 0) return true;
5544
- const held = indexOf(principal.token, "t");
5545
- return held !== null && mintedWith(state, row.id, held);
5546
- }
5547
- /**
5548
- * The access session's fold. It prunes by the events' own times, so every instance folds the same
5549
- * state, and each event costs a day's expired tokens at most. A child whose parent is gone counts
5550
- * as dead (`liveIn`), and lives no longer than its parent, so pruning never brings one back.
5551
- */
5506
+ /** The access session's fold. */
5552
5507
  function foldAccess(state, event) {
5553
5508
  const at = new Date(event.createdAt).getTime();
5554
- const day = Math.floor(at / DAY_MS);
5555
- if (state.pruned === null) state.pruned = day;
5556
- for (; state.pruned < day; state.pruned++) {
5557
- for (const id of state.expiring[state.pruned] ?? []) dropToken(state, id);
5558
- delete state.expiring[state.pruned];
5559
- }
5560
5509
  switch (event.type) {
5561
5510
  case "grant.set":
5562
- case "grant.revoked": break;
5511
+ case "grant.revoked":
5512
+ case "token.minted":
5513
+ case "token.revoked": break;
5563
5514
  case "grant.created": {
5564
5515
  const { principals, can, by } = event.payload;
5565
5516
  const id = state.nextGrant++;
@@ -5584,36 +5535,19 @@ function foldAccess(state, event) {
5584
5535
  });
5585
5536
  break;
5586
5537
  }
5587
- case "grant.deleted":
5588
- delete state.grants[event.payload.id];
5589
- break;
5590
- case "token.minted": {
5591
- const { payload } = event;
5592
- if (state.hashes[payload.hash] !== void 0) break;
5593
- state.tokens[event.index] = {
5594
- id: event.index,
5595
- ...payload,
5596
- minter: payload.minter,
5597
- at
5598
- };
5599
- state.hashes[payload.hash] = event.index;
5600
- (state.expiring[Math.floor(payload.expiresAt / DAY_MS)] ??= []).push(event.index);
5601
- break;
5602
- }
5603
- case "token.revoked": dropToken(state, event.payload.id);
5538
+ case "grant.deleted": delete state.grants[event.payload.id];
5604
5539
  }
5605
5540
  return state;
5606
5541
  }
5607
5542
  const accessReducer = reducer({
5608
5543
  contract: accessContract,
5609
- name: "board.access.v3",
5544
+ name: "board.access.v4",
5610
5545
  initialState: startingAccess()
5611
5546
  }).fold(foldAccess);
5612
5547
  const grantId = (id) => `g${id}`;
5613
- const tokenId = (id) => `t${id}`;
5614
- /** The index an ID names: `g12` or `t12` for 12. Null for one that names none. */
5615
- function indexOf(id, prefix) {
5616
- const found = new RegExp(`^${prefix}([1-9]\\d{0,15})$`).exec(id);
5548
+ /** The index a grant's ID names: `g12` for 12. Null for one that names none. */
5549
+ function indexOf(id) {
5550
+ const found = /^g([1-9]\d{0,15})$/.exec(id);
5617
5551
  return found ? Number(found[1]) : null;
5618
5552
  }
5619
5553
  /** A principal as views show it: the IDs, and the names the board knows, which on a local board are none. */
@@ -5665,23 +5599,6 @@ const storedGrant = (row) => ({
5665
5599
  principals: row.principals,
5666
5600
  can: row.can
5667
5601
  });
5668
- /** A token as the protocol shows it, with `can` what it may do now (`accessNow`'s, for its minter). */
5669
- const tokenView = (row, can) => ({
5670
- id: tokenId(row.id),
5671
- name: row.name,
5672
- can: can === null ? {} : can.summary(),
5673
- profile: row.profile,
5674
- session: row.session,
5675
- by: row.by,
5676
- at: new Date(row.at).toISOString(),
5677
- expiresAt: new Date(row.expiresAt).toISOString(),
5678
- parent: row.parent === null ? null : tokenId(row.parent)
5679
- });
5680
- /** A new token's secret: the prefix and 32 random bytes, base64url. */
5681
- function newSecret() {
5682
- const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
5683
- return `${BOARD_TOKEN_PREFIX}${btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
5684
- }
5685
5602
  /**
5686
5603
  * The principal an explain query names, as a token of its would make it: a person by user ID, a
5687
5604
  * project's deployment in one environment (production unless it says) on the board's team, a
@@ -5766,7 +5683,7 @@ function principalNamed(query, team) {
5766
5683
  * `manage` lets them, so a grant on people holds against people.
5767
5684
  */
5768
5685
  const isOwner = (principal) => principal.kind === "person" && principal.id.startsWith("local:user:") && principal.facts?.issuer !== "host";
5769
- /** Whether `identity` may list the grants: `manage` at `*`, or the owner, as far as its token's scope allows. */
5686
+ /** Whether `identity` may list the grants: `manage` at `*`, or the owner, as far as its `x-board-can` allows. */
5770
5687
  function lists({ principal }) {
5771
5688
  if (principal.access.at("manage", "*")) return true;
5772
5689
  return isOwner(principal) && (principal.scope === void 0 || compileAccess(parseCan(principal.scope)).at("manage", "*"));
@@ -5775,7 +5692,12 @@ function lists({ principal }) {
5775
5692
  function mayList(identity, what) {
5776
5693
  if (!lists(identity)) throw forbidden$1(`this token can't ${what}: it needs manage at *`);
5777
5694
  }
5778
- /** `grants` with no `everyone` in them: what a caller's own limits are, its role, its grants and its groups', and its token. */
5695
+ /**
5696
+ * What a caller that may not list the grants is told when it can't `what` one: the same for a grant
5697
+ * beyond its reach as for one that isn't there, since grant IDs count up and a difference maps them.
5698
+ */
5699
+ const unreachable = (what) => forbidden$1(`this token can't ${what}: it needs manage wherever that grant reaches`);
5700
+ /** `grants` with no `everyone` in them: what a caller's own limits are, its role, its grants and its groups', and its `x-board-can`. */
5779
5701
  const withoutEveryone = (grants) => grants.flatMap((grant) => {
5780
5702
  const principals = grant.principals.filter((principal) => principal.kind !== "everyone");
5781
5703
  return principals.length === 0 ? [] : [{
@@ -5785,7 +5707,7 @@ const withoutEveryone = (grants) => grants.flatMap((grant) => {
5785
5707
  });
5786
5708
  /**
5787
5709
  * What the caller may do on `grants`, the snapshot its write appends to (`caller`), and by its own
5788
- * limits alone (`own`): null for an owner no token narrows. A 403 when it may do nothing.
5710
+ * limits alone (`own`): null for an owner no `x-board-can` narrows. A 403 when it may do nothing.
5789
5711
  */
5790
5712
  async function changerAccess({ principal }, grants, accessIn) {
5791
5713
  if (isOwner(principal)) {
@@ -5818,7 +5740,7 @@ async function mayGrant(identity, change, before, after, accessIn, what = "this
5818
5740
  ...change
5819
5741
  });
5820
5742
  if (refused?.reason === "reach") {
5821
- if (change.revoked && !lists(identity)) throw forbidden$1(`this token can't ${what}: it needs manage wherever that grant reaches`);
5743
+ if (change.revoked && !lists(identity)) throw unreachable(what);
5822
5744
  throw forbidden$1(`${change.revoked ? `this token can't ${what}: it` : what} reaches ${refused.pattern}, where you can't manage grants`);
5823
5745
  }
5824
5746
  if (refused) throw forbidden$1(`you can't let anyone in: everyone gets ${refused.permission} in ${refused.pattern}, which you can't`);
@@ -5832,10 +5754,10 @@ const namesIssuer = (principals) => principals.some((principal) => principal.kin
5832
5754
  * already. `issuers` are the ones the board's rules trust.
5833
5755
  */
5834
5756
  async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team) {
5835
- const index = indexOf(id, "g");
5757
+ const index = indexOf(id);
5836
5758
  const row = index === null ? void 0 : state.grants[index];
5837
5759
  if (!row) {
5838
- mayList(identity, "update grants");
5760
+ if (!lists(identity)) throw unreachable(`update ${id}`);
5839
5761
  throw notFound(`grant not found: ${id}`, "grant_not_found");
5840
5762
  }
5841
5763
  const before = Object.values(state.grants).map(storedGrant);
@@ -5881,9 +5803,9 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
5881
5803
  };
5882
5804
  }
5883
5805
  /**
5884
- * The board's grants and tokens, in session `access` of its log: what a local board answers for them, and
5806
+ * The board's grants, in session `access` of its log: what a local board answers for them, and
5885
5807
  * what board() checks requests against. `accessNow`: what a principal may do now, under board()'s
5886
- * defaults and the grants, which a token's listing shows.
5808
+ * defaults and the grants.
5887
5809
  */
5888
5810
  function createTrust(options) {
5889
5811
  const accessIn = (principal, grants) => options.accessNow(principal, grants);
@@ -5892,62 +5814,12 @@ function createTrust(options) {
5892
5814
  store: options.store
5893
5815
  }).session(ACCESS_SESSION);
5894
5816
  const read = async () => (await session.state(accessReducer)).state;
5895
- /** The grants and tokens as they are now, and the index a conditional write holds them at. */
5817
+ /** The grants as they are now, and the index a conditional write holds them at. */
5896
5818
  const latest = () => session.state(accessReducer, { through: "latest" });
5897
- /**
5898
- * What each of `rows` may do now: its minter's access, narrowed by its scope. A minter's is worked
5899
- * out once, however many tokens it has.
5900
- */
5901
- async function viewsOf(rows) {
5902
- const minters = /* @__PURE__ */ new Map();
5903
- return Promise.all(rows.map(async (row) => {
5904
- const { scope, ...minter } = row.minter;
5905
- const key = JSON.stringify(minter);
5906
- let access = minters.get(key);
5907
- if (!access) minters.set(key, access = options.accessNow(minter));
5908
- const now = await access;
5909
- return tokenView(row, now === null || scope === void 0 ? now : now.narrow(parseCan(scope)));
5910
- }));
5911
- }
5912
- /** Whether token `id` and every token it was minted with are live now. */
5913
- function liveIn(state, id) {
5914
- let at = id;
5915
- for (let depth = 0; at !== null; depth++) {
5916
- const row = state.tokens[at];
5917
- if (!row || row.expiresAt <= Date.now() || depth > TOKEN_DEPTH_MAX) return false;
5918
- at = row.parent;
5919
- }
5920
- return true;
5921
- }
5922
5819
  return {
5923
- trust: {
5924
- async grants() {
5925
- return Object.values((await read()).grants).map(storedGrant);
5926
- },
5927
- async token(hash) {
5928
- const state = await read();
5929
- const id = state.hashes[hash];
5930
- if (id === void 0 || !liveIn(state, id)) return null;
5931
- const row = state.tokens[id];
5932
- return {
5933
- id: tokenId(row.id),
5934
- name: row.name,
5935
- minter: row.minter,
5936
- pinned: {
5937
- profile: row.profile,
5938
- avatar: row.avatar,
5939
- session: row.session,
5940
- handle: row.handle,
5941
- name: row.personName
5942
- },
5943
- expiresAt: new Date(row.expiresAt)
5944
- };
5945
- },
5946
- async live(id) {
5947
- const index = indexOf(id, "t");
5948
- return index !== null && liveIn(await read(), index);
5949
- }
5950
- },
5820
+ trust: { async grants() {
5821
+ return Object.values((await read()).grants).map(storedGrant);
5822
+ } },
5951
5823
  async grants(identity) {
5952
5824
  mayList(identity, "list grants");
5953
5825
  return { grants: Object.values((await read()).grants).sort((a, b) => a.id - b.id).map(grantView) };
@@ -5996,14 +5868,13 @@ function createTrust(options) {
5996
5868
  capped: null,
5997
5869
  can: []
5998
5870
  };
5999
- const { id, kind, handle, facts, scope, token } = identity.principal;
5871
+ const { id, kind, handle, facts, scope } = identity.principal;
6000
5872
  const principal = named ? principalNamed(query, await options.team()) : {
6001
5873
  id,
6002
5874
  kind,
6003
5875
  handle,
6004
5876
  ...facts ? { facts } : {},
6005
- ...scope !== void 0 ? { scope } : {},
6006
- ...token !== void 0 ? { token } : {}
5877
+ ...scope !== void 0 ? { scope } : {}
6007
5878
  };
6008
5879
  const decided = await options.explain(principal, query.channel);
6009
5880
  const { grants } = await read();
@@ -6014,7 +5885,7 @@ function createTrust(options) {
6014
5885
  over: decided.over,
6015
5886
  level: decided.level,
6016
5887
  grants: shown.flatMap((grant) => {
6017
- const row = grants[indexOf(grant.id, "g") ?? 0];
5888
+ const row = grants[indexOf(grant.id) ?? 0];
6018
5889
  return row ? [grantView(row)] : [];
6019
5890
  }),
6020
5891
  capped: null,
@@ -6024,10 +5895,10 @@ function createTrust(options) {
6024
5895
  async revokeGrant(identity, { id }) {
6025
5896
  return whileHeadMoves(async () => {
6026
5897
  const { state, index } = await latest();
6027
- const at = indexOf(id, "g");
5898
+ const at = indexOf(id);
6028
5899
  const row = at === null ? void 0 : state.grants[at];
6029
5900
  if (!row) {
6030
- mayList(identity, "revoke grants");
5901
+ if (!lists(identity)) throw unreachable(`revoke ${id}`);
6031
5902
  return { revoked: false };
6032
5903
  }
6033
5904
  const before = Object.values(state.grants).map(storedGrant);
@@ -6041,97 +5912,6 @@ function createTrust(options) {
6041
5912
  });
6042
5913
  return { revoked: true };
6043
5914
  });
6044
- },
6045
- async tokens(identity) {
6046
- const state = await read();
6047
- return { tokens: await viewsOf(Object.values(state.tokens).filter((row) => liveIn(state, row.id) && manages(state, identity, row)).sort((a, b) => a.id - b.id)) };
6048
- },
6049
- /** The board tokens `principal` came with: its own, then each it was minted with. Undefined with none. */
6050
- async chain(principal) {
6051
- if (principal.token === void 0) return void 0;
6052
- const state = await read();
6053
- const chain = [];
6054
- for (let at = indexOf(principal.token, "t"); at !== null && chain.length <= TOKEN_DEPTH_MAX; at = state.tokens[at]?.parent ?? null) chain.push(tokenId(at));
6055
- return chain;
6056
- },
6057
- async createToken(identity, body) {
6058
- const { principal, author, actor } = identity;
6059
- const state = await read();
6060
- const now = Date.now();
6061
- const asked = body.expires === void 0 ? TOKEN_DEFAULT_MS : duration(body.expires);
6062
- if (asked <= 0 || asked > 7776e6) throw badRequest("a token lives up to 90 days: pass expires as 90d or less", "invalid_expires");
6063
- let expiresAt = now + asked;
6064
- let parent = null;
6065
- if (principal.token !== void 0) {
6066
- const index = indexOf(principal.token, "t");
6067
- parent = index === null ? null : state.tokens[index] ?? null;
6068
- if (!parent || !liveIn(state, parent.id)) throw unauthorized("invalid token: revoked, expired, or not this board's");
6069
- let depth = 0;
6070
- for (let at = parent; at; at = at.parent === null ? void 0 : state.tokens[at.parent]) depth++;
6071
- if (depth >= TOKEN_DEPTH_MAX) throw badRequest(`tokens minted with tokens go ${TOKEN_DEPTH_MAX} deep at most`, "invalid_token");
6072
- expiresAt = Math.min(expiresAt, parent.expiresAt);
6073
- }
6074
- let can;
6075
- try {
6076
- can = compileAccess(body.can ?? DEFAULT_CAN);
6077
- } catch (error) {
6078
- throw badRequest(error.message, "invalid_scope");
6079
- }
6080
- const scope = canText((principal.scope === void 0 ? FULL_ACCESS : compileAccess(parseCan(principal.scope))).narrow(can));
6081
- if (scope.length > 4e3) throw badRequest(`a token's can is ${CAN_MAX} characters at most as a scope: name fewer channels`, "invalid_scope");
6082
- const minter = {
6083
- id: principal.id,
6084
- kind: principal.kind,
6085
- handle: principal.handle,
6086
- ...principal.facts ? { facts: principal.facts } : {},
6087
- scope
6088
- };
6089
- const pinned = principal.pinned;
6090
- const profile = pinned?.profile ?? body.profile ?? null;
6091
- const avatar = pinned?.profile ? pinned.avatar : profile !== null ? body.avatar ?? null : null;
6092
- const pinnedSession = pinned?.session ?? body.session ?? null;
6093
- const person = principal.kind === "person";
6094
- const base = author.profile === null ? actor.handle : actor.handle.slice(0, Math.max(0, actor.handle.length - author.profile.length - 1)) || principal.handle;
6095
- const handle = pinned?.handle ?? (person ? base : null);
6096
- const personName = pinned?.name ?? (person && author.profile === null ? actor.name : null);
6097
- const secret = newSecret();
6098
- const [row] = await session.append({
6099
- type: "token.minted",
6100
- payload: {
6101
- hash: await tokenHash(secret),
6102
- name: body.name,
6103
- minter,
6104
- profile,
6105
- avatar,
6106
- session: pinnedSession,
6107
- handle,
6108
- personName,
6109
- expiresAt,
6110
- parent: parent?.id ?? null,
6111
- by: actor.id
6112
- }
6113
- });
6114
- const minted = row && (await read()).tokens[row.index];
6115
- if (!minted) throw new Error("a token was minted but its log has no record of it");
6116
- const [view] = await viewsOf([minted]);
6117
- return {
6118
- token: view,
6119
- secret
6120
- };
6121
- },
6122
- async revokeToken(identity, { id }) {
6123
- const state = await read();
6124
- const index = indexOf(id, "t");
6125
- const row = index === null ? void 0 : state.tokens[index];
6126
- if (!row || !liveIn(state, row.id) || !manages(state, identity, row)) return { revoked: false };
6127
- await session.append({
6128
- type: "token.revoked",
6129
- payload: {
6130
- id: row.id,
6131
- by: identity.actor.id
6132
- }
6133
- });
6134
- return { revoked: true };
6135
5915
  }
6136
5916
  };
6137
5917
  }
@@ -6285,20 +6065,11 @@ function attachmentId() {
6285
6065
  if (!id.startsWith("-")) return id;
6286
6066
  }
6287
6067
  }
6288
- /**
6289
- * Whether an upload is the caller's own, to read and attach before a message carries it: its
6290
- * principal sent it, and the caller holds no board token, or holds the one it came with or one
6291
- * that token was minted with. A token acts as its minter, so the principal alone would hand it
6292
- * every file its minter, or another of its minter's tokens, uploaded.
6293
- */
6294
- function ownUpload(upload, caller) {
6295
- if (upload.uploadedBy !== caller.id) return false;
6296
- return caller.token === void 0 || (upload.uploadedWith?.includes(caller.token) ?? false);
6297
- }
6068
+ /** Whether an upload is the caller's own, to read and attach before a message carries it: its principal sent it. */
6069
+ const ownUpload = (upload, caller) => upload.uploadedBy === caller.id;
6298
6070
  /**
6299
6071
  * Stores an upload under a fresh ID, with its metadata beside it. `uploadedBy`
6300
- * is the principal that sent it, who can read it before any message carries it,
6301
- * and `uploadedWith` the board tokens it came with (`ownUpload`).
6072
+ * is the principal that sent it, who can read it before any message carries it.
6302
6073
  * `max` is the most it can be: `ATTACHMENT_BYTES_MAX` unless the board's own sync imports it.
6303
6074
  */
6304
6075
  async function writeUpload(blob, input, max = ATTACHMENT_BYTES_MAX) {
@@ -6314,8 +6085,7 @@ async function writeUpload(blob, input, max = ATTACHMENT_BYTES_MAX) {
6314
6085
  await blob.put(dataKey(attachment.id), input.data, attachment.type);
6315
6086
  const meta = input.uploadedBy === void 0 ? attachment : {
6316
6087
  ...attachment,
6317
- uploadedBy: input.uploadedBy,
6318
- ...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {}
6088
+ uploadedBy: input.uploadedBy
6319
6089
  };
6320
6090
  await blob.put(metaKey(attachment.id), new TextEncoder().encode(JSON.stringify(meta)), "application/json");
6321
6091
  return attachment;
@@ -6334,11 +6104,9 @@ async function readUpload(blob, id) {
6334
6104
  const found = Attachment.shape.id.safeParse(id).success ? await blob.get(metaKey(id)) : null;
6335
6105
  if (!found) throw attachmentNotFound(id);
6336
6106
  const meta = JSON.parse(new TextDecoder().decode(await bytes(found.data)));
6337
- const tokens = Array.isArray(meta.uploadedWith) && meta.uploadedWith.every((token) => typeof token === "string") ? meta.uploadedWith : null;
6338
6107
  return {
6339
6108
  attachment: Attachment.parse(meta),
6340
- uploadedBy: typeof meta.uploadedBy === "string" ? meta.uploadedBy : null,
6341
- uploadedWith: tokens
6109
+ uploadedBy: typeof meta.uploadedBy === "string" ? meta.uploadedBy : null
6342
6110
  };
6343
6111
  }
6344
6112
  /** An attachment's bytes as the store keeps them, a stream or the bytes, for board() to serve. */
@@ -6366,7 +6134,6 @@ async function startUpload(blob, input) {
6366
6134
  type: mediaType(input.type),
6367
6135
  size: input.size,
6368
6136
  uploadedBy: input.uploadedBy,
6369
- ...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {},
6370
6137
  expiresAt: expires.toISOString()
6371
6138
  };
6372
6139
  await blob.put(ticketKey(ticket.id), new TextEncoder().encode(JSON.stringify(ticket)), "application/json");
@@ -6407,13 +6174,9 @@ async function finishUpload(blob, id, caller) {
6407
6174
  size: stored.size
6408
6175
  };
6409
6176
  try {
6410
- const uploader = {
6411
- uploadedBy: ticket.uploadedBy,
6412
- ...ticket.uploadedWith ? { uploadedWith: ticket.uploadedWith } : {}
6413
- };
6414
6177
  await blob.put(metaKey(id), new TextEncoder().encode(JSON.stringify({
6415
6178
  ...attachment,
6416
- ...uploader
6179
+ uploadedBy: ticket.uploadedBy
6417
6180
  })), "application/json");
6418
6181
  } catch (error) {
6419
6182
  const done = await blob.get(metaKey(id)).catch(() => null);
@@ -6558,8 +6321,7 @@ const storedPrincipal = (principal) => ({
6558
6321
  kind: principal.kind,
6559
6322
  handle: principal.handle,
6560
6323
  ...principal.facts ? { facts: principal.facts } : {},
6561
- ...principal.scope !== void 0 ? { scope: principal.scope } : {},
6562
- ...principal.token !== void 0 ? { token: principal.token } : {}
6324
+ ...principal.scope !== void 0 ? { scope: principal.scope } : {}
6563
6325
  });
6564
6326
  /** What a registration shows: the principal's token facts stay on the board. */
6565
6327
  const viewOf = ({ principal: _principal, ...view }) => view;
@@ -6641,18 +6403,23 @@ function createRegistry(options) {
6641
6403
  const MAX_HOP_MS = 432e6;
6642
6404
  /** A timer that fires this early just waits again; any closer counts as on time. */
6643
6405
  const EARLY_MS = 1e3;
6406
+ /**
6407
+ * Who a schedule sends as: its creator, shown as its principal names it. One made before handles were
6408
+ * checked keeps the actor its creator's client named; it sends as what verified that creator instead.
6409
+ */
6644
6410
  const identityOf = (as) => {
6645
6411
  const { author, principal, actor } = as.payload.as;
6412
+ const stored = {
6413
+ ...principal,
6414
+ expiresAt: null
6415
+ };
6646
6416
  return {
6647
6417
  author,
6648
- principal: {
6649
- ...principal,
6650
- expiresAt: null
6651
- },
6652
- actor: {
6418
+ principal: stored,
6419
+ actor: ownedActor(stored, author, {
6653
6420
  ...actor,
6654
6421
  kind: actorKind(actor.kind)
6655
- }
6422
+ })
6656
6423
  };
6657
6424
  };
6658
6425
  function foldSchedules(state, event) {
@@ -6730,7 +6497,7 @@ function nextSend(schedule, n, at, now) {
6730
6497
  * needs `post` there now, as it would to create it. Where it can't read, the
6731
6498
  * schedule is its own only if it was created without reading too, so a
6732
6499
  * principal ID shared with a caller that reads doesn't reach that caller's.
6733
- * A board token that pins a profile owns only what was scheduled as it (`wroteAs`).
6500
+ * A profile owns only what was scheduled as it; its principal, as no profile, owns all of them (`wroteAs`).
6734
6501
  */
6735
6502
  const createdBy = (schedule, identity) => wroteAs(identity, {
6736
6503
  principal: schedule.as.principal.id,
@@ -6759,8 +6526,11 @@ const scheduleView = (schedule, actors) => {
6759
6526
  next: schedule.next === null ? null : new Date(schedule.next).toISOString(),
6760
6527
  last: schedule.last === null ? null : ref(schedule.last),
6761
6528
  state: schedule.canceled ? "canceled" : schedule.next === null ? "done" : "pending",
6762
- canceled: schedule.canceled,
6763
- by: schedule.as.author,
6529
+ canceled: schedule.canceled && {
6530
+ ...schedule.canceled,
6531
+ by: authorView(schedule.canceled.by)
6532
+ },
6533
+ by: authorView(schedule.as.author),
6764
6534
  author: {
6765
6535
  kind: author.kind,
6766
6536
  handle: author.handle,
@@ -7016,10 +6786,7 @@ function createSchedules(options) {
7016
6786
  if (every !== null && every > 316224e5) throw badRequest("`every` is at most a year");
7017
6787
  const first = body.at !== void 0 ? Date.parse(body.at) : now + duration(body.in ?? body.every);
7018
6788
  if (first < now - 6e4) throw badRequest("`at` is in the past");
7019
- const asked = body.until !== void 0 ? Date.parse(body.until) : body.for !== void 0 ? first + duration(body.for) : null;
7020
- const expires = identity.principal.token !== void 0 ? identity.principal.expiresAt?.getTime() ?? null : null;
7021
- if (expires !== null && first > expires) throw badRequest(`this token expires ${new Date(expires).toISOString()}, before the schedule's first send: schedule it with a credential that lasts`, "token_expires_first");
7022
- const until = expires !== null && (asked === null || asked > expires) ? expires : asked;
6789
+ const until = body.until !== void 0 ? Date.parse(body.until) : body.for !== void 0 ? first + duration(body.for) : null;
7023
6790
  if (until !== null && until < first) throw badRequest("the schedule stops before its first send");
7024
6791
  if (first > now + 316224e5 || until !== null && until > now + 316224e5) throw badRequest("a schedule reaches at most a year out: its first send and its stop");
7025
6792
  let channel = body.channel;
@@ -7118,7 +6885,7 @@ const SYNCED = /* @__PURE__ */ new Set([
7118
6885
  "labels.changed",
7119
6886
  "thread.synced"
7120
6887
  ]);
7121
- /** A watcher writes as `board:watch:<id>`, and its own writes never wake it. */
6888
+ /** A watcher writes as `board:watch:<id>`, and its own writes never wake it, but for a schedule's sends. */
7122
6889
  const actorOf = (id) => `board:watch:${id}`;
7123
6890
  /** `watch:@<principal>`: everything one registrant's watchers matched, queued for it to pull. */
7124
6891
  const registrantSession = (owner) => watchSession(`@${owner}`);
@@ -7201,6 +6968,7 @@ function createWatchers(options) {
7201
6968
  const [messages, { state: actors }] = await Promise.all([messagesBefore(event, ctx.signal), ctx.session.state(actorsReducer, { through })]);
7202
6969
  const { id, before, after } = foldEvent(messages, actors, event);
7203
6970
  const by = event.payload.by?.actor;
6971
+ const scheduled = event.type === "message.posted" && event.payload.schedule !== void 0;
7204
6972
  const message = after ?? before;
7205
6973
  const thread = event.payload.thread;
7206
6974
  let view;
@@ -7217,7 +6985,7 @@ function createWatchers(options) {
7217
6985
  };
7218
6986
  for (const watcher of targets) {
7219
6987
  if (event.type === "thread.synced") break;
7220
- if (by === watcher.actor) continue;
6988
+ if (by === watcher.actor && !scheduled) continue;
7221
6989
  if (RECEIPTS.has(event.type) && !watcher.all) continue;
7222
6990
  const { registration } = watcher;
7223
6991
  let access = FULL_ACCESS;
@@ -7616,6 +7384,20 @@ const OWN = {
7616
7384
  * and sync.
7617
7385
  */
7618
7386
  function selfIdentity(caller) {
7387
+ const identity = ownIdentity(caller);
7388
+ if (caller.can === void 0) return identity;
7389
+ const { principal } = identity;
7390
+ return {
7391
+ ...identity,
7392
+ principal: {
7393
+ ...principal,
7394
+ scope: caller.can,
7395
+ access: principal.access.narrow(parseCan(caller.can))
7396
+ }
7397
+ };
7398
+ }
7399
+ /** Who this deployment's own code is, before a handle's `can` narrows it. */
7400
+ function ownIdentity(caller) {
7619
7401
  const { self, origin } = caller;
7620
7402
  if (origin.via?.kind === "watcher") return deploymentIdentity(`board:watch:${self}`, self ?? "watch");
7621
7403
  if (origin.via?.kind === "middleware") return deploymentIdentity(MIDDLEWARE_ACTOR, "middleware");
@@ -7657,8 +7439,7 @@ function externalIdentity(author, through, platform) {
7657
7439
  author: {
7658
7440
  actor: id,
7659
7441
  principal: principal.id,
7660
- profile: through === null ? null : author.id,
7661
- session: null
7442
+ profile: through === null ? null : author.id
7662
7443
  },
7663
7444
  actor: {
7664
7445
  id,
@@ -7942,7 +7723,6 @@ function build(options, binding) {
7942
7723
  avatar: actor.avatar,
7943
7724
  profile: author.profile,
7944
7725
  ...actor.via ? { via: { ...actor.via } } : {},
7945
- session: author.session,
7946
7726
  expiresAt: principal.expiresAt?.toISOString() ?? null,
7947
7727
  can: principal.access.summary()
7948
7728
  };
@@ -8120,8 +7900,10 @@ function build(options, binding) {
8120
7900
  principal,
8121
7901
  actor
8122
7902
  });
7903
+ const by = query.by === "me" ? actor.id : query.by;
8123
7904
  return { schedules: (await schedules.list({
8124
7905
  ...query,
7906
+ ...by !== void 0 ? { by } : {},
8125
7907
  ...root !== void 0 ? { root } : {}
8126
7908
  }, visible)).map((schedule) => blindSchedule(schedule, principal.access, actor.id)) };
8127
7909
  },
@@ -8138,9 +7920,6 @@ function build(options, binding) {
8138
7920
  updateGrant: async (caller, input) => access.updateGrant(await identityOf(caller), input),
8139
7921
  explain: async (caller, query) => access.explain(await identityOf(caller), query),
8140
7922
  revokeGrant: async (caller, input) => access.revokeGrant(await identityOf(caller), input),
8141
- tokens: async (caller) => access.tokens(await identityOf(caller)),
8142
- createToken: async (caller, body) => access.createToken(await identityOf(caller), body),
8143
- revokeToken: async (caller, input) => access.revokeToken(await identityOf(caller), input),
8144
7923
  schemas: async () => schemaRegistry.schemas(),
8145
7924
  schema: async (_caller, input) => schemaRegistry.schema(input),
8146
7925
  createSchema: async (caller, body) => schemaRegistry.createSchema(await identityOf(caller), body),
@@ -8152,8 +7931,7 @@ function build(options, binding) {
8152
7931
  data,
8153
7932
  name,
8154
7933
  type,
8155
- uploadedBy: principal.id,
8156
- uploadedWith: await access.chain(principal)
7934
+ uploadedBy: principal.id
8157
7935
  }, max) };
8158
7936
  },
8159
7937
  async uploadStart(caller, { name, type, size }) {
@@ -8163,8 +7941,7 @@ function build(options, binding) {
8163
7941
  name: name ?? null,
8164
7942
  type: type ?? null,
8165
7943
  size,
8166
- uploadedBy: principal.id,
8167
- uploadedWith: await access.chain(principal)
7944
+ uploadedBy: principal.id
8168
7945
  });
8169
7946
  },
8170
7947
  async uploadFinish(caller, { id }) {
@@ -8277,12 +8054,14 @@ function build(options, binding) {
8277
8054
  if (!binding.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: read it where its sync runs`, "not_synced_here");
8278
8055
  const { principal } = await identityOf(caller);
8279
8056
  if (!principal.access.everywhere("manage")) throw forbidden$1("this token can't read a source: it needs manage in every channel");
8057
+ unnarrowed(principal, "read a source");
8280
8058
  return binding.readSource(key, target, limit ?? 50, after ?? null);
8281
8059
  },
8282
8060
  async joinSource(caller, { key, target }) {
8283
8061
  if (!binding.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: join it where its sync runs`, "not_synced_here");
8284
8062
  const { principal } = await identityOf(caller);
8285
8063
  if (!principal.access.everywhere("manage")) throw forbidden$1("this token can't join a source: it needs manage in every channel");
8064
+ unnarrowed(principal, "join a source");
8286
8065
  return binding.joinSource(key, target);
8287
8066
  },
8288
8067
  async synced(caller, { id }, signal) {
@@ -8632,7 +8411,7 @@ function build(options, binding) {
8632
8411
  return { ok: true };
8633
8412
  },
8634
8413
  async inbox(caller, { key, channel, limit }) {
8635
- const { principal } = await needSync(caller, "read an inbox");
8414
+ const { principal } = await needSync(caller, "read an inbox", true);
8636
8415
  const everywhere = principal.access.everywhere("sync");
8637
8416
  const entries = [];
8638
8417
  if (everywhere) {
@@ -8904,11 +8683,7 @@ function a2(options) {
8904
8683
  ...Object.fromEntries(METHODS.map((name) => [name, async (caller, input, signal) => (await ready()).methods[name](caller, input, signal)])),
8905
8684
  routes: [],
8906
8685
  keeps: true,
8907
- trust: {
8908
- grants: async () => (await ready()).trust.grants(),
8909
- token: async (hash) => (await ready()).trust.token(hash),
8910
- live: async (id) => (await ready()).trust.live(id)
8911
- },
8686
+ trust: { grants: async () => (await ready()).trust.grants() },
8912
8687
  bind(given) {
8913
8688
  if (binding) throw new Error("this backend already serves a board: create one per board()");
8914
8689
  binding = given;
@@ -9025,10 +8800,10 @@ function local(options = {}) {
9025
8800
  opening ??= (async () => {
9026
8801
  const file = localFile(bound.name);
9027
8802
  let store;
9028
- if (options.memory) store = (await import("./memory-BvVoglGv.mjs")).memory();
8803
+ if (options.memory) store = (await import("./memory-DhduVbUu.mjs")).memory();
9029
8804
  else {
9030
8805
  const { mkdir } = await import("node:fs/promises");
9031
- const { sqlite } = await import("./sqlite-D4mkYihG.mjs");
8806
+ const { sqlite } = await import("./sqlite-B3rCcIof.mjs");
9032
8807
  const path = join(dir, `${file}.db`);
9033
8808
  try {
9034
8809
  await mkdir(dir, {
@@ -9060,11 +8835,7 @@ function local(options = {}) {
9060
8835
  ...Object.fromEntries(METHODS.map((name) => [name, async (caller, input, signal) => (await open()).backend[name](caller, input, signal)])),
9061
8836
  routes: [],
9062
8837
  keeps: true,
9063
- trust: {
9064
- grants: async () => (await open()).backend.trust.grants(),
9065
- token: async (hash) => (await open()).backend.trust.token(hash),
9066
- live: async (id) => (await open()).backend.trust.live(id)
9067
- },
8838
+ trust: { grants: async () => (await open()).backend.trust.grants() },
9068
8839
  bind(given) {
9069
8840
  if (binding) throw new Error("local: this backend already serves a board: create one local() per board()");
9070
8841
  binding = given;