@botiverse/porthole 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (167) hide show
  1. package/README.md +41 -0
  2. package/dist/bridge/bridge.d.ts +13 -0
  3. package/dist/bridge/bridge.js +208 -13
  4. package/dist/bridge/navigation.d.ts +1 -6
  5. package/dist/bridge/navigation.js +11 -0
  6. package/dist/bridge/refusal.d.ts +5 -1
  7. package/dist/bridge/refusal.js +16 -0
  8. package/dist/bridge/types.d.ts +41 -4
  9. package/dist/check/check.d.ts +19 -3
  10. package/dist/check/check.js +55 -8
  11. package/dist/check/files.d.ts +26 -0
  12. package/dist/check/files.js +307 -0
  13. package/dist/check/instrument.d.ts +3 -0
  14. package/dist/check/lint.js +31 -12
  15. package/dist/check/page-source.js +1 -1
  16. package/dist/check/page.js +14 -0
  17. package/dist/check/tools.d.ts +23 -0
  18. package/dist/check/tools.js +27 -3
  19. package/dist/compile/policy.d.ts +34 -0
  20. package/dist/compile/policy.js +74 -0
  21. package/dist/config/capabilities.d.ts +62 -3
  22. package/dist/config/capabilities.js +20 -0
  23. package/dist/config/schema.d.ts +32 -0
  24. package/dist/config/validate.d.ts +1 -1
  25. package/dist/config/validate.js +74 -5
  26. package/dist/conformance/harness-source.js +1 -1
  27. package/dist/conformance/index.d.ts +1 -0
  28. package/dist/conformance/index.js +2 -0
  29. package/dist/conformance/runtime.d.ts +58 -0
  30. package/dist/conformance/runtime.js +314 -0
  31. package/dist/files/paths.d.ts +99 -0
  32. package/dist/files/paths.js +263 -0
  33. package/dist/files/types.d.ts +24 -0
  34. package/dist/files/types.js +83 -0
  35. package/dist/guide/gates.d.ts +3 -0
  36. package/dist/guide/gates.js +19 -0
  37. package/dist/guide/guide.d.ts +2 -0
  38. package/dist/guide/guide.js +44 -32
  39. package/dist/guide/limits.js +4 -4
  40. package/dist/guide/runtime.d.ts +13 -0
  41. package/dist/guide/runtime.js +202 -0
  42. package/dist/host/create-host.js +45 -0
  43. package/dist/host/locate.js +8 -0
  44. package/dist/host/locator.js +7 -0
  45. package/dist/host/types.d.ts +18 -0
  46. package/dist/index.d.ts +13 -4
  47. package/dist/index.js +16 -3
  48. package/dist/isolation/types.d.ts +8 -0
  49. package/dist/presets/presets.d.ts +6 -0
  50. package/dist/presets/presets.js +1 -0
  51. package/dist/protocol/adapter.d.ts +4 -0
  52. package/dist/protocol/mcp-apps.d.ts +6 -0
  53. package/dist/protocol/mcp-apps.js +6 -0
  54. package/dist/protocol/runtime-calls.d.ts +28 -0
  55. package/dist/protocol/runtime-calls.js +113 -0
  56. package/dist/protocol/shell-adapter.js +52 -3
  57. package/dist/react/dialog.js +31 -0
  58. package/dist/react/frame.d.ts +13 -0
  59. package/dist/react/frame.js +6 -0
  60. package/dist/runtime/contract.d.ts +193 -0
  61. package/dist/runtime/contract.js +216 -0
  62. package/dist/runtime/db.d.ts +153 -0
  63. package/dist/runtime/db.js +398 -0
  64. package/dist/runtime/declaration.d.ts +86 -0
  65. package/dist/runtime/declaration.js +266 -0
  66. package/dist/runtime/levels.d.ts +33 -0
  67. package/dist/runtime/levels.js +41 -0
  68. package/dist/runtime/requests.d.ts +125 -0
  69. package/dist/runtime/requests.js +199 -0
  70. package/dist/runtime/segments.d.ts +8 -0
  71. package/dist/runtime/segments.js +14 -0
  72. package/dist/runtime/types.generated.d.ts +1 -0
  73. package/dist/runtime/types.generated.js +19 -0
  74. package/dist/server/files.d.ts +57 -0
  75. package/dist/server/files.js +338 -0
  76. package/dist/server/host.d.ts +44 -2
  77. package/dist/server/host.js +42 -2
  78. package/dist/server/index.d.ts +5 -2
  79. package/dist/server/index.js +5 -1
  80. package/dist/server/keys.d.ts +8 -0
  81. package/dist/server/keys.js +34 -0
  82. package/dist/server/pseudonym.d.ts +9 -0
  83. package/dist/server/pseudonym.js +20 -0
  84. package/dist/server/server.d.ts +0 -5
  85. package/dist/server/server.js +468 -24
  86. package/dist/server/types.d.ts +118 -5
  87. package/dist/shell/document.d.ts +27 -0
  88. package/dist/shell/document.js +46 -2
  89. package/dist/shell/legacy.d.ts +21 -0
  90. package/dist/shell/legacy.js +63 -0
  91. package/dist/shell/plan.d.ts +17 -1
  92. package/dist/shell/plan.js +13 -2
  93. package/dist/shell/runtime.d.ts +2 -1
  94. package/dist/shell/runtime.js +114 -46
  95. package/dist/shell/use.d.ts +15 -0
  96. package/dist/shell/use.js +235 -0
  97. package/docs/ADOPTING.md +142 -5
  98. package/docs/ARCHITECTURE.md +34 -5
  99. package/docs/DECISIONS.md +716 -7
  100. package/docs/DESIGN.md +97 -3
  101. package/package.json +3 -1
  102. package/src/bridge/bridge.ts +281 -17
  103. package/src/bridge/navigation.ts +12 -0
  104. package/src/bridge/refusal.ts +16 -0
  105. package/src/bridge/types.ts +46 -4
  106. package/src/check/check.ts +100 -14
  107. package/src/check/files.ts +384 -0
  108. package/src/check/instrument.ts +3 -0
  109. package/src/check/lint.ts +33 -12
  110. package/src/check/page.ts +14 -0
  111. package/src/check/tools.ts +52 -3
  112. package/src/compile/policy.ts +92 -0
  113. package/src/config/capabilities.ts +49 -2
  114. package/src/config/schema.ts +32 -0
  115. package/src/config/validate.ts +107 -5
  116. package/src/conformance/index.ts +7 -0
  117. package/src/conformance/runtime.ts +573 -0
  118. package/src/files/paths.ts +323 -0
  119. package/src/files/types.ts +101 -0
  120. package/src/guide/gates.ts +25 -0
  121. package/src/guide/guide.ts +78 -52
  122. package/src/guide/limits.ts +4 -4
  123. package/src/guide/runtime.ts +244 -0
  124. package/src/host/create-host.ts +55 -0
  125. package/src/host/locate.ts +10 -0
  126. package/src/host/locator.ts +11 -0
  127. package/src/host/types.ts +18 -0
  128. package/src/index.ts +121 -0
  129. package/src/isolation/types.ts +8 -0
  130. package/src/presets/presets.ts +7 -0
  131. package/src/protocol/adapter.ts +3 -1
  132. package/src/protocol/mcp-apps.ts +7 -0
  133. package/src/protocol/runtime-calls.ts +138 -0
  134. package/src/protocol/shell-adapter.ts +56 -2
  135. package/src/react/dialog.tsx +33 -0
  136. package/src/react/frame.tsx +19 -0
  137. package/src/runtime/contract.ts +305 -0
  138. package/src/runtime/db.ts +530 -0
  139. package/src/runtime/declaration.ts +378 -0
  140. package/src/runtime/levels.ts +69 -0
  141. package/src/runtime/requests.ts +339 -0
  142. package/src/runtime/segments.ts +17 -0
  143. package/src/runtime/types.generated.ts +19 -0
  144. package/src/server/files.ts +425 -0
  145. package/src/server/host.ts +84 -3
  146. package/src/server/index.ts +22 -0
  147. package/src/server/keys.ts +53 -0
  148. package/src/server/pseudonym.ts +21 -0
  149. package/src/server/server.ts +565 -26
  150. package/src/server/types.ts +124 -4
  151. package/src/shell/document.ts +74 -4
  152. package/src/shell/legacy.ts +64 -0
  153. package/src/shell/plan.ts +37 -3
  154. package/src/shell/runtime.ts +114 -46
  155. package/src/shell/use.ts +235 -0
  156. package/types/runtime/v1/artifact.d.ts +50 -0
  157. package/types/runtime/v1/assets.d.ts +43 -0
  158. package/types/runtime/v1/chat.d.ts +13 -0
  159. package/types/runtime/v1/clipboard.d.ts +14 -0
  160. package/types/runtime/v1/comments.d.ts +24 -0
  161. package/types/runtime/v1/context.d.ts +16 -0
  162. package/types/runtime/v1/data.d.ts +29 -0
  163. package/types/runtime/v1/db.d.ts +110 -0
  164. package/types/runtime/v1/downloads.d.ts +22 -0
  165. package/types/runtime/v1/links.d.ts +13 -0
  166. package/types/runtime/v1/porthole.d.ts +44 -0
  167. package/types/runtime/v1/user.d.ts +19 -0
