@vercel/board 0.39.0 → 0.41.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 (100) hide show
  1. package/README.md +6 -4
  2. package/dist/{access-CVkjSfxj.mjs → access-C5HaO42b.mjs} +2 -2
  3. package/dist/access.d.mts +6 -6
  4. package/dist/access.mjs +5 -5
  5. package/dist/actors-nrOf7Y7z.mjs +160 -0
  6. package/dist/{auth-BXLCkeB0.d.mts → auth-Bn8J_1F2.d.mts} +14 -29
  7. package/dist/{auth-B3bBYOqf.mjs → auth-DAlYi6TN.mjs} +9 -19
  8. package/dist/{backend-HcCCGPG4.d.mts → backend-CYsTLxtP.d.mts} +139 -43
  9. package/dist/backend-local.d.mts +1 -1
  10. package/dist/backend-local.mjs +1 -1
  11. package/dist/blocks-CVoBC7ur.mjs +402 -0
  12. package/dist/blocks-DGvh2alZ.d.mts +33 -0
  13. package/dist/{chat-provider-1WKsLEnM.mjs → chat-provider-CPZg2MQb.mjs} +2 -2
  14. package/dist/{chat-provider-DyNy5xdC.d.mts → chat-provider-Cgkh9xJw.d.mts} +2 -2
  15. package/dist/cli-commands.d.mts +1 -1
  16. package/dist/cli-commands.mjs +1 -1
  17. package/dist/cli-embedded.d.mts +3 -3
  18. package/dist/cli-embedded.mjs +4 -4
  19. package/dist/cli.mjs +8 -13
  20. package/dist/{commands-B5d-lmNN.d.mts → commands-CrEVjASe.d.mts} +14 -26
  21. package/dist/{commands-BLS7erNu.mjs → commands-QRD0U9AQ.mjs} +114 -105
  22. package/dist/{conformance-D59Py2m2.mjs → conformance-ClxEEZ9C.mjs} +378 -101
  23. package/dist/conformance.d.mts +11 -9
  24. package/dist/conformance.mjs +1 -1
  25. package/dist/data-values-C-Cq80hz.mjs +176 -0
  26. package/dist/digest-Dna1CGa_.mjs +4 -0
  27. package/dist/{engine-eUgO5jTM.mjs → engine-8BcNeckB.mjs} +197 -84
  28. package/dist/{errors-rYDxZEuN.mjs → errors-DcQf5WeM.mjs} +123 -42
  29. package/dist/{events-C6HwB046.mjs → events-BT8y_81j.mjs} +2 -2
  30. package/dist/{exports-M5o4PTfO.mjs → exports-B6udRV_E.mjs} +961 -383
  31. package/dist/exports-C8zsIL1A.d.mts +4 -0
  32. package/dist/{external-CHDxWIVf.mjs → external-DymyhUzl.mjs} +1 -1
  33. package/dist/{index-rNqqgkyu.d.mts → index-fcpEFCTR.d.mts} +2 -2
  34. package/dist/index.d.mts +7 -6
  35. package/dist/index.mjs +8 -6
  36. package/dist/index.node.d.mts +7 -6
  37. package/dist/index.node.mjs +5 -4
  38. package/dist/inspect/app.js +110 -109
  39. package/dist/inspect/engine.js +5 -5
  40. package/dist/inspect-BsF3mYMY.mjs +2 -0
  41. package/dist/{inspect-BkXxR2uB.mjs → inspect-DPRoC_Gg.mjs} +6 -6
  42. package/dist/{local-DvkOWf4U.mjs → local-B9y4p6N7.mjs} +463 -512
  43. package/dist/{main-DtV_Po9i.mjs → main-S0A-c_kP.mjs} +549 -178
  44. package/dist/{memory-DkoqhxIH.mjs → memory-DhduVbUu.mjs} +2 -2
  45. package/dist/{mentions-CB6ShY4R.mjs → mentions-DfZGp3B-.mjs} +18 -4
  46. package/dist/{middleware-CPqAuRtp.mjs → middleware-DHdrxmoc.mjs} +71 -3
  47. package/dist/{targets-C1mT3M1N.mjs → origin-B3m2lnZC.mjs} +43 -64
  48. package/dist/{page-64IwoGRu.mjs → page-2jjHZmIW.mjs} +2 -2
  49. package/dist/page-CAUe4GmQ.mjs +2 -0
  50. package/dist/{provider-D5yVFisj.d.mts → provider-dY54GFNz.d.mts} +20 -34
  51. package/dist/{routes-BffuaoTX.d.mts → routes-By9lmvUD.d.mts} +91 -77
  52. package/dist/{schemas-AZkxk06N.mjs → schemas-DAzSsgWk.mjs} +8 -3
  53. package/dist/schemas.d.mts +37 -0
  54. package/dist/schemas.mjs +3 -0
  55. package/dist/{serve-CX1rqDF_.mjs → serve-B15I2Ibf.mjs} +5 -5
  56. package/dist/{server-DkYkyarg.mjs → server-DgpRZ4Nu.mjs} +74 -127
  57. package/dist/{serving-DJMcG0dT.mjs → serving-CALKWs9K.mjs} +1 -1
  58. package/dist/{sql-l3ysn4O5.mjs → sql-P9g-rLIF.mjs} +75 -12
  59. package/dist/{sqlite-CAwNHbQD.mjs → sqlite-B3rCcIof.mjs} +2 -2
  60. package/dist/{sqlite-db-cm5yhrD-.mjs → sqlite-db-D0Fyju-4.mjs} +1 -1
  61. package/dist/sync-chat-sdk.d.mts +2 -2
  62. package/dist/sync-chat-sdk.mjs +2 -2
  63. package/dist/sync-github.d.mts +2 -2
  64. package/dist/sync-github.mjs +2 -2
  65. package/dist/sync-linear.d.mts +3 -3
  66. package/dist/sync-linear.mjs +2 -2
  67. package/dist/sync-slack.d.mts +14 -8
  68. package/dist/sync-slack.mjs +46 -19
  69. package/dist/sync.d.mts +2 -2
  70. package/dist/sync.mjs +2 -2
  71. package/dist/{tokens-DA9ipsZ-.mjs → tokens-D7_ZIWpX.mjs} +4 -4
  72. package/docs/01-board/01-mounting.md +13 -16
  73. package/docs/01-board/03-identity.md +112 -74
  74. package/docs/01-board/04-messages.md +61 -2
  75. package/docs/01-board/05-reading.md +11 -5
  76. package/docs/01-board/06-watchers.md +17 -13
  77. package/docs/01-board/07-schedules.md +8 -6
  78. package/docs/01-board/08-middleware.md +1 -1
  79. package/docs/01-board/09-access.md +80 -132
  80. package/docs/02-sync/01-overview.md +75 -4
  81. package/docs/02-sync/02-functions.md +11 -6
  82. package/docs/02-sync/03-slack.md +43 -19
  83. package/docs/02-sync/06-providers.md +9 -4
  84. package/docs/03-guides/01-coding-agents.md +18 -22
  85. package/docs/03-guides/02-inspector.md +4 -5
  86. package/docs/03-guides/03-ci.md +7 -26
  87. package/docs/03-guides/04-triage.md +2 -2
  88. package/docs/03-guides/05-agent-factory.md +7 -9
  89. package/docs/03-guides/06-sandboxed-agents.md +149 -0
  90. package/docs/04-reference/01-cli.md +161 -104
  91. package/docs/04-reference/02-board.md +89 -37
  92. package/docs/04-reference/03-http.md +176 -71
  93. package/docs/04-reference/05-conformance.md +47 -21
  94. package/docs/index.md +5 -5
  95. package/package.json +5 -1
  96. package/dist/actors-kfMejhaw.mjs +0 -156
  97. package/dist/digest-krhjNAt4.mjs +0 -4
  98. package/dist/exports-vLQ2Y2Nd.d.mts +0 -4
  99. package/dist/inspect-lnv1sLXM.mjs +0 -2
  100. package/dist/page-BUj8_UZv.mjs +0 -2
@@ -1,16 +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-rYDxZEuN.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";
4
- import { a as runMatch, g as VERSION, h as SYNC, i as canonicalWatchers, l as METHODS, n as syncTarget, o as compileWatcher, r as withEmailMentions, s as hasCriteria } from "./targets-C1mT3M1N.mjs";
5
- import { a as waitUntil, c as isKeyIdOf, n as MIDDLEWARE_ACTOR, s as derivedId, t as DroppedError } from "./middleware-CPqAuRtp.mjs";
6
- import { a as canText, c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-CVkjSfxj.mjs";
7
- 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-B3bBYOqf.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-DcQf5WeM.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
+ 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-B3m2lnZC.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-DHdrxmoc.mjs";
7
+ import { c as compileAccess, i as authorize, o as checkGrantChange, t as FULL_ACCESS, u as parseCan } from "./access-C5HaO42b.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-DAlYi6TN.mjs";
8
9
  import { n as setOwn, t as own } from "./own-OwgPWdmh.mjs";
9
- import { n as replaceMentions } from "./mentions-CB6ShY4R.mjs";
10
- import { a as resolveMentions, n as actorSeen } from "./actors-kfMejhaw.mjs";
10
+ import { i as ownedActor, n as actorSeen, o as viaOf } from "./actors-nrOf7Y7z.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-l3ysn4O5.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";
14
15
  import { z } from "zod";
15
16
  import { createHash, randomBytes } from "node:crypto";
16
17
  import { mkdir, readFile, writeFile } from "node:fs/promises";
@@ -3843,7 +3844,6 @@ const boardEvents = {
3843
3844
  thread: ThreadKey,
3844
3845
  labels: Labels,
3845
3846
  noSync: z.boolean(),
3846
- mentions: z.array(ActorId),
3847
3847
  by: Author,
3848
3848
  origin: Origin.nullable(),
3849
3849
  from: From,
@@ -3888,7 +3888,6 @@ const boardEvents = {
3888
3888
  id: MessageId,
3889
3889
  thread: ThreadKey,
3890
3890
  text: MessageText,
3891
- mentions: z.array(ActorId),
3892
3891
  by: Author,
3893
3892
  from: From
3894
3893
  }),
@@ -3969,10 +3968,26 @@ const boardEvents = {
3969
3968
  name: z.string().min(1).max(128).refine(storable, "name has a NUL character or a lone surrogate"),
3970
3969
  avatar: z.string().url().nullable(),
3971
3970
  /**
3971
+ * (server) Who an actor with a profile acts through, as the board shows it: its principal's name
3972
+ * (a deployment's project, anyone else's handle), and a deployment's environment.
3973
+ */
3974
+ via: z.object({
3975
+ name: Handle,
3976
+ environment: z.string().min(1).max(128).nullable()
3977
+ }).optional(),
3978
+ /** (server) A platform user's platform (`slack`), as their sync key was registered with: for display. */
3979
+ platform: z.string().min(1).max(64).optional(),
3980
+ /**
3972
3981
  * (server) A principal a host's `authenticate` made, or one of its profiles: someone the board
3973
3982
  * signs in, whatever its ID or kind, so sync never writes as it. Others have none.
3974
3983
  */
3975
- host: z.literal(true).optional()
3984
+ host: z.literal(true).optional(),
3985
+ /**
3986
+ * (server) Whether this write's credential named the actor as shown, rather than taking it from what
3987
+ * the caller sent: under the handle it gave the principal, as itself or after `via`. Unlike `host`,
3988
+ * each `actor.seen` says it anew. Others, and events from before, have none.
3989
+ */
3990
+ verified: z.literal(true).optional()
3976
3991
  })
3977
3992
  };
3978
3993
  const BOARD_SESSION = "board";
@@ -4107,7 +4122,7 @@ const StoredPrincipal = z.object({
4107
4122
  team: z.string().max(200).optional()
4108
4123
  }).optional(),
4109
4124
  scope: z.string().max(CAN_MAX).optional(),
4110
- /** 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. */
4111
4126
  token: z.string().min(1).max(64).optional()
4112
4127
  });
4113
4128
  /** A watcher as a board on `http()` registers it: its tail. */
@@ -4156,7 +4171,11 @@ const ScheduleIdentity = z.object({
4156
4171
  kind: SeenActorKind,
4157
4172
  handle: Handle,
4158
4173
  name: z.string().min(1).max(128),
4159
- avatar: z.string().nullable()
4174
+ avatar: z.string().nullable(),
4175
+ via: z.object({
4176
+ name: Handle,
4177
+ environment: z.string().min(1).max(128).nullable()
4178
+ }).optional()
4160
4179
  })
