@botiverse/porthole 0.7.0 → 0.8.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 (153) hide show
  1. package/README.md +9 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/bridge/bounded-text.d.ts +34 -0
  4. package/dist/bridge/bounded-text.js +188 -0
  5. package/dist/bridge/bridge.d.ts +25 -5
  6. package/dist/bridge/bridge.js +311 -73
  7. package/dist/bridge/json-data.d.ts +28 -0
  8. package/dist/bridge/json-data.js +86 -0
  9. package/dist/bridge/navigation.d.ts +5 -0
  10. package/dist/bridge/navigation.js +7 -0
  11. package/dist/bridge/refusal.js +1 -0
  12. package/dist/bridge/types.d.ts +32 -1
  13. package/dist/check/page-source.js +1 -1
  14. package/dist/check/page.js +2 -0
  15. package/dist/compile/compile.d.ts +6 -0
  16. package/dist/compile/compile.js +3 -1
  17. package/dist/compile/policy.d.ts +38 -2
  18. package/dist/compile/policy.js +122 -7
  19. package/dist/config/capabilities.d.ts +23 -4
  20. package/dist/config/capabilities.js +12 -2
  21. package/dist/config/schema.d.ts +11 -0
  22. package/dist/config/validate.d.ts +8 -2
  23. package/dist/config/validate.js +28 -6
  24. package/dist/config/warnings.d.ts +20 -0
  25. package/dist/config/warnings.js +25 -0
  26. package/dist/conformance/behavior.js +46 -1
  27. package/dist/conformance/cookies.d.ts +15 -0
  28. package/dist/conformance/cookies.js +80 -0
  29. package/dist/conformance/harness/page.d.ts +1 -0
  30. package/dist/conformance/harness/page.js +9 -2
  31. package/dist/conformance/harness-source.js +1 -1
  32. package/dist/conformance/host-kit.js +5 -1
  33. package/dist/conformance/index.d.ts +10 -0
  34. package/dist/conformance/limits.js +38 -1
  35. package/dist/conformance/runtime.js +10 -0
  36. package/dist/conformance/served.d.ts +2 -0
  37. package/dist/conformance/served.js +737 -4
  38. package/dist/files/paths.js +4 -0
  39. package/dist/guide/gates.d.ts +7 -1
  40. package/dist/guide/gates.js +12 -0
  41. package/dist/guide/guide.js +2 -2
  42. package/dist/guide/runtime.js +11 -3
  43. package/dist/host/create-host.js +49 -37
  44. package/dist/host/pages-of-set.d.ts +43 -0
  45. package/dist/host/pages-of-set.js +196 -0
  46. package/dist/host/types.d.ts +8 -1
  47. package/dist/index.d.ts +5 -4
  48. package/dist/index.js +3 -2
  49. package/dist/mcp/adapter.js +11 -15
  50. package/dist/node/index.d.ts +36 -4
  51. package/dist/node/index.js +402 -101
  52. package/dist/presets/presets.d.ts +16 -8
  53. package/dist/presets/presets.js +39 -8
  54. package/dist/protocol/live-data.d.ts +6 -2
  55. package/dist/protocol/live-data.js +20 -1
  56. package/dist/protocol/mcp-apps.d.ts +13 -2
  57. package/dist/protocol/mcp-apps.js +10 -2
  58. package/dist/protocol/message-text.d.ts +8 -0
  59. package/dist/protocol/message-text.js +29 -0
  60. package/dist/protocol/runtime-calls.js +3 -0
  61. package/dist/protocol/shell-adapter.js +16 -22
  62. package/dist/react/context-notice.d.ts +32 -0
  63. package/dist/react/context-notice.js +28 -0
  64. package/dist/react/dialog.js +62 -18
  65. package/dist/react/frame.d.ts +12 -1
  66. package/dist/react/frame.js +79 -2
  67. package/dist/react/index.d.ts +2 -1
  68. package/dist/react/index.js +2 -1
  69. package/dist/runtime/contract.d.ts +9 -1
  70. package/dist/runtime/contract.js +31 -2
  71. package/dist/runtime/db.d.ts +41 -6
  72. package/dist/runtime/db.js +120 -16
  73. package/dist/runtime/declaration.d.ts +15 -1
  74. package/dist/runtime/declaration.js +184 -87
  75. package/dist/runtime/requests.js +27 -11
  76. package/dist/runtime/types.generated.js +1 -1
  77. package/dist/server/files.d.ts +5 -0
  78. package/dist/server/files.js +22 -7
  79. package/dist/server/host.d.ts +18 -1
  80. package/dist/server/host.js +132 -2
  81. package/dist/server/index.d.ts +1 -1
  82. package/dist/server/index.js +1 -1
  83. package/dist/server/peer.d.ts +4 -0
  84. package/dist/server/peer.js +19 -0
  85. package/dist/server/proxy.d.ts +6 -0
  86. package/dist/server/proxy.js +12 -3
  87. package/dist/server/server.js +113 -26
  88. package/dist/server/types.d.ts +6 -3
  89. package/dist/shell/document.d.ts +8 -0
  90. package/dist/shell/document.js +3 -0
  91. package/dist/shell/runtime.js +361 -14
  92. package/docs/ADOPTING.md +119 -14
  93. package/docs/ARCHITECTURE.md +13 -3
  94. package/docs/DECISIONS.md +1455 -8
  95. package/docs/DESIGN.md +79 -25
  96. package/docs/THREAT_MODEL.md +616 -0
  97. package/package.json +14 -3
  98. package/src/bridge/bounded-text.ts +240 -0
  99. package/src/bridge/bridge.ts +373 -84
  100. package/src/bridge/json-data.ts +95 -0
  101. package/src/bridge/navigation.ts +10 -0
  102. package/src/bridge/refusal.ts +1 -0
  103. package/src/bridge/types.ts +30 -1
  104. package/src/check/page.ts +2 -0
  105. package/src/compile/compile.ts +9 -1
  106. package/src/compile/policy.ts +130 -7
  107. package/src/config/capabilities.ts +22 -3
  108. package/src/config/schema.ts +11 -0
  109. package/src/config/validate.ts +43 -5
  110. package/src/config/warnings.ts +42 -0
  111. package/src/conformance/behavior.ts +54 -1
  112. package/src/conformance/cookies.ts +93 -0
  113. package/src/conformance/harness/page.ts +11 -2
  114. package/src/conformance/host-kit.ts +10 -1
  115. package/src/conformance/index.ts +10 -0
  116. package/src/conformance/limits.ts +39 -1
  117. package/src/conformance/runtime.ts +21 -0
  118. package/src/conformance/served.ts +888 -4
  119. package/src/files/paths.ts +4 -0
  120. package/src/guide/gates.ts +13 -1
  121. package/src/guide/guide.ts +3 -3
  122. package/src/guide/runtime.ts +12 -3
  123. package/src/host/create-host.ts +54 -36
  124. package/src/host/pages-of-set.ts +226 -0
  125. package/src/host/types.ts +15 -1
  126. package/src/index.ts +5 -0
  127. package/src/mcp/adapter.ts +16 -20
  128. package/src/node/index.ts +507 -116
  129. package/src/presets/presets.ts +60 -17
  130. package/src/protocol/live-data.ts +31 -3
  131. package/src/protocol/mcp-apps.ts +11 -2
  132. package/src/protocol/message-text.ts +36 -0
  133. package/src/protocol/runtime-calls.ts +3 -0
  134. package/src/protocol/shell-adapter.ts +27 -23
  135. package/src/react/context-notice.tsx +95 -0
  136. package/src/react/dialog.tsx +77 -17
  137. package/src/react/frame.tsx +101 -0
  138. package/src/react/index.ts +8 -1
  139. package/src/runtime/contract.ts +36 -2
  140. package/src/runtime/db.ts +140 -20
  141. package/src/runtime/declaration.ts +227 -89
  142. package/src/runtime/requests.ts +27 -11
  143. package/src/runtime/types.generated.ts +1 -1
  144. package/src/server/files.ts +29 -11
  145. package/src/server/host.ts +158 -3
  146. package/src/server/index.ts +1 -0
  147. package/src/server/peer.ts +21 -0
  148. package/src/server/proxy.ts +13 -3
  149. package/src/server/server.ts +139 -36
  150. package/src/server/types.ts +6 -3
  151. package/src/shell/document.ts +8 -0
  152. package/src/shell/runtime.ts +361 -14
  153. package/types/runtime/v1/context.d.ts +13 -2