package/src/check/lint.ts CHANGED
@@ -63,22 +63,41 @@ export function fragmentOf(content: string): string | null {
63
63
  return body.trim() === "" ? null : `${kept}${kept === "" ? "" : "\n"}${body.trim()}`;
64
64
  }
65
65
 
66
- /** Where content reaches out, by the kind of egress each would need. */
66
+ /**
67
+ * Where content reaches out, by the kind of egress each would need. Each pattern is bounded and
68
+ * never runs past its own delimiters (a tag's `<`, a string's quote), so a text is read in linear
69
+ * time however it was written.
70
+ */
67
71
  const REACHES: readonly { readonly kind: EgressKind; readonly pattern: RegExp }[] = [
68
- { kind: "script", pattern: /<script\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
69
- { kind: "script", pattern: /\bimport\s*(?:[\w{}\s*,]+from\s*)?\(?\s*["'](https?:\/\/[^"']+)/gu },
70
- { kind: "style", pattern: /<link\b[^>]*\bhref\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
71
- { kind: "style", pattern: /@import\s+(?:url\()?["']?(https?:\/\/[^"')\s]+)/giu },
72
- { kind: "img", pattern: /<img\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
73
- { kind: "img", pattern: /url\(\s*["']?(https?:\/\/[^"')\s]+)/giu },
72
+ {
73
+ kind: "script",
74
+ pattern: /<script\b[^<>]{0,8192}?\bsrc\s{0,64}=\s{0,64}["']?(https?:\/\/[^"'\s<>]{1,2048})/giu,
75
+ },
76
+ { kind: "script", pattern: /\bfrom\s{0,64}["'](https?:\/\/[^"'\n]{1,2048})/gu },
77
+ { kind: "script", pattern: /\bimport\s{0,64}\(?\s{0,64}["'](https?:\/\/[^"'\n]{1,2048})/gu },
78
+ {
79
+ kind: "style",
80
+ pattern: /<link\b[^<>]{0,8192}?\bhref\s{0,64}=\s{0,64}["']?(https?:\/\/[^"'\s<>]{1,2048})/giu,
81
+ },
82
+ {
83
+ kind: "style",
84
+ pattern: /@import\s{1,64}(?:url\()?["']?(https?:\/\/[^"')\s]{1,2048})/giu,
85
+ },
86
+ {
87
+ kind: "img",
88
+ pattern: /<img\b[^<>]{0,8192}?\bsrc\s{0,64}=\s{0,64}["']?(https?:\/\/[^"'\s<>]{1,2048})/giu,
89
+ },
90
+ { kind: "img", pattern: /url\(\s{0,64}["']?(https?:\/\/[^"')\s]{1,2048})/giu },
74
91
  {
75
92
  kind: "media",
76
- pattern: /<(?:video|audio|source)\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu,
93
+ pattern:
94
+ /<(?:video|audio|source)\b[^<>]{0,8192}?\bsrc\s{0,64}=\s{0,64}["']?(https?:\/\/[^"'\s<>]{1,2048})/giu,
77
95
  },
78
- { kind: "connect", pattern: /\bfetch\s*\(\s*["'`](https?:\/\/[^"'`]+)/gu },
96
+ { kind: "connect", pattern: /\bfetch\s{0,64}\(\s{0,64}["'`](https?:\/\/[^"'`\n]{1,2048})/gu },
79
97
  {
80
98
  kind: "connect",
81
- pattern: /\bnew\s+(?:WebSocket|EventSource)\s*\(\s*["'`]((?:https?|wss?):\/\/[^"'`]+)/gu,
99
+ pattern:
100
+ /\bnew\s{1,64}(?:WebSocket|EventSource)\s{0,64}\(\s{0,64}["'`]((?:https?|wss?):\/\/[^"'`\n]{1,2048})/gu,
82
101
  },
83
102
  ];
84
103
 
@@ -171,7 +190,9 @@ export function lintContent(config: PortholeConfig, content: string): Finding[]
171
190
  "clipboard",
172
191
  "warning",
173
192
  declared.has("copyText")
174
- ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
193
+ ? config.runtime === undefined
194
+ ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
195
+ : 'The clipboard is closed to content: a copy button calls (await porthole.use("clipboard")).copy(text) from its click.'
175
196
  : "The clipboard is closed to content: copying from a button doesn't work here.",
176
197
  clipboard.index,
177
198
  );
@@ -218,7 +239,7 @@ export function lintContent(config: PortholeConfig, content: string): Finding[]
218
239
  add(
219
240
  "egress",
220
241
  "warning",
221
- `Nothing loads from ${origin} here (${kind}): ${kind === "script" && librarySources(config).length > 0 ? "write it inline, or use one of the libraries served here (the manual's Libraries)" : kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" && config.capabilities.readData !== undefined ? "the content can't call it; read the app's data with readData" : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`,
242
+ `Nothing loads from ${origin} here (${kind}): ${kind === "script" && librarySources(config).length > 0 ? "write it inline, or use one of the libraries served here (the manual's Libraries)" : kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" && config.capabilities.readData !== undefined ? `the content can't call it; read the app's data with ${config.runtime === undefined ? "readData" : "data.read"}` : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`,
222
243
  match.index,
223
244
  );
224
245
  }
package/src/check/page.ts CHANGED
@@ -39,6 +39,16 @@ const DECLINED: { readonly [N in HandledCapability]: () => unknown } = {
39
39
  subscribeData: () => {
40
40
  throw new Error("The host declined the subscription");
41
41
  },
42
+ comments: () => false,
43
+ artifact: () => {
44
+ throw new Error("The host declined the artifact call");
45
+ },
46
+ assets: () => {
47
+ throw new Error("The host declined the asset call");
48
+ },
49
+ db: () => {
50
+ throw new Error("The host declined the db call");
51
+ },
42
52
  };
43
53
 
44
54
  /**
@@ -184,6 +194,10 @@ const check = {
184
194
  title: "Check",
185
195
  scheme: spec.scheme,
186
196
  ...(spec.instance === undefined ? {} : { instance: spec.instance }),
197
+ // Under a runtime: the page's declaration (none by default), a viewer who only views.
198
+ ...(spec.config.runtime === undefined
199
+ ? {}
200
+ : { declaration: spec.declaration ?? null, viewer: { level: "view" as const } }),
187
201
  });
188
202
  const run: Run = {
189
203
  display,
@@ -1,7 +1,7 @@
1
1
  import type { PortholeConfig } from "../config/schema.ts";
2
- import { BUILT_IN_TOPICS } from "../config/validate.ts";
3
- import { generateGuide, generateToolDescription } from "../guide/guide.ts";
2
+ import { builtInTopics, generateGuide, generateToolDescription } from "../guide/guide.ts";
4
3
  import { fragmentOf, lintContent, type Finding } from "./lint.ts";
4
+ import { lintFiles, whereOf, type FileContents, type FileFinding } from "./files.ts";
5
5
 
6
6
  /**
7
7
  * The agent's tools, as a tool list names them (P073): a name, a description and a JSON Schema
@@ -28,7 +28,7 @@ const guideName = (config: PortholeConfig) => config.guide.guideToolName ?? `${n
28
28
 
29
29
  /** The topics the manual has: the built-in ones and the config's own. */
30
30
  export function guideTopics(config: PortholeConfig): string[] {
31
- return [...BUILT_IN_TOPICS, ...Object.keys(config.guide.topics ?? {})];
31
+ return [...builtInTopics(config), ...Object.keys(config.guide.topics ?? {})];
32
32
  }
33
33
 
34
34
  /** The tool that shows content: `{ title, html }`. */
@@ -189,6 +189,55 @@ export function admitContent(
189
189
  };
190
190
  }
191
191
 
192
+ export type AdmitFilesResult =
193
+ | {
194
+ readonly ok: true;
195
+ /** Warnings (and errors, with `refuseOn: "never"`), for the tool's answer. */
196
+ readonly findings: readonly FileFinding[];
197
+ /** One line for the agent, or null when there's nothing to say. */
198
+ readonly note: string | null;
199
+ }
200
+ | {
201
+ readonly ok: false;
202
+ readonly findings: readonly FileFinding[];
203
+ /** What to tell the agent: what to change, and to call the tool again. */
204
+ readonly refusal: string;
205
+ };
206
+
207
+ /**
208
+ * A publish tool's check before it takes a page with files (P081): refuses only what certainly
209
+ * fails (a path or limit the server won't take, no entry, a page `admitContent` would refuse, a
210
+ * page's reference that starts with /); the rest, references to files that aren't in the set
211
+ * among them, are warnings. `refuseOn: "never"` refuses nothing.
212
+ */
213
+ export function admitFiles(
214
+ config: PortholeConfig,
215
+ files: FileContents,
216
+ options: { readonly entry?: string; readonly refuseOn?: "error" | "never" } = {},
217
+ ): AdmitFilesResult {
218
+ const findings = lintFiles(
219
+ config,
220
+ files,
221
+ options.entry === undefined ? {} : { entry: options.entry },
222
+ );
223
+ const errors = findings.filter((each) => each.severity === "error");
224
+ if (errors.length > 0 && (options.refuseOn ?? "error") === "error") {
225
+ return {
226
+ ok: false,
227
+ findings,
228
+ refusal: `Not published. Change this, then publish again:\n${errors.map((each) => `- ${whereOf(each)}${each.message}`).join("\n")}`,
229
+ };
230
+ }
231
+ return {
232
+ ok: true,
233
+ findings,
234
+ note:
235
+ findings.length === 0
236
+ ? null
237
+ : `Published. Fix these next time:\n${findings.map((each) => `- ${whereOf(each)}${each.message}`).join("\n")}`,
238
+ };
239
+ }
240
+
192
241
  /**
193
242
  * What to tell the agent when its manual changes (a display kind flipped between served and
194
243
  * opaque, P073): the lines that are new, or null when the manual reads the same.
@@ -1,6 +1,8 @@
1
1
  import { CAPABILITIES, type CapabilityName, type Gate } from "../config/capabilities.ts";
2
2
  import type { PortholeConfig } from "../config/schema.ts";
3
3
  import { LIBRARY_PATH } from "../libraries/libraries.ts";
4
+ import { assetCodeRuns, familyOf, methodGates, methodOf } from "../runtime/contract.ts";
5
+ import { ASSET_PATH } from "../runtime/requests.ts";
4
6
 
5
7
  /**
6
8
  * The frame's policies, derived from the config: its CSP (in the shell's `<meta>` for opaque
@@ -30,6 +32,22 @@ export function effectiveGates(config: PortholeConfig, name: CapabilityName): re
30
32
  return config.capabilities[name]?.gates ?? CAPABILITIES[name].defaultGates;
31
33
  }
32
34
 
35
+ /**
36
+ * The gates one call runs under: its host function's, and its runtime method's own (after the
37
+ * review: `artifact.publish`, `assets.delete`, an upload whose code may run), every one applying.
38
+ */
39
+ export function callGates(
40
+ config: PortholeConfig,
41
+ name: CapabilityName,
42
+ args: unknown,
43
+ ): readonly Gate[] {
44
+ const gates = effectiveGates(config, name);
45
+ const family = familyOf(name);
46
+ const method = family === null ? null : methodOf(name, args);
47
+ const own = family === null || method === null ? [] : methodGates(config, family.name, method);
48
+ return own.length === 0 ? gates : [...gates, ...own.filter((gate) => !gates.includes(gate))];
49
+ }
50
+
33
51
  const unique = (values: readonly string[]): string[] => [...new Set(values)];
34
52
 
35
53
  /** The origins content may reach for `kind`: the base allowlist plus every declared capability's. */
@@ -101,6 +119,80 @@ export function frameCspDirectives(config: PortholeConfig): CspDirective[] {
101
119
  ];
102
120
  }
103
121
 
122
+ /** The directives a page of a file set loads its own files under (P082): everything that loads. */
123
+ export const FILE_SET_DIRECTIVES = [
124
+ "script-src",
125
+ "style-src",
126
+ "font-src",
127
+ "img-src",
128
+ "media-src",
129
+ "connect-src",
130
+ "worker-src",
131
+ ] as const;
132
+
133
+ /**
134
+ * A served page's CSP when it comes with files (P082): the frame's, with its version's own files
135
+ * opened for each kind that loads (`FILE_SET_DIRECTIVES`), by `source`, the files' path on the
136
+ * content origin (`https://a-x.example-usercontent.com/v/3/`). Never `'self'`: the origin's other
137
+ * paths (other versions, Porthole's own) stay closed, and frames, plugins, forms and `<base>` stay
138
+ * `'none'`. Opaque frames have no files, and keep P022's rule whole.
139
+ */
140
+ export function fileSetCspDirectives(
141
+ directives: readonly CspDirective[],
142
+ source: string,
143
+ ): CspDirective[] {
144
+ const opened = new Set<string>(FILE_SET_DIRECTIVES);
145
+ return directives.map(([name, ...sources]) => {
146
+ if (!opened.has(name)) {
147
+ return [name, ...sources];
148
+ }
149
+ const kept = sources.filter((each) => each !== "'none'");
150
+ return [name, ...kept, source];
151
+ });
152
+ }
153
+
154
+ /**
155
+ * The directives a page opens its artifact's asset library to (P089), at `/_blob/` on its own
156
+ * origin: what loads without running, always; what runs (scripts, styles) only where uploads are
157
+ * the admins' alone, who publish the page's code anyway.
158
+ */
159
+ export const ASSET_DIRECTIVES = ["img-src", "media-src", "font-src", "connect-src"] as const;
160
+ export const ASSET_CODE_DIRECTIVES = ["script-src", "style-src"] as const;
161
+
162
+ export { assetCodeRuns };
163
+
164
+ /**
165
+ * A served page's CSP with its asset library opened (P089), on `origin` (the page's own, exact:
166
+ * never a sibling's): only where the config declares `assets`. Never `'self'`.
167
+ */
168
+ export function assetCspDirectives(
169
+ config: PortholeConfig,
170
+ directives: readonly CspDirective[],
171
+ origin: string,
172
+ ): CspDirective[] {
173
+ if (config.capabilities.assets === undefined || config.isolation !== "domain") {
174
+ return [...directives];
175
+ }
176
+ const source = `${origin}${ASSET_PATH}`;
177
+ const opened = new Set<string>([
178
+ ...ASSET_DIRECTIVES,
179
+ ...(assetCodeRuns(config) ? ASSET_CODE_DIRECTIVES : []),
180
+ ]);
181
+ return directives.map(([name, ...sources]) => {
182
+ if (!opened.has(name)) {
183
+ return [name, ...sources];
184
+ }
185
+ const kept = sources.filter((each) => each !== "'none'");
186
+ return [name, ...kept, source];
187
+ });
188
+ }
189
+
190
+ /**
191
+ * The CSP of a file of a set that is neither a page nor a script (P081): nothing loads from it,
192
+ * and opened as a document (an SVG, an XML file) it runs nothing, on an opaque origin.
193
+ */
194
+ export const INERT_FILE_CSP = "default-src 'none'; sandbox";
195
+
104
196
  export function serializeCsp(directives: readonly CspDirective[]): string {
105
197
  return directives.map((directive) => directive.join(" ")).join("; ");
106
198
  }
@@ -1,4 +1,14 @@
1
1
  import type { AnnotationReport } from "../annotate/types.ts";
2
+ import type { DbRequest, DbResult } from "../runtime/db.ts";
3
+ import type {
4
+ ArtifactInfo,
5
+ ArtifactRequest,
6
+ AssetInfo,
7
+ AssetRequest,
8
+ CommentRequest,
9
+ PublishedVersion,
10
+ UserInfo,
11
+ } from "../runtime/requests.ts";
2
12
 
3
13
  /**
4
14
  * The capability vocabulary (PRINCIPLE 4): every power content has beyond drawing is one of these
@@ -22,6 +32,12 @@ export const CAPABILITY_NAMES = [
22
32
  "resize",
23
33
  "copyText",
24
34
  "annotate",
35
+ // The capability runtime's own (P085, `config.runtime`): reached through `porthole.use`.
36
+ "user",
37
+ "comments",
38
+ "artifact",
39
+ "assets",
40
+ "db",
25
41
  ] as const;
26
42
 
27
43
  export type CapabilityName = (typeof CAPABILITY_NAMES)[number];
@@ -49,8 +65,11 @@ export type Gate =
49
65
  export interface CapabilitySpec {
50
66
  /** The gates a declared capability gets when its config names none. */
51
67
  readonly defaultGates: readonly Gate[];
52
- /** `handler`: the host passes a function that performs it. `event`: the framework emits it. */
53
- readonly served: "handler" | "event";
68
+ /**
69
+ * `handler`: the host passes a function that performs it. `event`: the framework emits it.
70
+ * `viewer`: the framework answers it from the viewer the host gave the display (`user`).
71
+ */
72
+ readonly served: "handler" | "event" | "viewer";
54
73
  /** The global the shell defines for it (sugar over the protocol message), if any. */
55
74
  readonly global?: string;
56
75
  /**
@@ -129,6 +148,20 @@ export const CAPABILITIES = {
129
148
  * (it shares the realm): UI hints for the host, never permissions.
130
149
  */
131
150
  annotate: { defaultGates: [rate(120)], served: "event" },
151
+ /** Who is viewing (P087): answered from the viewer the host gave the display. */
152
+ user: { defaultGates: [rate(60)], served: "viewer", request: { method: "porthole/call" } },
153
+ /** Opens the host's comment composer at the page's anchor (P090): write-only. */
154
+ comments: {
155
+ defaultGates: ["user-activation", rate(30)],
156
+ served: "handler",
157
+ request: { method: "porthole/call" },
158
+ },
159
+ /** This artifact's current version, and a new version of it, base-checked (P088). */
160
+ artifact: { defaultGates: [rate(10)], served: "handler", request: { method: "porthole/call" } },
161
+ /** The artifact's asset library, served at `/_blob/<id>` (P089). */
162
+ assets: { defaultGates: [rate(30)], served: "handler", request: { method: "porthole/call" } },
163
+ /** The artifact's shared document store (P088). */
164
+ db: { defaultGates: [rate(600)], served: "handler", request: { method: "porthole/call" } },
132
165
  } as const satisfies { readonly [N in CapabilityName]: CapabilitySpec };
133
166
 
134
167
  /** The arguments a call carries, once the adapter has validated them. */
@@ -156,6 +189,12 @@ export interface CapabilityArgs {
156
189
  readonly copyText: { readonly text: string };
157
190
  /** What the frame reported, once checked (`AnnotationReport`). */
158
191
  readonly annotate: AnnotationReport;
192
+ readonly user: Readonly<Record<string, never>>;
193
+ readonly comments: CommentRequest;
194
+ readonly artifact: ArtifactRequest;
195
+ readonly assets: AssetRequest;
196
+ /** Paths checked, `me` resolved, the viewer's own data only (P088). */
197
+ readonly db: DbRequest;
159
198
  }
160
199
 
161
200
  /** What a call resolves to. Protocol-shaped results (a tool's result) stay opaque to the core. */
@@ -176,6 +215,14 @@ export interface CapabilityResults {
176
215
  /** Whether the text was copied. */
177
216
  readonly copyText: boolean;
178
217
  readonly annotate: undefined;
218
+ readonly user: UserInfo;
219
+ /** Whether the composer opened. Never a thread: content doesn't read comments (P090). */
220
+ readonly comments: boolean;
221
+ /** `get`: the current version; `publish`: the new one. */
222
+ readonly artifact: ArtifactInfo | PublishedVersion;
223
+ /** `list`: the library; `upload`: the new asset; `delete`: whether it was removed. */
224
+ readonly assets: AssetInfo | readonly AssetInfo[] | boolean;
225
+ readonly db: DbResult;
179
226
  }
180
227
 
181
228
  /** The capabilities a host serves with a handler. */
@@ -1,3 +1,5 @@
1
+ import type { RuntimeVersion } from "../runtime/contract.ts";
2
+ import type { ViewerLevel } from "../runtime/levels.ts";
1
3
  import type { CapabilityName, Gate } from "./capabilities.ts";
2
4
 
3
5
  /**
@@ -44,6 +46,20 @@ export interface CapabilityConfig {
44
46
  readonly resource?: readonly string[];
45
47
  /** Replaces the generated manual entry for this capability. */
46
48
  readonly guide?: string;
49
+ /**
50
+ * The least viewer level that may call each of the runtime methods it serves (P087), by method
51
+ * name (`db: { levels: { set: "admin" } }`, `sendPrompt: { levels: { send: "admin" } }`): over
52
+ * the contract's own, never below a method's floor (`RUNTIME_CAPABILITIES`). For
53
+ * `assets.upload`, `admin` or above also lets the page run what was uploaded as scripts and
54
+ * styles (P089); `interact` doesn't.
55
+ */
56
+ readonly levels?: Readonly<Record<string, ViewerLevel>>;
57
+ /**
58
+ * Gates of each runtime method it serves, by name, in place of the contract's own (after the
59
+ * review: `artifact.publish` and `assets.delete` need a click and a yes; `assets.upload` a yes
60
+ * where uploaded code may run). Every one applies on top of `gates`. `[]`: none of its own.
61
+ */
62
+ readonly methodGates?: Readonly<Record<string, readonly Gate[]>>;
47
63
  }
48
64
 
49
65
  /** The declared capabilities. Absent: not available, not wired, not in the CSP, not in the manual. */
@@ -120,6 +136,14 @@ export interface Limits {
120
136
  * when absent.
121
137
  */
122
138
  readonly loadTimeoutMs?: number;
139
+ /**
140
+ * A served page's files (P081): the most a version holds (default 1000), the largest one,
141
+ * bytes (default 25 MiB), and all of them together, bytes (default 100 MiB: a host sets its
142
+ * own). The manual states them; `checkFileSet` and `lintFiles` hold a version to them.
143
+ */
144
+ readonly maxFiles?: number;
145
+ readonly maxFileBytes?: number;
146
+ readonly maxVersionBytes?: number;
123
147
  }
124
148
 
125
149
  /**
@@ -215,6 +239,14 @@ export interface PortholeConfig {
215
239
  * declares no `reportError`). Absent: the manual says they are reported to the app.
216
240
  */
217
241
  readonly errors?: "agent" | "host" | "none";
242
+ /**
243
+ * The capability runtime (P085): content reaches capabilities through one global,
244
+ * `porthole.use(name)`, under this contract version, and the manual teaches it (with declaring
245
+ * them, `capabilities: { name: config }`, for pages that are published). Only with it may the
246
+ * config declare the runtime's own host functions (`user`, `comments`, `artifact`, `assets`,
247
+ * `db`). Absent: 0.6's frames, globals and manual, exactly.
248
+ */
249
+ readonly runtime?: RuntimeVersion;
218
250
  }
219
251
 
220
252
  export interface StorageConfig {
@@ -1,4 +1,18 @@
1
- import { CAPABILITY_NAMES, isCapabilityName, type Gate } from "./capabilities.ts";
1
+ import {
2
+ CAPABILITY_NAMES,
3
+ isCapabilityName,
4
+ type CapabilityName,
5
+ type Gate,
6
+ } from "./capabilities.ts";
7
+ import {
8
+ RUNTIME_HOST_FUNCTIONS,
9
+ RUNTIME_VERSIONS,
10
+ familyOf,
11
+ isRuntimeVersion,
12
+ runtimeCapability,
13
+ type RuntimeMethod,
14
+ } from "../runtime/contract.ts";
15
+ import { atLeast, isViewerLevel } from "../runtime/levels.ts";
2
16
  import {
3
17
  PASSIVE_KINDS,
4
18
  URL_PERMISSIONS,
@@ -24,7 +38,7 @@ export class ConfigError extends Error {
24
38
  }
25
39
 
26
40
  /** The built-in manual topics; a host's own topics may not reuse these names. */
27
- export const BUILT_IN_TOPICS = ["widget", "chart", "interactive"] as const;
41
+ export const BUILT_IN_TOPICS = ["widget", "chart", "interactive", "capabilities"] as const;
28
42
 
29
43
  const LOOPBACK = /^(localhost|127\.0\.0\.1|\[::1\])$|\.localhost$/u;
30
44
 
@@ -293,6 +307,7 @@ export function validateConfig(input: unknown): PortholeConfig {
293
307
  "permissions",
294
308
  "storage",
295
309
  "errors",
310
+ "runtime",
296
311
  ],
297
312
  "config",
298
313
  );
@@ -314,7 +329,56 @@ export function validateConfig(input: unknown): PortholeConfig {
314
329
  fail(path, `is not a capability (${CAPABILITY_NAMES.join(", ")})`);
315
330
  }
316
331
  const capability = object(value, path);
317
- only(capability, ["gates", "connect", "resource", "guide"], path);
332
+ only(capability, ["gates", "connect", "resource", "guide", "levels", "methodGates"], path);
333
+ if (capability.methodGates !== undefined) {
334
+ const family = familyOf(name as CapabilityName);
335
+ for (const [method, gates] of Object.entries(
336
+ object(capability.methodGates, `${path}.methodGates`),
337
+ )) {
338
+ const methods: Readonly<Record<string, RuntimeMethod>> | undefined =
339
+ family === null ? undefined : runtimeCapability(family.name).methods;
340
+ if (
341
+ methods === undefined ||
342
+ !Object.hasOwn(methods, method) ||
343
+ methods[method]?.serves !== name
344
+ ) {
345
+ fail(`${path}.methodGates.${method}`, `is not a runtime method ${name} serves`);
346
+ }
347
+ if (!Array.isArray(gates)) {
348
+ fail(`${path}.methodGates.${method}`, "must be an array of gates");
349
+ }
350
+ (gates as unknown[]).forEach((each, index) =>
351
+ gate(each, `${path}.methodGates.${method}[${index}]`),
352
+ );
353
+ }
354
+ }
355
+ if (capability.levels !== undefined) {
356
+ const levels = object(capability.levels, `${path}.levels`);
357
+ const family = familyOf(name as CapabilityName);
358
+ for (const [method, level] of Object.entries(levels)) {
359
+ const methods: Readonly<Record<string, RuntimeMethod>> | undefined =
360
+ family === null ? undefined : runtimeCapability(family.name).methods;
361
+ const spec =
362
+ methods !== undefined && Object.hasOwn(methods, method) ? methods[method] : undefined;
363
+ if (family === null || spec === undefined || spec.serves !== name) {
364
+ fail(
365
+ `${path}.levels.${method}`,
366
+ family === null
367
+ ? `${name} serves no runtime method: it has no levels`
368
+ : `is not a method ${name} serves (${family.methods.join(", ")})`,
369
+ );
370
+ }
371
+ if (!isViewerLevel(level)) {
372
+ fail(`${path}.levels.${method}`, "must be view, interact, admin or owner");
373
+ }
374
+ if (spec !== undefined && !atLeast(level as never, spec.floor)) {
375
+ fail(
376
+ `${path}.levels.${method}`,
377
+ `can't be below ${spec.floor} (${family?.name}.${method}'s floor, P087)`,
378
+ );
379
+ }
380
+ }
381
+ }
318
382
  if (capability.gates !== undefined) {
319
383
  if (!Array.isArray(capability.gates)) {
320
384
  fail(`${path}.gates`, "must be an array");
@@ -332,6 +396,35 @@ export function validateConfig(input: unknown): PortholeConfig {
332
396
  if (config.mode === "url" && Object.keys(capabilities).length > 0) {
333
397
  fail("config.capabilities", "url mode has no shell, so it can declare no capabilities");
334
398
  }
399
+ // The capability runtime (P085): its global and its own host functions.
400
+ if (config.runtime !== undefined) {
401
+ if (!isRuntimeVersion(config.runtime)) {
402
+ fail("config.runtime", `must be a runtime contract version: ${RUNTIME_VERSIONS.join(", ")}`);
403
+ }
404
+ if (config.mode !== "inline" && config.mode !== "artifact") {
405
+ fail("config.runtime", "the runtime is the shell's: inline widgets and artifact pages only");
406
+ }
407
+ }
408
+ for (const name of RUNTIME_HOST_FUNCTIONS) {
409
+ if (capabilities[name] === undefined) {
410
+ continue;
411
+ }
412
+ if (config.runtime === undefined) {
413
+ fail(
414
+ `config.capabilities.${name}`,
415
+ "is the capability runtime's: set config.runtime (content reaches it through porthole.use)",
416
+ );
417
+ }
418
+ if ((name === "artifact" || name === "assets") && config.mode !== "artifact") {
419
+ fail(`config.capabilities.${name}`, "is an artifact page's: artifact mode only");
420
+ }
421
+ }
422
+ if (capabilities.assets !== undefined && config.isolation !== "domain") {
423
+ fail(
424
+ "config.capabilities.assets",
425
+ "assets are served from the page's own origin (/_blob/): domain isolation only",
426
+ );
427
+ }
335
428
 
336
429
  const egress = object(config.egress, "config.egress");
337
430
  const kinds = ["connect", "script", "style", "img", "font", "media"];
@@ -428,13 +521,20 @@ export function validateConfig(input: unknown): PortholeConfig {
428
521
  "maxPromptChars",
429
522
  "maxErrorReports",
430
523
  ];
431
- only(limits, [...limitNames, "loadTimeoutMs"], "config.limits");
524
+ const fileLimitNames = ["maxFiles", "maxFileBytes", "maxVersionBytes"];
525
+ only(limits, [...limitNames, "loadTimeoutMs", ...fileLimitNames], "config.limits");
432
526
  for (const name of limitNames) {
433
527
  positive(limits[name], `config.limits.${name}`);
434
528
  }
435
529
  if (limits.loadTimeoutMs !== undefined) {
436
530
  positive(limits.loadTimeoutMs, "config.limits.loadTimeoutMs", 600_000);
437
531
  }
532
+ // A served page's files (P081): optional, with fileLimits' defaults.
533
+ for (const name of fileLimitNames) {
534
+ if (limits[name] !== undefined) {
535
+ positive(limits[name], `config.limits.${name}`);
536
+ }
537
+ }
438
538
  if ((limits.minHeightPx as number) > (limits.maxHeightPx as number)) {
439
539
  fail("config.limits.minHeightPx", "must not exceed maxHeightPx");
440
540
  }
@@ -470,7 +570,9 @@ export function validateConfig(input: unknown): PortholeConfig {
470
570
  const path = `config.guide.topics.${name}`;
471
571
  if (
472
572
  !/^[a-z][a-z0-9-]{0,31}$/u.test(name) ||
473
- (BUILT_IN_TOPICS as readonly string[]).includes(name)
573
+ // `capabilities` is built in only under the runtime (P085): a 0.6 config's own stays.
574
+ ((BUILT_IN_TOPICS as readonly string[]).includes(name) &&
575
+ (name !== "capabilities" || config.runtime !== undefined))
474
576
  ) {
475
577
  fail(path, "must be a new topic name (lowercase), not a built-in one");
476
578
  }
@@ -120,6 +120,13 @@ export {
120
120
  // Redirect entry's cases (P068).
121
121
  export { entryTests, type EntryConformanceHost, type EntrySuiteOptions } from "./entry.ts";
122
122
 
123
+ // The capability runtime's cases an app runs against its own handlers (P085-P090): no browser.
124
+ export {
125
+ defineRuntimeConformance,
126
+ type RuntimeCase,
127
+ type RuntimeConformanceOptions,
128
+ } from "./runtime.ts";
129
+
123
130
  // The runner an app points at its real page and issue endpoint (P066).
124
131
  export {
125
132
  conformancePage,