@vercel/board 0.40.0 → 0.42.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (91) hide show
  1. package/README.md +1 -1
  2. package/dist/{access-Bl_k_Hpa.mjs → access-BgBiaCyx.mjs} +2 -2
  3. package/dist/access.d.mts +6 -6
  4. package/dist/access.mjs +5 -5
  5. package/dist/{actors-yBRWTpt5.mjs → actors-DkZsnMgA.mjs} +59 -40
  6. package/dist/{auth-DtmZzlHm.d.mts → auth-Bn8J_1F2.d.mts} +12 -30
  7. package/dist/{auth-C8URZHLx.mjs → auth-Ft4AJptx.mjs} +9 -19
  8. package/dist/{backend-BW5NbBsp.d.mts → backend-DMrK55mU.d.mts} +137 -48
  9. package/dist/backend-local.d.mts +1 -1
  10. package/dist/backend-local.mjs +1 -1
  11. package/dist/{chat-provider-1WKsLEnM.mjs → chat-provider-CPZg2MQb.mjs} +2 -2
  12. package/dist/{chat-provider-Bbb9JguG.d.mts → chat-provider-Cgkh9xJw.d.mts} +2 -2
  13. package/dist/cli-commands.d.mts +1 -1
  14. package/dist/cli-commands.mjs +1 -1
  15. package/dist/cli-embedded.d.mts +10 -5
  16. package/dist/cli-embedded.mjs +8 -6
  17. package/dist/cli.mjs +8 -13
  18. package/dist/{commands-BJLocuXj.d.mts → commands-CrEVjASe.d.mts} +8 -30
  19. package/dist/{commands-D6VWegVY.mjs → commands-QRD0U9AQ.mjs} +30 -101
  20. package/dist/{conformance-BWhZ0k8T.mjs → conformance-BORt5nky.mjs} +139 -109
  21. package/dist/conformance.d.mts +9 -8
  22. package/dist/conformance.mjs +1 -1
  23. package/dist/digest-CKC0Rmy1.mjs +4 -0
  24. package/dist/{engine-Djif8XVk.mjs → engine-BVHSH2Kn.mjs} +11 -12
  25. package/dist/{errors-CNRJqUuL.mjs → errors-DUzpDSrJ.mjs} +112 -30
  26. package/dist/{events-C6HwB046.mjs → events-BT8y_81j.mjs} +2 -2
  27. package/dist/{exports-C2OWIbLU.mjs → exports-BfNXPHN_.mjs} +473 -174
  28. package/dist/exports-Bw_OYNRl.d.mts +4 -0
  29. package/dist/{external-CHDxWIVf.mjs → external-DymyhUzl.mjs} +1 -1
  30. package/dist/{index-Cuxbz_E0.d.mts → index-CydxnBND.d.mts} +2 -2
  31. package/dist/index.d.mts +6 -6
  32. package/dist/index.mjs +6 -5
  33. package/dist/index.node.d.mts +6 -6
  34. package/dist/index.node.mjs +3 -3
  35. package/dist/inspect/app.js +41 -41
  36. package/dist/inspect/engine.js +2 -2
  37. package/dist/{inspect-cGcP8ZO9.mjs → inspect-CniRRiJ2.mjs} +6 -6
  38. package/dist/inspect-HlHh7OXa.mjs +2 -0
  39. package/dist/{local-CsleYuyM.mjs → local-CWLPYoiY.mjs} +130 -359
  40. package/dist/{main-D97xuqWZ.mjs → main-aVEEoc60.mjs} +429 -139
  41. package/dist/{memory-BvVoglGv.mjs → memory-DhduVbUu.mjs} +2 -2
  42. package/dist/{mentions-CT2bN5eP.mjs → mentions-DfZGp3B-.mjs} +1 -1
  43. package/dist/{middleware-BF9vnPPS.mjs → middleware-0DUFrav-.mjs} +2 -2
  44. package/dist/{origin-DLCmrwmE.mjs → origin-DAyYeDuW.mjs} +7 -36
  45. package/dist/{page-6BTCZWGY.mjs → page-BD6ygU49.mjs} +2 -2
  46. package/dist/page-BiJVe-7R.mjs +2 -0
  47. package/dist/{provider-YqkF1E2k.d.mts → provider-dY54GFNz.d.mts} +1 -25
  48. package/dist/{routes-CAjd5ARa.d.mts → routes-By9lmvUD.d.mts} +1 -63
  49. package/dist/{schemas-AZkxk06N.mjs → schemas-DAzSsgWk.mjs} +8 -3
  50. package/dist/{serve-Cs-e0Jke.mjs → serve-BnBqi0sw.mjs} +5 -5
  51. package/dist/{server-CIfMdIt3.mjs → server-Bcpkt6TS.mjs} +79 -131
  52. package/dist/{serving-B4l0nLng.mjs → serving-hcxzaCCO.mjs} +1 -1
  53. package/dist/{sql-Bv-RQu8n.mjs → sql-P9g-rLIF.mjs} +3 -3
  54. package/dist/{sqlite-D4mkYihG.mjs → sqlite-B3rCcIof.mjs} +2 -2
  55. package/dist/{sqlite-db-BraLvHtf.mjs → sqlite-db-D0Fyju-4.mjs} +1 -1
  56. package/dist/sync-chat-sdk.d.mts +2 -2
  57. package/dist/sync-chat-sdk.mjs +2 -2
  58. package/dist/sync-github.d.mts +2 -2
  59. package/dist/sync-github.mjs +2 -2
  60. package/dist/sync-linear.d.mts +3 -3
  61. package/dist/sync-linear.mjs +2 -2
  62. package/dist/sync-slack.d.mts +3 -3
  63. package/dist/sync-slack.mjs +4 -4
  64. package/dist/sync.d.mts +2 -2
  65. package/dist/sync.mjs +2 -2
  66. package/dist/{tokens-CrrXAVGz.mjs → tokens-BSMpTPEe.mjs} +4 -4
  67. package/docs/01-board/01-mounting.md +12 -17
  68. package/docs/01-board/03-identity.md +45 -39
  69. package/docs/01-board/04-messages.md +3 -1
  70. package/docs/01-board/05-reading.md +8 -2
  71. package/docs/01-board/06-watchers.md +15 -10
  72. package/docs/01-board/07-schedules.md +6 -2
  73. package/docs/01-board/09-access.md +59 -111
  74. package/docs/02-sync/01-overview.md +5 -2
  75. package/docs/02-sync/03-slack.md +12 -12
  76. package/docs/03-guides/01-coding-agents.md +18 -22
  77. package/docs/03-guides/02-inspector.md +4 -5
  78. package/docs/03-guides/03-ci.md +7 -26
  79. package/docs/03-guides/04-triage.md +2 -2
  80. package/docs/03-guides/05-agent-factory.md +7 -9
  81. package/docs/03-guides/06-sandboxed-agents.md +149 -0
  82. package/docs/04-reference/01-cli.md +59 -90
  83. package/docs/04-reference/02-board.md +53 -37
  84. package/docs/04-reference/03-http.md +32 -53
  85. package/docs/04-reference/05-conformance.md +37 -18
  86. package/docs/index.md +4 -4
  87. package/package.json +1 -1
  88. package/dist/digest-D32GV_mX.mjs +0 -4
  89. package/dist/exports-FyRBIAMs.d.mts +0 -4
  90. package/dist/inspect-CLy6FrOZ.mjs +0 -2
  91. package/dist/page-BnY8FhPn.mjs +0 -2