@@ -6,9 +6,19 @@ import {
6
6
  isRuntimeVersion,
7
7
  offeredCapabilities,
8
8
  runtimeCapability,
9
+ type RuntimeCapabilityName,
9
10
  type RuntimeVersion,
10
11
  } from "./contract.ts";
11
- import { dbRulesProblem, type DbRules } from "./db.ts";
12
+ import {
13
+ dbRuleLevel,
14
+ dbRuleOf,
15
+ dbRulesProblem,
16
+ foldCollection,
17
+ stricterDbRule,
18
+ type DbRule,
19
+ type DbRules,
20
+ type DeclarationStage,
21
+ } from "./db.ts";
12
22
  import { higher, isViewerLevel, type ViewerLevel } from "./levels.ts";
13
23
 
14
24
  /**
@@ -69,10 +79,19 @@ const KEYS: Readonly<Record<string, readonly string[]>> = {
69
79
  db: ["levels", "rules"],
70
80
  };
71
81
 
72
- const names = (values: unknown, path: string, problems: DeclarationProblem[]): void => {
82
+ /** The most names `data` lists at publish; where shown (an intersection of two), twice that (P093). */
83
+ const MAX_NAMES = 200;
84
+
85
+ const names = (
86
+ values: unknown,
87
+ path: string,
88
+ problems: DeclarationProblem[],
89
+ stage: DeclarationStage,
90
+ ): void => {
91
+ const most = stage === "publish" ? MAX_NAMES : 2 * MAX_NAMES;
73
92
  if (
74
93
  !Array.isArray(values) ||
75
- values.length > 200 ||
94
+ values.length > most ||
76
95
  values.some(
77
96
  (each) =>
78
97
  typeof each !== "string" ||
@@ -85,7 +104,7 @@ const names = (values: unknown, path: string, problems: DeclarationProblem[]): v
85
104
  ) {
86
105
  problems.push({
87
106
  path,
88
- message: "must be a list of names (at most 200), each exact or a prefix ending in *",
107
+ message: `must be a list of names (at most ${most}), each exact or a prefix ending in *`,
89
108
  });
90
109
  }
91
110
  };
@@ -98,6 +117,19 @@ export function declarationProblems(
98
117
  given: unknown,
99
118
  config: PortholeConfig,
100
119
  runtime: RuntimeVersion = RUNTIME_VERSION,
120
+ ): DeclarationProblem[] {
121
+ return stagedProblems(given, config, runtime, "publish");
122
+ }
123
+
124
+ /**
125
+ * `declarationProblems` at a stage (P093): at publish, the limits a page is held to; where a
126
+ * declaration is shown (a mount), an intersection of two such (`intersectDeclarations`) fits too.
127
+ */
128
+ function stagedProblems(
129
+ given: unknown,
130
+ config: PortholeConfig,
131
+ runtime: RuntimeVersion,
132
+ stage: DeclarationStage,
101
133
  ): DeclarationProblem[] {
102
134
  const problems: DeclarationProblem[] = [];
103
135
  if (!isRuntimeVersion(runtime)) {
@@ -116,8 +148,7 @@ export function declarationProblems(
116
148
  });
117
149
  continue;
118
150
  }
119
- const spec = runtimeCapability(name);
120
- if (spec.builtIn) {
151
+ if (runtimeCapability(name).builtIn) {
121
152
  problems.push({ path, message: "is built in: use it without declaring it" });
122
153
  continue;
123
154
  }
@@ -125,51 +156,63 @@ export function declarationProblems(
125
156
  problems.push({ path, message: "isn't offered here" });
126
157
  continue;
127
158
  }
128
- if (!isRecord(value)) {
129
- problems.push({ path, message: "must be an object ({} for none of its own)" });
130
- continue;
131
- }
132
- const allowed = KEYS[name] ?? ["levels"];
133
- for (const key of Object.keys(value)) {
134
- if (!allowed.includes(key)) {
135
- problems.push({ path: `${path}.${key}`, message: `is not a field of ${name}'s config` });
136
- }
159
+ configProblems(name, value, path, problems, stage);
160
+ }
161
+ return problems;
162
+ }
163
+
164
+ /** The problems with one capability's config, its shape alone (no host's offer needed). */
165
+ function configProblems(
166
+ name: RuntimeCapabilityName,
167
+ value: unknown,
168
+ path: string,
169
+ problems: DeclarationProblem[],
170
+ stage: DeclarationStage,
171
+ ): void {
172
+ const spec = runtimeCapability(name);
173
+ if (!isRecord(value)) {
174
+ problems.push({ path, message: "must be an object ({} for none of its own)" });
175
+ return;
176
+ }
177
+ const allowed = KEYS[name] ?? ["levels"];
178
+ for (const key of Object.keys(value)) {
179
+ if (!allowed.includes(key)) {
180
+ problems.push({ path: `${path}.${key}`, message: `is not a field of ${name}'s config` });
137
181
  }
138
- if (value.levels !== undefined) {
139
- if (!isRecord(value.levels)) {
140
- problems.push({ path: `${path}.levels`, message: "must be an object of levels by method" });
141
- } else {
142
- for (const [method, level] of Object.entries(value.levels)) {
143
- if (!Object.hasOwn(spec.methods, method)) {
144
- problems.push({
145
- path: `${path}.levels.${method}`,
146
- message: `is not a method of ${name} (${Object.keys(spec.methods).join(", ")})`,
147
- });
148
- } else if (!isViewerLevel(level)) {
149
- problems.push({
150
- path: `${path}.levels.${method}`,
151
- message: "must be view, interact, admin or owner",
152
- });
153
- }
182
+ }
183
+ if (value.levels !== undefined) {
184
+ if (!isRecord(value.levels)) {
185
+ problems.push({ path: `${path}.levels`, message: "must be an object of levels by method" });
186
+ } else {
187
+ for (const [method, level] of Object.entries(value.levels)) {
188
+ if (!Object.hasOwn(spec.methods, method)) {
189
+ problems.push({
190
+ path: `${path}.levels.${method}`,
191
+ message: `is not a method of ${name} (${Object.keys(spec.methods).join(", ")})`,
192
+ });
193
+ } else if (!isViewerLevel(level)) {
194
+ problems.push({
195
+ path: `${path}.levels.${method}`,
196
+ message: "must be view, interact, admin or owner",
197
+ });
154
198
  }
155
199
  }
156
200
  }
157
- if (name === "data") {
158
- if (value.resources !== undefined) {
159
- names(value.resources, `${path}.resources`, problems);
160
- }
161
- if (value.tools !== undefined) {
162
- names(value.tools, `${path}.tools`, problems);
163
- }
201
+ }
202
+ if (name === "data") {
203
+ if (value.resources !== undefined) {
204
+ names(value.resources, `${path}.resources`, problems, stage);
164
205
  }
165
- if (name === "db" && value.rules !== undefined) {
166
- const problem = dbRulesProblem(value.rules);
167
- if (problem !== null) {
168
- problems.push({ path: `${path}.rules`, message: problem });
169
- }
206
+ if (value.tools !== undefined) {
207
+ names(value.tools, `${path}.tools`, problems, stage);
208
+ }
209
+ }
210
+ if (name === "db" && value.rules !== undefined) {
211
+ const problem = dbRulesProblem(value.rules, stage);
212
+ if (problem !== null) {
213
+ problems.push({ path: `${path}.rules`, message: problem });
170
214
  }
171
215
  }
172
- return problems;
173
216
  }
174
217
 
175
218
  /** A declaration checked (a host's stored one, given to `mount`); throws a `TypeError` naming its problems. */
@@ -183,7 +226,7 @@ export function checkDeclaration(given: unknown, config: PortholeConfig): PageDe
183
226
  `A declaration's runtime ${JSON.stringify(runtime)} is not one this Porthole serves`,
184
227
  );
185
228
  }
186
- const problems = declarationProblems(given.capabilities, config, runtime);
229
+ const problems = stagedProblems(given.capabilities, config, runtime, "shown");
187
230
  if (problems.length > 0) {
188
231
  throw new TypeError(
189
232
  `The declaration doesn't fit this config: ${problems.map((each) => `${each.path} ${each.message}`).join("; ")}`,
@@ -239,15 +282,16 @@ export function declareCapabilities(options: {
239
282
  }
240
283
  const runtime: RuntimeVersion = options.runtime ?? stored?.runtime ?? RUNTIME_VERSION;
241
284
  if (given === undefined) {
242
- const declaration = stored ?? { capabilities: {}, runtime };
243
- const pinned = { capabilities: declaration.capabilities, runtime };
244
- // A stored declaration still fits the host's offer (a host may have narrowed its config).
245
- const problems = declarationProblems(pinned.capabilities, config, runtime);
285
+ const capabilities = stored?.capabilities ?? {};
286
+ // A stored declaration still fits the host's offer (a host may have narrowed its config); as
287
+ // stored, a page's from before P093 too (rule names in more than one case).
288
+ const problems = stagedProblems(capabilities, config, runtime, "shown");
246
289
  return problems.length > 0
247
290
  ? { ok: false, problems }
248
291
  : {
249
292
  ok: true,
250
- declaration: pinned,
293
+ // Its own copy, as at a publish that gives one (P093, after its review).
294
+ declaration: { capabilities: copied(capabilities) as CapabilityDeclaration, runtime },
251
295
  changed: stored === undefined || stored === null || stored.runtime !== runtime,
252
296
  };
253
297
  }
@@ -255,7 +299,8 @@ export function declareCapabilities(options: {
255
299
  if (problems.length > 0) {
256
300
  return { ok: false, problems };
257
301
  }
258
- const declaration = { capabilities: given as CapabilityDeclaration, runtime };
302
+ // Its own copy, without prototypes (P093): what was checked, not the caller's object.
303
+ const declaration = { capabilities: copied(given) as CapabilityDeclaration, runtime };
259
304
  return {
260
305
  ok: true,
261
306
  declaration,
@@ -285,18 +330,28 @@ export function declaredMatch(list: readonly string[] | undefined, name: string)
285
330
  );
286
331
  }
287
332
 
288
- /** The stricter of two declared level maps. */
333
+ /**
334
+ * An object without a prototype (P093): a name the page wrote (`__proto__`, a collection's) is an
335
+ * own key of it when set, never a prototype's setter or a prototype's name when read.
336
+ */
337
+ const bare = <T>(): Record<string, T> => Object.create(null) as Record<string, T>;
338
+
339
+ /** The stricter of two declared level maps (absent: the contract's, everywhere). */
289
340
  function stricterLevels(
290
341
  a: Readonly<Record<string, ViewerLevel>> | undefined,
291
342
  b: Readonly<Record<string, ViewerLevel>> | undefined,
292
343
  ): Readonly<Record<string, ViewerLevel>> | undefined {
293
- if (a === undefined || b === undefined) {
294
- return a ?? b;
344
+ if (a === undefined && b === undefined) {
345
+ return undefined;
295
346
  }
296
- const out: Record<string, ViewerLevel> = { ...a };
297
- for (const [method, level] of Object.entries(b)) {
298
- const other = Object.hasOwn(out, method) ? out[method] : undefined;
299
- out[method] = other === undefined ? level : higher(other, level);
347
+ const out = bare<ViewerLevel>();
348
+ for (const method of new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])) {
349
+ const x = a !== undefined && Object.hasOwn(a, method) ? a[method] : undefined;
350
+ const y = b !== undefined && Object.hasOwn(b, method) ? b[method] : undefined;
351
+ const level = x === undefined ? y : y === undefined ? x : higher(x, y);
352
+ if (level !== undefined) {
353
+ out[method] = level;
354
+ }
300
355
  }
301
356
  return out;
302
357
  }
@@ -307,7 +362,7 @@ function bothNames(
307
362
  b: readonly string[] | undefined,
308
363
  ): readonly string[] | undefined {
309
364
  if (a === undefined || b === undefined) {
310
- return a ?? b;
365
+ return a === undefined ? b?.slice() : a.slice();
311
366
  }
312
367
  return [
313
368
  ...new Set([
@@ -317,62 +372,145 @@ function bothNames(
317
372
  ];
318
373
  }
319
374
 
320
- /** The stricter of two pages' rules, by collection. */
375
+ /**
376
+ * The stricter of two pages' rules, by collection (P093, the 2026-10-19 audit's S02): each name
377
+ * either side's rules give, in any case, and `*`, is under the stricter of the rule EACH side
378
+ * puts it under, as `dbAccess` reads that side (`dbRuleOf`). A collection neither names is under
379
+ * both sides' `*`, the output's `*`. So the output allows a level at most what both allow it (an
380
+ * old version's `public` doesn't outlive the current `*`, nor the other way), and exactly that
381
+ * where both spell each collection alike; where they spell one differently it may be stricter
382
+ * (after the re-review). One name for each name in any case (as the first side spells it); none
383
+ * for a name whose rule is the output's `*`'s (after the review: it says nothing `*` doesn't).
384
+ */
321
385
  function stricterRules(a: DbRules | undefined, b: DbRules | undefined): DbRules | undefined {
322
- if (a === undefined || b === undefined) {
323
- return a ?? b;
386
+ if (a === undefined && b === undefined) {
387
+ return undefined;
324
388
  }
325
- const out: Record<string, { read?: ViewerLevel; write?: ViewerLevel }> = {};
326
- for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
327
- const x = Object.hasOwn(a, key) ? a[key] : undefined;
328
- const y = Object.hasOwn(b, key) ? b[key] : undefined;
329
- const read =
330
- x?.read === undefined ? y?.read : y?.read === undefined ? x.read : higher(x.read, y.read);
331
- const write =
332
- x?.write === undefined
333
- ? y?.write
334
- : y?.write === undefined
335
- ? x.write
336
- : higher(x.write, y.write);
337
- out[key] = {
338
- ...(read === undefined ? {} : { read }),
339
- ...(write === undefined ? {} : { write }),
340
- };
389
+ const wildcard = stricterDbRule(dbRuleOf(a, "*"), dbRuleOf(b, "*"));
390
+ const same = (rule: DbRule) =>
391
+ dbRuleLevel(rule, false) === dbRuleLevel(wildcard, false) &&
392
+ dbRuleLevel(rule, true) === dbRuleLevel(wildcard, true);
393
+ const out = bare<DbRule>();
394
+ const seen = new Set<string>();
395
+ for (const name of [...Object.keys(a ?? {}), ...Object.keys(b ?? {})]) {
396
+ const folded = foldCollection(name);
397
+ if (name === "*" || seen.has(folded)) {
398
+ continue;
399
+ }
400
+ seen.add(folded);
401
+ const rule = stricterDbRule(dbRuleOf(a, name), dbRuleOf(b, name));
402
+ if (!same(rule)) {
403
+ out[name] = rule;
404
+ }
405
+ }
406
+ if ((a !== undefined && Object.hasOwn(a, "*")) || (b !== undefined && Object.hasOwn(b, "*"))) {
407
+ out["*"] = wildcard;
341
408
  }
342
409
  return out;
343
410
  }
344
411
 
412
+ /**
413
+ * The problems with a declaration's shape where it is shown (no host's offer: the mount checks
414
+ * that), each path under `which`: what would be read as allowing anything could loosen the other
415
+ * side (`higher` with a level that isn't one returns the other).
416
+ */
417
+ function shapeProblems(declaration: unknown, which: string): DeclarationProblem[] {
418
+ const problems: DeclarationProblem[] = [];
419
+ if (!isRecord(declaration) || !isRecord(declaration.capabilities)) {
420
+ return [{ path: `${which}.capabilities`, message: "must be an object: { name: config }" }];
421
+ }
422
+ if (!isRuntimeVersion(declaration.runtime)) {
423
+ problems.push({
424
+ path: `${which}.runtime`,
425
+ message: "is not a runtime version Porthole serves",
426
+ });
427
+ }
428
+ for (const [name, value] of Object.entries(declaration.capabilities)) {
429
+ const path = `${which}.capabilities.${name}`;
430
+ if (!isRuntimeCapabilityName(name)) {
431
+ problems.push({ path, message: "is not a capability" });
432
+ } else if (runtimeCapability(name).builtIn) {
433
+ problems.push({ path, message: "is built in: use it without declaring it" });
434
+ } else {
435
+ configProblems(name, value, path, problems, "shown");
436
+ }
437
+ }
438
+ return problems;
439
+ }
440
+
345
441
  /**
346
442
  * What a version may do when it is shown (after the review): what it declared when it was
347
443
  * published AND what the artifact declares now. A host stores each version's declaration with
348
444
  * it (`declareCapabilities` at its publish) and mounts a version with this, so an old version
349
445
  * never keeps what the artifact has since revoked, nor gains what it declared later. Each
350
446
  * capability only where both declare it, at the stricter levels, the narrower `data` names and
351
- * the stricter `db` rules; the version's own pinned runtime.
447
+ * the stricter `db` rules (each side read as `dbAccess` reads it, P093); the version's own pinned
448
+ * runtime. Whatever the result allows, each side allows alone; a mount takes it (two pages at
449
+ * the publish limits make one within a mount's). Objects without a prototype.
450
+ *
451
+ * Answers its problems (P093, after its review) where either side isn't a declaration's shape
452
+ * (or the two make one past a mount's limits): show the version as an error, never with `null`
453
+ * (that is 0.6's surface) or with either side alone.
352
454
  */
353
- export function intersectDeclarations(
455
+ export function tryIntersectDeclarations(
354
456
  version: PageDeclaration,
355
457
  current: PageDeclaration,
356
- ): PageDeclaration {
357
- const capabilities: Record<string, DeclaredCapability & DeclaredData & DeclaredDb> = {};
458
+ ):
459
+ | { readonly ok: true; readonly declaration: PageDeclaration }
460
+ | { readonly ok: false; readonly problems: readonly DeclarationProblem[] } {
461
+ const problems = [...shapeProblems(version, "version"), ...shapeProblems(current, "current")];
462
+ if (problems.length > 0) {
463
+ return { ok: false, problems };
464
+ }
358
465
  const a = version.capabilities as Readonly<Record<string, DeclaredData & DeclaredDb>>;
359
466
  const b = current.capabilities as Readonly<Record<string, DeclaredData & DeclaredDb>>;
467
+ const capabilities = bare<DeclaredCapability & DeclaredData & DeclaredDb>();
360
468
  for (const name of Object.keys(a)) {
361
469
  if (!Object.hasOwn(b, name)) {
362
470
  continue;
363
471
  }
364
472
  const x = a[name] ?? {};
365
473
  const y = b[name] ?? {};
474
+ const out = Object.create(null) as {
475
+ levels?: Readonly<Record<string, ViewerLevel>>;
476
+ resources?: readonly string[];
477
+ tools?: readonly string[];
478
+ rules?: DbRules;
479
+ };
366
480
  const levels = stricterLevels(x.levels, y.levels);
367
481
  const resources = bothNames(x.resources, y.resources);
368
482
  const tools = bothNames(x.tools, y.tools);
369
483
  const rules = stricterRules(x.rules, y.rules);
370
- capabilities[name] = {
371
- ...(levels === undefined ? {} : { levels }),
372
- ...(resources === undefined ? {} : { resources }),
373
- ...(tools === undefined ? {} : { tools }),
374
- ...(rules === undefined ? {} : { rules }),
375
- };
484
+ if (levels !== undefined) {
485
+ out.levels = levels;
486
+ }
487
+ if (resources !== undefined) {
488
+ out.resources = resources;
489
+ }
490
+ if (tools !== undefined) {
491
+ out.tools = tools;
492
+ }
493
+ if (rules !== undefined) {
494
+ out.rules = rules;
495
+ }
496
+ capabilities[name] = out;
497
+ }
498
+ const declaration: PageDeclaration = { capabilities, runtime: version.runtime };
499
+ // Within a mount's limits: sides that were themselves intersections could make one past them.
500
+ const past = shapeProblems(declaration, "intersection");
501
+ return past.length > 0 ? { ok: false, problems: past } : { ok: true, declaration };
502
+ }
503
+
504
+ /** `tryIntersectDeclarations`, a `TypeError` naming the problems where it answers some. */
505
+ export function intersectDeclarations(
506
+ version: PageDeclaration,
507
+ current: PageDeclaration,
508
+ ): PageDeclaration {
509
+ const result = tryIntersectDeclarations(version, current);
510
+ if (!result.ok) {
511
+ throw new TypeError(
512
+ `The declarations don't intersect: ${result.problems.map((each) => `${each.path} ${each.message}`).join("; ")}`,
513
+ );
376
514
  }
377
- return { capabilities, runtime: version.runtime };
515
+ return result.declaration;
378
516
  }
@@ -15,9 +15,16 @@ type Parsed<T> = T | "too_large" | null;
15
15
  const isRecord = (value: unknown): value is Record<string, unknown> =>
16
16
  value !== null && typeof value === "object" && !Array.isArray(value);
17
17
 
18
- /** A short text of the content's: a string of `1..max` characters, no control characters. */
18
+ /**
19
+ * A short text of the content's: a string of `1..max` characters, no control characters, and
20
+ * well-formed Unicode (P095: a lone surrogate makes `encodeURIComponent` throw, and is no text).
21
+ */
19
22
  const shortText = (value: unknown, max: number): value is string =>
20
- typeof value === "string" && value.trim() !== "" && value.length <= max && !/\p{Cc}/u.test(value);
23
+ typeof value === "string" &&
24
+ value.trim() !== "" &&
25
+ value.length <= max &&
26
+ value.isWellFormed() &&
27
+ !/\p{Cc}/u.test(value);
21
28
 
22
29
  const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/u;
23
30
 
@@ -130,20 +137,24 @@ export function parseArtifactRequest(
130
137
  return null;
131
138
  }
132
139
  const { maxFiles, maxFileBytes, maxVersionBytes } = fileLimits(limits);
133
- const entries = Object.entries(args.files);
134
- if (entries.length === 0) {
140
+ // Its count before any file is read, and each file's size before it is encoded, against the
141
+ // version's total so far (P095: one file object shared under every path is one object to send).
142
+ const given = args.files;
143
+ const paths = Object.keys(given);
144
+ if (paths.length === 0) {
135
145
  return null;
136
146
  }
137
- if (entries.length > Math.min(MAX_PUBLISH_FILES, maxFiles)) {
147
+ if (paths.length > Math.min(MAX_PUBLISH_FILES, maxFiles)) {
138
148
  return "too_large";
139
149
  }
140
150
  // No prototype: a path named `__proto__` is a path (after the review).
141
151
  const files = Object.create(null) as Record<string, PublishedFile>;
142
152
  let total = 0;
143
- for (const [path, file] of entries) {
153
+ for (const path of paths) {
144
154
  if (filePathProblem(path) !== null) {
145
155
  return null;
146
156
  }
157
+ const file = given[path];
147
158
  if (file === null) {
148
159
  files[path] = null;
149
160
  continue;
@@ -153,9 +164,16 @@ export function parseArtifactRequest(
153
164
  }
154
165
  let size: number | null = null;
155
166
  if (typeof file.text === "string" && file.base64 === undefined) {
167
+ // A character is a byte or more in UTF-8: past a limit by its length, it isn't encoded.
168
+ if (file.text.length > maxFileBytes || total + file.text.length > maxVersionBytes) {
169
+ return "too_large";
170
+ }
156
171
  size = encoder.encode(file.text).length;
157
172
  files[path] = { text: file.text };
158
173
  } else if (file.text === undefined) {
174
+ if (typeof file.base64 === "string" && (file.base64.length / 4) * 3 - 2 > maxFileBytes) {
175
+ return "too_large";
176
+ }
159
177
  size = base64Bytes(file.base64);
160
178
  if (size !== null) {
161
179
  files[path] = { base64: file.base64 as string };
@@ -164,13 +182,10 @@ export function parseArtifactRequest(
164
182
  if (size === null) {
165
183
  return null;
166
184
  }
167
- if (size > maxFileBytes) {
185
+ total += size;
186
+ if (size > maxFileBytes || total > maxVersionBytes) {
168
187
  return "too_large";
169
188
  }
170
- total += size;
171
- }
172
- if (total > maxVersionBytes) {
173
- return "too_large";
174
189
  }
175
190
  if (
176
191
  (args.entry !== undefined && filePathProblem(args.entry) !== null) ||
@@ -238,6 +253,7 @@ export function assetNameProblem(name: unknown): string | null {
238
253
  typeof name !== "string" ||
239
254
  name.trim() === "" ||
240
255
  name.length > 255 ||
256
+ !name.isWellFormed() ||
241
257
  /[/\\\p{Cc}\p{Cf}]/u.test(name)
242
258
  ) {
243
259
  return "an asset's name is a file name: 1 to 255 characters, no / or \\";
@@ -8,7 +8,7 @@ export const RUNTIME_TYPES: Readonly<Record<string, Readonly<Record<string, stri
8
8
  "chat": "// Porthole capability runtime, contract 1: chat. Declare it: { chat: {} }.\n\ninterface PortholeChat {\n /**\n * Sends text to the agent as the person's message (\"explain this point\"). Call it from a click.\n * Resolves true if it was sent. Level: interact.\n */\n send(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n chat: PortholeChat;\n}\n",
9
9
  "clipboard": "// Porthole capability runtime, contract 1: clipboard. Built in: never declare it.\n\ninterface PortholeClipboard {\n /**\n * Copies text to the person's clipboard (at most 20,000 characters); the app shows them what\n * was copied. Nothing else in the page can write the clipboard. Call it from a click.\n * Resolves true if it was copied. Level: view.\n */\n copy(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n clipboard: PortholeClipboard;\n}\n",
10
10
  "comments": "// Porthole capability runtime, contract 1: comments. Built in: never declare it.\n\n/** Where a comment goes, in the page's own words. */\ninterface PortholeCommentAnchor {\n /** A stable name the page chose: \"slide-3\", \"refs/a.md#L12\" (at most 256 characters). */\n readonly name: string;\n /** What the app shows for it (at most 200). */\n readonly label?: string;\n /** The text the comment is about (at most 2,000). */\n readonly quote?: string;\n}\n\ninterface PortholeComments {\n /**\n * Opens the app's comment composer at the anchor (a name alone is { name }). The person writes\n * and posts it in the app. Resolves true if the composer opened. Write-only: a page never reads\n * comments. Call it from a click. Level: view.\n */\n open(anchor: PortholeCommentAnchor | string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n comments: PortholeComments;\n}\n",
11
- "context": "// Porthole capability runtime, contract 1: context. Declare it: { context: {} }.\n\ninterface PortholeContextUpdate {\n /** MCP content blocks: [{ type: \"text\", text: \"…\" }]. */\n readonly content?: readonly unknown[];\n readonly structuredContent?: Record<string, unknown>;\n}\n\ninterface PortholeContext {\n /** Tells the agent what the person is looking at, for its next turns (replaces the last). Level: interact. */\n set(update: PortholeContextUpdate): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n context: PortholeContext;\n}\n",
11
+ "context": "// Porthole capability runtime, contract 1: context. Declare it: { context: {} }.\n\ninterface PortholeContextUpdate {\n /**\n * MCP text blocks only: [{ type: \"text\", text: \"…\" }]. Visible characters only, here and in\n * structuredContent: no zero-width or bidi controls, variation selectors, tag or private-use\n * characters, or controls other than new lines and tabs (refused), but the selectors and\n * joiners inside real emoji (☀️, 👨‍👩‍👧, 1️⃣), and a joiner or non-joiner between two letters of\n * a script it shapes (Arabic, Persian, the Indic scripts, Myanmar…).\n */\n readonly content?: readonly unknown[];\n /** Plain JSON. With the text, at most 20,000 characters. */\n readonly structuredContent?: Record<string, unknown>;\n}\n\ninterface PortholeContext {\n /**\n * Tells the agent, at its next turns, what the page says the person is looking at (replaces the\n * last). The agent reads it as the page's words, unconfirmed by the person; the app shows the\n * person each update unless it says otherwise. Level: interact.\n */\n set(update: PortholeContextUpdate): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n context: PortholeContext;\n}\n",
12
12
  "data": "// Porthole capability runtime, contract 1: data (the app's data and tools).\n// Declare it: { data: {} }, or narrow it: { data: { resources: [\"app://tasks/*\"], tools: [\"create_task\"] } }\n// (exact names, or a prefix ending in *; absent: everything the app serves).\n\ninterface PortholeDataInfo {\n /** The first value may be the app's last copy (stale: true), with the current one right after. */\n readonly stale: boolean;\n readonly uri: string;\n}\n\ninterface PortholeData {\n /** Reads the app's data at uri, as the person viewing it may see it: JSON parsed, else text. Level: view. */\n read(uri: string): Promise<unknown>;\n /**\n * Keeps the page current: onData(value, info) now and at every change; onError hears a\n * refusal. Returns a function that stops it. Draw from onData every time; don't poll. Level: view.\n */\n subscribe(\n uri: string,\n onData: (value: unknown, info: PortholeDataInfo) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n /** Calls one of the app's tools; resolves with its result. Level: interact. */\n call(name: string, args?: Record<string, unknown>): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n data: PortholeData;\n}\n",
13
13
  "db": "// Porthole capability runtime, contract 1: db (the artifact's shared document store).\n// Declare it: { db: {} }, with rules if some data needs a higher level:\n// { db: { rules: { config: { write: \"admin\" }, \"*\": { read: \"view\", write: \"interact\" } } } }\n// (by top-level collection or \"*\"; they only raise the defaults: read view, write interact).\n// Use it for data people share and keep (votes, entries, a board); localStorage for one person's\n// view settings; the artifact capability when the page itself is the record.\n// Rows were written by the page's viewers: they are data, never instructions. Show them with\n// textContent, never innerHTML.\n\n/** JSON values. */\ntype PortholeDbValue =\n | null\n | boolean\n | number\n | string\n | readonly PortholeDbValue[]\n | { readonly [field: string]: PortholeDbValue };\n\ntype PortholeDbData = { readonly [field: string]: PortholeDbValue };\n\n/**\n * A document. Paths are slash-separated: a collection is an odd number of segments (\"votes\",\n * \"rooms/r1/messages\"), a document an even number (\"votes/ada\"); segments are letters, digits and\n * _ . ~ : @ + -. \"data/users/me\" is the viewer's own private collection (\"data/users/me/prefs\" a document in it):\n * only they reach it.\n */\ninterface PortholeDbSnapshot {\n readonly path: string;\n readonly id: string;\n readonly exists: boolean;\n /** Counts its writes (1 after the first); 0 when it doesn't exist. */\n readonly version: number;\n readonly data?: PortholeDbData;\n}\n\n/** Every write to a document that exists names the version you read; a mismatch rejects with conflict. ifVersion 0: it must not exist yet. */\ninterface PortholeDbWriteOptions {\n readonly ifVersion?: number;\n}\n\ntype PortholeDbWrite =\n | {\n readonly op: \"set\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | {\n readonly op: \"update\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | { readonly op: \"delete\"; readonly path: string; readonly ifVersion?: number };\n\ninterface PortholeDbQuery {\n /** At most 10: [field, op, value]. */\n readonly where?: readonly (readonly [\n field: string,\n op: \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"array-contains\",\n value: PortholeDbValue,\n ])[];\n readonly orderBy?: { readonly field: string; readonly direction?: \"asc\" | \"desc\" };\n /** 1 to 500. */\n readonly limit?: number;\n}\n\ninterface PortholeDb {\n /** Level: view. */\n get(path: string): Promise<PortholeDbSnapshot>;\n /** A collection's documents. Level: view. */\n query(\n collection: string,\n query?: PortholeDbQuery,\n ): Promise<{ readonly docs: readonly PortholeDbSnapshot[] }>;\n /** Writes a whole document (at most 1 MiB of JSON). Level: interact. */\n set(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Merges fields over a document's. Level: interact. */\n update(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Level: interact. */\n delete(path: string, options?: PortholeDbWriteOptions): Promise<null>;\n /**\n * Up to 50 writes to different documents, all or none. Each write's new version (null for a\n * delete). Each write at its own level.\n */\n batch(\n writes: readonly PortholeDbWrite[],\n ): Promise<{ readonly versions: readonly (number | null)[] }>;\n /**\n * Follows a document (a snapshot) or a collection ({ docs }) now and at every change. Returns a\n * function that stops it. Draw from onData; don't poll. Level: view.\n */\n onSnapshot(\n path: string,\n onData: (state: PortholeDbSnapshot | { readonly docs: readonly PortholeDbSnapshot[] }) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n}\n\ninterface PortholeCapabilities {\n db: PortholeDb;\n}\n",
14
14
  "downloads": "// Porthole capability runtime, contract 1: downloads. Built in: never declare it.\n\n/** A file to hand the person: its name, and its text or bytes. */\ninterface PortholeDownload {\n /** A file name, no slashes: \"report.csv\". Its extension gives its type unless `type` says. */\n readonly name: string;\n readonly type?: string;\n readonly text?: string;\n readonly data?: Blob | ArrayBuffer | ArrayBufferView;\n}\n\ninterface PortholeDownloads {\n /**\n * Hands the person a file to save (<a download> and script-driven saves don't work here).\n * Call it from a click. Resolves true if the download started. Level: view.\n */\n save(file: PortholeDownload): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n downloads: PortholeDownloads;\n}\n",
@@ -3,6 +3,8 @@ import {
3
3
  assetCspDirectives,
4
4
  fileSetCspDirectives,
5
5
  INERT_FILE_CSP,
6
+ servedDocumentCsp,
7
+ servedPermissionsPolicy,
6
8
  serializeCsp,
7
9
  } from "../compile/policy.ts";
8
10
  import { DEFAULT_ENTRY, lookupFile, requestFilePath, type FileLookup } from "../files/paths.ts";
@@ -43,6 +45,8 @@ export interface FileServing {
43
45
  * that address before it ends (`expires`, epoch ms).
44
46
  */
45
47
  readonly ticket?: { readonly expires: number };
48
+ /** The artifact version the set is, which its pages name in their notices to the host (P098). */
49
+ readonly artifact?: { readonly id: string; readonly version: string };
46
50
  }
47
51
 
48
52
  const HEX = /^[0-9a-f]{64}$/u;
@@ -230,22 +234,31 @@ export async function serveFile(serving: FileServing): Promise<Response> {
230
234
  ? "same-origin"
231
235
  : "no-referrer";
232
236
  // Its version's files (P082), and its artifact's assets where the config serves them (P089).
233
- const frameCsp = serializeCsp(
234
- assetCspDirectives(
235
- serving.compiled.config,
236
- fileSetCspDirectives(serving.compiled.cspDirectives, serving.source),
237
- serving.origin,
238
- ),
237
+ const directives = assetCspDirectives(
238
+ serving.compiled.config,
239
+ fileSetCspDirectives(serving.compiled.cspDirectives, serving.source),
240
+ serving.origin,
239
241
  );
242
+ // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
243
+ // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
244
+ // its own.
245
+ const csp =
246
+ role === "file"
247
+ ? INERT_FILE_CSP
248
+ : role === "page"
249
+ ? servedDocumentCsp(serving.compiled.config, directives)
250
+ : serializeCsp(directives);
240
251
  const headers = new Headers({
241
252
  "content-type": type,
242
253
  "x-content-type-options": "nosniff",
243
254
  "referrer-policy": referrer,
244
255
  "x-robots-tag": "noindex, nofollow",
245
- // A page and a script (a worker's policy is its script's) get the page's CSP; anything else
246
- // runs nothing when opened on its own.
247
- "content-security-policy": `${role === "file" ? INERT_FILE_CSP : frameCsp}; frame-ancestors ${serving.frameAncestors}`,
256
+ "content-security-policy": `${csp}; frame-ancestors ${serving.frameAncestors}`,
248
257
  });
258
+ const permissions = role === "page" ? servedPermissionsPolicy(serving.compiled.config) : null;
259
+ if (permissions !== null) {
260
+ headers.set("permissions-policy", permissions);
261
+ }
249
262
 
250
263
  if (role === "page") {
251
264
  // Every page of the set in the shell (P081): its hardening, its host functions, its theme.
@@ -263,6 +276,7 @@ export async function serveFile(serving: FileServing): Promise<Response> {
263
276
  address: `${base}${found.path.includes("/") ? encodePath(found.path) : ""}`,
264
277
  expires: serving.ticket.expires,
265
278
  }),
279
+ ...(serving.artifact === undefined ? {} : { set: serving.artifact }),
266
280
  },
267
281
  });
268
282
  if (serving.ticket !== undefined) {
@@ -366,8 +380,9 @@ export async function serveAsset(serving: {
366
380
  const typed = fileTypeOf(asset.name);
367
381
  // Never a page: an asset is the library's, outside the shell (P089); code only where it was
368
382
  // trusted when it was uploaded (after the review).
383
+ const asCode = typed.role !== "page" && isCodeAsset(asset.name) && serving.code;
369
384
  const type =
370
- typed.role === "page" || (isCodeAsset(asset.name) && !serving.code)
385
+ typed.role === "page" || (isCodeAsset(asset.name) && !asCode)
371
386
  ? "application/octet-stream"
372
387
  : typed.type;
373
388
  const headers = new Headers({
@@ -385,7 +400,10 @@ export async function serveAsset(serving: {
385
400
  if (type === "application/octet-stream") {
386
401
  headers.set("content-disposition", "attachment");
387
402
  }
388
- const etag = HEX.test(asset.sha256) ? `"${asset.sha256}"` : null;
403
+ // The ETag carries the decision too (P103): once a stricter config ships, a copy the browser
404
+ // kept as code is a different one, so its revalidation gets the download whole, never a 304
405
+ // that would leave it typed as code.
406
+ const etag = HEX.test(asset.sha256) ? `"${asset.sha256}-${asCode ? "code" : "inert"}"` : null;
389
407
  if (etag !== null) {
390
408
  headers.set("etag", etag);
391
409
  if (notModified(request, etag)) {