@botiverse/porthole 0.6.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 (208) hide show
  1. package/README.md +25 -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 +38 -5
  6. package/dist/bridge/bridge.js +469 -39
  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.d.ts +5 -1
  12. package/dist/bridge/refusal.js +17 -0
  13. package/dist/bridge/types.d.ts +73 -5
  14. package/dist/check/check.d.ts +7 -0
  15. package/dist/check/check.js +1 -0
  16. package/dist/check/instrument.d.ts +3 -0
  17. package/dist/check/lint.js +4 -2
  18. package/dist/check/page-source.js +1 -1
  19. package/dist/check/page.js +16 -0
  20. package/dist/check/tools.js +2 -3
  21. package/dist/compile/compile.d.ts +6 -0
  22. package/dist/compile/compile.js +3 -1
  23. package/dist/compile/policy.d.ts +55 -0
  24. package/dist/compile/policy.js +157 -0
  25. package/dist/config/capabilities.d.ts +85 -7
  26. package/dist/config/capabilities.js +32 -2
  27. package/dist/config/schema.d.ts +35 -0
  28. package/dist/config/validate.d.ts +9 -3
  29. package/dist/config/validate.js +92 -8
  30. package/dist/config/warnings.d.ts +20 -0
  31. package/dist/config/warnings.js +25 -0
  32. package/dist/conformance/behavior.js +46 -1
  33. package/dist/conformance/cookies.d.ts +15 -0
  34. package/dist/conformance/cookies.js +80 -0
  35. package/dist/conformance/harness/page.d.ts +1 -0
  36. package/dist/conformance/harness/page.js +9 -2
  37. package/dist/conformance/harness-source.js +1 -1
  38. package/dist/conformance/host-kit.js +5 -1
  39. package/dist/conformance/index.d.ts +11 -0
  40. package/dist/conformance/index.js +2 -0
  41. package/dist/conformance/limits.js +38 -1
  42. package/dist/conformance/runtime.d.ts +58 -0
  43. package/dist/conformance/runtime.js +324 -0
  44. package/dist/conformance/served.d.ts +2 -0
  45. package/dist/conformance/served.js +737 -4
  46. package/dist/files/paths.js +4 -0
  47. package/dist/guide/gates.d.ts +9 -0
  48. package/dist/guide/gates.js +31 -0
  49. package/dist/guide/guide.d.ts +2 -0
  50. package/dist/guide/guide.js +35 -33
  51. package/dist/guide/limits.js +4 -4
  52. package/dist/guide/runtime.d.ts +13 -0
  53. package/dist/guide/runtime.js +210 -0
  54. package/dist/host/create-host.js +73 -37
  55. package/dist/host/locate.js +8 -0
  56. package/dist/host/locator.js +7 -0
  57. package/dist/host/pages-of-set.d.ts +43 -0
  58. package/dist/host/pages-of-set.js +196 -0
  59. package/dist/host/types.d.ts +26 -1
  60. package/dist/index.d.ts +11 -4
  61. package/dist/index.js +11 -2
  62. package/dist/isolation/types.d.ts +8 -0
  63. package/dist/mcp/adapter.js +11 -15
  64. package/dist/node/index.d.ts +36 -4
  65. package/dist/node/index.js +402 -101
  66. package/dist/presets/presets.d.ts +22 -8
  67. package/dist/presets/presets.js +40 -8
  68. package/dist/protocol/live-data.d.ts +6 -2
  69. package/dist/protocol/live-data.js +20 -1
  70. package/dist/protocol/mcp-apps.d.ts +13 -2
  71. package/dist/protocol/mcp-apps.js +10 -2
  72. package/dist/protocol/message-text.d.ts +8 -0
  73. package/dist/protocol/message-text.js +29 -0
  74. package/dist/protocol/runtime-calls.d.ts +28 -0
  75. package/dist/protocol/runtime-calls.js +116 -0
  76. package/dist/protocol/shell-adapter.js +64 -25
  77. package/dist/react/context-notice.d.ts +32 -0
  78. package/dist/react/context-notice.js +28 -0
  79. package/dist/react/dialog.js +91 -16
  80. package/dist/react/frame.d.ts +25 -1
  81. package/dist/react/frame.js +85 -2
  82. package/dist/react/index.d.ts +2 -1
  83. package/dist/react/index.js +2 -1
  84. package/dist/runtime/contract.d.ts +201 -0
  85. package/dist/runtime/contract.js +245 -0
  86. package/dist/runtime/db.d.ts +188 -0
  87. package/dist/runtime/db.js +502 -0
  88. package/dist/runtime/declaration.d.ts +100 -0
  89. package/dist/runtime/declaration.js +363 -0
  90. package/dist/runtime/levels.d.ts +33 -0
  91. package/dist/runtime/levels.js +41 -0
  92. package/dist/runtime/requests.d.ts +125 -0
  93. package/dist/runtime/requests.js +215 -0
  94. package/dist/runtime/segments.d.ts +8 -0
  95. package/dist/runtime/segments.js +14 -0
  96. package/dist/runtime/types.generated.d.ts +1 -0
  97. package/dist/runtime/types.generated.js +19 -0
  98. package/dist/server/files.d.ts +19 -1
  99. package/dist/server/files.js +115 -6
  100. package/dist/server/host.d.ts +24 -2
  101. package/dist/server/host.js +137 -2
  102. package/dist/server/index.d.ts +3 -2
  103. package/dist/server/index.js +2 -1
  104. package/dist/server/peer.d.ts +4 -0
  105. package/dist/server/peer.js +19 -0
  106. package/dist/server/proxy.d.ts +6 -0
  107. package/dist/server/proxy.js +12 -3
  108. package/dist/server/pseudonym.d.ts +9 -0
  109. package/dist/server/pseudonym.js +20 -0
  110. package/dist/server/server.d.ts +0 -5
  111. package/dist/server/server.js +318 -52
  112. package/dist/server/types.d.ts +74 -2
  113. package/dist/shell/document.d.ts +16 -0
  114. package/dist/shell/document.js +19 -2
  115. package/dist/shell/legacy.d.ts +21 -0
  116. package/dist/shell/legacy.js +63 -0
  117. package/dist/shell/plan.d.ts +17 -1
  118. package/dist/shell/plan.js +13 -2
  119. package/dist/shell/runtime.js +390 -56
  120. package/dist/shell/use.d.ts +15 -0
  121. package/dist/shell/use.js +235 -0
  122. package/docs/ADOPTING.md +205 -15
  123. package/docs/ARCHITECTURE.md +34 -5
  124. package/docs/DECISIONS.md +1867 -11
  125. package/docs/DESIGN.md +137 -17
  126. package/docs/THREAT_MODEL.md +616 -0
  127. package/package.json +16 -3
  128. package/src/bridge/bounded-text.ts +240 -0
  129. package/src/bridge/bridge.ts +601 -51
  130. package/src/bridge/json-data.ts +95 -0
  131. package/src/bridge/navigation.ts +10 -0
  132. package/src/bridge/refusal.ts +17 -0
  133. package/src/bridge/types.ts +76 -5
  134. package/src/check/check.ts +8 -0
  135. package/src/check/instrument.ts +3 -0
  136. package/src/check/lint.ts +4 -2
  137. package/src/check/page.ts +16 -0
  138. package/src/check/tools.ts +2 -3
  139. package/src/compile/compile.ts +9 -1
  140. package/src/compile/policy.ts +177 -0
  141. package/src/config/capabilities.ts +71 -5
  142. package/src/config/schema.ts +35 -0
  143. package/src/config/validate.ts +141 -8
  144. package/src/config/warnings.ts +42 -0
  145. package/src/conformance/behavior.ts +54 -1
  146. package/src/conformance/cookies.ts +93 -0
  147. package/src/conformance/harness/page.ts +11 -2
  148. package/src/conformance/host-kit.ts +10 -1
  149. package/src/conformance/index.ts +17 -0
  150. package/src/conformance/limits.ts +39 -1
  151. package/src/conformance/runtime.ts +594 -0
  152. package/src/conformance/served.ts +888 -4
  153. package/src/files/paths.ts +4 -0
  154. package/src/guide/gates.ts +37 -0
  155. package/src/guide/guide.ts +61 -55
  156. package/src/guide/limits.ts +4 -4
  157. package/src/guide/runtime.ts +253 -0
  158. package/src/host/create-host.ts +88 -36
  159. package/src/host/locate.ts +10 -0
  160. package/src/host/locator.ts +11 -0
  161. package/src/host/pages-of-set.ts +226 -0
  162. package/src/host/types.ts +33 -1
  163. package/src/index.ts +94 -0
  164. package/src/isolation/types.ts +8 -0
  165. package/src/mcp/adapter.ts +16 -20
  166. package/src/node/index.ts +507 -116
  167. package/src/presets/presets.ts +67 -17
  168. package/src/protocol/live-data.ts +31 -3
  169. package/src/protocol/mcp-apps.ts +11 -2
  170. package/src/protocol/message-text.ts +36 -0
  171. package/src/protocol/runtime-calls.ts +141 -0
  172. package/src/protocol/shell-adapter.ts +79 -26
  173. package/src/react/context-notice.tsx +95 -0
  174. package/src/react/dialog.tsx +108 -15
  175. package/src/react/frame.tsx +120 -0
  176. package/src/react/index.ts +8 -1
  177. package/src/runtime/contract.ts +339 -0
  178. package/src/runtime/db.ts +650 -0
  179. package/src/runtime/declaration.ts +516 -0
  180. package/src/runtime/levels.ts +69 -0
  181. package/src/runtime/requests.ts +355 -0
  182. package/src/runtime/segments.ts +17 -0
  183. package/src/runtime/types.generated.ts +19 -0
  184. package/src/server/files.ts +138 -7
  185. package/src/server/host.ts +170 -3
  186. package/src/server/index.ts +4 -0
  187. package/src/server/peer.ts +21 -0
  188. package/src/server/proxy.ts +13 -3
  189. package/src/server/pseudonym.ts +21 -0
  190. package/src/server/server.ts +370 -57
  191. package/src/server/types.ts +73 -2
  192. package/src/shell/document.ts +29 -4
  193. package/src/shell/legacy.ts +64 -0
  194. package/src/shell/plan.ts +37 -3
  195. package/src/shell/runtime.ts +390 -56
  196. package/src/shell/use.ts +235 -0
  197. package/types/runtime/v1/artifact.d.ts +50 -0
  198. package/types/runtime/v1/assets.d.ts +43 -0
  199. package/types/runtime/v1/chat.d.ts +13 -0
  200. package/types/runtime/v1/clipboard.d.ts +14 -0
  201. package/types/runtime/v1/comments.d.ts +24 -0
  202. package/types/runtime/v1/context.d.ts +27 -0
  203. package/types/runtime/v1/data.d.ts +29 -0
  204. package/types/runtime/v1/db.d.ts +110 -0
  205. package/types/runtime/v1/downloads.d.ts +22 -0
  206. package/types/runtime/v1/links.d.ts +13 -0
  207. package/types/runtime/v1/porthole.d.ts +44 -0
  208. package/types/runtime/v1/user.d.ts +19 -0
