@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
package/README.md CHANGED
@@ -77,6 +77,22 @@ that opens that version's path and nothing else of its origin; `checkFileSet` ch
77
77
  paths and limits when it is published, `lintFiles` and `checkPage({ files })` are the agent's
78
78
  side. docs/ADOPTING.md § Pages made of many files.
79
79
 
80
+ ## A page that is an app: the capability runtime
81
+
82
+ With `runtime: "1"` in its config (0.7), a page reaches its host through one global, for what it
83
+ declared when it was published and what its viewer's level allows:
84
+
85
+ ```js
86
+ const db = await porthole.use("db"); // a frozen namespace, or null: draw without it
87
+ const votes = db && (await db.query("votes")).docs; // a refusal rejects with error.code and a sentence
88
+ ```
89
+
90
+ The host keeps the services: its handlers (`db`, `artifact`, `assets`, `comments`; `user` is the
91
+ viewer it gives), `declareCapabilities` at publish, the viewer's level in its access
92
+ (`Grant.level`), and an asset store `/server` serves at `/_blob/<id>`. `defineRuntimeConformance`
93
+ checks the handlers. The types: `types/runtime/v1/*.d.ts`. docs/ADOPTING.md § The capability
94
+ runtime.
95
+
80
96
  ## What the agent gets
81
97
 