4161
4180
  });
4162
4181
  /**
@@ -4271,9 +4290,8 @@ const GrantPrincipal = z.discriminatedUnion("kind", [
4271
4290
  /** A grant's `can`, as written: each pattern and `'all'` or its permissions. */
4272
4291
  const GrantCan = z.record(z.string().min(1).max(300), Grant);
4273
4292
  /**
4274
- * Who the board trusts beside its code's rules, outside the board log: grants, and the tokens it
4275
- * issued, of which only a hash is kept. Session `access`. A token's ID is the index of the event
4276
- * 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.
4277
4295
  */
4278
4296
  const accessContract = contract({
4279
4297
  name: "board-access",
@@ -4308,30 +4326,30 @@ const accessContract = contract({
4308
4326
  id: z.number().int().positive(),
4309
4327
  by: ActorId
4310
4328
  }),
4311
- "token.minted": z.object({
4312
- /** The secret's SHA-256, hex. */
4313
- hash: z.string().regex(/^[0-9a-f]{64}$/),
4314
- name: z.string().min(1).max(64),
4315
- /** Who it acts as, its scope narrowed to what the token may do. */
4316
- minter: StoredPrincipal,
4317
- profile: z.string().min(1).max(32).nullable(),
4318
- avatar: z.string().max(2048).nullable(),
4319
- session: z.string().min(1).max(128).nullable(),
4320
- /** A person's handle and name when they minted it. */
4321
- handle: Handle.nullable(),
4322
- personName: z.string().min(1).max(128).nullable(),
4323
- expiresAt: Millis,
4324
- /** The token it was minted with, which it stops with. */
4325
- parent: z.number().int().positive().nullable(),
4326
- by: ActorId
4327
- }),
4328
- "token.revoked": z.object({
4329
- id: z.number().int().positive(),
4330
- by: ActorId
4331
- })
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 })
4332
4333
  }
4333
4334
  });
4334
4335
  const ACCESS_SESSION = "access";