@@ -0,0 +1,516 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ import {
3
+ RUNTIME_CAPABILITY_NAMES,
4
+ RUNTIME_VERSION,
5
+ isRuntimeCapabilityName,
6
+ isRuntimeVersion,
7
+ offeredCapabilities,
8
+ runtimeCapability,
9
+ type RuntimeCapabilityName,
10
+ type RuntimeVersion,
11
+ } from "./contract.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";
22
+ import { higher, isViewerLevel, type ViewerLevel } from "./levels.ts";
23
+
24
+ /**
25
+ * A page's declaration (P086): the capabilities it uses, by name, each with its own config,
26
+ * stored with the artifact when it is published and handed to `mount` when it is shown; and the
27
+ * runtime contract it was written against, pinned. Built-ins are never declared.
28
+ *
29
+ * At publish (`declareCapabilities`): omitted carries the stored declaration forward (and its
30
+ * pin); `{}` clears it; a non-empty object replaces it whole. A page can't change its own: a
31
+ * publish from the page (`artifact.publish`) carries none.
32
+ */
33
+
34
+ /** Every capability's config may raise its methods' levels (never lower them). */
35
+ export interface DeclaredCapability {
36
+ readonly levels?: Readonly<Record<string, ViewerLevel>>;
37
+ }
38
+
39
+ /** `data`: which of the host's resources and tools the page uses (absent: all it serves). */
40
+ export interface DeclaredData extends DeclaredCapability {
41
+ /** URIs, exact, or a prefix ending in `*` (`app://tasks/*`). */
42
+ readonly resources?: readonly string[];
43
+ readonly tools?: readonly string[];
44
+ }
45
+
46
+ /** `db`: the page's rules for its data, by top-level collection (`DbRules`). */
47
+ export interface DeclaredDb extends DeclaredCapability {
48
+ readonly rules?: DbRules;
49
+ }
50
+
51
+ /** What a page declares, by runtime capability name. */
52
+ export interface CapabilityDeclaration {
53
+ readonly user?: DeclaredCapability;
54
+ readonly chat?: DeclaredCapability;
55
+ readonly data?: DeclaredData;
56
+ readonly context?: DeclaredCapability;
57
+ readonly artifact?: DeclaredCapability;
58
+ readonly assets?: DeclaredCapability;
59
+ readonly db?: DeclaredDb;
60
+ }
61
+
62
+ /** A declaration as an artifact stores it and a mount is given it. */
63
+ export interface PageDeclaration {
64
+ readonly capabilities: CapabilityDeclaration;
65
+ readonly runtime: RuntimeVersion;
66
+ }
67
+
68
+ export interface DeclarationProblem {
69
+ /** Where, as `capabilities.db.rules.votes`. */
70
+ readonly path: string;
71
+ readonly message: string;
72
+ }
73
+
74
+ const isRecord = (value: unknown): value is Record<string, unknown> =>
75
+ value !== null && typeof value === "object" && !Array.isArray(value);
76
+
77
+ const KEYS: Readonly<Record<string, readonly string[]>> = {
78
+ data: ["levels", "resources", "tools"],
79
+ db: ["levels", "rules"],
80
+ };
81
+
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;
92
+ if (
93
+ !Array.isArray(values) ||
94
+ values.length > most ||
95
+ values.some(
96
+ (each) =>
97
+ typeof each !== "string" ||
98
+ each === "" ||
99
+ each.length > 512 ||
100
+ /\p{Cc}/u.test(each) ||
101
+ // A `*` only at the end: a prefix.
102
+ (each.includes("*") && each.indexOf("*") !== each.length - 1),
103
+ )
104
+ ) {
105
+ problems.push({
106
+ path,
107
+ message: `must be a list of names (at most ${most}), each exact or a prefix ending in *`,
108
+ });
109
+ }
110
+ };
111
+
112
+ /**
113
+ * The problems with a declaration, against the host's offer (`config`): each name one the
114
+ * runtime knows, the config offers and isn't built in; each config of its own shape. Empty: fine.
115
+ */
116
+ export function declarationProblems(
117
+ given: unknown,
118
+ config: PortholeConfig,
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,
133
+ ): DeclarationProblem[] {
134
+ const problems: DeclarationProblem[] = [];
135
+ if (!isRuntimeVersion(runtime)) {
136
+ return [{ path: "runtime", message: `is not a runtime version Porthole serves` }];
137
+ }
138
+ if (!isRecord(given)) {
139
+ return [{ path: "capabilities", message: "must be an object: { name: config }" }];
140
+ }
141
+ const offered = offeredCapabilities(config);
142
+ for (const [name, value] of Object.entries(given)) {
143
+ const path = `capabilities.${name}`;
144
+ if (!isRuntimeCapabilityName(name)) {
145
+ problems.push({
146
+ path,
147
+ message: `is not a capability (${RUNTIME_CAPABILITY_NAMES.filter((each) => !runtimeCapability(each).builtIn).join(", ")})`,
148
+ });
149
+ continue;
150
+ }
151
+ if (runtimeCapability(name).builtIn) {
152
+ problems.push({ path, message: "is built in: use it without declaring it" });
153
+ continue;
154
+ }
155
+ if (!offered.includes(name)) {
156
+ problems.push({ path, message: "isn't offered here" });
157
+ continue;
158
+ }
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` });
181
+ }
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
+ });
198
+ }
199
+ }
200
+ }
201
+ }
202
+ if (name === "data") {
203
+ if (value.resources !== undefined) {
204
+ names(value.resources, `${path}.resources`, problems, stage);
205
+ }
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 });
214
+ }
215
+ }
216
+ }
217
+
218
+ /** A declaration checked (a host's stored one, given to `mount`); throws a `TypeError` naming its problems. */
219
+ export function checkDeclaration(given: unknown, config: PortholeConfig): PageDeclaration {
220
+ if (!isRecord(given)) {
221
+ throw new TypeError("A declaration is { capabilities, runtime }");
222
+ }
223
+ const runtime = given.runtime;
224
+ if (!isRuntimeVersion(runtime)) {
225
+ throw new TypeError(
226
+ `A declaration's runtime ${JSON.stringify(runtime)} is not one this Porthole serves`,
227
+ );
228
+ }
229
+ const problems = stagedProblems(given.capabilities, config, runtime, "shown");
230
+ if (problems.length > 0) {
231
+ throw new TypeError(
232
+ `The declaration doesn't fit this config: ${problems.map((each) => `${each.path} ${each.message}`).join("; ")}`,
233
+ );
234
+ }
235
+ return { capabilities: copied(given.capabilities) as CapabilityDeclaration, runtime };
236
+ }
237
+
238
+ /**
239
+ * A declaration's own copy, every object without a prototype (after the review): a rule or a
240
+ * level looked up by a name like `constructor` finds nothing but what the page wrote.
241
+ */
242
+ function copied(value: unknown): unknown {
243
+ if (Array.isArray(value)) {
244
+ return value.map(copied);
245
+ }
246
+ if (value === null || typeof value !== "object") {
247
+ return value;
248
+ }
249
+ const out = Object.create(null) as Record<string, unknown>;
250
+ for (const [key, each] of Object.entries(value)) {
251
+ out[key] = copied(each);
252
+ }
253
+ return out;
254
+ }
255
+
256
+ /**
257
+ * At publish (P086): the declaration a new version leaves the artifact with.
258
+ * - `given` undefined: the stored one, unchanged (its pin too); none stored: an empty one.
259
+ * - `given` `{}`: cleared.
260
+ * - `given` non-empty: it replaces the stored one whole (anything not restated is revoked).
261
+ * The pin moves only when the author asks (`runtime`). Checked against the host's offer.
262
+ */
263
+ export function declareCapabilities(options: {
264
+ readonly stored?: PageDeclaration | null;
265
+ readonly given?: unknown;
266
+ readonly config: PortholeConfig;
267
+ readonly runtime?: unknown;
268
+ }):
269
+ | {
270
+ readonly ok: true;
271
+ readonly declaration: PageDeclaration;
272
+ /** Whether it differs from the stored one. */
273
+ readonly changed: boolean;
274
+ }
275
+ | { readonly ok: false; readonly problems: readonly DeclarationProblem[] } {
276
+ const { stored, given, config } = options;
277
+ if (options.runtime !== undefined && !isRuntimeVersion(options.runtime)) {
278
+ return {
279
+ ok: false,
280
+ problems: [{ path: "runtime", message: "is not a runtime version Porthole serves" }],
281
+ };
282
+ }
283
+ const runtime: RuntimeVersion = options.runtime ?? stored?.runtime ?? RUNTIME_VERSION;
284
+ if (given === undefined) {
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");
289
+ return problems.length > 0
290
+ ? { ok: false, problems }
291
+ : {
292
+ ok: true,
293
+ // Its own copy, as at a publish that gives one (P093, after its review).
294
+ declaration: { capabilities: copied(capabilities) as CapabilityDeclaration, runtime },
295
+ changed: stored === undefined || stored === null || stored.runtime !== runtime,
296
+ };
297
+ }
298
+ const problems = declarationProblems(given, config, runtime);
299
+ if (problems.length > 0) {
300
+ return { ok: false, problems };
301
+ }
302
+ // Its own copy, without prototypes (P093): what was checked, not the caller's object.
303
+ const declaration = { capabilities: copied(given) as CapabilityDeclaration, runtime };
304
+ return {
305
+ ok: true,
306
+ declaration,
307
+ changed:
308
+ stored === undefined ||
309
+ stored === null ||
310
+ stored.runtime !== runtime ||
311
+ JSON.stringify(stored.capabilities) !== JSON.stringify(declaration.capabilities),
312
+ };
313
+ }
314
+
315
+ /**
316
+ * A name a prefix can't vouch for (after the review): a dot segment, or one written with an
317
+ * escape or a backslash, may resolve outside the prefix (`app://tasks/../secrets`).
318
+ */
319
+ const ESCAPES_PREFIX = /(^|[/\\])\.{1,2}([/\\?#]|$)|%2e|%2f|%5c|\\/iu;
320
+
321
+ /** Whether `name` matches a declared list's entry (exact, or a prefix ending in `*`). */
322
+ export function declaredMatch(list: readonly string[] | undefined, name: string): boolean {
323
+ return (
324
+ list === undefined ||
325
+ list.some((each) =>
326
+ each.endsWith("*")
327
+ ? name.startsWith(each.slice(0, -1)) && !ESCAPES_PREFIX.test(name)
328
+ : each === name,
329
+ )
330
+ );
331
+ }
332
+
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). */
340
+ function stricterLevels(
341
+ a: Readonly<Record<string, ViewerLevel>> | undefined,
342
+ b: Readonly<Record<string, ViewerLevel>> | undefined,
343
+ ): Readonly<Record<string, ViewerLevel>> | undefined {
344
+ if (a === undefined && b === undefined) {
345
+ return undefined;
346
+ }
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
+ }
355
+ }
356
+ return out;
357
+ }
358
+
359
+ /** The names both lists admit (absent: everything). */
360
+ function bothNames(
361
+ a: readonly string[] | undefined,
362
+ b: readonly string[] | undefined,
363
+ ): readonly string[] | undefined {
364
+ if (a === undefined || b === undefined) {
365
+ return a === undefined ? b?.slice() : a.slice();
366
+ }
367
+ return [
368
+ ...new Set([
369
+ ...a.filter((each) => declaredMatch(b, each)),
370
+ ...b.filter((each) => declaredMatch(a, each)),
371
+ ]),
372
+ ];
373
+ }
374
+
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
+ */
385
+ function stricterRules(a: DbRules | undefined, b: DbRules | undefined): DbRules | undefined {
386
+ if (a === undefined && b === undefined) {
387
+ return undefined;
388
+ }
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;
408
+ }
409
+ return out;
410
+ }
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
+
441
+ /**
442
+ * What a version may do when it is shown (after the review): what it declared when it was
443
+ * published AND what the artifact declares now. A host stores each version's declaration with
444
+ * it (`declareCapabilities` at its publish) and mounts a version with this, so an old version
445
+ * never keeps what the artifact has since revoked, nor gains what it declared later. Each
446
+ * capability only where both declare it, at the stricter levels, the narrower `data` names and
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.
454
+ */
455
+ export function tryIntersectDeclarations(
456
+ version: PageDeclaration,
457
+ current: PageDeclaration,
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
+ }
465
+ const a = version.capabilities as Readonly<Record<string, DeclaredData & DeclaredDb>>;
466
+ const b = current.capabilities as Readonly<Record<string, DeclaredData & DeclaredDb>>;
467
+ const capabilities = bare<DeclaredCapability & DeclaredData & DeclaredDb>();
468
+ for (const name of Object.keys(a)) {
469
+ if (!Object.hasOwn(b, name)) {
470
+ continue;
471
+ }
472
+ const x = a[name] ?? {};
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
+ };
480
+ const levels = stricterLevels(x.levels, y.levels);
481
+ const resources = bothNames(x.resources, y.resources);
482
+ const tools = bothNames(x.tools, y.tools);
483
+ const rules = stricterRules(x.rules, y.rules);
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
+ );
514
+ }
515
+ return result.declaration;
516
+ }
@@ -0,0 +1,69 @@
1
+ import { isDbSegment } from "./segments.ts";
2
+
3
+ /**
4
+ * Viewer levels (P087): who the person viewing a display is to it, in the host's words, which
5
+ * decides each capability method's audience. Ordered: `view` (see it, comment) < `interact` (use
6
+ * what the page does: write its data, ask the agent) < `admin` (publish its versions, manage its
7
+ * assets) < `owner`. The host says a viewer's level (its access, per request); Porthole carries it
8
+ * and refuses a call whose method needs more, before any handler runs.
9
+ */
10
+
11
+ export const VIEWER_LEVELS = ["view", "interact", "admin", "owner"] as const;
12
+
13
+ export type ViewerLevel = (typeof VIEWER_LEVELS)[number];
14
+
15
+ export function isViewerLevel(value: unknown): value is ViewerLevel {
16
+ return typeof value === "string" && (VIEWER_LEVELS as readonly string[]).includes(value);
17
+ }
18
+
19
+ /** Whether `level` reaches `needed`. */
20
+ export function atLeast(level: ViewerLevel, needed: ViewerLevel): boolean {
21
+ return VIEWER_LEVELS.indexOf(level) >= VIEWER_LEVELS.indexOf(needed);
22
+ }
23
+
24
+ /** The higher of two levels. */
25
+ export function higher(a: ViewerLevel, b: ViewerLevel): ViewerLevel {
26
+ return atLeast(a, b) ? a : b;
27
+ }
28
+
29
+ /**
30
+ * Who is viewing a display, as the host says (its access at issue, `Grant.level`, or a mount's
31
+ * `viewer`): the level decides what the page may do; `id` and `name` are what the `user`
32
+ * capability tells a page that declares it, and `id` is whose per-user data (`data/users/<id>`)
33
+ * the page reaches. All the host's words, never the content's. `id` is the host's public id for
34
+ * the person (not necessarily the `Grant.viewer` it keeps to itself).
35
+ */
36
+ export interface ViewerInfo {
37
+ readonly level: ViewerLevel;
38
+ /**
39
+ * One path segment (`A-Z a-z 0-9 _ . ~ : @ + -`, at most 128, never `me`): the host's public id
40
+ * for the person, or a pseudonym per artifact (`pseudonymFor`, P087), never their account id
41
+ * where pages shouldn't link people across artifacts.
42
+ */
43
+ readonly id?: string;
44
+ readonly name?: string;
45
+ }
46
+
47
+ const MAX_ID = 256;
48
+
49
+ /** A viewer as the host gave it (possibly over the network: an issue's answer), or null. */
50
+ export function parseViewer(value: unknown): ViewerInfo | null {
51
+ if (value === null || typeof value !== "object" || Array.isArray(value)) {
52
+ return null;
53
+ }
54
+ const { level, id, name } = value as Record<string, unknown>;
55
+ if (!isViewerLevel(level)) {
56
+ return null;
57
+ }
58
+ const text = (each: unknown) =>
59
+ typeof each === "string" && each !== "" && each.length <= MAX_ID && !/[\p{Cc}]/u.test(each);
60
+ // An id names the person's own data (`data/users/<id>`): one path segment, never `me`.
61
+ if ((id !== undefined && !isDbSegment(id)) || (name !== undefined && !text(name))) {
62
+ return null;
63
+ }
64
+ return {
65
+ level,
66
+ ...(id === undefined ? {} : { id }),
67
+ ...(name === undefined ? {} : { name: name as string }),
68
+ };
69
+ }