@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
@@ -1,14 +1,17 @@
1
1
  import { RUNTIME_CAPABILITY_NAMES, RUNTIME_VERSION, isRuntimeCapabilityName, isRuntimeVersion, offeredCapabilities, runtimeCapability, } from "./contract.js";
2
- import { dbRulesProblem } from "./db.js";
2
+ import { dbRuleLevel, dbRuleOf, dbRulesProblem, foldCollection, stricterDbRule, } from "./db.js";
3
3
  import { higher, isViewerLevel } from "./levels.js";
4
4
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5
5
  const KEYS = {
6
6
  data: ["levels", "resources", "tools"],
7
7
  db: ["levels", "rules"],
8
8
  };
9
- const names = (values, path, problems) => {
9
+ /** The most names `data` lists at publish; where shown (an intersection of two), twice that (P093). */
10
+ const MAX_NAMES = 200;
11
+ const names = (values, path, problems, stage) => {
12
+ const most = stage === "publish" ? MAX_NAMES : 2 * MAX_NAMES;
10
13
  if (!Array.isArray(values) ||
11
- values.length > 200 ||
14
+ values.length > most ||
12
15
  values.some((each) => typeof each !== "string" ||
13
16
  each === "" ||
14
17
  each.length > 512 ||
@@ -17,7 +20,7 @@ const names = (values, path, problems) => {
17
20
  (each.includes("*") && each.indexOf("*") !== each.length - 1))) {
18
21
  problems.push({
19
22
  path,
20
- message: "must be a list of names (at most 200), each exact or a prefix ending in *",
23
+ message: `must be a list of names (at most ${most}), each exact or a prefix ending in *`,
21
24
  });
22
25
  }
23
26
  };
@@ -26,6 +29,13 @@ const names = (values, path, problems) => {
26
29
  * runtime knows, the config offers and isn't built in; each config of its own shape. Empty: fine.
27
30
  */
28
31
  export function declarationProblems(given, config, runtime = RUNTIME_VERSION) {
32
+ return stagedProblems(given, config, runtime, "publish");
33
+ }
34
+ /**
35
+ * `declarationProblems` at a stage (P093): at publish, the limits a page is held to; where a
36
+ * declaration is shown (a mount), an intersection of two such (`intersectDeclarations`) fits too.
37
+ */
38
+ function stagedProblems(given, config, runtime, stage) {
29
39
  const problems = [];
30
40
  if (!isRuntimeVersion(runtime)) {
31
41
  return [{ path: "runtime", message: `is not a runtime version Porthole serves` }];
@@ -43,8 +53,7 @@ export function declarationProblems(given, config, runtime = RUNTIME_VERSION) {
43
53
  });
44
54
  continue;
45
55
  }
46
- const spec = runtimeCapability(name);
47
- if (spec.builtIn) {
56
+ if (runtimeCapability(name).builtIn) {
48
57
  problems.push({ path, message: "is built in: use it without declaring it" });
49
58
  continue;
50
59
  }
@@ -52,53 +61,58 @@ export function declarationProblems(given, config, runtime = RUNTIME_VERSION) {
52
61
  problems.push({ path, message: "isn't offered here" });
53
62
  continue;
54
63
  }
55
- if (!isRecord(value)) {
56
- problems.push({ path, message: "must be an object ({} for none of its own)" });
57
- continue;
64
+ configProblems(name, value, path, problems, stage);
65
+ }
66
+ return problems;
67
+ }
68
+ /** The problems with one capability's config, its shape alone (no host's offer needed). */
69
+ function configProblems(name, value, path, problems, stage) {
70
+ const spec = runtimeCapability(name);
71
+ if (!isRecord(value)) {
72
+ problems.push({ path, message: "must be an object ({} for none of its own)" });
73
+ return;
74
+ }
75
+ const allowed = KEYS[name] ?? ["levels"];
76
+ for (const key of Object.keys(value)) {
77
+ if (!allowed.includes(key)) {
78
+ problems.push({ path: `${path}.${key}`, message: `is not a field of ${name}'s config` });
58
79
  }
59
- const allowed = KEYS[name] ?? ["levels"];
60
- for (const key of Object.keys(value)) {
61
- if (!allowed.includes(key)) {
62
- problems.push({ path: `${path}.${key}`, message: `is not a field of ${name}'s config` });
63
- }
80
+ }
81
+ if (value.levels !== undefined) {
82
+ if (!isRecord(value.levels)) {
83
+ problems.push({ path: `${path}.levels`, message: "must be an object of levels by method" });
64
84
  }
65
- if (value.levels !== undefined) {
66
- if (!isRecord(value.levels)) {
67
- problems.push({ path: `${path}.levels`, message: "must be an object of levels by method" });
68
- }
69
- else {
70
- for (const [method, level] of Object.entries(value.levels)) {
71
- if (!Object.hasOwn(spec.methods, method)) {
72
- problems.push({
73
- path: `${path}.levels.${method}`,
74
- message: `is not a method of ${name} (${Object.keys(spec.methods).join(", ")})`,
75
- });
76
- }
77
- else if (!isViewerLevel(level)) {
78
- problems.push({
79
- path: `${path}.levels.${method}`,
80
- message: "must be view, interact, admin or owner",
81
- });
82
- }
85
+ else {
86
+ for (const [method, level] of Object.entries(value.levels)) {
87
+ if (!Object.hasOwn(spec.methods, method)) {
88
+ problems.push({
89
+ path: `${path}.levels.${method}`,
90
+ message: `is not a method of ${name} (${Object.keys(spec.methods).join(", ")})`,
91
+ });
92
+ }
93
+ else if (!isViewerLevel(level)) {
94
+ problems.push({
95
+ path: `${path}.levels.${method}`,
96
+ message: "must be view, interact, admin or owner",
97
+ });
83
98
  }
84
99
  }
85
100
  }
86
- if (name === "data") {
87
- if (value.resources !== undefined) {
88
- names(value.resources, `${path}.resources`, problems);
89
- }
90
- if (value.tools !== undefined) {
91
- names(value.tools, `${path}.tools`, problems);
92
- }
101
+ }
102
+ if (name === "data") {
103
+ if (value.resources !== undefined) {
104
+ names(value.resources, `${path}.resources`, problems, stage);
93
105
  }
94
- if (name === "db" && value.rules !== undefined) {
95
- const problem = dbRulesProblem(value.rules);
96
- if (problem !== null) {
97
- problems.push({ path: `${path}.rules`, message: problem });
98
- }
106
+ if (value.tools !== undefined) {
107
+ names(value.tools, `${path}.tools`, problems, stage);
108
+ }
109
+ }
110
+ if (name === "db" && value.rules !== undefined) {
111
+ const problem = dbRulesProblem(value.rules, stage);
112
+ if (problem !== null) {
113
+ problems.push({ path: `${path}.rules`, message: problem });
99
114
  }
100
115
  }
101
- return problems;
102
116
  }
103
117
  /** A declaration checked (a host's stored one, given to `mount`); throws a `TypeError` naming its problems. */
104
118
  export function checkDeclaration(given, config) {
@@ -109,7 +123,7 @@ export function checkDeclaration(given, config) {
109
123
  if (!isRuntimeVersion(runtime)) {
110
124
  throw new TypeError(`A declaration's runtime ${JSON.stringify(runtime)} is not one this Porthole serves`);
111
125
  }
112
- const problems = declarationProblems(given.capabilities, config, runtime);
126
+ const problems = stagedProblems(given.capabilities, config, runtime, "shown");
113
127
  if (problems.length > 0) {
114
128
  throw new TypeError(`The declaration doesn't fit this config: ${problems.map((each) => `${each.path} ${each.message}`).join("; ")}`);
115
129
  }
@@ -149,15 +163,16 @@ export function declareCapabilities(options) {
149
163
  }
150
164
  const runtime = options.runtime ?? stored?.runtime ?? RUNTIME_VERSION;
151
165
  if (given === undefined) {
152
- const declaration = stored ?? { capabilities: {}, runtime };
153
- const pinned = { capabilities: declaration.capabilities, runtime };
154
- // A stored declaration still fits the host's offer (a host may have narrowed its config).
155
- const problems = declarationProblems(pinned.capabilities, config, runtime);
166
+ const capabilities = stored?.capabilities ?? {};
167
+ // A stored declaration still fits the host's offer (a host may have narrowed its config); as
168
+ // stored, a page's from before P093 too (rule names in more than one case).
169
+ const problems = stagedProblems(capabilities, config, runtime, "shown");
156
170
  return problems.length > 0
157
171
  ? { ok: false, problems }
158
172
  : {
159
173
  ok: true,
160
- declaration: pinned,
174
+ // Its own copy, as at a publish that gives one (P093, after its review).
175
+ declaration: { capabilities: copied(capabilities), runtime },
161
176
  changed: stored === undefined || stored === null || stored.runtime !== runtime,
162
177
  };
163
178
  }
@@ -165,7 +180,8 @@ export function declareCapabilities(options) {
165
180
  if (problems.length > 0) {
166
181
  return { ok: false, problems };
167
182
  }
168
- const declaration = { capabilities: given, runtime };
183
+ // Its own copy, without prototypes (P093): what was checked, not the caller's object.
184
+ const declaration = { capabilities: copied(given), runtime };
169
185
  return {
170
186
  ok: true,
171
187
  declaration,
@@ -187,22 +203,31 @@ export function declaredMatch(list, name) {
187
203
  ? name.startsWith(each.slice(0, -1)) && !ESCAPES_PREFIX.test(name)
188
204
  : each === name));
189
205
  }
190
- /** The stricter of two declared level maps. */
206
+ /**
207
+ * An object without a prototype (P093): a name the page wrote (`__proto__`, a collection's) is an
208
+ * own key of it when set, never a prototype's setter or a prototype's name when read.
209
+ */
210
+ const bare = () => Object.create(null);
211
+ /** The stricter of two declared level maps (absent: the contract's, everywhere). */
191
212
  function stricterLevels(a, b) {
192
- if (a === undefined || b === undefined) {
193
- return a ?? b;
213
+ if (a === undefined && b === undefined) {
214
+ return undefined;
194
215
  }
195
- const out = { ...a };
196
- for (const [method, level] of Object.entries(b)) {
197
- const other = Object.hasOwn(out, method) ? out[method] : undefined;
198
- out[method] = other === undefined ? level : higher(other, level);
216
+ const out = bare();
217
+ for (const method of new Set([...Object.keys(a ?? {}), ...Object.keys(b ?? {})])) {
218
+ const x = a !== undefined && Object.hasOwn(a, method) ? a[method] : undefined;
219
+ const y = b !== undefined && Object.hasOwn(b, method) ? b[method] : undefined;
220
+ const level = x === undefined ? y : y === undefined ? x : higher(x, y);
221
+ if (level !== undefined) {
222
+ out[method] = level;
223
+ }
199
224
  }
200
225
  return out;
201
226
  }
202
227
  /** The names both lists admit (absent: everything). */
203
228
  function bothNames(a, b) {
204
229
  if (a === undefined || b === undefined) {
205
- return a ?? b;
230
+ return a === undefined ? b?.slice() : a.slice();
206
231
  }
207
232
  return [
208
233
  ...new Set([
@@ -211,56 +236,128 @@ function bothNames(a, b) {
211
236
  ]),
212
237
  ];
213
238
  }
214
- /** The stricter of two pages' rules, by collection. */
239
+ /**
240
+ * The stricter of two pages' rules, by collection (P093, the 2026-10-19 audit's S02): each name
241
+ * either side's rules give, in any case, and `*`, is under the stricter of the rule EACH side
242
+ * puts it under, as `dbAccess` reads that side (`dbRuleOf`). A collection neither names is under
243
+ * both sides' `*`, the output's `*`. So the output allows a level at most what both allow it (an
244
+ * old version's `public` doesn't outlive the current `*`, nor the other way), and exactly that
245
+ * where both spell each collection alike; where they spell one differently it may be stricter
246
+ * (after the re-review). One name for each name in any case (as the first side spells it); none
247
+ * for a name whose rule is the output's `*`'s (after the review: it says nothing `*` doesn't).
248
+ */
215
249
  function stricterRules(a, b) {
216
- if (a === undefined || b === undefined) {
217
- return a ?? b;
250
+ if (a === undefined && b === undefined) {
251
+ return undefined;
218
252
  }
219
- const out = {};
220
- for (const key of new Set([...Object.keys(a), ...Object.keys(b)])) {
221
- const x = Object.hasOwn(a, key) ? a[key] : undefined;
222
- const y = Object.hasOwn(b, key) ? b[key] : undefined;
223
- const read = x?.read === undefined ? y?.read : y?.read === undefined ? x.read : higher(x.read, y.read);
224
- const write = x?.write === undefined
225
- ? y?.write
226
- : y?.write === undefined
227
- ? x.write
228
- : higher(x.write, y.write);
229
- out[key] = {
230
- ...(read === undefined ? {} : { read }),
231
- ...(write === undefined ? {} : { write }),
232
- };
253
+ const wildcard = stricterDbRule(dbRuleOf(a, "*"), dbRuleOf(b, "*"));
254
+ const same = (rule) => dbRuleLevel(rule, false) === dbRuleLevel(wildcard, false) &&
255
+ dbRuleLevel(rule, true) === dbRuleLevel(wildcard, true);
256
+ const out = bare();
257
+ const seen = new Set();
258
+ for (const name of [...Object.keys(a ?? {}), ...Object.keys(b ?? {})]) {
259
+ const folded = foldCollection(name);
260
+ if (name === "*" || seen.has(folded)) {
261
+ continue;
262
+ }
263
+ seen.add(folded);
264
+ const rule = stricterDbRule(dbRuleOf(a, name), dbRuleOf(b, name));
265
+ if (!same(rule)) {
266
+ out[name] = rule;
267
+ }
268
+ }
269
+ if ((a !== undefined && Object.hasOwn(a, "*")) || (b !== undefined && Object.hasOwn(b, "*"))) {
270
+ out["*"] = wildcard;
233
271
  }
234
272
  return out;
235
273
  }
274
+ /**
275
+ * The problems with a declaration's shape where it is shown (no host's offer: the mount checks
276
+ * that), each path under `which`: what would be read as allowing anything could loosen the other
277
+ * side (`higher` with a level that isn't one returns the other).
278
+ */
279
+ function shapeProblems(declaration, which) {
280
+ const problems = [];
281
+ if (!isRecord(declaration) || !isRecord(declaration.capabilities)) {
282
+ return [{ path: `${which}.capabilities`, message: "must be an object: { name: config }" }];
283
+ }
284
+ if (!isRuntimeVersion(declaration.runtime)) {
285
+ problems.push({
286
+ path: `${which}.runtime`,
287
+ message: "is not a runtime version Porthole serves",
288
+ });
289
+ }
290
+ for (const [name, value] of Object.entries(declaration.capabilities)) {
291
+ const path = `${which}.capabilities.${name}`;
292
+ if (!isRuntimeCapabilityName(name)) {
293
+ problems.push({ path, message: "is not a capability" });
294
+ }
295
+ else if (runtimeCapability(name).builtIn) {
296
+ problems.push({ path, message: "is built in: use it without declaring it" });
297
+ }
298
+ else {
299
+ configProblems(name, value, path, problems, "shown");
300
+ }
301
+ }
302
+ return problems;
303
+ }
236
304
  /**
237
305
  * What a version may do when it is shown (after the review): what it declared when it was
238
306
  * published AND what the artifact declares now. A host stores each version's declaration with
239
307
  * it (`declareCapabilities` at its publish) and mounts a version with this, so an old version
240
308
  * never keeps what the artifact has since revoked, nor gains what it declared later. Each
241
309
  * capability only where both declare it, at the stricter levels, the narrower `data` names and
242
- * the stricter `db` rules; the version's own pinned runtime.
310
+ * the stricter `db` rules (each side read as `dbAccess` reads it, P093); the version's own pinned
311
+ * runtime. Whatever the result allows, each side allows alone; a mount takes it (two pages at
312
+ * the publish limits make one within a mount's). Objects without a prototype.
313
+ *
314
+ * Answers its problems (P093, after its review) where either side isn't a declaration's shape
315
+ * (or the two make one past a mount's limits): show the version as an error, never with `null`
316
+ * (that is 0.6's surface) or with either side alone.
243
317
  */
244
- export function intersectDeclarations(version, current) {
245
- const capabilities = {};
318
+ export function tryIntersectDeclarations(version, current) {
319
+ const problems = [...shapeProblems(version, "version"), ...shapeProblems(current, "current")];
320
+ if (problems.length > 0) {
321
+ return { ok: false, problems };
322
+ }
246
323
  const a = version.capabilities;
247
324
  const b = current.capabilities;
325
+ const capabilities = bare();
248
326
  for (const name of Object.keys(a)) {
249
327
  if (!Object.hasOwn(b, name)) {
250
328
  continue;
251
329
  }
252
330
  const x = a[name] ?? {};
253
331
  const y = b[name] ?? {};
332
+ const out = Object.create(null);
254
333
  const levels = stricterLevels(x.levels, y.levels);
255
334
  const resources = bothNames(x.resources, y.resources);
256
335
  const tools = bothNames(x.tools, y.tools);
257
336
  const rules = stricterRules(x.rules, y.rules);
258
- capabilities[name] = {
259
- ...(levels === undefined ? {} : { levels }),
260
- ...(resources === undefined ? {} : { resources }),
261
- ...(tools === undefined ? {} : { tools }),
262
- ...(rules === undefined ? {} : { rules }),
263
- };
337
+ if (levels !== undefined) {
338
+ out.levels = levels;
339
+ }
340
+ if (resources !== undefined) {
341
+ out.resources = resources;
342
+ }
343
+ if (tools !== undefined) {
344
+ out.tools = tools;
345
+ }
346
+ if (rules !== undefined) {
347
+ out.rules = rules;
348
+ }
349
+ capabilities[name] = out;
350
+ }
351
+ const declaration = { capabilities, runtime: version.runtime };
352
+ // Within a mount's limits: sides that were themselves intersections could make one past them.
353
+ const past = shapeProblems(declaration, "intersection");
354
+ return past.length > 0 ? { ok: false, problems: past } : { ok: true, declaration };
355
+ }
356
+ /** `tryIntersectDeclarations`, a `TypeError` naming the problems where it answers some. */
357
+ export function intersectDeclarations(version, current) {
358
+ const result = tryIntersectDeclarations(version, current);
359
+ if (!result.ok) {
360
+ throw new TypeError(`The declarations don't intersect: ${result.problems.map((each) => `${each.path} ${each.message}`).join("; ")}`);
264
361
  }
265
- return { capabilities, runtime: version.runtime };
362
+ return result.declaration;
266
363
  }
@@ -1,8 +1,15 @@
1
1
  import { fileLimits, filePathProblem } from "../files/paths.js";
2
2
  import { fileTypeOf } from "../files/types.js";
3
3
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
4
- /** A short text of the content's: a string of `1..max` characters, no control characters. */
5
- const shortText = (value, max) => typeof value === "string" && value.trim() !== "" && value.length <= max && !/\p{Cc}/u.test(value);
4
+ /**
5
+ * A short text of the content's: a string of `1..max` characters, no control characters, and
6
+ * well-formed Unicode (P095: a lone surrogate makes `encodeURIComponent` throw, and is no text).
7
+ */
8
+ const shortText = (value, max) => typeof value === "string" &&
9
+ value.trim() !== "" &&
10
+ value.length <= max &&
11
+ value.isWellFormed() &&
12
+ !/\p{Cc}/u.test(value);
6
13
  const BASE64 = /^[A-Za-z0-9+/]*={0,2}$/u;
7
14
  /** The bytes a base64 text decodes to, or null if it isn't base64. */
8
15
  export function base64Bytes(value) {
@@ -43,20 +50,24 @@ export function parseArtifactRequest(args, limits) {
43
50
  return null;
44
51
  }
45
52
  const { maxFiles, maxFileBytes, maxVersionBytes } = fileLimits(limits);
46
- const entries = Object.entries(args.files);
47
- if (entries.length === 0) {
53
+ // Its count before any file is read, and each file's size before it is encoded, against the
54
+ // version's total so far (P095: one file object shared under every path is one object to send).
55
+ const given = args.files;
56
+ const paths = Object.keys(given);
57
+ if (paths.length === 0) {
48
58
  return null;
49
59
  }
50
- if (entries.length > Math.min(MAX_PUBLISH_FILES, maxFiles)) {
60
+ if (paths.length > Math.min(MAX_PUBLISH_FILES, maxFiles)) {
51
61
  return "too_large";
52
62
  }
53
63
  // No prototype: a path named `__proto__` is a path (after the review).
54
64
  const files = Object.create(null);
55
65
  let total = 0;
56
- for (const [path, file] of entries) {
66
+ for (const path of paths) {
57
67
  if (filePathProblem(path) !== null) {
58
68
  return null;
59
69
  }
70
+ const file = given[path];
60
71
  if (file === null) {
61
72
  files[path] = null;
62
73
  continue;
@@ -66,10 +77,17 @@ export function parseArtifactRequest(args, limits) {
66
77
  }
67
78
  let size = null;
68
79
  if (typeof file.text === "string" && file.base64 === undefined) {
80
+ // A character is a byte or more in UTF-8: past a limit by its length, it isn't encoded.
81
+ if (file.text.length > maxFileBytes || total + file.text.length > maxVersionBytes) {
82
+ return "too_large";
83
+ }
69
84
  size = encoder.encode(file.text).length;
70
85
  files[path] = { text: file.text };
71
86
  }
72
87
  else if (file.text === undefined) {
88
+ if (typeof file.base64 === "string" && (file.base64.length / 4) * 3 - 2 > maxFileBytes) {
89
+ return "too_large";
90
+ }
73
91
  size = base64Bytes(file.base64);
74
92
  if (size !== null) {
75
93
  files[path] = { base64: file.base64 };
@@ -78,13 +96,10 @@ export function parseArtifactRequest(args, limits) {
78
96
  if (size === null) {
79
97
  return null;
80
98
  }
81
- if (size > maxFileBytes) {
99
+ total += size;
100
+ if (size > maxFileBytes || total > maxVersionBytes) {
82
101
  return "too_large";
83
102
  }
84
- total += size;
85
- }
86
- if (total > maxVersionBytes) {
87
- return "too_large";
88
103
  }
89
104
  if ((args.entry !== undefined && filePathProblem(args.entry) !== null) ||
90
105
  (args.label !== undefined && !shortText(args.label, 60)) ||
@@ -116,6 +131,7 @@ export function assetNameProblem(name) {
116
131
  if (typeof name !== "string" ||
117
132
  name.trim() === "" ||
118
133
  name.length > 255 ||
134
+ !name.isWellFormed() ||
119
135
  /[/\\\p{Cc}\p{Cf}]/u.test(name)) {
120
136
  return "an asset's name is a file name: 1 to 255 characters, no / or \\";
121
137
  }
@@ -8,7 +8,7 @@ export const RUNTIME_TYPES = {
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",
@@ -33,6 +33,11 @@ export interface FileServing {
33
33
  readonly ticket?: {
34
34
  readonly expires: number;
35
35
  };
36
+ /** The artifact version the set is, which its pages name in their notices to the host (P098). */
37
+ readonly artifact?: {
38
+ readonly id: string;
39
+ readonly version: string;
40
+ };
36
41
  }
37
42
  /** Whether the request is a page loading (a navigation), not a subresource. */
38
43
  export declare function isNavigation(request: Request): boolean;
@@ -1,4 +1,4 @@
1
- import { assetCspDirectives, fileSetCspDirectives, INERT_FILE_CSP, serializeCsp, } from "../compile/policy.js";
1
+ import { assetCspDirectives, fileSetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, serializeCsp, } from "../compile/policy.js";
2
2
  import { DEFAULT_ENTRY, lookupFile, requestFilePath } from "../files/paths.js";
3
3
  import { fileTypeOf } from "../files/types.js";
4
4
  import { isCodeAsset } from "../runtime/requests.js";
@@ -163,16 +163,26 @@ export async function serveFile(serving) {
163
163
  ? "same-origin"
164
164
  : "no-referrer";
165
165
  // Its version's files (P082), and its artifact's assets where the config serves them (P089).
166
- const frameCsp = serializeCsp(assetCspDirectives(serving.compiled.config, fileSetCspDirectives(serving.compiled.cspDirectives, serving.source), serving.origin));
166
+ const directives = assetCspDirectives(serving.compiled.config, fileSetCspDirectives(serving.compiled.cspDirectives, serving.source), serving.origin);
167
+ // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
168
+ // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
169
+ // its own.
170
+ const csp = role === "file"
171
+ ? INERT_FILE_CSP
172
+ : role === "page"
173
+ ? servedDocumentCsp(serving.compiled.config, directives)
174
+ : serializeCsp(directives);
167
175
  const headers = new Headers({
168
176
  "content-type": type,
169
177
  "x-content-type-options": "nosniff",
170
178
  "referrer-policy": referrer,
171
179
  "x-robots-tag": "noindex, nofollow",
172
- // A page and a script (a worker's policy is its script's) get the page's CSP; anything else
173
- // runs nothing when opened on its own.
174
- "content-security-policy": `${role === "file" ? INERT_FILE_CSP : frameCsp}; frame-ancestors ${serving.frameAncestors}`,
180
+ "content-security-policy": `${csp}; frame-ancestors ${serving.frameAncestors}`,
175
181
  });
182
+ const permissions = role === "page" ? servedPermissionsPolicy(serving.compiled.config) : null;
183
+ if (permissions !== null) {
184
+ headers.set("permissions-policy", permissions);
185
+ }
176
186
  if (role === "page") {
177
187
  // Every page of the set in the shell (P081): its hardening, its host functions, its theme.
178
188
  const html = serving.compiled.shellDocument({
@@ -189,6 +199,7 @@ export async function serveFile(serving) {
189
199
  address: `${base}${found.path.includes("/") ? encodePath(found.path) : ""}`,
190
200
  expires: serving.ticket.expires,
191
201
  }),
202
+ ...(serving.artifact === undefined ? {} : { set: serving.artifact }),
192
203
  },
193
204
  });
194
205
  if (serving.ticket !== undefined) {
@@ -280,7 +291,8 @@ export async function serveAsset(serving) {
280
291
  const typed = fileTypeOf(asset.name);
281
292
  // Never a page: an asset is the library's, outside the shell (P089); code only where it was
282
293
  // trusted when it was uploaded (after the review).
283
- const type = typed.role === "page" || (isCodeAsset(asset.name) && !serving.code)
294
+ const asCode = typed.role !== "page" && isCodeAsset(asset.name) && serving.code;
295
+ const type = typed.role === "page" || (isCodeAsset(asset.name) && !asCode)
284
296
  ? "application/octet-stream"
285
297
  : typed.type;
286
298
  const headers = new Headers({
@@ -298,7 +310,10 @@ export async function serveAsset(serving) {
298
310
  if (type === "application/octet-stream") {
299
311
  headers.set("content-disposition", "attachment");
300
312
  }
301
- const etag = HEX.test(asset.sha256) ? `"${asset.sha256}"` : null;
313
+ // The ETag carries the decision too (P103): once a stricter config ships, a copy the browser
314
+ // kept as code is a different one, so its revalidation gets the download whole, never a 304
315
+ // that would leave it typed as code.
316
+ const etag = HEX.test(asset.sha256) ? `"${asset.sha256}-${asCode ? "code" : "inert"}"` : null;
302
317
  if (etag !== null) {
303
318
  headers.set("etag", etag);
304
319
  if (notModified(request, etag)) {
@@ -128,10 +128,22 @@ export interface ContentHostOptions<V> {
128
128
  * served throw at startup.
129
129
  */
130
130
  readonly health?: HealthOptions;
131
- /** Issues per viewer (or address) per minute, in this process. */
131
+ /**
132
+ * Issues per viewer (or, with no viewer, per address) per minute, in this process. The address
133
+ * is one the host trusts, never one a client says (P092): the socket's peer (the Node adapter
134
+ * leaves it on the request), or on Workers `CF-Connecting-IP`. Behind proxies, say how many
135
+ * append to `X-Forwarded-For` (`trustedProxies`), or key it yourself (`key`); otherwise every
136
+ * request through a proxy is that proxy's address.
137
+ */
132
138
  readonly rateLimit?: {
133
139
  readonly perMinute: number;
134
140
  readonly key?: (request: Request, viewer: V | null) => string;
141
+ /**
142
+ * How many proxies in front of the app each append the address they saw to
143
+ * `X-Forwarded-For` (default 0: it is never read). The address is the entry the outermost
144
+ * appended; the entries before it are the client's to write.
145
+ */
146
+ readonly trustedProxies?: number;
135
147
  };
136
148
  /** The kit's events: a function, or a logger (`{ info, warn, error }`). */
137
149
  readonly log?: ((event: ContentHostEvent) => void) | ContentLogger;
@@ -303,4 +315,9 @@ export interface ContentHost<V> {
303
315
  /** Stops the health gate. */
304
316
  close(): void;
305
317
  }
318
+ /**
319
+ * The most an issue request's body may be (S06, P092). `{ instance }` is a few hundred bytes; an
320
+ * MCP view's declared egress, the largest proposal, a few KiB.
321
+ */
322
+ export declare const ISSUE_BODY_BYTES = 65536;
306
323
  export declare function createContentHost<V>(options: ContentHostOptions<V>): ContentHost<V>;