4336
+ /**
4337
+ * The board's schema registry, outside the board log: one session, `schemas`. A version is
4338
+ * registered once and never changes, so its event is all there is of it.
4339
+ */
4340
+ const schemasContract = contract({
4341
+ name: "board-schemas",
4342
+ events: {
4343
+ /** A schema version, for good: `name@version` is its ID, and `schema` the JSON Schema the board checked. */
4344
+ "schema.created": z.object({
4345
+ name: z.string().regex(SCHEMA_NAME),
4346
+ version: z.number().int().min(1).max(SCHEMA_VERSION_MAX),
4347
+ description: z.string().min(1).max(SCHEMA_DESCRIPTION_MAX).nullable(),
4348
+ schema: z.record(z.string(), z.unknown()),
4349
+ by: ActorId
4350
+ }) }
4351
+ });
4352
+ const SCHEMAS_SESSION = "schemas";
4335
4353
  reducer({
4336
4354
  contract: boardContract,
4337
4355
  name: "board.messages.v5",
@@ -4387,16 +4405,34 @@ const HIDDEN = /* @__PURE__ */ new Set([
4387
4405
  "message.synced",
4388
4406
  "message.files_synced"
4389
4407
  ]);
4408
+ /** Whether the board checked who an actor is, as people see them, at their last write (`actor.seen`'s `verified`). */
4409
+ const verifiedRecord = (actor) => actor.verified === true;
4390
4410
  function actorView(actors, id) {
4391
4411
  const author = own(actors.byId, id);
4392
4412
  if (!author) return null;
4413
+ const via = viaOfRecord(author);
4393
4414
  return {
4394
4415
  kind: author.kind,
4395
4416
  handle: author.handle,
4396
4417
  name: author.name,
4397
- avatar: author.avatar
4418
+ avatar: author.avatar,
4419
+ ...via ? { via } : {},
4420
+ ...author.platform ? { platform: author.platform } : {},
4421
+ ...verifiedRecord(author) ? { verified: true } : {}
4398
4422
  };
4399
4423
  }
4424
+ /**
4425
+ * Who an actor with a profile acts through, as its record says. An agent recorded before records
4426
+ * said, whose handle is `<person>/<profile>`, acts through the person its handle names.
4427
+ */
4428
+ function viaOfRecord(actor) {
4429
+ if (actor.via) return { ...actor.via };
4430
+ const slash = actor.handle.indexOf("/");
4431
+ return actorParts(actor.id).profile !== null && slash > 0 ? {
4432
+ name: actor.handle.slice(0, slash),
4433
+ environment: null
4434
+ } : void 0;
4435
+ }
4400
4436
  /** The board's own code, which reads every channel: it needs no messages to say so. */
4401
4437
  const OWN_CODE = {
4402
4438
  access: FULL_ACCESS,
@@ -4462,10 +4498,11 @@ const scheduleRef = (index) => `s${index}`;
4462
4498
  /** The log index a ref names on this board, or null for a string that names nothing here. */
4463
4499
  const indexOf$1 = (value) => /^(0|[1-9]\d{0,15})$/.test(value) ? Number(value) : null;
4464
4500
  /** A message as `reader` sees it. Every view names its reader, so none shows a link's snapshot by default. */
4465
- function view(message, actors, reader) {
4466
- const { blind, version, revision, schedule, ...shown } = message;
4501
+ function view$1(message, actors, reader) {
4502
+ const { blind, version, revision, schedule, platformText, mentions: _mentions, ...shown } = message;
4467
4503
  return {
4468
4504
  ...shown,
4505
+ by: authorView(message.by),
4469
4506
  ...blind ? { blind } : {},
4470
4507
  id: ref(message.id),
4471
4508
  re: message.re === null ? null : ref(message.re),
@@ -4479,14 +4516,14 @@ function view(message, actors, reader) {
4479
4516
  links: readableLinks(message.links, reader),
4480
4517
  labels: { ...message.labels },
4481
4518
  reactions: Object.fromEntries(Object.entries(message.reactions).map(([emoji, ids]) => [emoji, [...ids]])),
4482
- author: actorView(actors, message.by.actor)
4519
+ author: actorView(actors, message.by.actor),
4520
+ blocks: message.from === null && !platformText ? blocksIn(message.text) : []
4483
4521
  };
4484
4522
  }
4485
4523
  const actorSet = (value, actors) => own(actors.byId, value) ? /* @__PURE__ */ new Set([value]) : new Set(own(actors.byHandle, value.toLowerCase()) ?? []);
4486
4524
  /**
4487
- * Who a `--by` or `--mentions` value covers. A person (`julian`) is everyone they
4488
- * are: their own actor, and their agents (`julian/claude`). An agent or a platform
4489
- * actor is just itself.
4525
+ * Who a `--by` value covers. A person (`julian`) is everyone they are: their own
4526
+ * actor, and their agents (`julian/claude`). An agent or a platform actor is just itself.
4490
4527
  */
4491
4528
  function whoIs(value, actors) {
4492
4529
  const ids = actorSet(value, actors);
@@ -4495,6 +4532,49 @@ function whoIs(value, actors) {
4495
4532
  principals: new Set([...ids].filter((id) => own(actors.byId, id)?.kind === "person"))
4496
4533
  };
4497
4534
  }
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
+ /**
4548
+ * What a `--mentions` value matches in a message's text (`mentionTerms`): `me` is the caller's handle
4549
+ * and ID. Anyone else is the value as written, and what's under it: a person's agents
4550
+ * (`@julian/claude`), a project's imports (`@support/malte`), and their IDs. A reader of every
4551
+ * channel also gets each actor the value names, by ID or by handle, through their other name: their
4552
+ * handle and ID. Anyone else doesn't, since that would say who goes by what where it can't read.
4553
+ */
4554
+ function mentionFilter(value, context) {
4555
+ if (value === "me") return {
4556
+ terms: context.me === null ? [] : [mentionTerm(context.me.handle), context.me.id],
4557
+ prefixes: []
4558
+ };
4559
+ const under = (name) => name.includes(":") ? `${name}+` : `${mentionTerm(name)}/`;
4560
+ const terms = /* @__PURE__ */ new Set([mentionTerm(value)]);
4561
+ const prefixes = /* @__PURE__ */ new Set([under(value)]);
4562
+ if (!context.access.readsAll) return {
4563
+ terms: [...terms],
4564
+ prefixes: [...prefixes]
4565
+ };
4566
+ for (const id of actorSet(value, context.actors)) {
4567
+ const actor = own(context.actors.byId, id);
4568
+ terms.add(id).add(mentionTerm(actor.handle));
4569
+ prefixes.add(under(actor.handle)).add(under(id));
4570
+ }
4571
+ return {
4572
+ terms: [...terms],
4573
+ prefixes: [...prefixes]
4574
+ };
4575
+ }
4576
+ /** Whether `text` mentions what a `--mentions` filter matches. */
4577
+ const mentionsIn = (text, filter) => mentionTerms(text).some((term) => filter.terms.includes(term) || filter.prefixes.some((prefix) => term.startsWith(prefix)));
4498
4578
  /** Whether `author` is one of `who`: its actor, or an agent of one of its people. */
4499
4579
  const covers = (who, actor, principal) => who.actors.has(actor) || principal !== void 0 && who.principals.has(principal);
4500
4580
  const hasLabel = (labels, [key, values]) => Object.hasOwn(labels, key) && (values === null || values.includes(labels[key]));
@@ -4511,9 +4591,9 @@ function compileFilter(filters, context) {
4511
4591
  const labels = filters.label ?? [];
4512
4592
  const channel = filters.channel;
4513
4593
  const subtree = channel?.endsWith("/") ? channel.slice(0, -1) : null;
4514
- const by = filters.by === void 0 ? null : whoIs(filters.by, context.actors);
4594
+ const by = filters.by === void 0 ? null : authorOf(filters.by, context);
4515
4595
  const re = filters.re === void 0 ? void 0 : indexOf$1(filters.re) ?? -1;
4516
- const mentions = filters.mentions === void 0 ? null : filters.mentions === "me" ? new Set(context.me === null ? [] : [context.me]) : whoIs(filters.mentions, context.actors).actors;
4596
+ const mentions = filters.mentions === void 0 ? null : mentionFilter(filters.mentions, context);
4517
4597
  return (message) => {
4518
4598
  if (!message || !access.readable(message.channel)) return false;
4519
4599
  if (channel !== void 0) {
@@ -4523,7 +4603,7 @@ function compileFilter(filters, context) {
4523
4603
  }
4524
4604
  if (re !== void 0 && message.id !== re && message.re !== re) return false;
4525
4605
  if (by !== null && !covers(by, message.by.actor, message.by.principal)) return false;
4526
- if (mentions !== null && !message.mentions.some((id) => mentions.has(id))) return false;
4606
+ if (mentions !== null && !mentionsIn(message.text, mentions)) return false;
4527
4607
  if (filters.from !== void 0 && (message.from ?? "board") !== filters.from) return false;
4528
4608
  if (text !== void 0 && !message.text.toLowerCase().includes(text)) return false;
4529
4609
  if (labels.length > 0) {
@@ -4547,7 +4627,7 @@ function readableFilter(filter, known, access) {
4547
4627
  channels: [...known].filter((path) => within(path) && access.readable(path))
4548
4628
  };
4549
4629
  }
4550
- /** The filters as the tables take them: handles resolved to who they cover, `me` to the caller. */
4630
+ /** The filters as the tables take them: handles resolved to who they cover, mentions to the terms they match. */
4551
4631
  function toMessageFilter(filters, context) {
4552
4632
  const out = {};
4553
4633
  const channel = filters.channel;
@@ -4560,13 +4640,13 @@ function toMessageFilter(filters, context) {
4560
4640
  };
4561
4641
  if (filters.re !== void 0) out.re = indexOf$1(filters.re) ?? -1;
4562
4642
  if (filters.by !== void 0) {
4563
- const who = whoIs(filters.by, context.actors);
4643
+ const who = authorOf(filters.by, context);
4564
4644
  out.by = {
4565
4645
  actors: [...who.actors],
4566
4646
  principals: [...who.principals]
4567
4647
  };
4568
4648
  }
4569
- if (filters.mentions !== void 0) out.mentions = filters.mentions === "me" ? context.me === null ? [] : [context.me] : [...whoIs(filters.mentions, context.actors).actors];
4649
+ if (filters.mentions !== void 0) out.mentions = mentionFilter(filters.mentions, context);
4570
4650
  if (filters.from !== void 0) out.from = filters.from;
4571
4651
  if (filters.text !== void 0) out.text = filters.text.toLowerCase();
4572
4652
  if (filters.label?.length) out.labels = filters.label.map(([key, values]) => ({
@@ -4630,7 +4710,7 @@ function eventView(event, after, actors, reader) {
4630
4710
  type: event.type,
4631
4711
  createdAt: iso(event.createdAt),
4632
4712
  payload: payloadView(event.payload, links ? readableLinks(links, reader) : void 0),
4633
- ...after ? { message: view(after, actors, reader) } : {},
4713
+ ...after ? { message: view$1(after, actors, reader) } : {},
4634
4714
  ...actor ? { actor: {
4635
4715
  id: actor.id,
4636
4716
  ...actorView(actors, actor.id)
@@ -4639,12 +4719,13 @@ function eventView(event, after, actors, reader) {
4639
4719
  }
4640
4720
  /** An event's payload as clients see it: the message IDs in it are refs. */
4641
4721
  function payloadView(payload, links) {
4642
- const shown = { ...payload };
4722
+ const { mentions: _mentions, ...shown } = payload;
4643
4723
  for (const key of [
4644
4724
  "id",
4645
4725
  "re",
4646
4726
  "replyTo"
4647
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);
4648
4729
  const schedule = shown.schedule;
4649
4730
  if (schedule) shown.schedule = {
4650
4731
  id: scheduleRef(schedule.id),
@@ -4826,8 +4907,7 @@ function deploymentIdentity(actor, handle) {
4826
4907
  author: {
4827
4908
  actor,
4828
4909
  principal: actor,
4829
- profile: null,
4830
- session: null
4910
+ profile: null
4831
4911
  },
4832
4912
  actor: {
4833
4913
  id: actor,
@@ -4840,22 +4920,34 @@ function deploymentIdentity(actor, handle) {
4840
4920
  }
4841
4921
  /**
4842
4922
  * The `actor.seen` a write carries, or null: who its author is, as the board's record of them
4843
- * says, unless the board knows that already. A platform user's record is board-wide, so a write
4844
- * whose identity doesn't keep it (`records: false`) leaves it as it is. A host's principal and its
4845
- * profiles are recorded as the host's, which sync never writes as.
4923
+ * says, unless the board knows that already. A host's principal and its profiles are recorded as
4924
+ * the host's, which sync never writes as.
4846
4925
  */
4847
4926
  function seenFor(identity, actors) {
4848
- if (identity.records === false) return null;
4849
- return actorSeen(identity.actor, actors, identity.principal.facts?.issuer === "host");
4850
- }
4851
- /** The actors a write can mention: the ones the board knows, plus the ones an email named. */
4852
- const knownWith = (actors, found) => found.length === 0 ? actors : {
4853
- ...actors,
4854
- byId: {
4855
- ...actors.byId,
4856
- ...Object.fromEntries(found.map((a) => [a.id, a]))
4857
- }
4858
- };
4927
+ const { verified: _verified, ...actor } = identity.actor;
4928
+ return actorSeen(verifiedAs(identity) ? {
4929
+ ...actor,
4930
+ verified: true
4931
+ } : actor, actors, identity.principal.facts?.issuer === "host");
4932
+ }
4933
+ /**
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.
4939
+ */
4940
+ function verifiedAs({ principal, author, actor }) {
4941
+ if (principal.kind === "external") return actor.verified === true;
4942
+ if (principal.id.startsWith("board:")) return false;
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;
4945
+ }
4946
+ /**
4947
+ * Whether `identity` wrote `message`, to change it as its author: its principal did, as itself or
4948
+ * any of its agents, and a platform user a sync speaks for only as that same user.
4949
+ */
4950
+ const authored = (message, identity) => message.by.principal === identity.principal.id && (platformProfile(identity.author.profile) === null || message.by.actor === identity.author.actor);
4859
4951
  const messageNotFound = (id) => () => notFound(`message not found: #${id}`, "message_not_found");
4860
4952
  /**
4861
4953
  * A message the board looked up and the caller may act on with `permission`,
@@ -4875,7 +4967,7 @@ async function authorizeMessage(ctx, access, permission, id) {
4875
4967
  * read, it's yours only if it was posted without reading too: a write-only
4876
4968
  * source fixes what it wrote, but a principal ID it shares with a caller that
4877
4969
  * reads (a repo's workflows share one) doesn't reach that caller's messages.
4878
- * 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`).
4879
4971
  * Someone else's answers 404 where you can't read it, and 403 where you can.
4880
4972
  */
4881
4973
  async function authorizeOwn(ctx, identity, id, verb) {
@@ -4989,7 +5081,7 @@ async function landedFor(ctx, identity, landed) {
4989
5081
  if (!sameAuthor(landed.by, identity.author)) return null;
4990
5082
  const { access } = identity.principal;
4991
5083
  const { state: actors } = await ctx.session.state(actorsReducer);
4992
- if (access.readable(landed.channel)) return view(landed, actors, await readerFor(ctx, access, landed));
5084
+ if (access.readable(landed.channel)) return view$1(landed, actors, await readerFor(ctx, access, landed));
4993
5085
  if (!landed.blind) return null;
4994
5086
  const [event] = await ctx.session.history({
4995
5087
  gte: landed.id,
@@ -5000,18 +5092,17 @@ async function landedFor(ctx, identity, landed) {
5000
5092
  replies: {}
5001
5093
  }, event).byId[landed.id];
5002
5094
  return {
5003
- ...view(posted, actors, await readerFor(ctx, access, posted)),
5004
- text: blindText(posted.text, identity.actor.id),
5005
- mentions: []
5095
+ ...view$1(posted, actors, await readerFor(ctx, access, posted)),
5096
+ text: blindText(posted.text, identity.actor.id)
5006
5097
  };
5007
5098
  }
5008
5099
  /**
5009
5100
  * A message's text for its writer where it can't read: each exact mention but of itself shows as
5010
- * `@…`. The board may have turned an email it wrote into an actor ID, and who that is, `/actors`
5011
- * doesn't show it either.
5101
+ * `@…`. The board turned an email it wrote into an actor ID before mentions were text, and a sync's
5102
+ * import names its own profiles: who those are, `/actors` doesn't show it either.
5012
5103
  */
5013
5104
  const blindText = (text, own) => replaceMentions(text, (token) => token.kind === "actor" && token.actor !== own ? "@…" : null);
5014
- 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;
5015
5106
  async function commitPost(ctx, input, placed) {
5016
5107
  const { identity } = input;
5017
5108
  const { channel, re, replyTo, thread, id, sent } = placed;
@@ -5026,9 +5117,6 @@ async function commitPost(ctx, input, placed) {
5026
5117
  });
5027
5118
  }
5028
5119
  const seen = seenFor(identity, actors);
5029
- const { text, found } = await withEmailMentions(input.text);
5030
- const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
5031
- const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? identity.actor : void 0, input.lenientMentions ?? false, identity.principal.access.readsAll);
5032
5120
  const synced = await Promise.all(targets.map(async ({ target, kind, cause }) => ({
5033
5121
  type: "thread.synced",
5034
5122
  id: await derivedId("board", thread, "sync", target),
@@ -5042,19 +5130,17 @@ async function commitPost(ctx, input, placed) {
5042
5130
  })));
5043
5131
  const events = [
5044
5132
  ...seen ? [seen] : [],
5045
- ...named,
5046
5133
  {
5047
5134
  type: "message.posted",
5048
5135
  ...id ? { id } : {},
5049
5136
  payload: {
5050
5137
  channel,
5051
- text,
5138
+ text: input.text,
5052
5139
  re,
5053
5140
  replyTo,
5054
5141
  thread,
5055
5142
  labels: input.labels ?? {},
5056
5143
  noSync: input.noSync ?? false,
5057
- mentions,
5058
5144
  by: identity.author,
5059
5145
  origin: input.origin ?? null,
5060
5146
  from: input.from ?? null,
@@ -5089,25 +5175,22 @@ async function commitPost(ctx, input, placed) {
5089
5175
  ...actors,
5090
5176
  byId: {
5091
5177
  ...actors.byId,
5092
- [identity.actor.id]: identity.actor
5178
+ [identity.actor.id]: {
5179
+ ...identity.actor,
5180
+ ...seen.payload.host ? { host: true } : {},
5181
+ ...seen.payload.verified ? { verified: true } : {}
5182
+ }
5093
5183
  }
5094
5184
  } : actors;
5095
- return shownTo(view(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent, unknown);
5185
+ return shownTo(view$1(message, known, await readerFor(ctx, identity.principal.access, message)), identity.principal.access, sent);
5096
5186
  }
5097
5187
  /**
5098
5188
  * A post's view for its writer. One that can't read the channel gets back the
5099
- * text it sent, no mentions, and no `unknownMentions`: the board resolved its
5100
- * handles and emails to actor IDs, which `/actors` doesn't show it, and which
5101
- * handles matched no one would say which ones exist. The board keeps the
5102
- * mentions, so they still notify.
5189
+ * text it sent: what the board made of it (the middleware's changes) is for its readers.
5103
5190
  */
5104
- const shownTo = (shown, access, sent, unknown = []) => !access.readable(shown.channel) ? {
5191
+ const shownTo = (shown, access, sent) => !access.readable(shown.channel) ? {
5105
5192
  ...shown,
5106
- text: sent,
5107
- mentions: []
5108
- } : unknown.length ? {
5109
- ...shown,
5110
- unknownMentions: unknown
5193
+ text: sent
5111
5194
  } : shown;
5112
5195
  /** The writer, as the reader of the view its write returns. Only a link to a board message needs a lookup. */
5113
5196
  const readerFor = (ctx, access, message) => ctx.reads.reader(access, [message]);
@@ -5190,7 +5273,7 @@ function spent(authorized, permission) {
5190
5273
  }
5191
5274
  async function writeEdit(ctx, input) {
5192
5275
  const message = spent(input.authorized, "post");
5193
- if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can edit a message");
5276
+ if (input.asAuthor !== false && !authored(message, input.identity)) throw forbidden$1("only the author can edit a message");
5194
5277
  if (message.deleted) {
5195
5278
  if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
5196
5279
  throw badRequest("message was deleted", "message_deleted");
@@ -5200,26 +5283,17 @@ async function writeEdit(ctx, input) {
5200
5283
  async function commitEdit(ctx, input, message) {
5201
5284
  const { state: actors } = await ctx.session.state(actorsReducer);
5202
5285
  const seen = seenFor(input.identity, actors);
5203
- const { text, found } = await withEmailMentions(input.text);
5204
- const named = found.map((actor) => actorSeen(actor, actors)).filter((event) => event !== null);
5205
- const { mentions, unknown } = resolveMentions(text, knownWith(actors, found), seen ? input.identity.actor : void 0, input.from != null, input.identity.principal.access.readsAll);
5206
- const events = [
5207
- ...seen ? [seen] : [],
5208
- ...named,
5209
- {
5210
- type: "message.edited",
5211
- payload: {
5212
- id: message.id,
5213
- thread: message.thread,
5214
- text,
5215
- mentions,
5216
- by: input.identity.author,
5217
- from: input.from ?? null
5218
- }
5286
+ const events = [...seen ? [seen] : [], {
5287
+ type: "message.edited",
5288
+ payload: {
5289
+ id: message.id,
5290
+ thread: message.thread,
5291
+ text: input.text,
5292
+ by: input.identity.author,
5293
+ from: input.from ?? null
5219
5294
  }
5220
- ];
5295
+ }];
5221
5296
  await untilApplied(ctx, input.revision === void 0 ? await ctx.session.append(...events) : await appendWhile(ctx, revisionIs(ctx, message.id, input.revision), events));
5222
- return unknown.length && input.identity.principal.access.readable(message.channel) ? { unknownMentions: unknown } : {};
5223
5297
  }
5224
5298
  /** A message's links, replaced: a platform edit or unfurl changed what it links to. */
5225
5299
  async function writeLinks(ctx, input) {
@@ -5238,7 +5312,7 @@ async function writeLinks(ctx, input) {
5238
5312
  }
5239
5313
  async function writeDelete(ctx, input) {
5240
5314
  const message = spent(input.authorized, "post");
5241
- if (input.asAuthor !== false && message.by.principal !== input.identity.principal.id) throw forbidden$1("only the author can delete a message");
5315
+ if (input.asAuthor !== false && !authored(message, input.identity)) throw forbidden$1("only the author can delete a message");
5242
5316
  if (message.deleted) {
5243
5317
  if (input.revision !== void 0 && input.revision !== (message.revision ?? message.id)) throw new HttpError(409, "revision_conflict", `#${message.id} was deleted since revision ${input.revision}`);
5244
5318
  return;
@@ -5373,16 +5447,12 @@ const appendIfLast = (session, index, events) => session.append.ifLastIndex(inde
5373
5447
  const headMoved = (error) => error?.code === "LAST_INDEX_MISMATCH";
5374
5448
  //#endregion
5375
5449
  //#region src/server/trust.ts
5376
- /** How long a token lives when its minter doesn't say, and at most: npm caps its write tokens at 90 days. */
5377
- const TOKEN_DEFAULT_MS = 2592e6;
5378
- /** How deep tokens minted with tokens go: each request walks the chain to its root. */
5379
- const TOKEN_DEPTH_MAX = 8;
5380
5450
  /**
5381
5451
  * The grants a board starts with, as a team's board in Vercel's API does: g1, every person may do
5382
5452
  * everything (no team roles cap it here), g2, every project on the board's team, in every
5383
- * environment, reads, posts, reacts, and labels everywhere, and g3, every app on the team, the
5384
- * same. A local board has no apps, so g3 names no one here, but the defaults are the same
5385
- * everywhere. Revoke or change them like any other.
5453
+ * environment, reads, posts, reacts, labels, and syncs everywhere, and g3, every app on the team,
5454
+ * reads, posts, reacts, and labels. A local board has no apps, so g3 names no one here, but the
5455
+ * defaults are the same everywhere. Revoke or change them like any other.
5386
5456
  */
5387
5457
  const STARTING_GRANTS = {
5388
5458
  1: {
@@ -5408,7 +5478,8 @@ const STARTING_GRANTS = {
5408
5478
  "read",
5409
5479
  "post",
5410
5480
  "react",
5411
- "label"
5481
+ "label",
5482
+ "sync"
5412
5483
  ] },
5413
5484
  by: null,
5414
5485
  at: null
@@ -5427,59 +5498,19 @@ const STARTING_GRANTS = {
5427
5498
  at: null
5428
5499
  }
5429
5500
  };
5430
- /** 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. */
5431
5502
  const startingAccess = () => ({
5432
5503
  grants: structuredClone(STARTING_GRANTS),
5433
- nextGrant: 4,
5434
- tokens: {},
5435
- hashes: {},
5436
- expiring: {},
5437
- pruned: null
5504
+ nextGrant: 4
5438
5505
  });
5439
- const DAY_MS = 864e5;
5440
- function dropToken(state, id) {
5441
- const row = state.tokens[id];
5442
- if (!row) return;
5443
- delete state.hashes[row.hash];
5444
- delete state.tokens[id];
5445
- }
5446
- /** Whether token `id` is token `ancestor`, or was minted with it at any depth. */
5447
- function mintedWith(state, id, ancestor) {
5448
- let at = id;
5449
- for (let depth = 0; at !== null && depth <= TOKEN_DEPTH_MAX; depth++) {
5450
- if (at === ancestor) return true;
5451
- at = state.tokens[at]?.parent ?? null;
5452
- }
5453
- return false;
5454
- }
5455
- /**
5456
- * Whether `identity` may see and revoke token `row`: anyone's with `manage` in every channel. A
5457
- * token acts as its minter, so its principal alone would hand it every token its minter has: with
5458
- * a token, it's that token and those minted with it; without one, those its principal minted.
5459
- */
5460
- function manages(state, { principal }, row) {
5461
- if (principal.access.everywhere("manage")) return true;
5462
- if (row.minter.id !== principal.id) return false;
5463
- if (principal.token === void 0) return true;
5464
- const held = indexOf(principal.token, "t");
5465
- return held !== null && mintedWith(state, row.id, held);
5466
- }
5467
- /**
5468
- * The access session's fold. It prunes by the events' own times, so every instance folds the same
5469
- * state, and each event costs a day's expired tokens at most. A child whose parent is gone counts
5470
- * as dead (`liveIn`), and lives no longer than its parent, so pruning never brings one back.
5471
- */
5506
+ /** The access session's fold. */
5472
5507
  function foldAccess(state, event) {
5473
5508
  const at = new Date(event.createdAt).getTime();
5474
- const day = Math.floor(at / DAY_MS);
5475
- if (state.pruned === null) state.pruned = day;
5476
- for (; state.pruned < day; state.pruned++) {
5477
- for (const id of state.expiring[state.pruned] ?? []) dropToken(state, id);
5478
- delete state.expiring[state.pruned];
5479
- }
5480
5509
  switch (event.type) {
5481
5510
  case "grant.set":
5482
- case "grant.revoked": break;
5511
+ case "grant.revoked":
5512
+ case "token.minted":
5513
+ case "token.revoked": break;
5483
5514
  case "grant.created": {
5484
5515
  const { principals, can, by } = event.payload;
5485
5516
  const id = state.nextGrant++;
@@ -5504,36 +5535,19 @@ function foldAccess(state, event) {
5504
5535
  });
5505
5536
  break;
5506
5537
  }
5507
- case "grant.deleted":
5508
- delete state.grants[event.payload.id];
5509
- break;
5510
- case "token.minted": {
5511
- const { payload } = event;
5512
- if (state.hashes[payload.hash] !== void 0) break;
5513
- state.tokens[event.index] = {
5514
- id: event.index,
5515
- ...payload,
5516
- minter: payload.minter,
5517
- at
5518
- };
5519
- state.hashes[payload.hash] = event.index;
5520
- (state.expiring[Math.floor(payload.expiresAt / DAY_MS)] ??= []).push(event.index);
5521
- break;
5522
- }
5523
- case "token.revoked": dropToken(state, event.payload.id);
5538
+ case "grant.deleted": delete state.grants[event.payload.id];
5524
5539
  }
5525
5540
  return state;
5526
5541
  }
5527
5542
  const accessReducer = reducer({
5528
5543
  contract: accessContract,
5529
- name: "board.access.v2",
5544
+ name: "board.access.v4",
5530
5545
  initialState: startingAccess()
5531
5546
  }).fold(foldAccess);
5532
5547
  const grantId = (id) => `g${id}`;
5533
- const tokenId = (id) => `t${id}`;
5534
- /** The index an ID names: `g12` or `t12` for 12. Null for one that names none. */
5535
- function indexOf(id, prefix) {
5536
- 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);
5537
5551
  return found ? Number(found[1]) : null;
5538
5552
  }
5539
5553
  /** A principal as views show it: the IDs, and the names the board knows, which on a local board are none. */
@@ -5585,23 +5599,6 @@ const storedGrant = (row) => ({
5585
5599
  principals: row.principals,
5586
5600
  can: row.can
5587
5601
  });
5588
- /** A token as the protocol shows it, with `can` what it may do now (`accessNow`'s, for its minter). */
5589
- const tokenView = (row, can) => ({
5590
- id: tokenId(row.id),
5591
- name: row.name,
5592
- can: can === null ? {} : can.summary(),
5593
- profile: row.profile,
5594
- session: row.session,
5595
- by: row.by,
5596
- at: new Date(row.at).toISOString(),
5597
- expiresAt: new Date(row.expiresAt).toISOString(),
5598
- parent: row.parent === null ? null : tokenId(row.parent)
5599
- });
5600
- /** A new token's secret: the prefix and 32 random bytes, base64url. */
5601
- function newSecret() {
5602
- const bytes = crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(32));
5603
- return `${BOARD_TOKEN_PREFIX}${btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "")}`;
5604
- }
5605
5602
  /**
5606
5603
  * The principal an explain query names, as a token of its would make it: a person by user ID, a
5607
5604
  * project's deployment in one environment (production unless it says) on the board's team, a
@@ -5686,7 +5683,7 @@ function principalNamed(query, team) {
5686
5683
  * `manage` lets them, so a grant on people holds against people.
5687
5684
  */
5688
5685
  const isOwner = (principal) => principal.kind === "person" && principal.id.startsWith("local:user:") && principal.facts?.issuer !== "host";
5689
- /** 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. */
5690
5687
  function lists({ principal }) {
5691
5688
  if (principal.access.at("manage", "*")) return true;
5692
5689
  return isOwner(principal) && (principal.scope === void 0 || compileAccess(parseCan(principal.scope)).at("manage", "*"));
@@ -5695,7 +5692,12 @@ function lists({ principal }) {
5695
5692
  function mayList(identity, what) {
5696
5693
  if (!lists(identity)) throw forbidden$1(`this token can't ${what}: it needs manage at *`);
5697
5694
  }
5698
- /** `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`. */
5699
5701
  const withoutEveryone = (grants) => grants.flatMap((grant) => {
5700
5702
  const principals = grant.principals.filter((principal) => principal.kind !== "everyone");
5701
5703
  return principals.length === 0 ? [] : [{
@@ -5705,7 +5707,7 @@ const withoutEveryone = (grants) => grants.flatMap((grant) => {
5705
5707
  });
5706
5708
  /**
5707
5709
  * What the caller may do on `grants`, the snapshot its write appends to (`caller`), and by its own
5708
- * 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.
5709
5711
  */
5710
5712
  async function changerAccess({ principal }, grants, accessIn) {
5711
5713
  if (isOwner(principal)) {
@@ -5738,7 +5740,7 @@ async function mayGrant(identity, change, before, after, accessIn, what = "this
5738
5740
  ...change
5739
5741
  });
5740
5742
  if (refused?.reason === "reach") {
5741
- 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);
5742
5744
  throw forbidden$1(`${change.revoked ? `this token can't ${what}: it` : what} reaches ${refused.pattern}, where you can't manage grants`);
5743
5745
  }
5744
5746
  if (refused) throw forbidden$1(`you can't let anyone in: everyone gets ${refused.permission} in ${refused.pattern}, which you can't`);
@@ -5752,10 +5754,10 @@ const namesIssuer = (principals) => principals.some((principal) => principal.kin
5752
5754
  * already. `issuers` are the ones the board's rules trust.
5753
5755
  */
5754
5756
  async function updated(identity, state, { id, add, remove, can }, issuers, accessIn, team) {
5755
- const index = indexOf(id, "g");
5757
+ const index = indexOf(id);
5756
5758
  const row = index === null ? void 0 : state.grants[index];
5757
5759
  if (!row) {
5758
- mayList(identity, "update grants");
5760
+ if (!lists(identity)) throw unreachable(`update ${id}`);
5759
5761
  throw notFound(`grant not found: ${id}`, "grant_not_found");
5760
5762
  }
5761
5763
  const before = Object.values(state.grants).map(storedGrant);
@@ -5801,9 +5803,9 @@ async function updated(identity, state, { id, add, remove, can }, issuers, acces
5801
5803
  };
5802
5804
  }
5803
5805
  /**
5804
- * 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
5805
5807
  * what board() checks requests against. `accessNow`: what a principal may do now, under board()'s
5806
- * defaults and the grants, which a token's listing shows.
5808
+ * defaults and the grants.
5807
5809
  */
5808
5810
  function createTrust(options) {
5809
5811
  const accessIn = (principal, grants) => options.accessNow(principal, grants);
@@ -5812,62 +5814,12 @@ function createTrust(options) {
5812
5814
  store: options.store
5813
5815
  }).session(ACCESS_SESSION);
5814
5816
  const read = async () => (await session.state(accessReducer)).state;
5815
- /** 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. */
5816
5818
  const latest = () => session.state(accessReducer, { through: "latest" });
5817
- /**
5818
- * What each of `rows` may do now: its minter's access, narrowed by its scope. A minter's is worked
5819
- * out once, however many tokens it has.
5820
- */
5821
- async function viewsOf(rows) {
5822
- const minters = /* @__PURE__ */ new Map();
5823
- return Promise.all(rows.map(async (row) => {
5824
- const { scope, ...minter } = row.minter;
5825
- const key = JSON.stringify(minter);
5826
- let access = minters.get(key);
5827
- if (!access) minters.set(key, access = options.accessNow(minter));
5828
- const now = await access;
5829
- return tokenView(row, now === null || scope === void 0 ? now : now.narrow(parseCan(scope)));
5830
- }));
5831
- }
5832
- /** Whether token `id` and every token it was minted with are live now. */
5833
- function liveIn(state, id) {
5834
- let at = id;
5835
- for (let depth = 0; at !== null; depth++) {
5836
- const row = state.tokens[at];
5837
- if (!row || row.expiresAt <= Date.now() || depth > TOKEN_DEPTH_MAX) return false;
5838
- at = row.parent;
5839
- }
5840
- return true;
5841
- }
5842
5819
  return {
5843
- trust: {
5844
- async grants() {
5845
- return Object.values((await read()).grants).map(storedGrant);
5846
- },
5847
- async token(hash) {
5848
- const state = await read();
5849
- const id = state.hashes[hash];
5850
- if (id === void 0 || !liveIn(state, id)) return null;
5851
- const row = state.tokens[id];
5852
- return {
5853
- id: tokenId(row.id),
5854
- name: row.name,
5855
- minter: row.minter,
5856
- pinned: {
5857
- profile: row.profile,
5858
- avatar: row.avatar,
5859
- session: row.session,
5860
- handle: row.handle,
5861
- name: row.personName
5862
- },
5863
- expiresAt: new Date(row.expiresAt)
5864
- };
5865
- },
5866
- async live(id) {
5867
- const index = indexOf(id, "t");
5868
- return index !== null && liveIn(await read(), index);
5869
- }
5870
- },
5820
+ trust: { async grants() {
5821
+ return Object.values((await read()).grants).map(storedGrant);
5822
+ } },
5871
5823
  async grants(identity) {
5872
5824
  mayList(identity, "list grants");
5873
5825
  return { grants: Object.values((await read()).grants).sort((a, b) => a.id - b.id).map(grantView) };
@@ -5916,14 +5868,13 @@ function createTrust(options) {
5916
5868
  capped: null,
5917
5869
  can: []
5918
5870
  };
5919
- const { id, kind, handle, facts, scope, token } = identity.principal;
5871
+ const { id, kind, handle, facts, scope } = identity.principal;
5920
5872
  const principal = named ? principalNamed(query, await options.team()) : {
5921
5873
  id,
5922
5874
  kind,
5923
5875
  handle,
5924
5876
  ...facts ? { facts } : {},
5925
- ...scope !== void 0 ? { scope } : {},
5926
- ...token !== void 0 ? { token } : {}
5877
+ ...scope !== void 0 ? { scope } : {}
5927
5878
  };
5928
5879
  const decided = await options.explain(principal, query.channel);
5929
5880
  const { grants } = await read();
@@ -5934,7 +5885,7 @@ function createTrust(options) {
5934
5885
  over: decided.over,
5935
5886
  level: decided.level,
5936
5887
  grants: shown.flatMap((grant) => {
5937
- const row = grants[indexOf(grant.id, "g") ?? 0];
5888
+ const row = grants[indexOf(grant.id) ?? 0];
5938
5889
  return row ? [grantView(row)] : [];
5939
5890
  }),
5940
5891
  capped: null,
@@ -5944,10 +5895,10 @@ function createTrust(options) {
5944
5895
  async revokeGrant(identity, { id }) {
5945
5896
  return whileHeadMoves(async () => {
5946
5897
  const { state, index } = await latest();
5947
- const at = indexOf(id, "g");
5898
+ const at = indexOf(id);
5948
5899
  const row = at === null ? void 0 : state.grants[at];
5949
5900
  if (!row) {
5950
- mayList(identity, "revoke grants");
5901
+ if (!lists(identity)) throw unreachable(`revoke ${id}`);
5951
5902
  return { revoked: false };
5952
5903
  }
5953
5904
  const before = Object.values(state.grants).map(storedGrant);
@@ -5961,97 +5912,108 @@ function createTrust(options) {
5961
5912
  });
5962
5913
  return { revoked: true };
5963
5914
  });
5915
+ }
5916
+ };
5917
+ }
5918
+ //#endregion
5919
+ //#region src/server/schemas.ts
5920
+ /** The schemas session's fold: a version is its first event, and nothing changes it after. */
5921
+ function foldSchemas(state, event) {
5922
+ const { name, version, description, schema, by } = event.payload;
5923
+ state.byId[schemaId(name, version)] ??= {
5924
+ name,
5925
+ version,
5926
+ description,
5927
+ schema,
5928
+ by,
5929
+ at: new Date(event.createdAt).getTime()
5930
+ };
5931
+ return state;
5932
+ }
5933
+ const schemasReducer = reducer({
5934
+ contract: schemasContract,
5935
+ name: "board.schemas.v1",
5936
+ initialState: { byId: {} }
5937
+ }).fold(foldSchemas);
5938
+ const builtIns = BUILT_IN_SCHEMAS.map((schema) => ({
5939
+ id: schemaId(schema.name, schema.version),
5940
+ ...schema,
5941
+ builtIn: true,
5942
+ by: null,
5943
+ at: null
5944
+ }));
5945
+ const view = (row) => ({
5946
+ id: schemaId(row.name, row.version),
5947
+ name: row.name,
5948
+ version: row.version,
5949
+ description: row.description,
5950
+ schema: row.schema,
5951
+ builtIn: false,
5952
+ by: row.by,
5953
+ at: new Date(row.at).toISOString()
5954
+ });
5955
+ /**
5956
+ * The board's schema registry, in session `schemas` of its log: what a local board answers for
5957
+ * them. Anyone the board let in reads it, and registering takes `manage` at `*`, since a schema is
5958
+ * the whole board's.
5959
+ */
5960
+ function createSchemas(options) {
5961
+ const session = createServer({
5962
+ contract: schemasContract,
5963
+ store: options.store
5964
+ }).session(SCHEMAS_SESSION);
5965
+ const read = async () => (await session.state(schemasReducer)).state;
5966
+ /** The registry as it is now, and the index a conditional write holds it at. */
5967
+ const latest = () => session.state(schemasReducer, { through: "latest" });
5968
+ return {
5969
+ async schemas() {
5970
+ const own = Object.values((await read()).byId).sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : a.version - b.version);
5971
+ return { schemas: [...builtIns, ...own.map(view)] };
5964
5972
  },
5965
- async tokens(identity) {
5966
- const state = await read();
5967
- 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)) };
5968
- },
5969
- /** The board tokens `principal` came with: its own, then each it was minted with. Undefined with none. */
5970
- async chain(principal) {
5971
- if (principal.token === void 0) return void 0;
5972
- const state = await read();
5973
- const chain = [];
5974
- for (let at = indexOf(principal.token, "t"); at !== null && chain.length <= TOKEN_DEPTH_MAX; at = state.tokens[at]?.parent ?? null) chain.push(tokenId(at));
5975
- return chain;
5976
- },
5977
- async createToken(identity, body) {
5978
- const { principal, author, actor } = identity;
5979
- const state = await read();
5980
- const now = Date.now();
5981
- const asked = body.expires === void 0 ? TOKEN_DEFAULT_MS : duration(body.expires);
5982
- if (asked <= 0 || asked > 7776e6) throw badRequest("a token lives up to 90 days: pass expires as 90d or less", "invalid_expires");
5983
- let expiresAt = now + asked;
5984
- let parent = null;
5985
- if (principal.token !== void 0) {
5986
- const index = indexOf(principal.token, "t");
5987
- parent = index === null ? null : state.tokens[index] ?? null;
5988
- if (!parent || !liveIn(state, parent.id)) throw unauthorized("invalid token: revoked, expired, or not this board's");
5989
- let depth = 0;
5990
- for (let at = parent; at; at = at.parent === null ? void 0 : state.tokens[at.parent]) depth++;
5991
- if (depth >= TOKEN_DEPTH_MAX) throw badRequest(`tokens minted with tokens go ${TOKEN_DEPTH_MAX} deep at most`, "invalid_token");
5992
- expiresAt = Math.min(expiresAt, parent.expiresAt);
5993
- }
5994
- let can;
5995
- try {
5996
- can = compileAccess(body.can ?? DEFAULT_CAN);
5997
- } catch (error) {
5998
- throw badRequest(error.message, "invalid_scope");
5999
- }
6000
- const scope = canText((principal.scope === void 0 ? FULL_ACCESS : compileAccess(parseCan(principal.scope))).narrow(can));
6001
- if (scope.length > 4e3) throw badRequest(`a token's can is ${CAN_MAX} characters at most as a scope: name fewer channels`, "invalid_scope");
6002
- const minter = {
6003
- id: principal.id,
6004
- kind: principal.kind,
6005
- handle: principal.handle,
6006
- ...principal.facts ? { facts: principal.facts } : {},
6007
- scope
6008
- };
6009
- const pinned = principal.pinned;
6010
- const profile = pinned?.profile ?? body.profile ?? null;
6011
- const avatar = pinned?.profile ? pinned.avatar : profile !== null ? body.avatar ?? null : null;
6012
- const pinnedSession = pinned?.session ?? body.session ?? null;
6013
- const person = principal.kind === "person";
6014
- const base = author.profile === null ? actor.handle : actor.handle.slice(0, Math.max(0, actor.handle.length - author.profile.length - 1)) || principal.handle;
6015
- const handle = pinned?.handle ?? (person ? base : null);
6016
- const personName = pinned?.name ?? (person && author.profile === null ? actor.name : null);
6017
- const secret = newSecret();
6018
- const [row] = await session.append({
6019
- type: "token.minted",
6020
- payload: {
6021
- hash: await tokenHash(secret),
6022
- name: body.name,
6023
- minter,
6024
- profile,
6025
- avatar,
6026
- session: pinnedSession,
6027
- handle,
6028
- personName,
6029
- expiresAt,
6030
- parent: parent?.id ?? null,
6031
- by: actor.id
6032
- }
6033
- });
6034
- const minted = row && (await read()).tokens[row.index];
6035
- if (!minted) throw new Error("a token was minted but its log has no record of it");
6036
- const [view] = await viewsOf([minted]);
6037
- return {
6038
- token: view,
6039
- secret
6040
- };
5973
+ async schema({ id }) {
5974
+ if (!parseSchemaId(id)) throw badRequest(`${id} doesn't name a schema: one is name@version, like sandbox@1`, "invalid_schema_id");
5975
+ const builtIn = builtIns.find((schema) => schema.id === id);
5976
+ if (builtIn) return { schema: builtIn };
5977
+ const row = (await read()).byId[id];
5978
+ if (!row) throw notFound(`schema not found: ${id}`, "schema_not_found");
5979
+ return { schema: view(row) };
6041
5980
  },
6042
- async revokeToken(identity, { id }) {
6043
- const state = await read();
6044
- const index = indexOf(id, "t");
6045
- const row = index === null ? void 0 : state.tokens[index];
6046
- if (!row || !liveIn(state, row.id) || !manages(state, identity, row)) return { revoked: false };
6047
- await session.append({
6048
- type: "token.revoked",
6049
- payload: {
6050
- id: row.id,
6051
- by: identity.actor.id
5981
+ async createSchema({ principal, actor }, body) {
5982
+ if (!principal.access.at("manage", "*")) throw forbidden$1("this token can't register schemas: it needs manage at *");
5983
+ const id = schemaId(body.name, body.version);
5984
+ if (isBuiltInName(body.name)) throw new HttpError(409, "reserved_schema", `${body.name} is a built-in schema: register yours under another name`);
5985
+ const problem = checkDefinition(body.schema);
5986
+ if (problem !== null) throw badRequest(problem, "invalid_schema");
5987
+ const description = body.description ?? null;
5988
+ return whileHeadMoves(async () => {
5989
+ const { state, index } = await latest();
5990
+ const existing = state.byId[id];
5991
+ if (existing) {
5992
+ const differs = canonical(existing.schema) !== canonical(body.schema) ? "definition" : existing.description !== description ? "description" : null;
5993
+ if (differs !== null) throw new HttpError(409, "schema_immutable", `${id} is registered with another ${differs}, and a version never changes: register a new version`);
5994
+ return {
5995
+ schema: view(existing),
5996
+ created: false
5997
+ };
6052
5998
  }
5999
+ if (Object.keys(state.byId).length >= 500) throw badRequest(`a board registers at most 500 schema versions`, "too_many_schemas");
6000
+ await session.append.ifLastIndex(index, {
6001
+ type: "schema.created",
6002
+ payload: {
6003
+ name: body.name,
6004
+ version: body.version,
6005
+ description,
6006
+ schema: body.schema,
6007
+ by: actor.id
6008
+ }
6009
+ });
6010
+ const made = (await read()).byId[id];
6011
+ if (!made) throw new Error("a schema was registered but its log has no record of it");
6012
+ return {
6013
+ schema: view(made),
6014
+ created: true
6015
+ };
6053
6016
  });
6054
- return { revoked: true };
6055
6017
  }
6056
6018
  };
6057
6019
  }
@@ -6103,20 +6065,11 @@ function attachmentId() {
6103
6065
  if (!id.startsWith("-")) return id;
6104
6066
  }
6105
6067
  }
6106
- /**
6107
- * Whether an upload is the caller's own, to read and attach before a message carries it: its
6108
- * principal sent it, and the caller holds no board token, or holds the one it came with or one
6109
- * that token was minted with. A token acts as its minter, so the principal alone would hand it
6110
- * every file its minter, or another of its minter's tokens, uploaded.
6111
- */
6112
- function ownUpload(upload, caller) {
6113
- if (upload.uploadedBy !== caller.id) return false;
6114
- return caller.token === void 0 || (upload.uploadedWith?.includes(caller.token) ?? false);
6115
- }
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;
6116
6070
  /**
6117
6071
  * Stores an upload under a fresh ID, with its metadata beside it. `uploadedBy`
6118
- * is the principal that sent it, who can read it before any message carries it,
6119
- * 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.
6120
6073
  * `max` is the most it can be: `ATTACHMENT_BYTES_MAX` unless the board's own sync imports it.
6121
6074
  */
6122
6075
  async function writeUpload(blob, input, max = ATTACHMENT_BYTES_MAX) {
@@ -6132,8 +6085,7 @@ async function writeUpload(blob, input, max = ATTACHMENT_BYTES_MAX) {
6132
6085
  await blob.put(dataKey(attachment.id), input.data, attachment.type);
6133
6086
  const meta = input.uploadedBy === void 0 ? attachment : {
6134
6087
  ...attachment,
6135
- uploadedBy: input.uploadedBy,
6136
- ...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {}
6088
+ uploadedBy: input.uploadedBy
6137
6089
  };
6138
6090
  await blob.put(metaKey(attachment.id), new TextEncoder().encode(JSON.stringify(meta)), "application/json");
6139
6091
  return attachment;
@@ -6152,11 +6104,9 @@ async function readUpload(blob, id) {
6152
6104
  const found = Attachment.shape.id.safeParse(id).success ? await blob.get(metaKey(id)) : null;
6153
6105
  if (!found) throw attachmentNotFound(id);
6154
6106
  const meta = JSON.parse(new TextDecoder().decode(await bytes(found.data)));
6155
- const tokens = Array.isArray(meta.uploadedWith) && meta.uploadedWith.every((token) => typeof token === "string") ? meta.uploadedWith : null;
6156
6107
  return {
6157
6108
  attachment: Attachment.parse(meta),
6158
- uploadedBy: typeof meta.uploadedBy === "string" ? meta.uploadedBy : null,
6159
- uploadedWith: tokens
6109
+ uploadedBy: typeof meta.uploadedBy === "string" ? meta.uploadedBy : null
6160
6110
  };
6161
6111
  }
6162
6112
  /** An attachment's bytes as the store keeps them, a stream or the bytes, for board() to serve. */
@@ -6184,7 +6134,6 @@ async function startUpload(blob, input) {
6184
6134
  type: mediaType(input.type),
6185
6135
  size: input.size,
6186
6136
  uploadedBy: input.uploadedBy,
6187
- ...input.uploadedWith ? { uploadedWith: input.uploadedWith } : {},
6188
6137
  expiresAt: expires.toISOString()
6189
6138
  };
6190
6139
  await blob.put(ticketKey(ticket.id), new TextEncoder().encode(JSON.stringify(ticket)), "application/json");
@@ -6225,13 +6174,9 @@ async function finishUpload(blob, id, caller) {
6225
6174
  size: stored.size
6226
6175
  };
6227
6176
  try {
6228
- const uploader = {
6229
- uploadedBy: ticket.uploadedBy,
6230
- ...ticket.uploadedWith ? { uploadedWith: ticket.uploadedWith } : {}
6231
- };
6232
6177
  await blob.put(metaKey(id), new TextEncoder().encode(JSON.stringify({
6233
6178
  ...attachment,
6234
- ...uploader
6179
+ uploadedBy: ticket.uploadedBy
6235
6180
  })), "application/json");
6236
6181
  } catch (error) {
6237
6182
  const done = await blob.get(metaKey(id)).catch(() => null);
@@ -6376,8 +6321,7 @@ const storedPrincipal = (principal) => ({
6376
6321
  kind: principal.kind,
6377
6322
  handle: principal.handle,
6378
6323
  ...principal.facts ? { facts: principal.facts } : {},
6379
- ...principal.scope !== void 0 ? { scope: principal.scope } : {},
6380
- ...principal.token !== void 0 ? { token: principal.token } : {}
6324
+ ...principal.scope !== void 0 ? { scope: principal.scope } : {}
6381
6325
  });
6382
6326
  /** What a registration shows: the principal's token facts stay on the board. */
6383
6327
  const viewOf = ({ principal: _principal, ...view }) => view;
@@ -6459,18 +6403,23 @@ function createRegistry(options) {
6459
6403
  const MAX_HOP_MS = 432e6;
6460
6404
  /** A timer that fires this early just waits again; any closer counts as on time. */
6461
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
+ */
6462
6410
  const identityOf = (as) => {
6463
6411
  const { author, principal, actor } = as.payload.as;
6412
+ const stored = {
6413
+ ...principal,
6414
+ expiresAt: null
6415
+ };
6464
6416
  return {
6465
6417
  author,
6466
- principal: {
6467
- ...principal,
6468
- expiresAt: null
6469
- },
6470
- actor: {
6418
+ principal: stored,
6419
+ actor: ownedActor(stored, author, {
6471
6420
  ...actor,
6472
6421
  kind: actorKind(actor.kind)
6473
- }
6422
+ })
6474
6423
  };
6475
6424
  };
6476
6425
  function foldSchedules(state, event) {
@@ -6548,7 +6497,7 @@ function nextSend(schedule, n, at, now) {
6548
6497
  * needs `post` there now, as it would to create it. Where it can't read, the
6549
6498
  * schedule is its own only if it was created without reading too, so a
6550
6499
  * principal ID shared with a caller that reads doesn't reach that caller's.
6551
- * 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`).
6552
6501
  */
6553
6502
  const createdBy = (schedule, identity) => wroteAs(identity, {
6554
6503
  principal: schedule.as.principal.id,
@@ -6556,6 +6505,11 @@ const createdBy = (schedule, identity) => wroteAs(identity, {
6556
6505
  }) && identity.principal.access.can("post", schedule.channel) && (schedule.blind || identity.principal.access.readable(schedule.channel));
6557
6506
  const scheduleView = (schedule, actors) => {
6558
6507
  const author = actors.byId[schedule.as.actor.id] ?? schedule.as.actor;
6508
+ const via = viaOfRecord({
6509
+ id: schedule.as.actor.id,
6510
+ handle: author.handle,
6511
+ via: "via" in author ? author.via : void 0
6512
+ });
6559
6513
  return {
6560
6514
  id: scheduleRef(schedule.id),
6561
6515
  channel: schedule.channel,
@@ -6572,13 +6526,17 @@ const scheduleView = (schedule, actors) => {
6572
6526
  next: schedule.next === null ? null : new Date(schedule.next).toISOString(),
6573
6527
  last: schedule.last === null ? null : ref(schedule.last),
6574
6528
  state: schedule.canceled ? "canceled" : schedule.next === null ? "done" : "pending",
6575
- canceled: schedule.canceled,
6576
- by: schedule.as.author,
6529
+ canceled: schedule.canceled && {
6530
+ ...schedule.canceled,
6531
+ by: authorView(schedule.canceled.by)
6532
+ },
6533
+ by: authorView(schedule.as.author),
6577
6534
  author: {
6578
6535
  kind: author.kind,
6579
6536
  handle: author.handle,
6580
6537
  name: author.name,
6581
- avatar: author.avatar
6538
+ avatar: author.avatar,
6539
+ ...via ? { via } : {}
6582
6540
  },
6583
6541
  createdAt: schedule.createdAt
6584
6542
  };
@@ -6828,15 +6786,9 @@ function createSchedules(options) {
6828
6786
  if (every !== null && every > 316224e5) throw badRequest("`every` is at most a year");
6829
6787
  const first = body.at !== void 0 ? Date.parse(body.at) : now + duration(body.in ?? body.every);
6830
6788
  if (first < now - 6e4) throw badRequest("`at` is in the past");
6831
- const asked = body.until !== void 0 ? Date.parse(body.until) : body.for !== void 0 ? first + duration(body.for) : null;
6832
- const expires = identity.principal.token !== void 0 ? identity.principal.expiresAt?.getTime() ?? null : null;
6833
- 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");
6834
- 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;
6835
6790
  if (until !== null && until < first) throw badRequest("the schedule stops before its first send");
6836
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");
6837
- const { state: known } = await writes.session.state(actorsReducer);
6838
- const withoutEmails = replaceMentions(body.text, (t) => t.kind === "actor" && t.actor.includes("@") ? t.actor : null);
6839
- const { unknown } = resolveMentions(withoutEmails, known, identity.actor, false, identity.principal.access.readsAll);
6840
6792
  let channel = body.channel;
6841
6793
  let re = null;
6842
6794
  if (body.re !== void 0) {
@@ -6870,11 +6822,7 @@ function createSchedules(options) {
6870
6822
  const created = state.byId[row.index];
6871
6823
  if (created.next !== null) await arm("first", created.id, created.sent, created.next);
6872
6824
  const { state: actors } = await writes.session.state(actorsReducer);
6873
- const schedule = scheduleView(created, actors);
6874
- return unknown.length && identity.principal.access.readable(channel) ? {
6875
- schedule,
6876
- unknownMentions: unknown
6877
- } : { schedule };
6825
+ return { schedule: scheduleView(created, actors) };
6878
6826
  },
6879
6827
  /**
6880
6828
  * Its creator may cancel it while they can post there, and so may `manage`
@@ -6937,7 +6885,7 @@ const SYNCED = /* @__PURE__ */ new Set([
6937
6885
  "labels.changed",
6938
6886
  "thread.synced"
6939
6887
  ]);
6940
- /** 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. */
6941
6889
  const actorOf = (id) => `board:watch:${id}`;
6942
6890
  /** `watch:@<principal>`: everything one registrant's watchers matched, queued for it to pull. */
6943
6891
  const registrantSession = (owner) => watchSession(`@${owner}`);
@@ -7020,9 +6968,10 @@ function createWatchers(options) {
7020
6968
  const [messages, { state: actors }] = await Promise.all([messagesBefore(event, ctx.signal), ctx.session.state(actorsReducer, { through })]);
7021
6969
  const { id, before, after } = foldEvent(messages, actors, event);
7022
6970
  const by = event.payload.by?.actor;
6971
+ const scheduled = event.type === "message.posted" && event.payload.schedule !== void 0;
7023
6972
  const message = after ?? before;
7024
6973
  const thread = event.payload.thread;
7025
- let view$1;
6974
+ let view;
7026
6975
  /** Each session's matches, appended together: one append per watcher in config, one per registrant. */
7027
6976
  const appends = /* @__PURE__ */ new Map();
7028
6977
  const add = (session, matched) => (appends.get(session) ?? appends.set(session, []).get(session)).push(matched);
@@ -7036,7 +6985,7 @@ function createWatchers(options) {
7036
6985
  };
7037
6986
  for (const watcher of targets) {
7038
6987
  if (event.type === "thread.synced") break;
7039
- if (by === watcher.actor) continue;
6988
+ if (by === watcher.actor && !scheduled) continue;
7040
6989
  if (RECEIPTS.has(event.type) && !watcher.all) continue;
7041
6990
  const { registration } = watcher;
7042
6991
  let access = FULL_ACCESS;
@@ -7053,7 +7002,7 @@ function createWatchers(options) {
7053
7002
  });
7054
7003
  if (!(watcher.criteria ? match(before) || match(after) : id !== null)) continue;
7055
7004
  const key = registration ? `@${registration.owner}/${watcher.id}` : watcher.id;
7056
- const shown = registration ? eventView(event, after, actors, await reads.reader(access, after ? [after] : [])) : view$1 ??= eventView(event, after, actors, OWN_CODE);
7005
+ const shown = registration ? eventView(event, after, actors, await reads.reader(access, after ? [after] : [])) : view ??= eventView(event, after, actors, OWN_CODE);
7057
7006
  add(registration ? registrantSession(registration.owner) : watchSession(watcher.id), {
7058
7007
  type: "watch.matched",
7059
7008
  id: await idempotentId("board-watch", key, event.id),
@@ -7073,7 +7022,7 @@ function createWatchers(options) {
7073
7022
  const reader = await reads.reader(now, [about, ...before ? [before] : []]);
7074
7023
  const shown = {
7075
7024
  ...eventView(event, about, actors, reader),
7076
- ...event.type === "labels.changed" && before ? { before: view(before, actors, reader) } : {}
7025
+ ...event.type === "labels.changed" && before ? { before: view$1(before, actors, reader) } : {}
7077
7026
  };
7078
7027
  add(registrantSession(registration.owner), {
7079
7028
  type: "watch.matched",
@@ -7381,8 +7330,6 @@ function failure(found, error) {
7381
7330
  }
7382
7331
  //#endregion
7383
7332
  //#region src/server/a2.ts
7384
- /** Sync's own lookups and receipts, from board() in this deployment. */
7385
- const SYNC_ACTOR = "board:sync";
7386
7333
  /** The board's own code, through its handle: `team.post(…)`. With `as(profile)`, `board:client:<profile>`. */
7387
7334
  const CLIENT_ACTOR = "board:client";
7388
7335
  /** A cursor or message ref in a request, as this board's log index: decimals, from 0. */
@@ -7445,6 +7392,11 @@ function selfIdentity(caller) {
7445
7392
  if (!ID.test(self)) throw badRequest(`as: profiles use lowercase letters, numbers, - and _, got: ${self}`);
7446
7393
  return deploymentIdentity(`${CLIENT_ACTOR}:${self}`, self);
7447
7394
  }
7395
+ /** An actor's name as people see it, with who it acts through: `Malte via www (preview)`. */
7396
+ const shownOf = (actor) => actor ? shownName({
7397
+ name: actor.name,
7398
+ via: viaOfRecord(actor)
7399
+ }) : void 0;
7448
7400
  /** A schedule as its creator sees it where it can't read: its text as a blind writer's message's is. */
7449
7401
  const blindSchedule = (schedule, access, own) => access.readable(schedule.channel) ? schedule : {
7450
7402
  ...schedule,
@@ -7452,32 +7404,39 @@ const blindSchedule = (schedule, access, own) => access.readable(schedule.channe
7452
7404
  };
7453
7405
  /**
7454
7406
  * A platform user, writing through sync: full access, and each write still proved against the
7455
- * channel it lands in. Their avatar is an https URL or none. `records`: the write keeps the
7456
- * board's record of who they are, which only a sync that may sync everywhere does.
7407
+ * channel it lands in. Their avatar is an https URL or none. This board's own sync checked the
7408
+ * platform said so, so its platform users are themselves (`slack:user:U0456`); a sync elsewhere's
7409
+ * are its word, a profile of its principal (`vercel:project:prj_1:production+slack:user:U0456`),
7410
+ * whose record only its own imports change.
7457
7411
  */
7458
- function externalIdentity(author, records) {
7412
+ function externalIdentity(author, through, platform) {
7413
+ const id = through === null ? author.id : `${through.id}+${author.id}`;
7414
+ const host = through?.facts?.issuer === "host" ? { facts: through.facts } : {};
7415
+ const principal = {
7416
+ id: through?.id ?? author.id,
7417
+ kind: "external",
7418
+ handle: author.handle,
7419
+ access: FULL_ACCESS,
7420
+ expiresAt: null,
7421
+ ...host
7422
+ };
7459
7423
  return {
7460
- principal: {
7461
- id: author.id,
7462
- kind: "external",
7463
- handle: author.handle,
7464
- access: FULL_ACCESS,
7465
- expiresAt: null
7466
- },
7424
+ principal,
7467
7425
  author: {
7468
- actor: author.id,
7469
- principal: author.id,
7470
- profile: null,
7471
- session: null
7426
+ actor: id,
7427
+ principal: principal.id,
7428
+ profile: through === null ? null : author.id
7472
7429
  },
7473
7430
  actor: {
7474
- id: author.id,
7431
+ id,
7475
7432
  kind: "external",
7476
- handle: author.handle,
7433
+ handle: through === null ? author.handle : importedHandle(viaOf(through).name, author.handle, userIdOf(author.id)),
7477
7434
  name: author.name,
7478
- avatar: platformAvatar(author.avatar)
7479
- },
7480
- ...records ? {} : { records: false }
7435
+ avatar: platformAvatar(author.avatar),
7436
+ ...through === null ? {} : { via: viaOf(through) },
7437
+ platform,
7438
+ ...through !== null && !through.id.startsWith("board:") ? { verified: true } : {}
7439
+ }
7481
7440
  };
7482
7441
  }
7483
7442
  /** The board events sync delivers: what a platform shows, and a thread's new targets. */
@@ -7559,7 +7518,7 @@ function build(options, binding) {
7559
7518
  const { before, after } = foldEvent(messages, actors, event);
7560
7519
  const shown = {
7561
7520
  ...eventView(event, event.type === "thread.synced" ? (await reads.ensure(event.index - 1, ctx.signal), await store.tables.byEventId(event.payload.thread)) ?? void 0 : after, actors, OWN_CODE),
7562
- ...event.type === "labels.changed" && before ? { before: view(before, actors, OWN_CODE) } : {}
7521
+ ...event.type === "labels.changed" && before ? { before: view$1(before, actors, OWN_CODE) } : {}
7563
7522
  };
7564
7523
  await delivering.run(ctx, () => binding.run(SYNC, shown, {
7565
7524
  trigger: ctx.event.id,
@@ -7612,6 +7571,7 @@ function build(options, binding) {
7612
7571
  explain: (principal, channel) => binding.explain(principal, channel),
7613
7572
  team: async () => (await binding.project()).teamId
7614
7573
  });
7574
+ const schemaRegistry = createSchemas({ store: log });
7615
7575
  const inboxes = inboxServer.session(INBOXES_SESSION);
7616
7576
  /** The inboxes this instance knows have an `inbox.opened`, so most pushes write nothing more. */
7617
7577
  const opened = /* @__PURE__ */ new Set();
@@ -7647,7 +7607,7 @@ function build(options, binding) {
7647
7607
  through: index
7648
7608
  };
7649
7609
  }
7650
- /** Who wrote, was mentioned, or reacted in the channels `access` reads, a page at a time. */
7610
+ /** Who wrote, was mentioned by actor ID (`@[actor-id]`), or reacted in the channels `access` reads, a page at a time. */
7651
7611
  async function actorsIn(access) {
7652
7612
  const ids = /* @__PURE__ */ new Set();
7653
7613
  const { filter } = await readable({}, access);
@@ -7658,7 +7618,7 @@ function build(options, binding) {
7658
7618
  });
7659
7619
  for (const message of messages) {
7660
7620
  ids.add(message.by.actor);
7661
- for (const id of message.mentions) ids.add(id);
7621
+ for (const token of extractMentions(message.text)) if (token.kind === "actor" && !isEmail(token.actor)) ids.add(token.actor);
7662
7622
  for (const reactors of Object.values(message.reactions)) for (const id of reactors) ids.add(id);
7663
7623
  }
7664
7624
  if (messages.length < 500) return ids;
@@ -7703,7 +7663,7 @@ function build(options, binding) {
7703
7663
  if (fromRequest(caller) && body.id?.startsWith("sync:")) throw badRequest("id: sync:… IDs are what sync imports, under the principal that imports them");
7704
7664
  const attachments = await attachmentsFor(principal, body.attachments);
7705
7665
  const { schedule } = caller.origin;
7706
- const { unknownMentions, ...message } = await writePost(writes, {
7666
+ return { message: await writePost(writes, {
7707
7667
  attachments,
7708
7668
  identity,
7709
7669
  proofs,
@@ -7715,15 +7675,8 @@ function build(options, binding) {
7715
7675
  id: body.id,
7716
7676
  sync: body.sync,
7717
7677
  after: afterAt(body.after),
7718
- ...schedule && !fromRequest(caller) ? {
7719
- schedule,
7720
- lenientMentions: true
7721
- } : {}
7722
- });
7723
- return {
7724
- message,
7725
- ...unknownMentions ? { unknownMentions } : {}
7726
- };
7678
+ ...schedule && !fromRequest(caller) ? { schedule } : {}
7679
+ }) };
7727
7680
  }
7728
7681
  /**
7729
7682
  * The sync entry an import says it came through, when it names one: one its caller syncs, or a
@@ -7755,7 +7708,7 @@ function build(options, binding) {
7755
7708
  name: actor.name,
7756
7709
  avatar: actor.avatar,
7757
7710
  profile: author.profile,
7758
- session: author.session,
7711
+ ...actor.via ? { via: { ...actor.via } } : {},
7759
7712
  expiresAt: principal.expiresAt?.toISOString() ?? null,
7760
7713
  can: principal.access.summary()
7761
7714
  };
@@ -7784,7 +7737,15 @@ function build(options, binding) {
7784
7737
  seen = (id) => ids.has(id);
7785
7738
  }
7786
7739
  return {
7787
- actors: Object.values(state.byId).filter((a) => seen === null || seen(a.id)).sort((a, b) => a.handle.localeCompare(b.handle)).map(({ host: _host, ...a }) => a),
7740
+ actors: Object.values(state.byId).filter((a) => seen === null || seen(a.id)).sort((a, b) => a.handle.localeCompare(b.handle)).map((found) => {
7741
+ const { host: _host, via: _via, ...a } = found;
7742
+ const via = viaOfRecord(found);
7743
+ return {
7744
+ ...a,
7745
+ ...via ? { via } : {},
7746
+ ...verifiedRecord(found) ? { verified: true } : {}
7747
+ };
7748
+ }),
7788
7749
  cursor: ref(index)
7789
7750
  };
7790
7751
  },
@@ -7792,8 +7753,12 @@ function build(options, binding) {
7792
7753
  const { principal, actor } = await identityOf(caller);
7793
7754
  const { state: actors } = await session.state(actorsReducer);
7794
7755
  const { filter, through } = await readable(toMessageFilter(query, {
7795
- me: actor.id,
7796
- actors
7756
+ me: {
7757
+ id: actor.id,
7758
+ handle: actor.handle
7759
+ },
7760
+ actors,
7761
+ access: principal.access
7797
7762
  }), principal.access);
7798
7763
  const { messages, position } = await reads.messages(filter, {
7799
7764
  ...query.before !== void 0 ? { before: cursorAt(query.before) } : {},
@@ -7802,7 +7767,7 @@ function build(options, binding) {
7802
7767
  });
7803
7768
  const reader = await reads.reader(principal.access, messages);
7804
7769
  return {
7805
- messages: messages.map((m) => view(m, actors, reader)),
7770
+ messages: messages.map((m) => view$1(m, actors, reader)),
7806
7771
  cursor: ref(Math.min(position, through))
7807
7772
  };
7808
7773
  },
@@ -7810,8 +7775,12 @@ function build(options, binding) {
7810
7775
  const { principal, actor } = await identityOf(caller);
7811
7776
  const { state: actors } = await session.state(actorsReducer);
7812
7777
  const { filter, through } = await readable(toMessageFilter(query, {
7813
- me: actor.id,
7814
- actors
7778
+ me: {
7779
+ id: actor.id,
7780
+ handle: actor.handle
7781
+ },
7782
+ actors,
7783
+ access: principal.access
7815
7784
  }), principal.access);
7816
7785
  const { threads, position } = await reads.threads(filter, {
7817
7786
  ...query.after !== void 0 ? { after: cursorAt(query.after) } : {},
@@ -7820,9 +7789,9 @@ function build(options, binding) {
7820
7789
  const reader = await reads.reader(principal.access, threads.flatMap((t) => t.last ? [t.root, t.last] : [t.root]));
7821
7790
  return {
7822
7791
  threads: threads.map((t) => ({
7823
- message: view(t.root, actors, reader),
7792
+ message: view$1(t.root, actors, reader),
7824
7793
  replies: t.replies,
7825
- last: t.last && view(t.last, actors, reader)
7794
+ last: t.last && view$1(t.last, actors, reader)
7826
7795
  })),
7827
7796
  cursor: ref(Math.min(position, through))
7828
7797
  };
@@ -7836,8 +7805,8 @@ function build(options, binding) {
7836
7805
  const [root, ...replies] = messages;
7837
7806
  const reader = await reads.reader(principal.access, messages);
7838
7807
  return {
7839
- message: view(root, actors, reader),
7840
- replies: replies.map((reply) => view(reply, actors, reader)),
7808
+ message: view$1(root, actors, reader),
7809
+ replies: replies.map((reply) => view$1(reply, actors, reader)),
7841
7810
  cursor: ref(cursor),
7842
7811
  schedules: await schedules.forThread(root.id)
7843
7812
  };
@@ -7855,16 +7824,13 @@ function build(options, binding) {
7855
7824
  async edit(caller, { id, text, revision }) {
7856
7825
  const identity = await identityOf(caller);
7857
7826
  const authorized = await authorizeOwn(writes, identity, messageAt(id), "edit");
7858
- const { unknownMentions } = await writeEdit(writes, {
7827
+ await writeEdit(writes, {
7859
7828
  identity,
7860
7829
  authorized,
7861
7830
  text,
7862
7831
  revision
7863
7832
  });
7864
- return {
7865
- ok: true,
7866
- ...unknownMentions ? { unknownMentions } : {}
7867
- };
7833
+ return { ok: true };
7868
7834
  },
7869
7835
  async delete(caller, { id, revision }) {
7870
7836
  const identity = await identityOf(caller);
@@ -7920,8 +7886,10 @@ function build(options, binding) {
7920
7886
  principal,
7921
7887
  actor
7922
7888
  });
7889
+ const by = query.by === "me" ? actor.id : query.by;
7923
7890
  return { schedules: (await schedules.list({
7924
7891
  ...query,
7892
+ ...by !== void 0 ? { by } : {},
7925
7893
  ...root !== void 0 ? { root } : {}
7926
7894
  }, visible)).map((schedule) => blindSchedule(schedule, principal.access, actor.id)) };
7927
7895
  },
@@ -7938,9 +7906,9 @@ function build(options, binding) {
7938
7906
  updateGrant: async (caller, input) => access.updateGrant(await identityOf(caller), input),
7939
7907
  explain: async (caller, query) => access.explain(await identityOf(caller), query),
7940
7908
  revokeGrant: async (caller, input) => access.revokeGrant(await identityOf(caller), input),
7941
- tokens: async (caller) => access.tokens(await identityOf(caller)),
7942
- createToken: async (caller, body) => access.createToken(await identityOf(caller), body),
7943
- revokeToken: async (caller, input) => access.revokeToken(await identityOf(caller), input),
7909
+ schemas: async () => schemaRegistry.schemas(),
7910
+ schema: async (_caller, input) => schemaRegistry.schema(input),
7911
+ createSchema: async (caller, body) => schemaRegistry.createSchema(await identityOf(caller), body),
7944
7912
  async upload(caller, { data, name, type }) {
7945
7913
  const { principal } = await identityOf(caller);
7946
7914
  if (!principal.access.anywhere("post") && !principal.access.anywhere("sync")) throw forbidden$1("this token can't post anywhere, so it can't upload");
@@ -7949,8 +7917,7 @@ function build(options, binding) {
7949
7917
  data,
7950
7918
  name,
7951
7919
  type,
7952
- uploadedBy: principal.id,
7953
- uploadedWith: await access.chain(principal)
7920
+ uploadedBy: principal.id
7954
7921
  }, max) };
7955
7922
  },
7956
7923
  async uploadStart(caller, { name, type, size }) {
@@ -7960,8 +7927,7 @@ function build(options, binding) {
7960
7927
  name: name ?? null,
7961
7928
  type: type ?? null,
7962
7929
  size,
7963
- uploadedBy: principal.id,
7964
- uploadedWith: await access.chain(principal)
7930
+ uploadedBy: principal.id
7965
7931
  });
7966
7932
  },
7967
7933
  async uploadFinish(caller, { id }) {
@@ -8050,7 +8016,10 @@ function build(options, binding) {
8050
8016
  after,
8051
8017
  filters: query,
8052
8018
  all: query.all ?? false,
8053
- me: actor.id,
8019
+ me: {
8020
+ id: actor.id,
8021
+ handle: actor.handle
8022
+ },
8054
8023
  actors,
8055
8024
  access: principal.access
8056
8025
  }, (query.wait ?? 0) * 1e3, signal);
@@ -8132,15 +8101,11 @@ function build(options, binding) {
8132
8101
  },
8133
8102
  async syncImport(caller, body, signal) {
8134
8103
  const { principal } = await needSync(caller, "import", true);
8135
- await speaksFor(caller, principal.id, body.author, body.op === "seen" ? null : body.from);
8136
- const author = externalIdentity(body.author, recordsActors(caller, principal));
8137
- if (body.op === "seen") {
8138
- const { state: actors } = await session.state(actorsReducer);
8139
- const seen = author.records === false ? null : actorSeen(author.actor, actors);
8140
- if (seen) await session.append(seen);
8141
- return { message: null };
8142
- }
8104
+ const platform = await speaksFor(caller, principal.id, body.author, body.from);
8105
+ const author = externalIdentity(body.author, ownSync(caller) ? null : principal, platform);
8143
8106
  const may = (channel) => principal.access.can("sync", channel);
8107
+ const keys = ownSync(caller) ? [] : (await entriesOf(caller, principal.id)).map(({ key }) => key);
8108
+ const asNamed = (text) => keys.length === 0 ? text : replaceMentions(text, (token) => token.kind === "actor" && keys.some((key) => token.actor.startsWith(`${key}:`)) ? `@[${principal.id}+${token.actor}]` : null);
8144
8109
  if (body.op === "post") {
8145
8110
  if (body.channel === void 0 === (body.re === void 0)) throw badRequest("an import needs `channel`; a reply needs `re`");
8146
8111
  let re;
@@ -8166,7 +8131,7 @@ function build(options, binding) {
8166
8131
  proofs,
8167
8132
  channel: body.channel,
8168
8133
  re,
8169
- text,
8134
+ text: asNamed(text),
8170
8135
  labels,
8171
8136
  noSync: body.noSync,
8172
8137
  id,
@@ -8174,7 +8139,6 @@ function build(options, binding) {
8174
8139
  from: body.from,
8175
8140
  ...body.origin && !ownSync(caller) ? { importedBy: principal.id } : {},
8176
8141
  after: afterAt(body.after),
8177
- lenientMentions: true,
8178
8142
  attachments,
8179
8143
  links: await linksOf(principal, body.links)
8180
8144
  })).id;
@@ -8200,7 +8164,7 @@ function build(options, binding) {
8200
8164
  await writeEdit(writes, {
8201
8165
  identity: author,
8202
8166
  authorized: proof,
8203
- text,
8167
+ text: asNamed(text),
8204
8168
  from: body.from,
8205
8169
  asAuthor,
8206
8170
  revision: body.revision
@@ -8214,7 +8178,7 @@ function build(options, binding) {
8214
8178
  re: found.re === null ? null : ref(found.re),
8215
8179
  text: body.text
8216
8180
  };
8217
- if (!found.deleted && !(asAuthor && found.by.principal !== body.author.id)) await checkSource(caller, principal.id, body.source);
8181
+ if (!found.deleted && !(asAuthor && found.by.actor !== author.author.actor)) await checkSource(caller, principal.id, body.source);
8218
8182
  return { message: await commit(write) };
8219
8183
  }
8220
8184
  if (body.op === "delete") await writeDelete(writes, {
@@ -8495,15 +8459,18 @@ function build(options, binding) {
8495
8459
  return [...found.values()];
8496
8460
  }
8497
8461
  /**
8498
- * Whether a caller may write as `author`: a platform user, never anyone this board
8499
- * signs in, on a platform it syncs: the one of entry `from`, when it names one.
8462
+ * Whether a caller may write as `author`, and the platform of the sync key they're a user of: a
8463
+ * platform user, never anyone this board signs in, named under a key it syncs (`slack-eu:…`):
8464
+ * entry `from`, when it names one.
8500
8465
  */
8501
8466
  async function speaksFor(caller, principal, author, from) {
8502
8467
  if (authenticates(author.id) || await signedIn(author.id)) throw forbidden$1(`${author.id} is someone this board signs in, not a platform user: sync can't write as them`);
8503
8468
  const entries = await entriesOf(caller, principal);
8504
- const platforms = (from === null ? entries : entries.filter((entry) => entry.key === from)).map((entry) => entry.platform);
8505
- if (from !== null && platforms.length === 0) throw forbidden$1(`this token doesn't sync ${from} here: its board registers its sync entries`);
8506
- if (!platforms.some((platform) => author.id.startsWith(`${platform}:`))) throw forbidden$1(`${author.id} isn't a user of ${platforms.length ? platforms.join(" or ") : "a platform this token syncs"}`);
8469
+ const keys = from === null ? entries : entries.filter((entry) => entry.key === from);
8470
+ if (from !== null && keys.length === 0) throw forbidden$1(`this token doesn't sync ${from} here: its board registers its sync entries`);
8471
+ const entry = keys.find(({ key }) => author.id.startsWith(`${key}:`));
8472
+ if (!entry) throw forbidden$1(`${author.id} isn't a user of ${keys.length ? keys.map(({ key }) => key).join(" or ") : "a sync key this token has"}: their ID starts with its key`);
8473
+ return entry.platform;
8507
8474
  }
8508
8475
  /**
8509
8476
  * Whether `id` is someone this board signs in that `authenticates` can't tell by its shape: a
@@ -8531,14 +8498,6 @@ function build(options, binding) {
8531
8498
  if (principal.scope !== void 0) throw forbidden$1("this token is narrowed with x-board-can: registering and running watchers is its project's job");
8532
8499
  }
8533
8500
  /**
8534
- * Whether a sync's writes keep the board's record of the platform users they're by (name and
8535
- * avatar), which every channel shows: this board's own sync's, and those of one that may sync in every
8536
- * channel. Anyone else's still carry their author, and leave the record as it is.
8537
- */
8538
- function recordsActors(caller, principal) {
8539
- return ownSync(caller) || principal.access.everywhere("sync");
8540
- }
8541
- /**
8542
8501
  * The caller, when it may sync somewhere: what every sync route needs. `records`: what it does
8543
8502
  * keeps sync's records (imports, receipts, its inbox, links), which only an integration does,
8544
8503
  * never a caller narrowed with `x-board-can`.
@@ -8620,7 +8579,7 @@ function build(options, binding) {
8620
8579
  message: null
8621
8580
  };
8622
8581
  const snapshot = {
8623
- author: actors.byId[found.by.actor]?.name ?? found.by.actor,
8582
+ author: shownOf(actors.byId[found.by.actor]) ?? found.by.actor,
8624
8583
  text: found.text,
8625
8584
  createdAt: found.createdAt,
8626
8585
  files: found.attachments.map((file) => ({
@@ -8708,11 +8667,7 @@ function a2(options) {
8708
8667
  ...Object.fromEntries(METHODS.map((name) => [name, async (caller, input, signal) => (await ready()).methods[name](caller, input, signal)])),
8709
8668
  routes: [],
8710
8669
  keeps: true,
8711
- trust: {
8712
- grants: async () => (await ready()).trust.grants(),
8713
- token: async (hash) => (await ready()).trust.token(hash),
8714
- live: async (id) => (await ready()).trust.live(id)
8715
- },
8670
+ trust: { grants: async () => (await ready()).trust.grants() },
8716
8671
  bind(given) {
8717
8672
  if (binding) throw new Error("this backend already serves a board: create one per board()");
8718
8673
  binding = given;
@@ -8829,10 +8784,10 @@ function local(options = {}) {
8829
8784
  opening ??= (async () => {
8830
8785
  const file = localFile(bound.name);
8831
8786
  let store;
8832
- if (options.memory) store = (await import("./memory-DkoqhxIH.mjs")).memory();
8787
+ if (options.memory) store = (await import("./memory-DhduVbUu.mjs")).memory();
8833
8788
  else {
8834
8789
  const { mkdir } = await import("node:fs/promises");
8835
- const { sqlite } = await import("./sqlite-CAwNHbQD.mjs");
8790
+ const { sqlite } = await import("./sqlite-B3rCcIof.mjs");
8836
8791
  const path = join(dir, `${file}.db`);
8837
8792
  try {
8838
8793
  await mkdir(dir, {
@@ -8864,11 +8819,7 @@ function local(options = {}) {
8864
8819
  ...Object.fromEntries(METHODS.map((name) => [name, async (caller, input, signal) => (await open()).backend[name](caller, input, signal)])),
8865
8820
  routes: [],
8866
8821
  keeps: true,
8867
- trust: {
8868
- grants: async () => (await open()).backend.trust.grants(),
8869
- token: async (hash) => (await open()).backend.trust.token(hash),
8870
- live: async (id) => (await open()).backend.trust.live(id)
8871
- },
8822
+ trust: { grants: async () => (await open()).backend.trust.grants() },
8872
8823
  bind(given) {
8873
8824
  if (binding) throw new Error("local: this backend already serves a board: create one local() per board()");
8874
8825
  binding = given;