@botiverse/porthole 0.6.0 → 0.7.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 (145) hide show
  1. package/README.md +16 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +200 -8
  4. package/dist/bridge/refusal.d.ts +5 -1
  5. package/dist/bridge/refusal.js +16 -0
  6. package/dist/bridge/types.d.ts +41 -4
  7. package/dist/check/check.d.ts +7 -0
  8. package/dist/check/check.js +1 -0
  9. package/dist/check/instrument.d.ts +3 -0
  10. package/dist/check/lint.js +4 -2
  11. package/dist/check/page-source.js +1 -1
  12. package/dist/check/page.js +14 -0
  13. package/dist/check/tools.js +2 -3
  14. package/dist/compile/policy.d.ts +19 -0
  15. package/dist/compile/policy.js +42 -0
  16. package/dist/config/capabilities.d.ts +62 -3
  17. package/dist/config/capabilities.js +20 -0
  18. package/dist/config/schema.d.ts +24 -0
  19. package/dist/config/validate.d.ts +1 -1
  20. package/dist/config/validate.js +66 -4
  21. package/dist/conformance/harness-source.js +1 -1
  22. package/dist/conformance/index.d.ts +1 -0
  23. package/dist/conformance/index.js +2 -0
  24. package/dist/conformance/runtime.d.ts +58 -0
  25. package/dist/conformance/runtime.js +314 -0
  26. package/dist/guide/gates.d.ts +3 -0
  27. package/dist/guide/gates.js +19 -0
  28. package/dist/guide/guide.d.ts +2 -0
  29. package/dist/guide/guide.js +34 -32
  30. package/dist/guide/limits.js +4 -4
  31. package/dist/guide/runtime.d.ts +13 -0
  32. package/dist/guide/runtime.js +202 -0
  33. package/dist/host/create-host.js +24 -0
  34. package/dist/host/locate.js +8 -0
  35. package/dist/host/locator.js +7 -0
  36. package/dist/host/types.d.ts +18 -0
  37. package/dist/index.d.ts +8 -2
  38. package/dist/index.js +9 -1
  39. package/dist/isolation/types.d.ts +8 -0
  40. package/dist/presets/presets.d.ts +6 -0
  41. package/dist/presets/presets.js +1 -0
  42. package/dist/protocol/runtime-calls.d.ts +28 -0
  43. package/dist/protocol/runtime-calls.js +113 -0
  44. package/dist/protocol/shell-adapter.js +48 -3
  45. package/dist/react/dialog.js +31 -0
  46. package/dist/react/frame.d.ts +13 -0
  47. package/dist/react/frame.js +6 -0
  48. package/dist/runtime/contract.d.ts +193 -0
  49. package/dist/runtime/contract.js +216 -0
  50. package/dist/runtime/db.d.ts +153 -0
  51. package/dist/runtime/db.js +398 -0
  52. package/dist/runtime/declaration.d.ts +86 -0
  53. package/dist/runtime/declaration.js +266 -0
  54. package/dist/runtime/levels.d.ts +33 -0
  55. package/dist/runtime/levels.js +41 -0
  56. package/dist/runtime/requests.d.ts +125 -0
  57. package/dist/runtime/requests.js +199 -0
  58. package/dist/runtime/segments.d.ts +8 -0
  59. package/dist/runtime/segments.js +14 -0
  60. package/dist/runtime/types.generated.d.ts +1 -0
  61. package/dist/runtime/types.generated.js +19 -0
  62. package/dist/server/files.d.ts +14 -1
  63. package/dist/server/files.js +97 -3
  64. package/dist/server/host.d.ts +6 -1
  65. package/dist/server/host.js +5 -0
  66. package/dist/server/index.d.ts +2 -1
  67. package/dist/server/index.js +1 -0
  68. package/dist/server/pseudonym.d.ts +9 -0
  69. package/dist/server/pseudonym.js +20 -0
  70. package/dist/server/server.d.ts +0 -5
  71. package/dist/server/server.js +214 -35
  72. package/dist/server/types.d.ts +69 -0
  73. package/dist/shell/document.d.ts +8 -0
  74. package/dist/shell/document.js +16 -2
  75. package/dist/shell/legacy.d.ts +21 -0
  76. package/dist/shell/legacy.js +63 -0
  77. package/dist/shell/plan.d.ts +17 -1
  78. package/dist/shell/plan.js +13 -2
  79. package/dist/shell/runtime.js +29 -42
  80. package/dist/shell/use.d.ts +15 -0
  81. package/dist/shell/use.js +235 -0
  82. package/docs/ADOPTING.md +91 -6
  83. package/docs/ARCHITECTURE.md +22 -3
  84. package/docs/DECISIONS.md +415 -6
  85. package/docs/DESIGN.md +66 -0
  86. package/package.json +3 -1
  87. package/src/bridge/bridge.ts +273 -12
  88. package/src/bridge/refusal.ts +16 -0
  89. package/src/bridge/types.ts +46 -4
  90. package/src/check/check.ts +8 -0
  91. package/src/check/instrument.ts +3 -0
  92. package/src/check/lint.ts +4 -2
  93. package/src/check/page.ts +14 -0
  94. package/src/check/tools.ts +2 -3
  95. package/src/compile/policy.ts +54 -0
  96. package/src/config/capabilities.ts +49 -2
  97. package/src/config/schema.ts +24 -0
  98. package/src/config/validate.ts +99 -4
  99. package/src/conformance/index.ts +7 -0
  100. package/src/conformance/runtime.ts +573 -0
  101. package/src/guide/gates.ts +25 -0
  102. package/src/guide/guide.ts +59 -53
  103. package/src/guide/limits.ts +4 -4
  104. package/src/guide/runtime.ts +244 -0
  105. package/src/host/create-host.ts +34 -0
  106. package/src/host/locate.ts +10 -0
  107. package/src/host/locator.ts +11 -0
  108. package/src/host/types.ts +18 -0
  109. package/src/index.ts +89 -0
  110. package/src/isolation/types.ts +8 -0
  111. package/src/presets/presets.ts +7 -0
  112. package/src/protocol/runtime-calls.ts +138 -0
  113. package/src/protocol/shell-adapter.ts +52 -3
  114. package/src/react/dialog.tsx +33 -0
  115. package/src/react/frame.tsx +19 -0
  116. package/src/runtime/contract.ts +305 -0
  117. package/src/runtime/db.ts +530 -0
  118. package/src/runtime/declaration.ts +378 -0
  119. package/src/runtime/levels.ts +69 -0
  120. package/src/runtime/requests.ts +339 -0
  121. package/src/runtime/segments.ts +17 -0
  122. package/src/runtime/types.generated.ts +19 -0
  123. package/src/server/files.ts +117 -4
  124. package/src/server/host.ts +12 -0
  125. package/src/server/index.ts +3 -0
  126. package/src/server/pseudonym.ts +21 -0
  127. package/src/server/server.ts +247 -37
  128. package/src/server/types.ts +68 -0
  129. package/src/shell/document.ts +21 -4
  130. package/src/shell/legacy.ts +64 -0
  131. package/src/shell/plan.ts +37 -3
  132. package/src/shell/runtime.ts +29 -42
  133. package/src/shell/use.ts +235 -0
  134. package/types/runtime/v1/artifact.d.ts +50 -0
  135. package/types/runtime/v1/assets.d.ts +43 -0
  136. package/types/runtime/v1/chat.d.ts +13 -0
  137. package/types/runtime/v1/clipboard.d.ts +14 -0
  138. package/types/runtime/v1/comments.d.ts +24 -0
  139. package/types/runtime/v1/context.d.ts +16 -0
  140. package/types/runtime/v1/data.d.ts +29 -0
  141. package/types/runtime/v1/db.d.ts +110 -0
  142. package/types/runtime/v1/downloads.d.ts +22 -0
  143. package/types/runtime/v1/links.d.ts +13 -0
  144. package/types/runtime/v1/porthole.d.ts +44 -0
  145. package/types/runtime/v1/user.d.ts +19 -0