@@ -1,11 +1,11 @@
1
- import { a as forbidden, c as toErrorResponse, d as createBoardClient, f as duration, g as fileName, h as IMPORT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as ATTACHMENT_BYTES_MAX, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as mediaType } from "./errors-CNRJqUuL.mjs";
2
- import { h as RemoteWatcherId } from "./schemas-AZkxk06N.mjs";
1
+ import { _ as IMPORT_BYTES_MAX, a as forbidden, b as mediaType, c as toErrorResponse, d as createBoardClient, f as duration, h as ATTACHMENT_BYTES_MAX, l as unauthorized, n as RejectedError, o as json, p as formatProfileHeader, r as badRequest, s as notFound, t as HttpError, u as BoardError, v as fileName } from "./errors-DUzpDSrJ.mjs";
2
+ import { h as RemoteWatcherId } from "./schemas-DAzSsgWk.mjs";
3
3
  import { f as schemaId, n as blocksIn, r as findBlocks } from "./blocks-CVoBC7ur.mjs";
4
- import { A as MessagesQuery, B as SyncBody, C as InboxAckBody, D as LabelBody, E as InboxQuery, F as ScheduleBody, G as ThreadsQuery, H as SyncFindQuery, I as SchedulesQuery, J as UpdateGrantBody, K as TokenBody, L as SchemaBody, M as ReactBody, N as Ref, O as LinkedQuery, P as RegisterBody, R as SourceJoinBody, S as GrantBody, T as InboxPushBody, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as UploadStartBody, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as runMatch, j as PostBody, k as MatchesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, q as TypingBody, r as canonicalWatchers, t as SYNC_ACTOR, u as openapi, v as DeleteBody, w as InboxNextQuery, x as ExplainQuery, y as EditBody, z as SourceReadQuery } from "./origin-DLCmrwmE.mjs";
5
- import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-BF9vnPPS.mjs";
6
- import { a as canText, c as compileAccess, d as parsePattern, r as PERMISSIONS, u as parseCan } from "./access-Bl_k_Hpa.mjs";
7
- import { S as verifiesTokens, T as explainGrants, a as VERCEL_ISSUER, d as fromTokens, f as grantIssuers, p as hostPrincipal, u as createAuthority, x as verifiedIssuers, y as tokenHash } from "./auth-C8URZHLx.mjs";
8
- import { a as viaOf, i as resolveActor, r as claimsOf, t as KNOWN_AGENTS } from "./actors-yBRWTpt5.mjs";
4
+ import { A as MessagesQuery, B as SyncBody, C as InboxAckBody, D as LabelBody, E as InboxQuery, F as ScheduleBody, G as ThreadsQuery, H as SyncFindQuery, I as SchedulesQuery, J as UploadStartBody, K as TypingBody, L as SchemaBody, M as ReactBody, N as Ref, O as LinkedQuery, P as RegisterBody, R as SourceJoinBody, S as GrantBody, T as InboxPushBody, U as SyncImportBody, V as SyncCopiesQuery, W as SyncReceiptBody, Y as routes, _ as CreateChannelBody, a as compileWatcher, b as EventsQuery, c as METHODS, d as queryObject, f as readCapped, g as AckBody, h as VERSION, i as runMatch, j as PostBody, k as MatchesQuery, l as createRouter, m as SYNC, n as syncTarget, p as readJson, q as UpdateGrantBody, r as canonicalWatchers, t as SYNC_ACTOR, u as openapi, v as DeleteBody, w as InboxNextQuery, x as ExplainQuery, y as EditBody, z as SourceReadQuery } from "./origin-DAyYeDuW.mjs";
5
+ import { _ as sha256, a as waitUntil, c as platformProfile, d as userIdOf, m as derivedId, o as actorParts, r as runMiddleware, s as importedHandle, t as DroppedError, u as underPrincipal } from "./middleware-0DUFrav-.mjs";
6
+ import { a as canText, c as compileAccess, d as parsePattern, n as InvalidCan, r as PERMISSIONS, t as FULL_ACCESS, u as parseCan } from "./access-BgBiaCyx.mjs";
7
+ import { C as explainGrants, b as verifiesTokens, d as grantIssuers, f as hostPrincipal, i as VERCEL_ISSUER, l as createAuthority, t as DEFAULT_CAN$1, u as fromTokens, y as verifiedIssuers } from "./auth-Ft4AJptx.mjs";
8
+ import { a as resolveActor, o as viaOf, r as claimsOf, t as KNOWN_AGENTS } from "./actors-DkZsnMgA.mjs";
9
9
  import { t as checkValue } from "./data-values-C-Cq80hz.mjs";
10
10
  //#region src/server/registrant.ts
11
11
  /** Registering again this soon after the same registration only repeats it. */
@@ -248,7 +248,7 @@ function tailWatchers(options) {
248
248
  }
249
249
  after = page.cursor;