82
98
  ```js
@@ -1,6 +1,8 @@
1
1
  import { type CapabilityName } from "../config/capabilities.ts";
2
2
  import type { AnnotationReport } from "../annotate/types.ts";
3
3
  import type { PortholeConfig } from "../config/schema.ts";
4
+ import { type PageDeclaration } from "../runtime/declaration.ts";
5
+ import { type ViewerInfo } from "../runtime/levels.ts";
4
6
  import { type Refused } from "./refusal.ts";
5
7
  import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal } from "./types.ts";
6
8
  /**
@@ -49,6 +51,17 @@ export interface BridgeOptions {
49
51
  readonly onEvent: (event: BridgeEvent) => void;
50
52
  /** The clock, in milliseconds (tests pass their own). */
51
53
  readonly now?: () => number;
54
+ /**
55
+ * Who is viewing (P087), as the host said: each runtime method's level is checked against it,
56
+ * and the runtime's own host functions need it. Absent: 0.6's functions run unchecked, as before.
57
+ */
58
+ readonly viewer?: ViewerInfo;
59
+ /**
60
+ * What the display's page declared (P086), checked against the config (`checkDeclaration`).
61
+ * Absent: a page without one (0.6's): built-ins only through the runtime, and 0.6's globals and
62
+ * requests as before.
63
+ */
64
+ readonly declaration?: PageDeclaration | null;
52
65
  }
53
66
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
54
67
  export declare function linkTarget(value: unknown): string | null;
@@ -1,7 +1,12 @@
1
1
  import { MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
2
2
  import { parseReport } from "../annotate/validate.js";
3
- import { effectiveGates } from "../compile/policy.js";
3
+ import { callGates, effectiveGates } from "../compile/policy.js";
4
4
  import { blockedNavigationMessage, withoutSealedAddresses } from "./navigation.js";
5
+ import { RUNTIME_HOST_FUNCTIONS, familyOf, methodLevel, methodOf, assetCodeRuns, rosterOf, runtimeCapability, } from "../runtime/contract.js";
6
+ import { declaredMatch, } from "../runtime/declaration.js";
7
+ import { dbAccess, parseDbRequest, withMe } from "../runtime/db.js";
8
+ import { atLeast, higher } from "../runtime/levels.js";
9
+ import { isCodeAsset, parseArtifactRequest, parseAssetRequest, parseCommentRequest, } from "../runtime/requests.js";
5
10
  import { defaultReason, isRefused, pendingReason, reasonOf, } from "./refusal.js";
6
11
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
7
12
  const MAX_URL = 4_096;
@@ -98,6 +103,13 @@ const VALIDATORS = {
98
103
  : null;
99
104
  },
100
105
  annotate: (args) => parseReport(args),
106
+ // The runtime's own (P088-P090): their shapes and limits, before any gate.
107
+ user: (args) => (args === undefined || isRecord(args) ? {} : null),
108
+ comments: (args) => parseCommentRequest(args),
109
+ artifact: (args, config) => parseArtifactRequest(args, config.limits),
110
+ // Code-typed names only where uploaded code may run (P089, after the review).
111
+ assets: (args, config) => parseAssetRequest(args, config.limits, assetCodeRuns(config)),
112
+ db: (args) => parseDbRequest(args),
101
113
  resize: (args) => {
102
114
  if (!isRecord(args) ||
103
115
  typeof args.height !== "number" ||
@@ -138,6 +150,13 @@ export function onceConsent(consent) {
138
150
  return given;
139
151
  };
140
152
  }
153
+ /** What the page declared for one runtime capability, if it declared it. */
154
+ function declaredOf(declaration, family) {
155
+ const capabilities = declaration?.capabilities;
156
+ return capabilities !== undefined && Object.hasOwn(capabilities, family)
157
+ ? capabilities[family]
158
+ : undefined;
159
+ }
141
160
  export function createBridge(options) {
142
161
  const { config, display, handlers, onEvent } = options;
143
162
  const now = options.now ?? (() => Date.now());
@@ -164,23 +183,155 @@ export function createBridge(options) {
164
183
  calls.set(capability, recent);
165
184
  return true;
166
185
  };
186
+ /** The least level a call needs: its method's, and a db batch's writes' or a watch's read's. */
187
+ function levelOf(capability, family, method, args) {
188
+ const declared = declaredOf(options.declaration ?? undefined, family);
189
+ const own = methodLevel(config, family, method, declared);
190
+ if (capability !== "db" || own === null) {
191
+ return own;
192
+ }
193
+ // A batch is each of its writes; a watch is a read (after the review: neither escapes the
194
+ // levels of what it does).
195
+ const request = args;
196
+ const inner = request.op === "batch"
197
+ ? request.writes.map((write) => write.op)
198
+ : request.op === "watch"
199
+ ? [request.path.split("/").length % 2 === 0 ? "get" : "query"]
200
+ : [];
201
+ return inner.reduce((most, op) => higher(most, methodLevel(config, family, op, declared) ?? most), own);
202
+ }
203
+ /**
204
+ * Whether this viewer may make this call (P087), and the call as the handler gets it: the
205
+ * call's level (the contract's, the host's, the page's; a batch's writes', a watch's read's),
206
+ * the resources and tools a page's `data` names, and a `db` call's paths (another person's data
207
+ * refused, `me` resolved, the page's rules). Without a viewer: the runtime's own are refused,
208
+ * and under a runtime anything above view; a 0.6 config's functions run as before.
209
+ */
210
+ function checkAudience(capability, family, args) {
211
+ const { viewer } = options;
212
+ const declaration = options.declaration ?? undefined;
213
+ const method = methodOf(capability, args);
214
+ if (method === null) {
215
+ return args;
216
+ }
217
+ const needed = levelOf(capability, family, method, args);
218
+ if (viewer === undefined) {
219
+ if (RUNTIME_HOST_FUNCTIONS.includes(capability)) {
220
+ return "level";
221
+ }
222
+ // Under a runtime, a level the host set is never skipped for want of a viewer.
223
+ return config.runtime !== undefined && needed !== null && needed !== "view" ? "level" : args;
224
+ }
225
+ if (needed !== null && !atLeast(viewer.level, needed)) {
226
+ return "level";
227
+ }
228
+ if (family === "data" && declaration !== undefined) {
229
+ const data = declaration.capabilities.data;
230
+ const named = capability === "callTool"
231
+ ? declaredMatch(data?.tools, args.name)
232
+ : declaredMatch(data?.resources, args.uri);
233
+ if (!named) {
234
+ return "undeclared";
235
+ }
236
+ }
237
+ if (capability === "db") {
238
+ const rules = declaration?.capabilities.db?.rules;
239
+ const access = dbAccess(args, viewer, rules);
240
+ return access.ok ? access.request : "level";
241
+ }
242
+ if (capability === "assets" && args.op === "upload") {
243
+ // What an upload may become (P089): code only an admin added where uploaded code may run.
244
+ const upload = args;
245
+ return {
246
+ ...upload,
247
+ trusted: isCodeAsset(upload.name) && assetCodeRuns(config) && atLeast(viewer.level, "admin"),
248
+ };
249
+ }
250
+ return args;
251
+ }
252
+ /**
253
+ * The cheap checks for the runtime's own, before their arguments are read (after the review: a
254
+ * malformed call costs nothing but its rate): a method by its `op`, a viewer at its level, its
255
+ * host function's rate.
256
+ */
257
+ function precheck(capability, raw) {
258
+ if (!RUNTIME_HOST_FUNCTIONS.includes(capability)) {
259
+ return null;
260
+ }
261
+ const family = familyOf(capability);
262
+ const method = methodOf(capability, raw);
263
+ if (family === null || method === null) {
264
+ return "invalid";
265
+ }
266
+ const viewer = options.viewer;
267
+ const needed = methodLevel(config, family.name, method, declaredOf(options.declaration ?? undefined, family.name));
268
+ if (viewer === undefined || (needed !== null && !atLeast(viewer.level, needed))) {
269
+ return "level";
270
+ }
271
+ for (const gate of effectiveGates(config, capability)) {
272
+ if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
273
+ return "rate-limited";
274
+ }
275
+ }
276
+ return null;
277
+ }
167
278
  return {
168
279
  declared: (capability) => config.capabilities[capability] !== undefined,
280
+ roster: () => rosterOf(config, options.declaration === undefined || options.declaration === null
281
+ ? []
282
+ : Object.keys(options.declaration.capabilities)),
169
283
  async call(capability, raw, callOptions) {
170
284
  if (config.capabilities[capability] === undefined) {
171
285
  return refuse(capability, "not-declared");
172
286
  }
173
- const args = VALIDATORS[capability](raw, config);
174
- if (args === null) {
287
+ // The page's declaration (P086): a built-in needs none; any other runtime capability only
288
+ // a page that declared it reaches; a page with no declaration, none of the runtime's own.
289
+ const family = familyOf(capability);
290
+ // No declaration, or the host's explicit null for a page from before 0.7 (P086).
291
+ const declaration = options.declaration ?? undefined;
292
+ if (family !== null &&
293
+ !runtimeCapability(family.name).builtIn &&
294
+ (declaration === undefined
295
+ ? RUNTIME_HOST_FUNCTIONS.includes(capability)
296
+ : !Object.hasOwn(declaration.capabilities, family.name))) {
297
+ return refuse(capability, "undeclared");
298
+ }
299
+ const early = precheck(capability, raw);
300
+ if (early !== null) {
301
+ return refuse(capability, early);
302
+ }
303
+ const parsed = VALIDATORS[capability](raw, config);
304
+ if (parsed === null) {
175
305
  return refuse(capability, "invalid");
176
306
  }
177
- const gates = effectiveGates(config, capability);
307
+ if (parsed === "too_large") {
308
+ return refuse(capability, "too-large");
309
+ }
310
+ let args = parsed;
311
+ // Who may (P087): the method's level against the viewer's, the page's own narrowing.
312
+ if (family !== null) {
313
+ const audience = checkAudience(capability, family.name, args);
314
+ if (audience === "undeclared" || audience === "level") {
315
+ return refuse(capability, audience);
316
+ }
317
+ args = audience;
318
+ }
319
+ // Its host function's gates, and its method's own (after the review): all apply.
320
+ const gates = callGates(config, capability, args);
321
+ const own = new Set(effectiveGates(config, capability));
178
322
  const confirms = gates.includes("confirm");
179
323
  if (confirms && muted) {
180
324
  return refuse(capability, "muted");
181
325
  }
326
+ const method = family === null ? null : methodOf(capability, args);
182
327
  for (const gate of gates) {
183
- if (typeof gate === "object" && !withinRate(capability, gate.rateLimit.perMinute)) {
328
+ if (typeof gate !== "object") {
329
+ continue;
330
+ }
331
+ // The runtime's own were counted before their arguments were read (`precheck`).
332
+ const counted = own.has(gate) && RUNTIME_HOST_FUNCTIONS.includes(capability);
333
+ const key = own.has(gate) ? capability : `${capability}.${method ?? ""}`;
334
+ if (!counted && !withinRate(key, gate.rateLimit.perMinute)) {
184
335
  return refuse(capability, "rate-limited");
185
336
  }
186
337
  }
@@ -262,11 +413,35 @@ export function createBridge(options) {
262
413
  }
263
414
  return { ok: true, value: undefined };
264
415
  }
416
+ if (capabilitySpec(capability).served === "viewer") {
417
+ // `user` (P087): the viewer the host gave the display, and nothing else.
418
+ const viewer = options.viewer;
419
+ if (viewer === undefined) {
420
+ return refuse(capability, "level");
421
+ }
422
+ return {
423
+ ok: true,
424
+ value: {
425
+ id: viewer.id ?? null,
426
+ name: viewer.name ?? null,
427
+ level: viewer.level,
428
+ },
429
+ };
430
+ }
265
431
  const handler = handlers[capability];
266
432
  if (handler === undefined) {
267
433
  return refuse(capability, "not-declared");
268
434
  }
269
- const context = { displayId: display.id, title: display.title, capability };
435
+ const family = familyOf(capability);
436
+ const declared = family === null ? undefined : declaredOf(options.declaration ?? undefined, family.name);
437
+ const context = {
438
+ displayId: display.id,
439
+ title: display.title,
440
+ capability,
441
+ ...(display.instance === undefined ? {} : { instance: display.instance }),
442
+ ...(options.viewer === undefined ? {} : { viewer: options.viewer }),
443
+ ...(declared === undefined ? {} : { declared }),
444
+ };
270
445
  // A read the content subscribes to may be answered from the host's cache, marked stale; the
271
446
  // fresh one follows as an update (the adapter asks for it). A cache that fails is no answer.
272
447
  if (capability === "readData" && callOptions?.stale === true && options.cached) {
@@ -281,11 +456,28 @@ export function createBridge(options) {
281
456
  }
282
457
  }
283
458
  const subscription = callOptions?.subscription;
284
- if (capability === "subscribeData" && subscription === undefined) {
459
+ // A subscription (`subscribeData`, a `db` watch) needs its channel back.
460
+ const watches = capability === "subscribeData" ||
461
+ (capability === "db" && args.op === "watch");
462
+ if (watches && subscription === undefined) {
285
463
  return refuse(capability, "invalid");
286
464
  }
465
+ // A db answer names the viewer's own tree `me`, never their id (after the review, P088).
466
+ const viewer = options.viewer;
467
+ const channel = watches && subscription !== undefined && capability === "db"
468
+ ? {
469
+ changed: (state) => subscription.changed(withMe(state, viewer)),
470
+ signal: subscription.signal,
471
+ }
472
+ : subscription;
287
473
  try {
288
- const value = await handler(args, capability === "subscribeData" ? { ...context, ...subscription } : context);
474
+ const answered = await handler(args, watches ? { ...context, ...channel } : context);
475
+ const value = capability === "db" ? withMe(answered, viewer) : answered;
476
+ // Comments are write-only (P090): content hears whether the composer opened, never what
477
+ // the host answered beyond that (a thread, its text).
478
+ if (capability === "comments") {
479
+ return { ok: true, value: (value === true) };
480
+ }
289
481
  return { ok: true, value: value };
290
482
  }
291
483
  catch (error) {
@@ -11,8 +11,12 @@ import type { Refusal } from "./types.ts";
11
11
  * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
12
12
  * serve, a page where data never runs).
13
13
  * - `failed`: the host tried and couldn't.
14
+ * - `forbidden` (P087): the person viewing it may see the content but not do this (their level).
15
+ * - `conflict` (P088): what it changes moved since it was read (a document's version, the
16
+ * artifact's base): read it again, then write.
17
+ * - `too_large` (P088): more than a limit (a document, a batch, an upload, a publish).
14
18
  */
15
- export declare const REFUSAL_CODES: readonly ["consent_required", "denied", "rate_limited", "not_allowed", "failed"];
19
+ export declare const REFUSAL_CODES: readonly ["consent_required", "denied", "rate_limited", "not_allowed", "failed", "forbidden", "conflict", "too_large"];
16
20
  export type RefusalCode = (typeof REFUSAL_CODES)[number];
17
21
  /** What content is told about a refusal: the JSON-RPC error's `data`. */
18
22
  export interface RefusalReason {
@@ -9,6 +9,10 @@
9
9
  * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
10
10
  * serve, a page where data never runs).
11
11
  * - `failed`: the host tried and couldn't.
12
+ * - `forbidden` (P087): the person viewing it may see the content but not do this (their level).
13
+ * - `conflict` (P088): what it changes moved since it was read (a document's version, the
14
+ * artifact's base): read it again, then write.
15
+ * - `too_large` (P088): more than a limit (a document, a batch, an upload, a publish).
12
16
  */
13
17
  export const REFUSAL_CODES = [
14
18
  "consent_required",
@@ -16,6 +20,9 @@ export const REFUSAL_CODES = [
16
20
  "rate_limited",
17
21
  "not_allowed",
18
22
  "failed",
23
+ "forbidden",
24
+ "conflict",
25
+ "too_large",
19
26
  ];
20
27
  /** The most a refusal's message carries to content. */
21
28
  const MAX_MESSAGE = 500;
@@ -68,6 +75,9 @@ const DEFAULT_MESSAGES = {
68
75
  rate_limited: "Too many requests: try again in a minute.",
69
76
  not_allowed: "This isn't available here.",
70
77
  failed: "The app couldn't do this.",
78
+ forbidden: "You don't have permission to do this here.",
79
+ conflict: "This changed since it was read: read it again, then try again.",
80
+ too_large: "This is too large.",
71
81
  };
72
82
  /** Where a data capability's words differ: they name the data. */
73
83
  const DATA_MESSAGES = {
@@ -76,6 +86,9 @@ const DATA_MESSAGES = {
76
86
  rate_limited: "Too many data requests: try again in a minute.",
77
87
  not_allowed: "This data isn't available here.",
78
88
  failed: "The app couldn't get this data.",
89
+ forbidden: "You don't have permission to read this data.",
90
+ conflict: DEFAULT_MESSAGES.conflict,
91
+ too_large: DEFAULT_MESSAGES.too_large,
79
92
  };
80
93
  /** Each refusal's code, as content is told it. */
81
94
  const CODES = {
@@ -90,6 +103,9 @@ const CODES = {
90
103
  denied: "denied",
91
104
  "rate-limited": "rate_limited",
92
105
  failed: "failed",
106
+ undeclared: "not_allowed",
107
+ level: "forbidden",
108
+ "too-large": "too_large",
93
109
  };
94
110
  /** Refusals whose own words say more than their code's. */
95
111
  const OWN_MESSAGES = {
@@ -1,5 +1,8 @@
1
1
  import type { CapabilityArgs, CapabilityName, CapabilityResults, HandledCapability } from "../config/capabilities.ts";
2
2
  import type { InstanceRef } from "../isolation/types.ts";
3
+ import type { RuntimeCapabilityName } from "../runtime/contract.ts";
4
+ import type { DeclaredData, DeclaredDb } from "../runtime/declaration.ts";
5
+ import type { ViewerInfo } from "../runtime/levels.ts";
3
6
  import type { RefusalReason } from "./refusal.ts";
4
7
  /**
5
8
  * The host-function bridge (ARCHITECTURE § Framework layer): carries a capability call from the
@@ -13,11 +16,24 @@ export interface CallContext {
13
16
  /** The display's title, as the host gave it (never the content's words). */
14
17
  readonly title: string;
15
18
  readonly capability: CapabilityName;
19
+ /** The instance the host gave the display (which artifact, which version), if any. */
20
+ readonly instance?: InstanceRef;
21
+ /**
22
+ * Who is viewing, as the host said (P087): the bridge already checked the method's level
23
+ * against it. A host's own API checks again: it is its data's wall.
24
+ */
25
+ readonly viewer?: ViewerInfo;
26
+ /**
27
+ * The page's declaration for this capability (P086): its levels, `data`'s resources and tools,
28
+ * `db`'s rules (the fields of the one it is).
29
+ */
30
+ readonly declared?: DeclaredData & DeclaredDb;
16
31
  }
17
- export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: N extends "subscribeData" ? SubscriptionContext : CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
32
+ export type CapabilityHandler<N extends CapabilityName> = (args: CapabilityArgs[N], context: N extends "subscribeData" ? SubscriptionContext : N extends "db" ? DbContext : CallContext) => CapabilityResults[N] | Promise<CapabilityResults[N]>;
18
33
  /**
19
- * A subscription's context (`subscribeData`, P079): how the host tells the content its resource
20
- * changed, and when to stop.
34
+ * A subscription's context (`subscribeData`, P079; a `db` watch, P088): how the host tells the
35
+ * content its resource changed, and when to stop. A `db` watch's `changed` takes the new state
36
+ * (a snapshot, or a collection's `{ docs }`), which goes to the content as it is.
21
37
  */
22
38
  export interface SubscriptionContext extends CallContext {
23
39
  /**
@@ -29,6 +45,8 @@ export interface SubscriptionContext extends CallContext {
29
45
  /** Aborted when the content unsubscribes, its frame stops, or the display is destroyed. */
30
46
  readonly signal: AbortSignal;
31
47
  }
48
+ /** A `db` call's context: a watch's (`op: "watch"`) carries its channel back and its end. */
49
+ export type DbContext = CallContext & Partial<Pick<SubscriptionContext, "changed" | "signal">>;
32
50
  /** The host's handlers: one for each declared capability served by a handler. */
33
51
  export type CapabilityHandlers = {
34
52
  readonly [N in HandledCapability]?: CapabilityHandler<N>;
@@ -105,7 +123,20 @@ export type Refusal =
105
123
  /** The host's `consent` said no (for this display's life). */
106
124
  | "denied" | "rate-limited"
107
125
  /** The host's handler threw or rejected. */
108
- | "failed";
126
+ | "failed"
127
+ /**
128
+ * The display's page declared capabilities and not this one (P086): a built-in needs none, any
129
+ * other is reachable only by a page that declared it (and only the resources and tools it named).
130
+ */
131
+ | "undeclared"
132
+ /**
133
+ * The viewer's level doesn't reach the method's (P087), or the call reaches data that isn't
134
+ * theirs (another person's `data/users/<id>`); or the host gave the display no viewer, which a
135
+ * runtime capability needs.
136
+ */
137
+ | "level"
138
+ /** Past a limit: a document, a batch, an upload, a publish (P088). */
139
+ | "too-large";
109
140
  export type CallOutcome<T> =
110
141
  /** `stale`: a `readData` answered from the host's cache (`DataCache`). */
111
142
  {
@@ -133,4 +164,10 @@ export interface HostFunctionBridge {
133
164
  /** Validates `args` for `capability`, applies its gates, then runs the host's handler. */
134
165
  call<N extends CapabilityName>(capability: N, args: unknown, options?: CallOptions): Promise<CallOutcome<CapabilityResults[N]>>;
135
166
  declared(capability: CapabilityName): boolean;
167
+ /**
168
+ * What the runtime offers this display (P085): each runtime capability it may `use`, with its
169
+ * methods. Empty without `config.runtime`. The same whatever the viewer's level: levels refuse
170
+ * at call time.
171
+ */
172
+ roster(): Readonly<Partial<Record<RuntimeCapabilityName, readonly string[]>>>;
136
173
  }
@@ -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 FileContents, type FileFinding } from "./files.ts";
3
4
  import { type CheckCall } from "./instrument.ts";
@@ -43,6 +44,12 @@ export interface CheckOptions {
43
44
  readonly files?: FileContents;
44
45
  /** The page a set opens at (default `index.html`). */
45
46
  readonly entry?: string;
47
+ /**
48
+ * Under a runtime (P085): what the page declares (default null: a page with none, so a
49
+ * declared capability is null in the check, as in a preview). Its calls are answered as a
50
+ * declining host answers, by a view-level viewer.
51
+ */
52
+ readonly declaration?: PageDeclaration | null;
46
53
  readonly driver: CheckDriver;
47
54
  /** Widths, px. Default: the manual's phone and desktop widths (`config.layout`). */
48
55
  readonly widths?: readonly number[];
@@ -141,6 +141,7 @@ export async function checkPage(options) {
141
141
  content,
142
142
  scriptLines,
143
143
  ...(instance === undefined ? {} : { instance }),
144
+ ...(options.declaration === undefined ? {} : { declaration: options.declaration }),
144
145
  widthPx: width,
145
146
  ...(fills ? { heightPx: 700 } : {}),
146
147
  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
  /**
@@ -12,6 +13,8 @@ export interface CheckRunSpec {
12
13
  readonly scriptLines: readonly number[];
13
14
  /** A served config's instance (located through the check's own server), else opaque. */
14
15
  readonly instance?: InstanceRef;
16
+ /** Under a runtime: the page's declaration (null: none). */
17
+ readonly declaration?: PageDeclaration | null;
15
18
  readonly widthPx: number;
16
19
  readonly heightPx?: number;
17
20
  readonly scheme: ColorScheme;
@@ -109,7 +109,9 @@ export function lintContent(config, content) {
109
109
  const clipboard = /\bnavigator\s*\.\s*clipboard\b|\bexecCommand\s*\(\s*["'](?:copy|cut)["']/u.exec(content);
110
110
  if (clipboard !== null) {
111
111
  add("clipboard", "warning", declared.has("copyText")
112
- ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
112
+ ? config.runtime === undefined
113
+ ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
114
+ : 'The clipboard is closed to content: a copy button calls (await porthole.use("clipboard")).copy(text) from its click.'
113
115
  : "The clipboard is closed to content: copying from a button doesn't work here.", clipboard.index);
114
116
  }
115
117
  const dialog = /(?:^|[^.\w$])(?:window\s*\.\s*)?(alert|confirm|prompt)\s*\(/u.exec(content);
@@ -139,7 +141,7 @@ export function lintContent(config, content) {
139
141
  egressOrigins(config, kind).some((source) => source === origin || originMatchesSource(origin, source));
140
142
  if (!open && !reported.has(`${kind} ${origin}`)) {
141
143
  reported.add(`${kind} ${origin}`);
142
- add("egress", "warning", `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"}.`, match.index);
144
+ add("egress", "warning", `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"}.`, match.index);
143
145
  }
144
146
  const own = OWN_CDN.find((each) => each.host.test(address));
145
147
  if (own !== undefined && kind === "script" && !own.pinned.test(new URL(address).pathname)) {