@@ -8,8 +8,31 @@ import {
8
8
  import type { AnnotationReport } from "../annotate/types.ts";
9
9
  import { parseReport } from "../annotate/validate.ts";
10
10
  import type { PortholeConfig } from "../config/schema.ts";
11
- import { effectiveGates } from "../compile/policy.ts";
11
+ import { callGates, effectiveGates } from "../compile/policy.ts";
12
12
  import { blockedNavigationMessage, withoutSealedAddresses } from "./navigation.ts";
13
+ import {
14
+ RUNTIME_HOST_FUNCTIONS,
15
+ familyOf,
16
+ methodLevel,
17
+ methodOf,
18
+ assetCodeRuns,
19
+ rosterOf,
20
+ runtimeCapability,
21
+ type RuntimeCapabilityName,
22
+ } from "../runtime/contract.ts";
23
+ import {
24
+ declaredMatch,
25
+ type DeclaredCapability,
26
+ type PageDeclaration,
27
+ } from "../runtime/declaration.ts";
28
+ import { dbAccess, parseDbRequest, withMe, type DbRequest } from "../runtime/db.ts";
29
+ import { atLeast, higher, type ViewerInfo, type ViewerLevel } from "../runtime/levels.ts";
30
+ import {
31
+ isCodeAsset,
32
+ parseArtifactRequest,
33
+ parseAssetRequest,
34
+ parseCommentRequest,
35
+ } from "../runtime/requests.ts";
13
36
  import {
14
37
  defaultReason,
15
38
  isRefused,
@@ -67,6 +90,17 @@ export interface BridgeOptions {
67
90
  readonly onEvent: (event: BridgeEvent) => void;
68
91
  /** The clock, in milliseconds (tests pass their own). */
69
92
  readonly now?: () => number;
93
+ /**
94
+ * Who is viewing (P087), as the host said: each runtime method's level is checked against it,
95
+ * and the runtime's own host functions need it. Absent: 0.6's functions run unchecked, as before.
96
+ */
97
+ readonly viewer?: ViewerInfo;
98
+ /**
99
+ * What the display's page declared (P086), checked against the config (`checkDeclaration`).
100
+ * Absent: a page without one (0.6's): built-ins only through the runtime, and 0.6's globals and
101
+ * requests as before.
102
+ */
103
+ readonly declaration?: PageDeclaration | null;
70
104
  }
71
105
 
72
106
  const isRecord = (value: unknown): value is Record<string, unknown> =>
@@ -101,10 +135,11 @@ function resourceUri(args: unknown): { uri: string } | null {
101
135
  return typeof uri === "string" && uri !== "" && uri.length <= MAX_URL ? { uri } : null;
102
136
  }
103
137
 
138
+ /** A call's arguments checked: the capability's, or null (malformed), or "too_large". */
104
139
  type Validator<N extends CapabilityName> = (
105
140
  args: unknown,
106
141
  config: PortholeConfig,
107
- ) => CapabilityArgs[N] | null;
142
+ ) => CapabilityArgs[N] | "too_large" | null;
108
143
 
109
144
  const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
110
145
  sendPrompt: (args, config) => {
@@ -179,6 +214,13 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
179
214
  : null;
180
215
  },
181
216
  annotate: (args) => parseReport(args),
217
+ // The runtime's own (P088-P090): their shapes and limits, before any gate.
218
+ user: (args) => (args === undefined || isRecord(args) ? {} : null),
219
+ comments: (args) => parseCommentRequest(args),
220
+ artifact: (args, config) => parseArtifactRequest(args, config.limits),
221
+ // Code-typed names only where uploaded code may run (P089, after the review).
222
+ assets: (args, config) => parseAssetRequest(args, config.limits, assetCodeRuns(config)),
223
+ db: (args) => parseDbRequest(args),
182
224
  resize: (args) => {
183
225
  if (
184
226
  !isRecord(args) ||
@@ -225,10 +267,23 @@ export function onceConsent(consent: Consent): Consent {
225
267
  };
226
268
  }
227
269
 
270
+ /** What the page declared for one runtime capability, if it declared it. */
271
+ function declaredOf(
272
+ declaration: PageDeclaration | undefined,
273
+ family: RuntimeCapabilityName,
274
+ ): DeclaredCapability | undefined {
275
+ const capabilities = declaration?.capabilities as
276
+ | Readonly<Record<string, DeclaredCapability>>
277
+ | undefined;
278
+ return capabilities !== undefined && Object.hasOwn(capabilities, family)
279
+ ? capabilities[family]
280
+ : undefined;
281
+ }
282
+
228
283
  export function createBridge(options: BridgeOptions): HostFunctionBridge {
229
284
  const { config, display, handlers, onEvent } = options;
230
285
  const now = options.now ?? (() => Date.now());
231
- const calls = new Map<CapabilityName, number[]>();
286
+ const calls = new Map<string, number[]>();
232
287
  let declines = 0;
233
288
  let muted = false;
234
289
 
@@ -247,7 +302,7 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
247
302
  };
248
303
  };
249
304
 
250
- const withinRate = (capability: CapabilityName, perMinute: number): boolean => {
305
+ const withinRate = (capability: string, perMinute: number): boolean => {
251
306
  const at = now();
252
307
  const recent = (calls.get(capability) ?? []).filter((time) => at - time < 60_000);
253
308
  if (recent.length >= perMinute) {
@@ -259,9 +314,132 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
259
314
  return true;
260
315
  };
261
316
 
317
+ /** The least level a call needs: its method's, and a db batch's writes' or a watch's read's. */
318
+ function levelOf(
319
+ capability: CapabilityName,
320
+ family: RuntimeCapabilityName,
321
+ method: string,
322
+ args: unknown,
323
+ ): ViewerLevel | null {
324
+ const declared = declaredOf(options.declaration ?? undefined, family);
325
+ const own = methodLevel(config, family, method, declared);
326
+ if (capability !== "db" || own === null) {
327
+ return own;
328
+ }
329
+ // A batch is each of its writes; a watch is a read (after the review: neither escapes the
330
+ // levels of what it does).
331
+ const request = args as DbRequest;
332
+ const inner =
333
+ request.op === "batch"
334
+ ? request.writes.map((write) => write.op)
335
+ : request.op === "watch"
336
+ ? [request.path.split("/").length % 2 === 0 ? "get" : "query"]
337
+ : [];
338
+ return inner.reduce<ViewerLevel>(
339
+ (most, op) => higher(most, methodLevel(config, family, op, declared) ?? most),
340
+ own,
341
+ );
342
+ }
343
+
344
+ /**
345
+ * Whether this viewer may make this call (P087), and the call as the handler gets it: the
346
+ * call's level (the contract's, the host's, the page's; a batch's writes', a watch's read's),
347
+ * the resources and tools a page's `data` names, and a `db` call's paths (another person's data
348
+ * refused, `me` resolved, the page's rules). Without a viewer: the runtime's own are refused,
349
+ * and under a runtime anything above view; a 0.6 config's functions run as before.
350
+ */
351
+ function checkAudience<N extends CapabilityName>(
352
+ capability: N,
353
+ family: RuntimeCapabilityName,
354
+ args: CapabilityArgs[N],
355
+ ): CapabilityArgs[N] | "undeclared" | "level" {
356
+ const { viewer } = options;
357
+ const declaration = options.declaration ?? undefined;
358
+ const method = methodOf(capability, args);
359
+ if (method === null) {
360
+ return args;
361
+ }
362
+ const needed = levelOf(capability, family, method, args);
363
+ if (viewer === undefined) {
364
+ if (RUNTIME_HOST_FUNCTIONS.includes(capability)) {
365
+ return "level";
366
+ }
367
+ // Under a runtime, a level the host set is never skipped for want of a viewer.
368
+ return config.runtime !== undefined && needed !== null && needed !== "view" ? "level" : args;
369
+ }
370
+ if (needed !== null && !atLeast(viewer.level, needed)) {
371
+ return "level";
372
+ }
373
+ if (family === "data" && declaration !== undefined) {
374
+ const data = declaration.capabilities.data;
375
+ const named =
376
+ capability === "callTool"
377
+ ? declaredMatch(data?.tools, (args as CapabilityArgs["callTool"]).name)
378
+ : declaredMatch(data?.resources, (args as CapabilityArgs["readData"]).uri);
379
+ if (!named) {
380
+ return "undeclared";
381
+ }
382
+ }
383
+ if (capability === "db") {
384
+ const rules = declaration?.capabilities.db?.rules;
385
+ const access = dbAccess(args as DbRequest, viewer, rules);
386
+ return access.ok ? (access.request as CapabilityArgs[N]) : "level";
387
+ }
388
+ if (capability === "assets" && (args as CapabilityArgs["assets"]).op === "upload") {
389
+ // What an upload may become (P089): code only an admin added where uploaded code may run.
390
+ const upload = args as CapabilityArgs["assets"] & { readonly op: "upload" };
391
+ return {
392
+ ...upload,
393
+ trusted:
394
+ isCodeAsset(upload.name) && assetCodeRuns(config) && atLeast(viewer.level, "admin"),
395
+ } as CapabilityArgs[N];
396
+ }
397
+ return args;
398
+ }
399
+
400
+ /**
401
+ * The cheap checks for the runtime's own, before their arguments are read (after the review: a
402
+ * malformed call costs nothing but its rate): a method by its `op`, a viewer at its level, its
403
+ * host function's rate.
404
+ */
405
+ function precheck(capability: CapabilityName, raw: unknown): Refusal | null {
406
+ if (!RUNTIME_HOST_FUNCTIONS.includes(capability)) {
407
+ return null;
408
+ }
409
+ const family = familyOf(capability);
410
+ const method = methodOf(capability, raw);
411
+ if (family === null || method === null) {
412
+ return "invalid";
413
+ }
414
+ const viewer = options.viewer;
415
+ const needed = methodLevel(
416
+ config,
417
+ family.name,
418
+ method,
419
+ declaredOf(options.declaration ?? undefined, family.name),
420
+ );
421
+ if (viewer === undefined || (needed !== null && !atLeast(viewer.level, needed))) {
422
+ return "level";
423
+ }
424
+ for (const gate of effectiveGates(config, capability)) {
425
+ if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
426
+ return "rate-limited";
427
+ }
428
+ }
429
+ return null;
430
+ }
431
+
262
432
  return {
263
433
  declared: (capability) => config.capabilities[capability] !== undefined,
264
434
 
435
+ roster: () =>
436
+ rosterOf(
437
+ config,
438
+ options.declaration === undefined || options.declaration === null
439
+ ? []
440
+ : Object.keys(options.declaration.capabilities),
441
+ ),
442
+
265
443
  async call<N extends CapabilityName>(
266
444
  capability: N,
267
445
  raw: unknown,
@@ -271,17 +449,56 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
271
449
  if (config.capabilities[capability] === undefined) {
272
450
  return refuse<Result>(capability, "not-declared");
273
451
  }
274
- const args = (VALIDATORS[capability] as Validator<N>)(raw, config);
275
- if (args === null) {
452
+ // The page's declaration (P086): a built-in needs none; any other runtime capability only
453
+ // a page that declared it reaches; a page with no declaration, none of the runtime's own.
454
+ const family = familyOf(capability);
455
+ // No declaration, or the host's explicit null for a page from before 0.7 (P086).
456
+ const declaration = options.declaration ?? undefined;
457
+ if (
458
+ family !== null &&
459
+ !runtimeCapability(family.name).builtIn &&
460
+ (declaration === undefined
461
+ ? RUNTIME_HOST_FUNCTIONS.includes(capability)
462
+ : !Object.hasOwn(declaration.capabilities, family.name))
463
+ ) {
464
+ return refuse<Result>(capability, "undeclared");
465
+ }
466
+ const early = precheck(capability, raw);
467
+ if (early !== null) {
468
+ return refuse<Result>(capability, early);
469
+ }
470
+ const parsed = (VALIDATORS[capability] as Validator<N>)(raw, config);
471
+ if (parsed === null) {
276
472
  return refuse<Result>(capability, "invalid");
277
473
  }
278
- const gates = effectiveGates(config, capability);
474
+ if (parsed === "too_large") {
475
+ return refuse<Result>(capability, "too-large");
476
+ }
477
+ let args: CapabilityArgs[N] = parsed;
478
+ // Who may (P087): the method's level against the viewer's, the page's own narrowing.
479
+ if (family !== null) {
480
+ const audience = checkAudience(capability, family.name, args);
481
+ if (audience === "undeclared" || audience === "level") {
482
+ return refuse<Result>(capability, audience as Refusal);
483
+ }
484
+ args = audience;
485
+ }
486
+ // Its host function's gates, and its method's own (after the review): all apply.
487
+ const gates = callGates(config, capability, args);
488
+ const own = new Set(effectiveGates(config, capability));
279
489
  const confirms = gates.includes("confirm");
280
490
  if (confirms && muted) {
281
491
  return refuse<Result>(capability, "muted");
282
492
  }
493
+ const method = family === null ? null : methodOf(capability, args);
283
494
  for (const gate of gates) {
284
- if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
495
+ if (typeof gate !== "object") {
496
+ continue;
497
+ }
498
+ // The runtime's own were counted before their arguments were read (`precheck`).
499
+ const counted = own.has(gate) && RUNTIME_HOST_FUNCTIONS.includes(capability);
500
+ const key = own.has(gate) ? capability : `${capability}.${method ?? ""}`;
501
+ if (!counted && !withinRate(key, gate.rateLimit.perMinute)) {
285
502
  return refuse<Result>(capability, "rate-limited");
286
503
  }
287
504
  }
@@ -374,11 +591,36 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
374
591
  }
375
592
  return { ok: true, value: undefined as Result };
376
593
  }
594
+ if (capabilitySpec(capability).served === "viewer") {
595
+ // `user` (P087): the viewer the host gave the display, and nothing else.
596
+ const viewer = options.viewer;
597
+ if (viewer === undefined) {
598
+ return refuse<Result>(capability, "level");
599
+ }
600
+ return {
601
+ ok: true,
602
+ value: {
603
+ id: viewer.id ?? null,
604
+ name: viewer.name ?? null,
605
+ level: viewer.level,
606
+ } as Result,
607
+ };
608
+ }
377
609
  const handler = (handlers as Record<string, CapabilityHandler<N> | undefined>)[capability];
378
610
  if (handler === undefined) {
379
611
  return refuse<Result>(capability, "not-declared");
380
612
  }
381
- const context = { displayId: display.id, title: display.title, capability };
613
+ const family = familyOf(capability);
614
+ const declared =
615
+ family === null ? undefined : declaredOf(options.declaration ?? undefined, family.name);
616
+ const context = {
617
+ displayId: display.id,
618
+ title: display.title,
619
+ capability,
620
+ ...(display.instance === undefined ? {} : { instance: display.instance }),
621
+ ...(options.viewer === undefined ? {} : { viewer: options.viewer }),
622
+ ...(declared === undefined ? {} : { declared }),
623
+ };
382
624
  // A read the content subscribes to may be answered from the host's cache, marked stale; the
383
625
  // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
384
626
  if (capability === "readData" && callOptions?.stale === true && options.cached) {
@@ -392,14 +634,33 @@ export function createBridge(options: BridgeOptions): HostFunctionBridge {
392
634
  }
393
635
  }
394
636
  const subscription = callOptions?.subscription;
395
- if (capability === "subscribeData" && subscription === undefined) {
637
+ // A subscription (`subscribeData`, a `db` watch) needs its channel back.
638
+ const watches =
639
+ capability === "subscribeData" ||
640
+ (capability === "db" && (args as CapabilityArgs["db"]).op === "watch");
641
+ if (watches && subscription === undefined) {
396
642
  return refuse<Result>(capability, "invalid");
397
643
  }
644
+ // A db answer names the viewer's own tree `me`, never their id (after the review, P088).
645
+ const viewer = options.viewer;
646
+ const channel =
647
+ watches && subscription !== undefined && capability === "db"
648
+ ? {
649
+ changed: (state?: unknown) => subscription.changed(withMe(state, viewer)),
650
+ signal: subscription.signal,
651
+ }
652
+ : subscription;
398
653
  try {
399
- const value = await (handler as (args: unknown, context: unknown) => unknown)(
654
+ const answered = await (handler as (args: unknown, context: unknown) => unknown)(
400
655
  args,
401
- capability === "subscribeData" ? { ...context, ...subscription } : context,
656
+ watches ? { ...context, ...channel } : context,
402
657
  );
658
+ const value = capability === "db" ? withMe(answered, viewer) : answered;
659
+ // Comments are write-only (P090): content hears whether the composer opened, never what
660
+ // the host answered beyond that (a thread, its text).
661
+ if (capability === "comments") {
662
+ return { ok: true, value: (value === true) as Result };
663
+ }
403
664
  return { ok: true, value: value as Result };
404
665
  } catch (error) {
405
666
  // A host's Refused tells content its reason (P080); any other error stays the host's.
@@ -12,6 +12,10 @@ import type { Refusal } from "./types.ts";
12
12
  * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
13
13
  * serve, a page where data never runs).
14
14
  * - `failed`: the host tried and couldn't.
15
+ * - `forbidden` (P087): the person viewing it may see the content but not do this (their level).
16
+ * - `conflict` (P088): what it changes moved since it was read (a document's version, the
17
+ * artifact's base): read it again, then write.
18
+ * - `too_large` (P088): more than a limit (a document, a batch, an upload, a publish).
15
19
  */
16
20
  export const REFUSAL_CODES = [
17
21
  "consent_required",
@@ -19,6 +23,9 @@ export const REFUSAL_CODES = [
19
23
  "rate_limited",
20
24
  "not_allowed",
21
25
  "failed",
26
+ "forbidden",
27
+ "conflict",
28
+ "too_large",
22
29
  ] as const;
23
30
 
24
31
  export type RefusalCode = (typeof REFUSAL_CODES)[number];
@@ -89,6 +96,9 @@ const DEFAULT_MESSAGES: { readonly [Code in RefusalCode]: string } = {
89
96
  rate_limited: "Too many requests: try again in a minute.",
90
97
  not_allowed: "This isn't available here.",
91
98
  failed: "The app couldn't do this.",
99
+ forbidden: "You don't have permission to do this here.",
100
+ conflict: "This changed since it was read: read it again, then try again.",
101
+ too_large: "This is too large.",
92
102
  };
93
103
 
94
104
  /** Where a data capability's words differ: they name the data. */
@@ -98,6 +108,9 @@ const DATA_MESSAGES: { readonly [Code in RefusalCode]: string } = {
98
108
  rate_limited: "Too many data requests: try again in a minute.",
99
109
  not_allowed: "This data isn't available here.",
100
110
  failed: "The app couldn't get this data.",
111
+ forbidden: "You don't have permission to read this data.",
112
+ conflict: DEFAULT_MESSAGES.conflict,
113
+ too_large: DEFAULT_MESSAGES.too_large,
101
114
  };
102
115
 
103
116
  /** Each refusal's code, as content is told it. */
@@ -113,6 +126,9 @@ const CODES: { readonly [R in Refusal]: RefusalCode } = {
113
126
  denied: "denied",
114
127
  "rate-limited": "rate_limited",
115
128
  failed: "failed",
129
+ undeclared: "not_allowed",
130
+ level: "forbidden",
131
+ "too-large": "too_large",
116
132
  };
117
133
 
118
134
  /** Refusals whose own words say more than their code's. */
@@ -5,6 +5,9 @@ import type {
5
5
  HandledCapability,
6
6
  } from "../config/capabilities.ts";
7
7
  import type { InstanceRef } from "../isolation/types.ts";
8
+ import type { RuntimeCapabilityName } from "../runtime/contract.ts";
9
+ import type { DeclaredData, DeclaredDb } from "../runtime/declaration.ts";
10
+ import type { ViewerInfo } from "../runtime/levels.ts";
8
11
  import type { RefusalReason } from "./refusal.ts";
9
12
 
10
13
  /**
@@ -20,16 +23,33 @@ export interface CallContext {
20
23
  /** The display's title, as the host gave it (never the content's words). */
21
24
  readonly title: string;
22
25
  readonly capability: CapabilityName;
26
+ /** The instance the host gave the display (which artifact, which version), if any. */
27
+ readonly instance?: InstanceRef;
28
+ /**
29
+ * Who is viewing, as the host said (P087): the bridge already checked the method's level
30
+ * against it. A host's own API checks again: it is its data's wall.
31
+ */
32
+ readonly viewer?: ViewerInfo;
33
+ /**
34
+ * The page's declaration for this capability (P086): its levels, `data`'s resources and tools,
35
+ * `db`'s rules (the fields of the one it is).
36
+ */
37
+ readonly declared?: DeclaredData & DeclaredDb;
23
38
  }
24
39
 
25
40
  export type CapabilityHandler<N extends CapabilityName> = (
26
41
  args: CapabilityArgs[N],
27
- context: N extends "subscribeData" ? SubscriptionContext : CallContext,
42
+ context: N extends "subscribeData"
43
+ ? SubscriptionContext
44
+ : N extends "db"
45
+ ? DbContext
46
+ : CallContext,
28
47
  ) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
29
48
 
30
49
  /**
31
- * A subscription's context (`subscribeData`, P079): how the host tells the content its resource
32
- * changed, and when to stop.
50
+ * A subscription's context (`subscribeData`, P079; a `db` watch, P088): how the host tells the
51
+ * content its resource changed, and when to stop. A `db` watch's `changed` takes the new state
52
+ * (a snapshot, or a collection's `{ docs }`), which goes to the content as it is.
33
53
  */
34
54
  export interface SubscriptionContext extends CallContext {
35
55
  /**
@@ -42,6 +62,9 @@ export interface SubscriptionContext extends CallContext {
42
62
  readonly signal: AbortSignal;
43
63
  }
44
64
 
65
+ /** A `db` call's context: a watch's (`op: "watch"`) carries its channel back and its end. */
66
+ export type DbContext = CallContext & Partial<Pick<SubscriptionContext, "changed" | "signal">>;
67
+
45
68
  /** The host's handlers: one for each declared capability served by a handler. */
46
69
  export type CapabilityHandlers = { readonly [N in HandledCapability]?: CapabilityHandler<N> };
47
70
 
@@ -125,7 +148,20 @@ export type Refusal =
125
148
  | "denied"
126
149
  | "rate-limited"
127
150
  /** The host's handler threw or rejected. */
128
- | "failed";
151
+ | "failed"
152
+ /**
153
+ * The display's page declared capabilities and not this one (P086): a built-in needs none, any
154
+ * other is reachable only by a page that declared it (and only the resources and tools it named).
155
+ */
156
+ | "undeclared"
157
+ /**
158
+ * The viewer's level doesn't reach the method's (P087), or the call reaches data that isn't
159
+ * theirs (another person's `data/users/<id>`); or the host gave the display no viewer, which a
160
+ * runtime capability needs.
161
+ */
162
+ | "level"
163
+ /** Past a limit: a document, a batch, an upload, a publish (P088). */
164
+ | "too-large";
129
165
 
130
166
  export type CallOutcome<T> =
131
167
  /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
@@ -157,4 +193,10 @@ export interface HostFunctionBridge {
157
193
  options?: CallOptions,
158
194
  ): Promise<CallOutcome<CapabilityResults[N]>>;
159
195
  declared(capability: CapabilityName): boolean;
196
+ /**
197
+ * What the runtime offers this display (P085): each runtime capability it may `use`, with its
198
+ * methods. Empty without `config.runtime`. The same whatever the viewer's level: levels refuse
199
+ * at call time.
200
+ */
201
+ roster(): Readonly<Partial<Record<RuntimeCapabilityName, readonly string[]>>>;
160
202
  }
@@ -1,3 +1,4 @@
1
+ import type { PageDeclaration } from "../runtime/declaration.ts";
1
2
  import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
2
3
  import type { InstanceRef } from "../isolation/types.ts";
3
4
  import { presets } from "../presets/presets.ts";
@@ -68,6 +69,12 @@ export interface CheckOptions {
68
69
  readonly files?: FileContents;
69
70
  /** The page a set opens at (default `index.html`). */
70
71
  readonly entry?: string;
72
+ /**
73
+ * Under a runtime (P085): what the page declares (default null: a page with none, so a
74
+ * declared capability is null in the check, as in a preview). Its calls are answered as a
75
+ * declining host answers, by a view-level viewer.
76
+ */
77
+ readonly declaration?: PageDeclaration | null;
71
78
  readonly driver: CheckDriver;
72
79
  /** Widths, px. Default: the manual's phone and desktop widths (`config.layout`). */
73
80
  readonly widths?: readonly number[];
@@ -277,6 +284,7 @@ export async function checkPage(options: CheckOptions): Promise<CheckReport> {
277
284
  content,
278
285
  scriptLines,
279
286
  ...(instance === undefined ? {} : { instance }),
287
+ ...(options.declaration === undefined ? {} : { declaration: options.declaration }),
280
288
  widthPx: width,
281
289
  ...(fills ? { heightPx: 700 } : {}),
282
290
  scheme,
@@ -1,3 +1,4 @@
1
+ import type { PageDeclaration } from "../runtime/declaration.ts";
1
2
  import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
2
3
  import type { InstanceRef } from "../isolation/types.ts";
3
4
 
@@ -14,6 +15,8 @@ export interface CheckRunSpec {
14
15
  readonly scriptLines: readonly number[];
15
16
  /** A served config's instance (located through the check's own server), else opaque. */
16
17
  readonly instance?: InstanceRef;
18
+ /** Under a runtime: the page's declaration (null: none). */
19
+ readonly declaration?: PageDeclaration | null;
17
20
  readonly widthPx: number;
18
21
  readonly heightPx?: number;
19
22
  readonly scheme: ColorScheme;
package/src/check/lint.ts CHANGED
@@ -190,7 +190,9 @@ export function lintContent(config: PortholeConfig, content: string): Finding[]
190
190
  "clipboard",
191
191
  "warning",
192
192
  declared.has("copyText")
193
- ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
193
+ ? config.runtime === undefined
194
+ ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
195
+ : 'The clipboard is closed to content: a copy button calls (await porthole.use("clipboard")).copy(text) from its click.'
194
196
  : "The clipboard is closed to content: copying from a button doesn't work here.",
195
197
  clipboard.index,
196
198
  );
@@ -237,7 +239,7 @@ export function lintContent(config: PortholeConfig, content: string): Finding[]
237
239
  add(
238
240
  "egress",
239
241
  "warning",
240
- `Nothing loads from ${origin} here (${kind}): ${kind === "script" && librarySources(config).length > 0 ? "write it inline, or use one of the libraries served here (the manual's Libraries)" : kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" && config.capabilities.readData !== undefined ? "the content can't call it; read the app's data with readData" : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`,
242
+ `Nothing loads from ${origin} here (${kind}): ${kind === "script" && librarySources(config).length > 0 ? "write it inline, or use one of the libraries served here (the manual's Libraries)" : kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" && config.capabilities.readData !== undefined ? `the content can't call it; read the app's data with ${config.runtime === undefined ? "readData" : "data.read"}` : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`,
241
243
  match.index,
242
244
  );
243
245
  }
package/src/check/page.ts CHANGED
@@ -39,6 +39,16 @@ const DECLINED: { readonly [N in HandledCapability]: () => unknown } = {
39
39
  subscribeData: () => {
40
40
  throw new Error("The host declined the subscription");
41
41
  },
42
+ comments: () => false,
43
+ artifact: () => {
44
+ throw new Error("The host declined the artifact call");
45
+ },
46
+ assets: () => {
47
+ throw new Error("The host declined the asset call");
48
+ },
49
+ db: () => {
50
+ throw new Error("The host declined the db call");
51
+ },
42
52
  };
43
53
 
44
54
  /**
@@ -184,6 +194,10 @@ const check = {
184
194
  title: "Check",
185
195
  scheme: spec.scheme,
186
196
  ...(spec.instance === undefined ? {} : { instance: spec.instance }),
197
+ // Under a runtime: the page's declaration (none by default), a viewer who only views.
198
+ ...(spec.config.runtime === undefined
199
+ ? {}
200
+ : { declaration: spec.declaration ?? null, viewer: { level: "view" as const } }),
187
201
  });
188
202
  const run: Run = {
189
203
  display,
@@ -1,6 +1,5 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
- import { BUILT_IN_TOPICS } from "../config/validate.ts";
3
- import { generateGuide, generateToolDescription } from "../guide/guide.ts";
2
+ import { builtInTopics, generateGuide, generateToolDescription } from "../guide/guide.ts";
4
3
  import { fragmentOf, lintContent, type Finding } from "./lint.ts";
5
4
  import { lintFiles, whereOf, type FileContents, type FileFinding } from "./files.ts";
6
5
 
@@ -29,7 +28,7 @@ const guideName = (config: PortholeConfig) => config.guide.guideToolName ?? `${n
29
28
 
30
29
  /** The topics the manual has: the built-in ones and the config's own. */
31
30
  export function guideTopics(config: PortholeConfig): string[] {
32
- return [...BUILT_IN_TOPICS, ...Object.keys(config.guide.topics ?? {})];
31
+ return [...builtInTopics(config), ...Object.keys(config.guide.topics ?? {})];
33
32
  }
34
33
 
35
34
  /** The tool that shows content: `{ title, html }`. */