250
250
  for (const event of page.events) {
251
- if (event.actor?.id === own) continue;
251
+ if (event.actor?.id === own && !(event.type === "message.posted" && event.message?.schedule)) continue;
252
252
  const thread = event.message?.thread ?? "";
253
253
  const match = {
254
254
  id: `${boot}:${matched++}`,
@@ -306,9 +306,251 @@ const sleep = (ms, signal) => new Promise((resolve) => {
306
306
  signal.addEventListener("abort", () => (clearTimeout(timer), resolve()), { once: true });
307
307
  });
308
308
  //#endregion
309
+ //#region src/server/sandbox.ts
310
+ /** Outside Node there's no deployment credential to find: a sandbox's policy needs the one it's given. */
311
+ const withoutToken = (url) => {
312
+ throw new HttpError(400, "no_token", `There's no credential here to hand a sandbox for ${url}: pass one, sandboxPolicy({ token }).`, { origin: "handle" });
313
+ };
314
+ /**
315
+ * `x-board-can` for `can`, read here as the board reads it, so a bad one fails before the sandbox
316
+ * does: any `Can` (`'all'`, a list for every channel, a map from pattern to grant, a grant's `'none'`
317
+ * included), or a header's own text (`dev/=read,post`).
318
+ */
319
+ function canHeader(can) {
320
+ if (typeof can === "string" && can !== "all") {
321
+ parseCan(can);
322
+ return can;
323
+ }
324
+ const given = can === void 0 ? DEFAULT_CAN$1 : can === "all" || Array.isArray(can) ? can : Object.fromEntries(Object.entries(can).map(([pattern, grant]) => [pattern, grant === "none" ? [] : grant]));
325
+ return canText(compileAccess(given));
326
+ }
327
+ /**
328
+ * Routes under a board that the policy never adds the credential to: what hands out what outreaches
329
+ * the policy (a grant, a watcher's registration, sync's records and a platform's events), and what a
330
+ * platform or the board's own deployments call (webhooks, wake-ups), where the credential could speak
331
+ * for them.
332
+ */
333
+ const WITHHELD = [
334
+ "grants",
335
+ "watchers",
336
+ "wake",
337
+ "webhooks",
338
+ "sync",
339
+ "inbox",
340
+ "sources"
341
+ ];
342
+ const escaped = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
343
+ /** `value` in any case, as a router that ignores case reads it: a regular expression without flags, as RE2 and JavaScript both take it. */
344
+ const caseless = (value) => [...value].map((char) => /[a-z]/i.test(char) ? `[${char.toLowerCase()}${char.toUpperCase()}]` : escaped(char)).join("");
345
+ /** A path segment, percent-encoded as clients write them; the first rule refuses a dot segment and an encoded slash or dot. */
346
+ const SEGMENT = "(?:[A-Za-z0-9_.@~:+=,!$&'*-]|%[0-9A-Fa-f]{2})+";
347
+ /**
348
+ * The protocol's routes a sandbox reaches: every route but those under a withheld segment. Each is
349
+ * named whole, because a board mounted without a `basePath` matches a route as the end of a path, and
350
+ * `/api/board/x/grants` would be its `/grants` under `/api/board/x`.
351
+ */
352
+ const PROTOCOL_ROUTES = Object.values(routes).filter(({ path }) => !WITHHELD.includes(path.split("/").filter(Boolean)[0] ?? "")).map(({ method, path }) => ({
353
+ method,
354
+ path: path === "/" ? "" : path
355
+ }));
356
+ /** `routes`' rules: one a method, its paths' shapes in one expression after `prefix`. */
357
+ function routeRules(prefix, routes, scoped, transform) {
358
+ const byMethod = /* @__PURE__ */ new Map();
359
+ for (const { method, path } of routes) {
360
+ const shape = path.split("/").filter(Boolean).map((part) => part.startsWith(":") ? `/${SEGMENT}` : `/${escaped(part)}`).join("");
361
+ byMethod.set(method, [...byMethod.get(method) ?? [], shape]);
362
+ }
363
+ return [...byMethod].map(([method, shapes]) => ({
364
+ match: scoped({
365
+ method: [method],
366
+ path: { regex: `^${prefix}(?:${shapes.join("|")})/?$` }
367
+ }),
368
+ transform
369
+ }));
370
+ }
371
+ const refused = (why) => ({ response: {
372
+ statusCode: 403,
373
+ body: JSON.stringify({ error: {
374
+ code: "forbidden",
375
+ message: why
376
+ } }),
377
+ contentType: "application/json"
378
+ } });
379
+ /**
380
+ * The policy that hands the board `reach` names to a sandbox: its host, and on it only the board's
381
+ * own routes, under its URL's path and with its query (`teamId`), each request carrying `reach`'s
382
+ * headers. Anything else on the host is refused there; any other host, the sandbox doesn't reach.
383
+ */
384
+ function boardPolicy(reach) {
385
+ const url = new URL(reach.url);
386
+ const prefix = escaped(url.pathname.replace(/\/+$/, ""));
387
+ const query = [...url.searchParams].map(([key, value]) => ({
388
+ key: { exact: key },
389
+ value: { exact: value }
390
+ }));
391
+ const scoped = (match) => query.length > 0 ? {
392
+ ...match,
393
+ queryString: query
394
+ } : match;
395
+ const transform = [{ headers: { ...reach.headers } }];
396
+ return { allow: { [url.host]: [
397
+ {
398
+ match: { path: { regex: "(?:^|/)\\.\\.?(?:/|$)|%2[eEfF]|%5[cC]|\\\\" } },
399
+ ...refused("not a board route")
400
+ },
401
+ {
402
+ match: { queryString: [{ key: { regex: `^${caseless("x-vercel-set-bypass-cookie")}$` } }] },
403
+ ...refused("not a board route")
404
+ },
405
+ {
406
+ match: { headers: [{ key: { exact: "x-vercel-set-bypass-cookie" } }] },
407
+ ...refused("not a board route")
408
+ },
409
+ ...routeRules(prefix, reach.routes, scoped, transform),
410
+ ...(reach.reads ?? []).map((path) => ({
411
+ match: scoped({
412
+ path: { exact: path },
413
+ method: ["GET"]
414
+ }),
415
+ transform
416
+ })),
417
+ {
418
+ match: { path: { regex: `^${prefix}/(?:${WITHHELD.map(caseless).join("|")})(?:/|$)` } },
419
+ ...refused("not a route this sandbox's policy hands it")
420
+ },
421
+ refused("not this board's")
422
+ ] } };
423
+ }
424
+ //#endregion
309
425
  //#region src/server/backend-vercel.ts
310
426
  const PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
311
- const SESSION = /^[A-Za-z0-9_.:-]{1,128}$/;
427
+ /**
428
+ * What `vb` on this board calls in Vercel's API for what a sandboxed agent does, by method and path
429
+ * under `/boards/<id>`: reading, posting and replying, editing and deleting its own, reacting and
430
+ * labeling, files, schedules, and finding a platform link's message. A sandbox's policy hands it these
431
+ * and nothing else under the board: not the board itself (`PATCH`, `DELETE`), its members, its
432
+ * grants, watchers, or sync's records, nor a route the API adds later.
433
+ */
434
+ const SANDBOX_ROUTES = [
435
+ {
436
+ method: "GET",
437
+ path: ""
438
+ },
439
+ {
440
+ method: "GET",
441
+ path: "/me"
442
+ },
443
+ {
444
+ method: "GET",
445
+ path: "/channels"
446
+ },
447
+ {
448
+ method: "POST",
449
+ path: "/channels"
450
+ },
451
+ {
452
+ method: "GET",
453
+ path: "/actors"
454
+ },
455
+ {
456
+ method: "GET",
457
+ path: "/messages"
458
+ },
459
+ {
460
+ method: "GET",
461
+ path: "/messages/:id"
462
+ },
463
+ {
464
+ method: "GET",
465
+ path: "/messages/:id/synced"
466
+ },
467
+ {
468
+ method: "GET",
469
+ path: "/changes"
470
+ },
471
+ {
472
+ method: "GET",
473
+ path: "/threads"
474
+ },
475
+ {
476
+ method: "POST",
477
+ path: "/threads"
478
+ },
479
+ {
480
+ method: "GET",
481
+ path: "/threads/:thread/messages"
482
+ },
483
+ {
484
+ method: "POST",
485
+ path: "/threads/:thread/messages"
486
+ },
487
+ {
488
+ method: "PATCH",
489
+ path: "/threads/:thread/messages/:n"
490
+ },
491
+ {
492
+ method: "POST",
493
+ path: "/threads/:thread/messages/:n/delete"
494
+ },
495
+ {
496
+ method: "GET",
497
+ path: "/threads/:thread/messages/:n/reactions"
498
+ },
499
+ {
500
+ method: "POST",
501
+ path: "/threads/:thread/messages/:n/reactions"
502
+ },
503
+ {
504
+ method: "POST",
505
+ path: "/threads/:thread/messages/:n/labels"
506
+ },
507
+ {
508
+ method: "GET",
509
+ path: "/posts/:id"
510
+ },
511
+ {
512
+ method: "POST",
513
+ path: "/attachments"
514
+ },
515
+ {
516
+ method: "GET",
517
+ path: "/attachments/:id"
518
+ },
519
+ {
520
+ method: "POST",
521
+ path: "/attachments/:id/complete"
522
+ },
523
+ {
524
+ method: "GET",
525
+ path: "/schedules"
526
+ },
527
+ {
528
+ method: "POST",
529
+ path: "/schedules"
530
+ },
531
+ {
532
+ method: "POST",
533
+ path: "/schedules/:id/cancel"
534
+ },
535
+ {
536
+ method: "GET",
537
+ path: "/sync/linked"
538
+ }
539
+ ];
540
+ /**
541
+ * Who a request to Vercel's API writes as, as the API reads it today: the profile's name alone in
542
+ * `x-board-profile`, and its avatar in `x-board-avatar`, which board's protocol refuses for the
543
+ * avatar parameter of `x-board-profile` (`formatProfileHeader`). Every request and sandbox policy
544
+ * for the API gets its profile from here, so this is the one place that changes once the API reads
545
+ * the profile header as the protocol has it.
546
+ */
547
+ function apiProfileHeaders(profile) {
548
+ if (!profile) return {};
549
+ return {
550
+ "x-board-profile": profile.name,
551
+ ...profile.avatar?.startsWith("https://") ? { "x-board-avatar": profile.avatar } : {}
552
+ };
553
+ }
312
554
  const CLIENT_ID = /^[A-Za-z0-9_.:-]{1,128}$/;
313
555
  const MESSAGE_ID = /^msg_([0-9a-f-]{36})_([1-9]\d*)$/;
314
556
  /** Whether `value` is a message ID Vercel's API hands out (`msg_<thread>_<n>`): the CLI takes one as a message, even where a channel has its name. */
@@ -435,12 +677,6 @@ const grantFrom = (grant) => ({
435
677
  ...grant,
436
678
  at: expiryOf(grant.at)
437
679
  });
438
- /** A token as the API answers it, its times in milliseconds, as the protocol has them. */
439
- const tokenFrom = (token) => ({
440
- ...token,
441
- at: expiryOf(token.at) ?? token.at,
442
- expiresAt: expiryOf(token.expiresAt) ?? token.expiresAt
443
- });
444
680
  /** A schema the API keeps, as the protocol shows it. */
445
681
  const schemaFrom = (schema) => ({
446
682
  id: schema.id,
@@ -583,15 +819,13 @@ const shortName = (principal) => principal.type === "user" ? `user-${principal.u
583
819
  const authorOf = (actor) => ({
584
820
  actor: actor.id,
585
821
  principal: principalId(actor.principal),
586
- profile: actor.profile?.name ?? null,
587
- session: actor.session ?? null
822
+ profile: actor.profile?.name ?? null
588
823
  });
589
824
  /** Who cancels a schedule when no one did: the API, once its creator can no longer post it, as a local board's scheduler. */
590
825
  const SCHEDULER = {
591
826
  actor: "board:schedule",
592
827
  principal: "board:schedule",
593
- profile: null,
594
- session: null
828
+ profile: null
595
829
  };
596
830
  /**
597
831
  * An actor where the API doesn't name them: its handle is its profile, or a short form of its
@@ -699,10 +933,11 @@ function createVercel(options, environment) {
699
933
  if (typeof value === "string") url.searchParams.set(name, value);
700
934
  else for (const one of value) url.searchParams.append(name, one);
701
935
  }
702
- const headers = { "content-type": "application/json" };
703
- if (who.profile) headers["x-board-profile"] = who.profile.name;
704
- if (who.profile?.avatar?.startsWith("https://")) headers["x-board-avatar"] = who.profile.avatar;
705
- if (who.session && SESSION.test(who.session)) headers["x-board-session"] = who.session;
936
+ const headers = {
937
+ "content-type": "application/json",
938
+ ...apiProfileHeaders(who.profile),
939
+ ...who.can !== void 0 ? { "x-board-can": who.can } : {}
940
+ };
706
941
  const repeatable = method !== "POST" && method !== "PATCH" || typeof init.body?.operationId === "string";
707
942
  for (let attempt = 0;; attempt++) {
708
943
  let response;
@@ -730,10 +965,6 @@ function createVercel(options, environment) {
730
965
  continue;
731
966
  }
732
967
  const error = body?.error;
733
- if (error?.code === "board_token_scope") throw new HttpError(403, "board_token_scope", "a board token reaches only its own board, by its ID.", {
734
- hint: "Name its board by URL or ID: BOARD_URL, --url, or vercel({ board }).",
735
- origin: "handle"
736
- });
737
968
  throw new HttpError(response.status, error?.code ?? "remote_error", error?.message ?? `Vercel's API answered ${response.status}`);
738
969
  }
739
970
  }
@@ -1094,8 +1325,7 @@ function createVercel(options, environment) {
1094
1325
  const by = {
1095
1326
  id: await actorOf(who),
1096
1327
  principal: actor.principal,
1097
- ...who.profile ? { profile: who.profile } : {},
1098
- ...who.session ? { session: who.session } : {}
1328
+ ...who.profile ? { profile: who.profile } : {}
1099
1329
  };
1100
1330
  const attachments = (await Promise.all((input.attachments ?? []).map(async (id) => api(who, "GET", await onBoard(who, `/attachments/${encodeURIComponent(id)}`)).then(({ attachment }) => fileOf(attachment), () => null)))).filter((file) => file !== null);
1101
1331
  return {
@@ -1291,7 +1521,15 @@ function createVercel(options, environment) {
1291
1521
  });
1292
1522
  /** The actor `who` writes as: the credentials' principal, and its profile, as the API names it. */
1293
1523
  const actorOf = async (who) => `${principalId((await self(who)).actor.principal)}${who.profile ? `+${who.profile.name.toLowerCase()}` : ""}`;
1294
- /** Who a caller acts as there: its profile and session, beside this deployment's credentials. */
1524
+ /**
1525
+ * Refuses a handle narrowed with `as(profile, { can })` a source: the platform's app reads and
1526
+ * joins what it can, not what the caller can, so it's this deployment's sync's job, as on a board
1527
+ * of its own.
1528
+ */
1529
+ function ownSources(caller, what) {
1530
+ if ("self" in caller && caller.can !== void 0) throw new HttpError(403, "forbidden", `this handle is narrowed with a can, so it can't ${what}: that's its project's sync's job`);
1531
+ }
1532
+ /** Who a caller acts as there: its profile, beside this deployment's credentials. */
1295
1533
  function whoOf(caller) {
1296
1534
  if ("identity" in caller) throw servesNone();
1297
1535
  const named = (profile) => {
@@ -1305,23 +1543,12 @@ function createVercel(options, environment) {
1305
1543
  };
1306
1544
  if (caller.origin.via?.kind === "client") {
1307
1545
  const asked = "profile" in caller ? caller.profile : caller.self ?? void 0;
1308
- const found = environment?.profile() ?? {
1309
- profile: null,
1310
- session: null
1311
- };
1312
- if (asked === void 0) return {
1313
- profile: named(found.profile),
1314
- session: found.session
1315
- };
1316
1546
  return {
1317
- profile: named(asked),
1318
- session: asked === null ? null : found.session
1547
+ profile: named(asked === void 0 ? environment?.profile() ?? null : asked),
1548
+ ...caller.can !== void 0 ? { can: caller.can } : {}
1319
1549
  };
1320
1550
  }
1321
- return {
1322
- profile: named(caller.self ?? "client"),
1323
- session: null
1324
- };
1551
+ return { profile: named(caller.self ?? "client") };
1325
1552
  }
1326
1553
  /** A post's client ID, as the API takes one: its own when it fits, a hash of it when it doesn't. */
1327
1554
  const clientIdOf = async (id) => CLIENT_ID.test(id) ? id : `h.${(await sha256(id)).slice(0, 64)}`;
@@ -1800,12 +2027,11 @@ function createVercel(options, environment) {
1800
2027
  ...found.branch ? { branch: found.branch } : {}
1801
2028
  } : { url: null };
1802
2029
  /**
1803
- * Vercel's API takes watchers only from a deployment's own credentials: never a person's, an app's,
1804
- * or a board token's, whoever made it. Anyone else's registration, pull, or ack is its 403
1805
- * `watchers_need_project`.
2030
+ * Vercel's API takes watchers only from a deployment's own credentials: never a person's or an
2031
+ * app's. Anyone else's registration, pull, or ack is its 403 `watchers_need_project`.
1806
2032
  */
1807
2033
  const notADeployment = () => new HttpError(403, "watchers_need_project", "Vercel's API takes watchers only from a deployment's own credentials.", {
1808
- hint: "Register them from the project's deployment, with no board token. Watchers in board()'s config run in this process instead.",
2034
+ hint: "Register them from the project's deployment. Watchers in board()'s config run in this process instead.",
1809
2035
  origin: "handle"
1810
2036
  });
1811
2037
  const needsProject = (error) => error instanceof HttpError && error.code === "watchers_need_project" ? notADeployment() : error;
@@ -1960,10 +2186,7 @@ function createVercel(options, environment) {
1960
2186
  } });
1961
2187
  }
1962
2188
  /** This deployment's own: what its config's watchers run as. */
1963
- const deployment = {
1964
- profile: null,
1965
- session: null
1966
- };
2189
+ const deployment = { profile: null };
1967
2190
  /** This board's config's watchers, which run here when the API wakes it. */
1968
2191
  let tails = {};
1969
2192
  const bound = () => {
@@ -1973,14 +2196,7 @@ function createVercel(options, environment) {
1973
2196
  const runner = registrant({
1974
2197
  remote: "Vercel's API",
1975
2198
  registry: {
1976
- register: (where) => registerAs(deployment, where, tails, bound().sync, true, holding).catch((error) => {
1977
- if (error instanceof HttpError && error.code === "watchers_need_project") {
1978
- refused = true;
1979
- runner.close();
1980
- runHere();
1981
- }
1982
- throw error;
1983
- }),
2199
+ register: (where) => registerAs(deployment, where, tails, bound().sync, true, holding),
1984
2200
  matches: ({ signal, ...query }) => pullAs(deployment, query, signal, tails),
1985
2201
  ack: (id, body) => ackAs(deployment, id, body)
1986
2202
  },
@@ -1994,19 +2210,11 @@ function createVercel(options, environment) {
1994
2210
  registerFor: async (caller, request) => json(await methods.register(caller, RegisterBody.parse(await request.json()), request.signal))
1995
2211
  });
1996
2212
  let deployed = null;
1997
- /** Whether Vercel's API refused to register this board's watchers: its credentials aren't a deployment's own. */
1998
- let refused = false;
1999
- /**
2000
- * Whether this board's own credentials are a deployment's own: a project's, and no board token. A
2001
- * board token you set says so; one in a `fetch` passed in says so when the API refuses it.
2002
- */
2003
- const isDeployment = async () => {
2004
- if (refused || !options.fetch && environment?.boardToken()) return false;
2005
- return (deployed ??= self(deployment).then((found) => found.actor.principal.type === "project")).catch((error) => {
2006
- deployed = null;
2007
- throw error;
2008
- });
2009
- };
2213
+ /** Whether this board's own credentials are a deployment's own: a project's. */
2214
+ const isDeployment = () => (deployed ??= self(deployment).then((found) => found.actor.principal.type === "project")).catch((error) => {
2215
+ deployed = null;
2216
+ throw error;
2217
+ });
2010
2218
  let here = null;
2011
2219
  let deployedElse = false;
2012
2220
  /** Anyone else's watchers run in this process, as tails: nothing wakes a person. */
@@ -2014,7 +2222,7 @@ function createVercel(options, environment) {
2014
2222
  if (here || deployedElse) return;
2015
2223
  if (deployedOnVercel()) {
2016
2224
  deployedElse = true;
2017
- console.error("[board] watchers on a deployment need its own OIDC token: with a board token or another Vercel token, none run here");
2225
+ console.error("[board] watchers on a deployment need its own OIDC token: with another Vercel token, none run here");
2018
2226
  return;
2019
2227
  }
2020
2228
  const { sync, run } = bound();
@@ -2028,10 +2236,7 @@ function createVercel(options, environment) {
2028
2236
  here = tailWatchers({
2029
2237
  watchers,
2030
2238
  events: (query, signal) => eventsAs(deployment, query, signal),
2031
- actorOf: (id) => actorOf({
2032
- profile: { name: id },
2033
- session: null
2034
- }),
2239
+ actorOf: (id) => actorOf({ profile: { name: id } }),
2035
2240
  run
2036
2241
  });
2037
2242
  here.start();
@@ -2148,23 +2353,12 @@ function createVercel(options, environment) {
2148
2353
  });
2149
2354
  throw error;
2150
2355
  };
2151
- /** A mint Vercel's API won't make: only a deployment mints board tokens there, and a board token mints from itself. */
2152
- const mintRefused = (error) => {
2153
- if (error instanceof HttpError && error.code === "unsupported_principal") throw new HttpError(403, "unsupported_principal", "Vercel's board mints board tokens only for a deployment.", {
2154
- hint: "Mint it from a deployment, with its OIDC token, or from a board token.",
2155
- origin: "handle"
2156
- });
2157
- throw error;
2158
- };
2159
2356
  const methods = {
2160
2357
  ...Object.fromEntries(METHODS.map((method) => [method, async () => {
2161
2358
  throw notSupported(method === "register" || method === "watchers" || method === "matches" || method === "ack" ? "watchers" : method);
2162
2359
  }])),
2163
2360
  async discovery() {
2164
- const who = {
2165
- profile: null,
2166
- session: null
2167
- };
2361
+ const who = { profile: null };
2168
2362
  const team = await teamId();
2169
2363
  if (options.board) await api(who, "GET", await onBoard(who));
2170
2364
  const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
@@ -2207,7 +2401,6 @@ function createVercel(options, environment) {
2207
2401
  avatar: shown.avatar,
2208
2402
  profile: found.actor.profile?.name ?? null,
2209
2403
  ...via,
2210
- session: found.actor.session ?? null,
2211
2404
  expiresAt: expiryOf(found.expiresAt),
2212
2405
  can: canOf(found.can)
2213
2406
  };
@@ -2599,31 +2792,6 @@ function createVercel(options, environment) {
2599
2792
  ...signal ? { signal } : {}
2600
2793
  });
2601
2794
  },
2602
- async tokens(caller, _input, signal) {
2603
- const who = whoOf(caller);
2604
- return { tokens: (await all(who, await onBoard(who, "/tokens"), "tokens", {}, signal)).map(tokenFrom) };
2605
- },
2606
- async createToken(caller, input, signal) {
2607
- const who = whoOf(caller);
2608
- const created = await api(who, "POST", await onBoard(who, "/tokens"), {
2609
- body: {
2610
- operationId: operationId(),
2611
- ...input
2612
- },
2613
- ...signal ? { signal } : {}
2614
- }).catch(mintRefused);
2615
- return {
2616
- ...created,
2617
- token: tokenFrom(created.token)
2618
- };
2619
- },
2620
- async revokeToken(caller, { id }, signal) {
2621
- const who = whoOf(caller);
2622
- return api(who, "POST", await onBoard(who, `/tokens/${encodeURIComponent(id)}/revoke`), {
2623
- body: { operationId: operationId() },
2624
- ...signal ? { signal } : {}
2625
- });
2626
- },
2627
2795
  async schemas(caller, _input, signal) {
2628
2796
  const schemas = (await all(whoOf(caller), "/schemas", "schemas", {}, signal)).map(schemaFrom);
2629
2797
  const order = (schema) => schema.builtIn ? 0 : 1;
@@ -2718,14 +2886,17 @@ function createVercel(options, environment) {
2718
2886
  async typing(caller, { id, status }, signal) {
2719
2887
  if (!binding || binding.sync.length === 0) return { targets: [] };
2720
2888
  const { message, replies } = await methods.message(caller, { id }, signal);
2889
+ if ("self" in caller && caller.can !== void 0 && !compileAccess(parseCan(caller.can)).can("post", message.channel)) throw new HttpError(403, "forbidden", `this handle can't post in ${message.channel}`);
2721
2890
  return { targets: await binding.typing([message, ...replies], status) };
2722
2891
  },
2723
- async readSource(_caller, { key, target, limit, after }) {
2892
+ async readSource(caller, { key, target, limit, after }) {
2724
2893
  if (!binding?.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: read it where its sync runs`, "not_synced_here");
2894
+ ownSources(caller, "read a source");
2725
2895
  return binding.readSource(key, target, limit ?? 50, after ?? null);
2726
2896
  },
2727
- async joinSource(_caller, { key, target }) {
2897
+ async joinSource(caller, { key, target }) {
2728
2898
  if (!binding?.sync.some((entry) => entry.key === key)) throw notFound(`this board doesn't run sync entry ${key}: join it where its sync runs`, "not_synced_here");
2899
+ ownSources(caller, "join a source");
2729
2900
  return binding.joinSource(key, target);
2730
2901
  },
2731
2902
  async syncImport(caller, body, signal) {
@@ -2916,6 +3087,28 @@ function createVercel(options, environment) {
2916
3087
  }])),
2917
3088
  routes,
2918
3089
  keeps: false,
3090
+ /**
3091
+ * A sandbox's way to this board in Vercel's API: its routes, by its ID and team, and `/me`, which a
3092
+ * handle on it asks, held to `can` by `x-board-can` as a board of its own would be. The API reads the
3093
+ * profile as `apiProfileHeaders` sends it.
3094
+ */
3095
+ async sandbox({ profile, can, token }) {
3096
+ if (profile.avatar !== void 0 && !profile.avatar.startsWith("https://")) throw new HttpError(400, "invalid_profile", `${profile.avatar} isn't an avatar Vercel's API takes: one is an https URL.`, { origin: "handle" });
3097
+ const who = { profile: null };
3098
+ const team = await teamId();
3099
+ const id = team?.startsWith("team_") ? team : (await self(who)).teamId;
3100
+ const url = `${origin}/v1/messageboard${await onBoard(who)}?teamId=${encodeURIComponent(id)}`;
3101
+ return {
3102
+ url,
3103
+ headers: {
3104
+ ...environment ? await environment.sandbox(url, token) : token === void 0 ? withoutToken(url) : { authorization: `Bearer ${token}` },
3105
+ ...apiProfileHeaders(profile),
3106
+ "x-board-can": can
3107
+ },
3108
+ routes: SANDBOX_ROUTES,
3109
+ reads: ["/v1/messageboard/me"]
3110
+ };
3111
+ },
2919
3112
  sendsSchedulesHere: false,
2920
3113
  syncedHere: holds,
2921
3114
  bind(next) {
@@ -2997,18 +3190,6 @@ function createPolicy(options, keeps, serving, trust = null) {
2997
3190
  const issuers = verifiedIssuers([], grantIssuers(await grants()));
2998
3191
  if (issuers.join("\n") !== context.issuers.join("\n")) context.issuers = issuers;
2999
3192
  }
3000
- /** Who a board token is: the principal that minted it, narrowed, until it's revoked or expires. */
3001
- async function tokenPrincipal(secret) {
3002
- if (!trust) throw unauthorized("this board issues no tokens: send a board token to the board that minted it");
3003
- const found = await trust.token(await tokenHash(secret));
3004
- if (!found || found.expiresAt.getTime() <= Date.now()) throw unauthorized("invalid token: revoked, expired, or not this board's");
3005
- return {
3006
- ...found.minter,
3007
- expiresAt: found.expiresAt,
3008
- token: found.id,
3009
- pinned: found.pinned
3010
- };
3011
- }
3012
3193
  /** Verified principals by credential, until they expire, so a stream's polls don't verify from scratch. */
3013
3194
  const verified = /* @__PURE__ */ new Map();
3014
3195
  /** And by request, for one with no credential (a session cookie), for as long as it's served. */
@@ -3030,7 +3211,7 @@ function createPolicy(options, keeps, serving, trust = null) {
3030
3211
  const principal = verify(request);
3031
3212
  perRequest.set(request, principal);
3032
3213
  if (key !== null) principal.then((found) => {
3033
- if (found.facts?.issuer === "host" || found.expiresAt === null || found.token !== void 0) return;
3214
+ if (found.facts?.issuer === "host" || found.expiresAt === null) return;
3034
3215
  if (verified.size >= 1e3) verified.delete(verified.keys().next().value);
3035
3216
  verified.set(key, {
3036
3217
  principal,
@@ -3040,7 +3221,6 @@ function createPolicy(options, keeps, serving, trust = null) {
3040
3221
  return principal;
3041
3222
  }
3042
3223
  async function verify(request) {
3043
- if (request.credential?.startsWith("board_")) return tokenPrincipal(request.credential);
3044
3224
  if (request.credential !== null) await learnIssuers(request.credential);
3045
3225
  const authenticate = await verifier();
3046
3226
  let result;
@@ -3107,13 +3287,12 @@ function createPolicy(options, keeps, serving, trust = null) {
3107
3287
  */
3108
3288
  async identify(request) {
3109
3289
  const found = await principalOf(request);
3110
- const claims = found.pinned ? pinnedClaims(found.pinned, request.claims) : request.claims;
3111
- const scope = found.scope === void 0 ? claims.scope ?? void 0 : claims.scope === null ? found.scope : canText(compileAccess(parseCan(found.scope)).narrow(parseCan(claims.scope)));
3112
- const principal = scope === void 0 ? found : {
3290
+ const { claims } = request;
3291
+ const principal = claims.scope === null ? found : {
3113
3292
  ...found,
3114
- scope
3293
+ scope: claims.scope
3115
3294
  };
3116
- const { author, actor } = resolveActor(principal, claims, request.audience);
3295
+ const { author, actor } = resolveActor(principal, claims);
3117
3296
  return {
3118
3297
  principal: {
3119
3298
  ...principal,
@@ -3124,26 +3303,13 @@ function createPolicy(options, keeps, serving, trust = null) {
3124
3303
  };
3125
3304
  },
3126
3305
  explain,
3127
- /** What a stored principal (a schedule's creator, a watcher's registrant) may do now: null once nothing, its board token's revoking included. */
3306
+ /** What a stored principal (a schedule's creator, a watcher's registrant) may do now: null once nothing, or once it was made with a board token. */
3128
3307
  async accessNow(principal, grants) {
3129
- if (principal.token !== void 0 && !await trust?.live(principal.token)) return null;
3308
+ if (principal.token !== void 0) return null;
3130
3309
  return authority.accessNow(principal, grants);
3131
3310
  }
3132
3311
  };
3133
3312
  }
3134
- /** A board token's pins, over what the request says: its profile and session win, and a person's name is the minter's. */
3135
- function pinnedClaims(pinned, claims) {
3136
- return {
3137
- ...claims,
3138
- ...pinned.profile !== null ? {
3139
- profile: pinned.profile,
3140
- avatar: pinned.avatar
3141
- } : {},
3142
- ...pinned.session !== null ? { session: pinned.session } : {},
3143
- handle: pinned.handle,
3144
- name: pinned.name
3145
- };
3146
- }
3147
3313
  /** A JWT's `iss`, read but not verified: which issuer's keys would check it. Null for anything else. */
3148
3314
  function issuerOf(credential) {
3149
3315
  const payload = credential.split(".")[1];
@@ -3194,7 +3360,7 @@ const STYLES = {
3194
3360
  mark: { glyph: "π" }
3195
3361
  }
3196
3362
  };
3197
- /** A built-in avatar for a detected agent; other names get their initial. */
3363
+ /** A known agent's mark, for a caller to pass as its avatar; other names get their initial. */
3198
3364
  function avatarSvg(name) {
3199
3365
  const style = STYLES[name] ?? {
3200
3366
  background: "#666666",
@@ -3242,14 +3408,12 @@ async function inputOf(name, request, url, params) {
3242
3408
  case "actors":
3243
3409
  case "watchers":
3244
3410
  case "grants":
3245
- case "tokens":
3246
3411
  case "schemas": return {};
3247
3412
  case "message":
3248
3413
  case "posted":
3249
3414
  case "synced":
3250
3415
  case "cancelSchedule":
3251
3416
  case "revokeGrant":
3252
- case "revokeToken":
3253
3417
  case "schema":
3254
3418
  case "attachment":
3255
3419
  case "uploadFinish": return { id };
@@ -3272,7 +3436,6 @@ async function inputOf(name, request, url, params) {
3272
3436
  ...UpdateGrantBody.parse(await body())
3273
3437
  };
3274
3438
  case "explain": return ExplainQuery.parse(queryObject(url));
3275
- case "createToken": return TokenBody.parse(await body());
3276
3439
  case "createSchema": return SchemaBody.parse(await body());
3277
3440
  case "register": return RegisterBody.parse(await body());
3278
3441
  case "edit": return {
@@ -3436,9 +3599,12 @@ async function createServe(context) {
3436
3599
  * What a verified caller may do, as board()'s `access` said when it verified them: board() checks
3437
3600
  * it before it does anything for them past calling the backend (a platform call, sync's own write,
3438
3601
  * reading an upload, the middleware), so a caller it won't let in starts none of it. Null for this
3439
- * deployment's own code, which may do everything.
3602
+ * deployment's own code, which may do everything, unless `as(profile, { can })` narrowed its
3603
+ * handle: then what that `can` leaves it, as a request narrowed with x-board-can is checked.
3440
3604
  */
3441
- const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : null;
3605
+ const accessOf = (caller) => "identity" in caller ? caller.identity.principal.access : caller.can !== void 0 ? FULL_ACCESS.narrow(parseCan(caller.can)) : null;
3606
+ /** Whether `caller` is narrowed with a `can`: a request's x-board-can, or a handle's from `as()`. */
3607
+ const narrowed = (caller) => "identity" in caller ? caller.identity.principal.scope !== void 0 : caller.can !== void 0;
3442
3608
  /**
3443
3609
  * Whether board() may work for a write of `caller`'s that lands in `channel`, or in the thread of
3444
3610
  * message `re`, which it must read: `post` there. One it may not goes to the backend as it came,
@@ -3690,7 +3856,7 @@ async function createServe(context) {
3690
3856
  };
3691
3857
  if (middleware.length === 0 || caller.origin.via?.kind === "middleware" || body.op !== "post" && body.op !== "edit") return send(body);
3692
3858
  const access = accessOf(caller);
3693
- if (access && (!access.anywhere("sync") || "identity" in caller && caller.identity.principal.scope !== void 0)) return send(body);
3859
+ if (access && (!access.anywhere("sync") || narrowed(caller))) return send(body);
3694
3860
  const dropped = async (commit) => {
3695
3861
  try {
3696
3862
  return await commit();
@@ -4148,8 +4314,68 @@ async function createServe(context) {
4148
4314
  }
4149
4315
  //#endregion
4150
4316
  //#region src/server/board.ts
4317
+ /** A handle's own, with every request it makes ended by a signal: what `vb()` runs a command on. Global, so another copy of board finds it. */
4318
+ const STOPPED_BY = Symbol.for("@vercel/board/stopped-by");
4319
+ /**
4320
+ * `board`, with each request it makes ended by `signal`: the backend's call gets it, and the request
4321
+ * rejects with its reason when it fires, whether or not the backend heeds it. A request already
4322
+ * sent may still have done what it asked. Null for a handle board() didn't make.
4323
+ */
4324
+ function stoppedBy(board, signal) {
4325
+ const own = board[STOPPED_BY];
4326
+ return typeof own === "function" ? own(signal) : null;
4327
+ }
4328
+ /** `response`, with a body that errors with `signal`'s reason once it fires: a download whose body stalls ends too. */
4329
+ function bounded(response, signal) {
4330
+ if (!response.ok || !response.body) return response;
4331
+ const reader = response.body.getReader();
4332
+ const body = new ReadableStream({
4333
+ start(controller) {
4334
+ const stop = () => {
4335
+ controller.error(signal.reason);
4336
+ reader.cancel(signal.reason).catch(() => {});
4337
+ };
4338
+ if (signal.aborted) stop();
4339
+ else signal.addEventListener("abort", stop, { once: true });
4340
+ },
4341
+ async pull(controller) {
4342
+ let read;
4343
+ try {
4344
+ read = await reader.read();
4345
+ } catch (error) {
4346
+ if (!signal.aborted) controller.error(error);
4347
+ return;
4348
+ }
4349
+ if (signal.aborted) return;
4350
+ if (read.done) controller.close();
4351
+ else controller.enqueue(read.value);
4352
+ },
4353
+ cancel: (reason) => reader.cancel(reason)
4354
+ });
4355
+ return new Response(body, {
4356
+ status: response.status,
4357
+ statusText: response.statusText,
4358
+ headers: response.headers
4359
+ });
4360
+ }
4361
+ /** `work`, or `signal`'s reason once it fires, whichever comes first. */
4362
+ function until(signal, work) {
4363
+ if (signal.aborted) return Promise.reject(signal.reason);
4364
+ return new Promise((resolve, reject) => {
4365
+ const stop = () => reject(signal.reason);
4366
+ signal.addEventListener("abort", stop, { once: true });
4367
+ work.then(resolve, reject).finally(() => signal.removeEventListener("abort", stop));
4368
+ });
4369
+ }
4151
4370
  /** How long a handle's live events wait for the next, in seconds, before asking again. */
4152
4371
  const EVENTS_WAIT_S = 25;
4372
+ /** A profile's name, as the board takes one in `x-board-profile`. */
4373
+ const SANDBOX_PROFILE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
4374
+ /** An avatar the board takes: an https URL, or http on localhost. */
4375
+ const avatarUrl = (value) => {
4376
+ const url = URL.parse(value);
4377
+ return url !== null && (url.protocol === "https:" || url.protocol === "http:" && ["localhost", "127.0.0.1"].includes(url.hostname));
4378
+ };
4153
4379
  /** A board's name: 1 to 64 characters, no `/`. */
4154
4380
  const BOARD_NAME = /^[^/]{1,64}$/;
4155
4381
  /** A team, by its ID or its slug. */
@@ -4191,26 +4417,92 @@ function createBoard(options, runtime) {
4191
4417
  loading.catch(() => loading = null);
4192
4418
  return loading;
4193
4419
  }
4194
- function clientAs(caller, trigger) {
4195
- const writes = { made: 0 };
4420
+ function clientAs(caller, trigger, stop, writes = { made: 0 }) {
4421
+ const inject = async (request) => (await server()).inject(request, caller, trigger, writes);
4196
4422
  return createBoardClient({
4197
4423
  url: inProcess,
4198
4424
  token: "in-process",
4199
- fetch: (async (input, init) => (await server()).inject(new Request(input, init), caller, trigger, writes))
4425
+ fetch: (async (input, init) => {
4426
+ if (!stop) return inject(new Request(input, init));
4427
+ const signal = init?.signal ? AbortSignal.any([init.signal, stop]) : stop;
4428
+ if (signal.aborted) throw signal.reason;
4429
+ return bounded(await until(signal, inject(new Request(input, {
4430
+ ...init,
4431
+ signal
4432
+ }))), signal);
4433
+ }),
4434
+ ...stop ? { storeFetch: ((input, init) => globalThis.fetch(input, {
4435
+ ...init,
4436
+ signal: init?.signal ? AbortSignal.any([init.signal, stop]) : stop
4437
+ })) } : {}
4200
4438
  });
4201
4439
  }
4202
4440
  const serve = async (request) => (await server()).dispatch(request, null);
4441
+ /** How a sandbox reaches this board, where it keeps the board itself: at its own URL, with this deployment's credential. */
4442
+ async function ownReach({ profile, can, token }) {
4443
+ const url = ownUrl();
4444
+ if (url === null) throw new HttpError(400, "no_url", "A sandbox reaches this board at its URL, and it doesn't know it yet.", {
4445
+ hint: "Pass board({ url }).",
4446
+ origin: "handle"
4447
+ });
4448
+ return {
4449
+ url,
4450
+ headers: {
4451
+ ...runtime.sandbox ? await runtime.sandbox(url, token) : token === void 0 ? withoutToken(url) : { authorization: `Bearer ${token}` },
4452
+ "x-board-profile": formatProfileHeader(profile),
4453
+ "x-board-can": can
4454
+ },
4455
+ routes: PROTOCOL_ROUTES
4456
+ };
4457
+ }
4458
+ /** `can`'s header text, read as the board reads one: a 400 `invalid_scope` for one it doesn't. */
4459
+ function canOf(can) {
4460
+ try {
4461
+ return canHeader(can);
4462
+ } catch (error) {
4463
+ if (error instanceof InvalidCan) throw new BoardError("invalid_scope", error.message, 400);
4464
+ throw error;
4465
+ }
4466
+ }
4467
+ /** What a handle narrowed to `held` (or nothing) may do once `can` narrows it too: never more than either. */
4468
+ const within = (held, can) => held === void 0 ? can : canText(compileAccess(parseCan(held)).narrow(parseCan(can)));
4469
+ /** The `can` a handle as `caller` holds: what `as(profile, { can })` gave it. */
4470
+ const heldBy = (caller) => "self" in caller ? caller.can : void 0;
4471
+ /** The policy that hands this board to a sandbox, for a handle as `caller`. */
4472
+ async function sandboxPolicy(caller, options = {}) {
4473
+ const own = "profile" in caller ? caller.profile : null;
4474
+ const named = options.profile ?? (own === null || own === void 0 ? null : typeof own === "string" ? { name: own } : own);
4475
+ if (named === null) throw new BoardError("invalid_profile", "A sandbox writes as a profile of this deployment, and this names none: the sandbox could send its own, and write as any.", 400, { hint: "Name one: sandboxPolicy({ profile: { name } }), or team.as('<name>').sandboxPolicy()." });
4476
+ if (!SANDBOX_PROFILE.test(named.name)) throw new BoardError("invalid_profile", `${named.name} isn't a profile's name: one starts with a letter and uses up to 32 letters, numbers, and hyphens.`, 400);
4477
+ if (named.avatar !== void 0 && !avatarUrl(named.avatar)) throw new BoardError("invalid_profile", `${named.avatar} isn't an avatar: one is an https URL, or http on localhost.`, 400);
4478
+ const input = {
4479
+ profile: named,
4480
+ can: within(heldBy(caller), canOf(options.can)),
4481
+ token: options.token
4482
+ };
4483
+ try {
4484
+ return boardPolicy(backend.sandbox ? await backend.sandbox(input) : await ownReach(input));
4485
+ } catch (error) {
4486
+ if (error instanceof HttpError) throw new BoardError(error.code, error.message, error.status, {
4487
+ ...error.hint !== void 0 ? { hint: error.hint } : {},
4488
+ origin: error.origin
4489
+ });
4490
+ throw error;
4491
+ }
4492
+ }
4203
4493
  /** A handle on `client`, which `as` gives other profiles of. */
4204
- function handle(client, url) {
4494
+ function handle(client, url, caller, trigger, stop, writes) {
4205
4495
  const made = {
4206
4496
  ...client,
4207
4497
  fetch: serve,
4208
- as
4498
+ as: asFrom(caller, stop),
4499
+ sandboxPolicy: (options) => sandboxPolicy(caller, options)
4209
4500
  };
4210
4501
  if (url) Object.defineProperty(made, "url", {
4211
4502
  get: url,
4212
4503
  enumerable: true
4213
4504
  });
4505
+ Object.defineProperty(made, STOPPED_BY, { value: (signal) => handleOf(caller, trigger, signal, writes) });
4214
4506
  return made;
4215
4507
  }
4216
4508
  /**
@@ -4218,12 +4510,12 @@ function createBoard(options, runtime) {
4218
4510
  * so a retry posts once and no request can take it first. A verified caller's are a backend's,
4219
4511
  * derived already (a schedule's send's), so they go as they are.
4220
4512
  */
4221
- function handleOf(caller, trigger) {
4222
- const client = clientAs(caller, trigger);
4513
+ function handleOf(caller, trigger, stop, writes = { made: 0 }) {
4514
+ const client = clientAs(caller, trigger, stop, writes);
4223
4515
  if ("identity" in caller) return handle({
4224
4516
  ...client,
4225
4517
  events: (query, opts) => events(client, query, opts)
4226
- }, () => ownUrl() ?? inProcess);
4518
+ }, () => ownUrl() ?? inProcess, caller, trigger, stop, writes);
4227
4519
  const via = caller.origin.via?.kind ?? "client";
4228
4520
  const id = (given) => derivedId(`board-${via === "watcher" ? "watch" : via}`, caller.self ?? "", given);
4229
4521
  const owned = async (input) => typeof input === "string" || input.id === void 0 ? input : {
@@ -4237,25 +4529,32 @@ function createBoard(options, runtime) {
4237
4529
  posted: async (given) => client.posted(await id(given)),
4238
4530
  request: (path, init = {}) => {
4239
4531
  const { as: profile, ...rest } = init;
4240
- return profile !== void 0 ? as(profile).request(path, rest) : client.request(path, rest);
4532
+ return profile !== void 0 ? asFrom(caller, stop)(profile).request(path, rest) : client.request(path, rest);
4241
4533
  },
4242
4534
  events: (query, opts) => events(client, query, opts)
4243
- }, () => ownUrl() ?? inProcess);
4535
+ }, () => ownUrl() ?? inProcess, caller, trigger, stop, writes);
4244
4536
  }
4245
- const profileCaller = (profile) => {
4537
+ const profileCaller = (profile, can) => {
4246
4538
  const name = profile === null ? null : typeof profile === "string" ? profile : profile.name;
4247
4539
  return {
4248
4540
  self: name,
4249
4541
  profile,
4542
+ ...can !== void 0 ? { can } : {},
4250
4543
  origin: { via: {
4251
4544
  kind: "client",
4252
4545
  name
4253
4546
  } }
4254
4547
  };
4255
4548
  };
4256
- function as(profile) {
4257
- return handleOf(profileCaller(profile), null);
4258
- }
4549
+ /**
4550
+ * `as()` on a handle as `caller`: another profile, held to what that handle holds, and to `can`
4551
+ * when it's given, and stopped by what stops that handle.
4552
+ */
4553
+ const asFrom = (caller, stop) => (profile, options = {}) => {
4554
+ const held = heldBy(caller);
4555
+ const can = options.can === void 0 ? held : within(held, canOf(options.can));
4556
+ return handleOf(profileCaller(profile, can), null, stop);
4557
+ };
4259
4558
  const context = {
4260
4559
  options,
4261
4560
  backend,
@@ -4353,4 +4652,4 @@ async function* events(client, query = {}, opts = {}) {
4353
4652
  }
4354
4653
  }
4355
4654
  //#endregion
4356
- export { tailWatchers as a, isApiMessageId as i, isBoardName as n, deployedOnVercel as o, createVercel as r, createBoard as t };
4655
+ export { isApiMessageId as a, tailWatchers as c, createVercel as i, deployedOnVercel as l, isBoardName as n, PROTOCOL_ROUTES as o, stoppedBy as r, withoutToken as s, createBoard as t };