@botiverse/porthole 0.5.0 → 0.6.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 (90) hide show
  1. package/README.md +25 -0
  2. package/dist/bridge/bridge.d.ts +12 -4
  3. package/dist/bridge/bridge.js +62 -27
  4. package/dist/bridge/navigation.d.ts +6 -0
  5. package/dist/bridge/navigation.js +41 -0
  6. package/dist/bridge/refusal.d.ts +53 -0
  7. package/dist/bridge/refusal.js +121 -0
  8. package/dist/bridge/types.d.ts +7 -0
  9. package/dist/check/check.d.ts +12 -3
  10. package/dist/check/check.js +54 -8
  11. package/dist/check/files.d.ts +26 -0
  12. package/dist/check/files.js +307 -0
  13. package/dist/check/lint.js +27 -10
  14. package/dist/check/page-source.js +1 -1
  15. package/dist/check/page.js +5 -0
  16. package/dist/check/tools.d.ts +23 -0
  17. package/dist/check/tools.js +25 -0
  18. package/dist/compile/policy.d.ts +15 -0
  19. package/dist/compile/policy.js +32 -0
  20. package/dist/config/capabilities.d.ts +5 -0
  21. package/dist/config/schema.d.ts +8 -0
  22. package/dist/config/validate.js +8 -1
  23. package/dist/conformance/harness-source.js +1 -1
  24. package/dist/files/paths.d.ts +99 -0
  25. package/dist/files/paths.js +263 -0
  26. package/dist/files/types.d.ts +24 -0
  27. package/dist/files/types.js +83 -0
  28. package/dist/guide/guide.js +25 -5
  29. package/dist/host/create-host.js +36 -4
  30. package/dist/host/types.d.ts +15 -2
  31. package/dist/index.d.ts +7 -3
  32. package/dist/index.js +10 -3
  33. package/dist/mcp/adapter.js +22 -7
  34. package/dist/protocol/adapter.d.ts +4 -0
  35. package/dist/protocol/mcp-apps.d.ts +12 -0
  36. package/dist/protocol/mcp-apps.js +12 -0
  37. package/dist/protocol/shell-adapter.js +18 -2
  38. package/dist/react/frame.d.ts +19 -4
  39. package/dist/react/frame.js +37 -9
  40. package/dist/server/files.d.ts +44 -0
  41. package/dist/server/files.js +244 -0
  42. package/dist/server/host.d.ts +38 -1
  43. package/dist/server/host.js +37 -2
  44. package/dist/server/index.d.ts +4 -2
  45. package/dist/server/index.js +4 -1
  46. package/dist/server/keys.d.ts +8 -0
  47. package/dist/server/keys.js +34 -0
  48. package/dist/server/server.js +287 -22
  49. package/dist/server/types.d.ts +49 -5
  50. package/dist/shell/document.d.ts +19 -0
  51. package/dist/shell/document.js +30 -0
  52. package/dist/shell/runtime.d.ts +2 -1
  53. package/dist/shell/runtime.js +117 -10
  54. package/docs/ADOPTING.md +95 -13
  55. package/docs/ARCHITECTURE.md +13 -3
  56. package/docs/DECISIONS.md +396 -4
  57. package/docs/DESIGN.md +43 -10
  58. package/package.json +1 -1
  59. package/src/bridge/bridge.ts +74 -23
  60. package/src/bridge/navigation.ts +46 -0
  61. package/src/bridge/refusal.ts +151 -0
  62. package/src/bridge/types.ts +12 -1
  63. package/src/check/check.ts +92 -14
  64. package/src/check/files.ts +384 -0
  65. package/src/check/lint.ts +29 -10
  66. package/src/check/page.ts +7 -0
  67. package/src/check/tools.ts +50 -0
  68. package/src/compile/policy.ts +38 -0
  69. package/src/config/capabilities.ts +5 -1
  70. package/src/config/schema.ts +8 -0
  71. package/src/config/validate.ts +8 -1
  72. package/src/files/paths.ts +323 -0
  73. package/src/files/types.ts +101 -0
  74. package/src/guide/guide.ts +38 -4
  75. package/src/host/create-host.ts +37 -4
  76. package/src/host/types.ts +13 -2
  77. package/src/index.ts +41 -0
  78. package/src/mcp/adapter.ts +26 -6
  79. package/src/protocol/adapter.ts +3 -1
  80. package/src/protocol/mcp-apps.ts +14 -0
  81. package/src/protocol/shell-adapter.ts +20 -2
  82. package/src/react/frame.tsx +53 -14
  83. package/src/server/files.ts +312 -0
  84. package/src/server/host.ts +72 -3
  85. package/src/server/index.ts +19 -0
  86. package/src/server/keys.ts +53 -0
  87. package/src/server/server.ts +353 -24
  88. package/src/server/types.ts +56 -4
  89. package/src/shell/document.ts +53 -0
  90. package/src/shell/runtime.ts +117 -10
@@ -0,0 +1,323 @@
1
+ import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+
3
+ /**
4
+ * A version made of files (P081): the rules a published path follows, the limits a version is
5
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
6
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
7
+ * only, never on a filesystem.
8
+ */
9
+
10
+ /** The most files a version holds, by default. */
11
+ export const DEFAULT_MAX_FILES = 1_000;
12
+ /** The largest file of a version, bytes, by default (25 MiB). */
13
+ export const DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024;
14
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
15
+ export const DEFAULT_MAX_VERSION_BYTES = 100 * 1024 * 1024;
16
+ /** The longest path, characters, and the longest segment of one. */
17
+ export const MAX_FILE_PATH_CHARS = 512;
18
+ export const MAX_SEGMENT_CHARS = 255;
19
+ /** The page a version opens at by default. */
20
+ export const DEFAULT_ENTRY = "index.html";
21
+
22
+ /**
23
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
24
+ * origin of its own. Opaque frames have no origin to serve them from.
25
+ */
26
+ export const servesFiles = (config: PortholeConfig): boolean =>
27
+ config.mode === "artifact" && config.isolation === "domain";
28
+
29
+ export interface FileLimits {
30
+ readonly maxFiles: number;
31
+ readonly maxFileBytes: number;
32
+ readonly maxVersionBytes: number;
33
+ }
34
+
35
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
36
+ export function fileLimits(limits?: Partial<Limits> | null): FileLimits {
37
+ return {
38
+ maxFiles: limits?.maxFiles ?? DEFAULT_MAX_FILES,
39
+ maxFileBytes: limits?.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES,
40
+ maxVersionBytes: limits?.maxVersionBytes ?? DEFAULT_MAX_VERSION_BYTES,
41
+ };
42
+ }
43
+
44
+ /**
45
+ * What a request's path can never hold once decoded, and a published path never holds: control
46
+ * and format characters (`Cc`, `Cf`: a right-to-left override, a zero-width space, a BOM would make
47
+ * a path read as another), and `\ % ? #`.
48
+ */
49
+ // oxlint-disable-next-line no-control-regex -- control characters are what it refuses
50
+ const FORBIDDEN = /[\p{Cc}\p{Cf}\\%?#]/u;
51
+
52
+ /**
53
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
54
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
55
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
56
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
57
+ */
58
+ export function filePathProblem(path: unknown): string | null {
59
+ if (typeof path !== "string" || path.length === 0) {
60
+ return "a path is a non-empty string";
61
+ }
62
+ if (path.length > MAX_FILE_PATH_CHARS) {
63
+ return `a path is at most ${MAX_FILE_PATH_CHARS} characters`;
64
+ }
65
+ if (path.startsWith("/")) {
66
+ return "a path is relative: no leading /";
67
+ }
68
+ if (path.endsWith("/")) {
69
+ return "a path names a file: no trailing /";
70
+ }
71
+ const forbidden = FORBIDDEN.exec(path);
72
+ if (forbidden !== null) {
73
+ const char = forbidden[0];
74
+ return `a path holds no ${char === "\\" || char === "%" || char === "?" || char === "#" ? char : "control or format character"}`;
75
+ }
76
+ if (path.normalize("NFC") !== path) {
77
+ return "a path is in Unicode NFC";
78
+ }
79
+ const segments = path.split("/");
80
+ for (const segment of segments) {
81
+ if (segment === "") {
82
+ return "a path has no empty segment (//)";
83
+ }
84
+ if (segment === "." || segment === "..") {
85
+ return `a path has no ${segment} segment`;
86
+ }
87
+ if (segment.length > MAX_SEGMENT_CHARS) {
88
+ return `a path's segment is at most ${MAX_SEGMENT_CHARS} characters`;
89
+ }
90
+ if (segment.startsWith(" ") || segment.endsWith(" ")) {
91
+ return "a path's segment doesn't start or end with a space";
92
+ }
93
+ }
94
+ if (segments[0] === "__porthole") {
95
+ return "__porthole/ is Porthole's own";
96
+ }
97
+ return null;
98
+ }
99
+
100
+ /** A published path's metadata, as far as the checks read it. */
101
+ export interface FileSetEntryLike {
102
+ readonly size: number;
103
+ }
104
+
105
+ export interface FileSetProblem {
106
+ /** The path it is about, where it is about one. */
107
+ readonly path?: string;
108
+ readonly code: "path" | "collision" | "count" | "size" | "total" | "entry";
109
+ /** What to change, for the agent or the person publishing. */
110
+ readonly message: string;
111
+ }
112
+
113
+ const sizeOf = (bytes: number): string =>
114
+ bytes >= 1024 * 1024
115
+ ? `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`
116
+ : bytes >= 1024
117
+ ? `${Math.round(bytes / 1024)} KiB`
118
+ : `${bytes} bytes`;
119
+
120
+ /**
121
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
122
+ * two paths that differ only in case, and no path that is both a file and a directory; the
123
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
124
+ * `fileLimits`). Empty when it may be published.
125
+ */
126
+ export function checkFileSet(
127
+ files: Readonly<Record<string, FileSetEntryLike>>,
128
+ options: { readonly entry?: string; readonly limits?: FileLimits } = {},
129
+ ): FileSetProblem[] {
130
+ const limits = options.limits ?? fileLimits();
131
+ const problems: FileSetProblem[] = [];
132
+ const paths = Object.keys(files);
133
+ if (paths.length > limits.maxFiles) {
134
+ problems.push({
135
+ code: "count",
136
+ message: `${paths.length} files: a version holds at most ${limits.maxFiles}`,
137
+ });
138
+ }
139
+ const folded = new Map<string, string>();
140
+ const directories = new Set<string>();
141
+ let total = 0;
142
+ for (const path of paths) {
143
+ const problem = filePathProblem(path);
144
+ if (problem !== null) {
145
+ problems.push({ path, code: "path", message: `${JSON.stringify(path)}: ${problem}` });
146
+ continue;
147
+ }
148
+ const lower = path.toLowerCase();
149
+ const other = folded.get(lower);
150
+ if (other !== undefined) {
151
+ problems.push({
152
+ path,
153
+ code: "collision",
154
+ message: `${JSON.stringify(path)} and ${JSON.stringify(other)} differ only in case: rename one`,
155
+ });
156
+ } else {
157
+ folded.set(lower, path);
158
+ }
159
+ const segments = path.split("/");
160
+ for (let index = 1; index < segments.length; index += 1) {
161
+ directories.add(segments.slice(0, index).join("/"));
162
+ }
163
+ const size = files[path]?.size;
164
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) {
165
+ problems.push({ path, code: "size", message: `${JSON.stringify(path)}: no size` });
166
+ continue;
167
+ }
168
+ if (size > limits.maxFileBytes) {
169
+ problems.push({
170
+ path,
171
+ code: "size",
172
+ message: `${JSON.stringify(path)} is ${sizeOf(size)}: a file is at most ${sizeOf(limits.maxFileBytes)}`,
173
+ });
174
+ }
175
+ total += size;
176
+ }
177
+ for (const path of paths) {
178
+ if (directories.has(path)) {
179
+ problems.push({
180
+ path,
181
+ code: "collision",
182
+ message: `${JSON.stringify(path)} is a file and a directory: rename one`,
183
+ });
184
+ }
185
+ }
186
+ if (total > limits.maxVersionBytes) {
187
+ problems.push({
188
+ code: "total",
189
+ message: `The files are ${sizeOf(total)} together: a version holds at most ${sizeOf(limits.maxVersionBytes)}`,
190
+ });
191
+ }
192
+ const entry = options.entry ?? DEFAULT_ENTRY;
193
+ if (!Object.hasOwn(files, entry)) {
194
+ problems.push({
195
+ path: entry,
196
+ code: "entry",
197
+ message: `No ${JSON.stringify(entry)}: the page the version opens at is one of its files`,
198
+ });
199
+ }
200
+ return problems;
201
+ }
202
+
203
+ /**
204
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
205
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
206
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
207
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
208
+ * `/` stays (a directory).
209
+ */
210
+ export function requestFilePath(raw: string): string | null {
211
+ if (raw.length > MAX_FILE_PATH_CHARS * 3 + 1) {
212
+ return null;
213
+ }
214
+ const segments = raw.split("/");
215
+ const decoded: string[] = [];
216
+ for (const [index, segment] of segments.entries()) {
217
+ if (segment === "") {
218
+ // Only the last segment may be empty: a directory's trailing slash (or the base itself).
219
+ if (index !== segments.length - 1) {
220
+ return null;
221
+ }
222
+ decoded.push("");
223
+ continue;
224
+ }
225
+ let value: string;
226
+ try {
227
+ value = decodeURIComponent(segment);
228
+ } catch {
229
+ return null;
230
+ }
231
+ if (value === "." || value === ".." || value.includes("/") || FORBIDDEN.test(value)) {
232
+ return null;
233
+ }
234
+ decoded.push(value);
235
+ }
236
+ return decoded.join("/");
237
+ }
238
+
239
+ /** What a request's path finds in a version's manifest. */
240
+ export type FileLookup =
241
+ /** The file to answer with, and its status (404 for a `404.html`). */
242
+ | { readonly kind: "file"; readonly path: string; readonly status: 200 | 404 }
243
+ /** The canonical address: `dir` → `dir/` (or `page/` → `page`), relative to the base. */
244
+ | { readonly kind: "redirect"; readonly to: string }
245
+ /** Nothing: a plain 404. */
246
+ | { readonly kind: "none" };
247
+
248
+ export interface LookupOptions {
249
+ /** The page the version opens at (default `index.html`). */
250
+ readonly entry?: string;
251
+ /** A single-page app's routes: a navigation that finds nothing answers the entry. */
252
+ readonly spa?: boolean;
253
+ /** Whether the request is a navigation (a page loading), not a subresource. */
254
+ readonly navigation: boolean;
255
+ }
256
+
257
+ /**
258
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
259
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
260
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
261
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
262
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
263
+ */
264
+ export function lookupFile(
265
+ has: (path: string) => boolean,
266
+ path: string,
267
+ options: LookupOptions,
268
+ ): FileLookup {
269
+ const entry = options.entry ?? DEFAULT_ENTRY;
270
+ if (path === "") {
271
+ if (!has(entry)) {
272
+ return notFound(has, "", options);
273
+ }
274
+ // An entry in a directory opens there, so its relative addresses are its directory's.
275
+ return entry.includes("/")
276
+ ? { kind: "redirect", to: entry }
277
+ : { kind: "file", path: entry, status: 200 };
278
+ }
279
+ if (path.endsWith("/")) {
280
+ const index = `${path}index.html`;
281
+ if (has(index)) {
282
+ return { kind: "file", path: index, status: 200 };
283
+ }
284
+ const page = `${path.slice(0, -1)}.html`;
285
+ if (has(page)) {
286
+ return { kind: "redirect", to: path.slice(0, -1) };
287
+ }
288
+ return notFound(has, path, options);
289
+ }
290
+ if (has(path)) {
291
+ return { kind: "file", path, status: 200 };
292
+ }
293
+ if (has(`${path}.html`)) {
294
+ return { kind: "file", path: `${path}.html`, status: 200 };
295
+ }
296
+ if (has(`${path}/index.html`)) {
297
+ return { kind: "redirect", to: `${path}/` };
298
+ }
299
+ return notFound(has, path, options);
300
+ }
301
+
302
+ function notFound(
303
+ has: (path: string) => boolean,
304
+ path: string,
305
+ options: LookupOptions,
306
+ ): FileLookup {
307
+ if (!options.navigation) {
308
+ return { kind: "none" };
309
+ }
310
+ const entry = options.entry ?? DEFAULT_ENTRY;
311
+ if (options.spa === true && has(entry)) {
312
+ return { kind: "file", path: entry, status: 200 };
313
+ }
314
+ // The nearest 404.html: in the request's directory, then each one above it.
315
+ const segments = path.split("/").slice(0, -1);
316
+ for (let depth = segments.length; depth >= 0; depth -= 1) {
317
+ const candidate = [...segments.slice(0, depth), "404.html"].join("/");
318
+ if (has(candidate)) {
319
+ return { kind: "file", path: candidate, status: 404 };
320
+ }
321
+ }
322
+ return { kind: "none" };
323
+ }
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The media type a file of a set is served with (P081): Porthole's own table, by the path's
3
+ * extension, never the uploader's word and never sniffed. A file whose extension isn't here is
4
+ * `application/octet-stream`, served as a download. Pure: any runtime.
5
+ */
6
+
7
+ /** How a type is served: a page (in the shell), a script (it may run as a worker), or a file. */
8
+ export type FileRole = "page" | "script" | "file";
9
+
10
+ export interface FileType {
11
+ /** The `content-type` header. */
12
+ readonly type: string;
13
+ readonly role: FileRole;
14
+ }
15
+
16
+ const UTF8 = "; charset=utf-8";
17
+
18
+ /** Extension (lowercase, no dot) to media type. Standard web types only. */
19
+ const TABLE: Readonly<Record<string, string>> = {
20
+ html: `text/html${UTF8}`,
21
+ htm: `text/html${UTF8}`,
22
+ css: `text/css${UTF8}`,
23
+ js: `text/javascript${UTF8}`,
24
+ mjs: `text/javascript${UTF8}`,
25
+ cjs: `text/javascript${UTF8}`,
26
+ json: `application/json${UTF8}`,
27
+ map: `application/json${UTF8}`,
28
+ webmanifest: `application/manifest+json${UTF8}`,
29
+ txt: `text/plain${UTF8}`,
30
+ md: `text/markdown${UTF8}`,
31
+ markdown: `text/markdown${UTF8}`,
32
+ csv: `text/csv${UTF8}`,
33
+ tsv: `text/tab-separated-values${UTF8}`,
34
+ xml: `application/xml${UTF8}`,
35
+ vtt: `text/vtt${UTF8}`,
36
+ svg: "image/svg+xml",
37
+ png: "image/png",
38
+ jpg: "image/jpeg",
39
+ jpeg: "image/jpeg",
40
+ gif: "image/gif",
41
+ webp: "image/webp",
42
+ avif: "image/avif",
43
+ ico: "image/x-icon",
44
+ bmp: "image/bmp",
45
+ woff: "font/woff",
46
+ woff2: "font/woff2",
47
+ ttf: "font/ttf",
48
+ otf: "font/otf",
49
+ mp3: "audio/mpeg",
50
+ wav: "audio/wav",
51
+ ogg: "audio/ogg",
52
+ oga: "audio/ogg",
53
+ opus: "audio/ogg",
54
+ m4a: "audio/mp4",
55
+ flac: "audio/flac",
56
+ aac: "audio/aac",
57
+ mp4: "video/mp4",
58
+ m4v: "video/mp4",
59
+ webm: "video/webm",
60
+ ogv: "video/ogg",
61
+ wasm: "application/wasm",
62
+ pdf: "application/pdf",
63
+ glb: "model/gltf-binary",
64
+ gltf: `model/gltf+json${UTF8}`,
65
+ zip: "application/zip",
66
+ };
67
+
68
+ /** What a file whose extension isn't in the table is served as: a download. */
69
+ export const UNKNOWN_TYPE = "application/octet-stream";
70
+
71
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
72
+ export function extensionOf(path: string): string {
73
+ const last = path.slice(path.lastIndexOf("/") + 1);
74
+ const dot = last.lastIndexOf(".");
75
+ return dot <= 0 ? "" : last.slice(dot + 1).toLowerCase();
76
+ }
77
+
78
+ /** The type a path is served with, and how. */
79
+ export function fileTypeOf(path: string): FileType {
80
+ const extension = extensionOf(path);
81
+ const type = Object.hasOwn(TABLE, extension) ? TABLE[extension] : undefined;
82
+ if (type === undefined) {
83
+ return { type: UNKNOWN_TYPE, role: "file" };
84
+ }
85
+ const role: FileRole =
86
+ extension === "html" || extension === "htm"
87
+ ? "page"
88
+ : type.startsWith("text/javascript")
89
+ ? "script"
90
+ : "file";
91
+ return { type, role };
92
+ }
93
+
94
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
95
+ export const knownType = (path: string): boolean => fileTypeOf(path).type !== UNKNOWN_TYPE;
96
+
97
+ /** Whether a path names a page: an `.html` file. */
98
+ export const isPagePath = (path: string): boolean => fileTypeOf(path).role === "page";
99
+
100
+ /** Every extension the table knows, for the manual and tests. */
101
+ export const KNOWN_EXTENSIONS: readonly string[] = Object.keys(TABLE);
@@ -14,6 +14,7 @@ import {
14
14
  librarySources,
15
15
  type EgressKind,
16
16
  } from "../compile/policy.ts";
17
+ import { fileLimits, servesFiles } from "../files/paths.ts";
17
18
  import { VENDORED_LIBRARIES, libraryPath } from "../libraries/libraries.ts";
18
19
  import { shellPlan } from "../shell/plan.ts";
19
20
  import { themeDefault } from "../theme/variables.ts";
@@ -108,6 +109,23 @@ const sourcesFor = (config: PortholeConfig, kind: EgressKind): string[] => [
108
109
  /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
109
110
  const servesLibraries = (config: PortholeConfig): boolean => librarySources(config).length > 0;
110
111
 
112
+ /** The manual's lines on a page's own files (P081-P084), where it may have them. */
113
+ function files(config: PortholeConfig): string | null {
114
+ if (!servesFiles(config)) {
115
+ return null;
116
+ }
117
+ const limits = fileLimits(config.limits);
118
+ const downloads = config.capabilities.downloadFile !== undefined;
119
+ return lines(
120
+ "Files: a page may come with files of its own (stylesheets, scripts and modules, images, fonts, data, workers, other pages), published beside it, with index.html the page it opens at.",
121
+ '- Name them by relative path (./style.css, assets/app.js, data.json), never with a leading / or a full address: a page loads only its own version\'s files. fetch("./data.json") works; a module\'s imports and a worker\'s script resolve from the module (new Worker(new URL("./worker.js", import.meta.url))).',
122
+ `- A link to another of your pages (about.html, or about; docs/ for docs/index.html) opens it in place. A link to any other file doesn't open: show an image with <img>${downloads ? ", offer a file with downloadFile" : ""}. A missing path shows your 404.html, if you publish one.`,
123
+ "- Paths are case-sensitive, relative, with no .., //, \\, %, ? or #. Each file is served as its extension says (.html a page, .js and .mjs scripts, .css, .json, .txt, .svg, .png, .woff2, .mp4, …), never as what it holds; an extension the server doesn't know is a download.",
124
+ '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.',
125
+ `- At most ${limits.maxFiles.toLocaleString("en-US")} files, ${sizeWords(limits.maxFileBytes)} each (a page under ${sizeWords(config.limits.maxBytes)}) and ${sizeWords(limits.maxVersionBytes)} in all.`,
126
+ );
127
+ }
128
+
111
129
  /** What content may load, in prose, from the same origins the CSP lists. */
112
130
  function network(config: PortholeConfig): string {
113
131
  const kinds: EgressKind[] = ["script", "style", "font", "img", "media", "connect"];
@@ -242,6 +260,8 @@ function widget(c: Context): string {
242
260
  "The sandbox:",
243
261
  ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`),
244
262
  `Keep it under ${sizeWords(limits.maxBytes)}.`,
263
+ servesFiles(config) ? "" : null,
264
+ files(config),
245
265
  loadsScripts(config)
246
266
  ? "\nLibraries: pin an exact version at least two weeks old (chart.js@4.4.1 in its URL), never @latest or a range, so the code can't be swapped under you and draws the same every time."
247
267
  : null,
@@ -382,7 +402,7 @@ function gateWords(gates: readonly Gate[], effect: string): string {
382
402
  const sentences: string[] = [];
383
403
  if (gates.includes("consent")) {
384
404
  sentences.push(
385
- "The first data call asks the person to allow it; if they don't, every one fails (show that the data isn't allowed, not an error).",
405
+ "The first data call asks the person to allow it; if they don't, every one fails with code denied (show that the data isn't allowed, not an error).",
386
406
  );
387
407
  }
388
408
  if (gates.includes("confirm")) {
@@ -401,6 +421,20 @@ function gateWords(gates: readonly Gate[], effect: string): string {
401
421
  return sentences.join(" ");
402
422
  }
403
423
 
424
+ /**
425
+ * What a data refusal tells content (P080): the codes and the sentence, for the author to draw. With
426
+ * the shell's globals they are the error's own fields; without, the JSON-RPC error's data.
427
+ */
428
+ function refusalWords(c: Context, global: boolean): string {
429
+ const where = global
430
+ ? "The error's code says why"
431
+ : "A refusal is an error whose data is { code, message }; code says why";
432
+ return `${where}: consent_required (not allowed yet), denied (the person said no), rate_limited, not_allowed (not here: some places show the ${c.noun} without data) or failed; ${global ? "its" : ""} message is a sentence for the person. Draw the ${c.noun} without that data, with that sentence where it would be; don't retry in a loop.`.replace(
433
+ / {2,}/gu,
434
+ " ",
435
+ );
436
+ }
437
+
404
438
  const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Gate[]) => string } =
405
439
  {
406
440
  sendPrompt: (c, gates) =>
@@ -417,11 +451,11 @@ const ENTRIES: { readonly [N in CapabilityName]: (c: Context, gates: readonly Ga
417
451
  `- Tools: the MCP Apps request tools/call (with the App SDK, app.callServerTool). ${gateWords(gates, "the call")}`,
418
452
  readData: (c, gates) =>
419
453
  c.global("readData")
420
- ? `- readData(uri): reads the app's data at uri (a resource the app names), as the person viewing the ${c.noun} may see it, and returns a promise of it: JSON parsed, else text. ${gateWords(gates, "the request")} It rejects when the app refuses or fails: draw the ${c.noun} without that data, saying why.`
421
- : `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")}`,
454
+ ? `- readData(uri): reads the app's data at uri (a resource the app names), as the person viewing the ${c.noun} may see it, and returns a promise of it: JSON parsed, else text. ${gateWords(gates, "the request")} It rejects when the app refuses or fails. ${refusalWords(c, true)}`
455
+ : `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")} ${refusalWords(c, false)}`,
422
456
  subscribeData: (c, gates) =>
423
457
  c.global("subscribeData")
424
- ? `- subscribeData(uri, onData, onError): keeps the ${c.noun} current. It calls onData(value, { stale }) with the data at uri now, and again each time it changes; the first value may be the app's last copy (stale: true), with the current one right after. It returns a function that stops it. onError(error) hears a refusal. ${gateWords(gates, "the request")} Draw from onData every time; don't poll.`
458
+ ? `- subscribeData(uri, onData, onError): keeps the ${c.noun} current. It calls onData(value, { stale }) with the data at uri now, and again each time it changes; the first value may be the app's last copy (stale: true), with the current one right after. It returns a function that stops it. onError(error) hears a refusal, with the same code and message as readData's. ${gateWords(gates, "the request")} Draw from onData every time; don't poll.`
425
459
  : `- Live data: the MCP request resources/subscribe with { uri }; the app then sends notifications/resources/updated with { uri } each time it changes: read it again (resources/read). resources/unsubscribe stops it. ${gateWords(gates, "the request")}`,
426
460
  setModelContext: (_c, gates) =>
427
461
  `- Context for the agent: the MCP Apps request ui/update-model-context (with the App SDK, app.updateModelContext). ${gateWords(gates, "it")}`,
@@ -8,7 +8,9 @@ import { annotateMode, checkMarks, parseReport } from "../annotate/validate.ts";
8
8
  import { createBridge, onceConsent, type BridgeEvent } from "../bridge/bridge.ts";
9
9
  import type { HostFunctionBridge } from "../bridge/types.ts";
10
10
  import { compile } from "../compile/compile.ts";
11
- import { declaredCapabilities } from "../compile/policy.ts";
11
+ import { servesFiles } from "../files/paths.ts";
12
+ import { declaredCapabilities, effectiveGates } from "../compile/policy.ts";
13
+ import { isRefused } from "../bridge/refusal.ts";
12
14
  import { capabilitySpec } from "../config/capabilities.ts";
13
15
  import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
14
16
  import { locateServed } from "./locate.ts";
@@ -37,6 +39,8 @@ import type {
37
39
  /** How long a display may take to load before its outcome is a timeout, by default. */
38
40
  const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
39
41
 
42
+ /** How long a set's page said its next load is another of its pages (P084), ms. */
43
+ const PAGE_OF_SET_MS = 10_000;
40
44
  /** How many times a display is started again after its content navigated its frame away. */
41
45
  const MAX_RESTARTS = 3;
42
46
 
@@ -79,10 +83,14 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
79
83
  compiled,
80
84
  mount(container: HTMLElement, mount: MountOptions): DisplayHandle<C> {
81
85
  const handlers = { ...options.handlers, ...mount.handlers };
86
+ // A host whose consent is a Refused refuses every consent-gated call before its handler:
87
+ // those need none (P080).
88
+ const refusesAll = isRefused(options.consent);
82
89
  const missing = declaredCapabilities(config).filter(
83
90
  (name) =>
84
91
  capabilitySpec(name).served === "handler" &&
85
- (handlers as Record<string, unknown>)[name] === undefined,
92
+ (handlers as Record<string, unknown>)[name] === undefined &&
93
+ !(refusesAll && effectiveGates(config, name).includes("consent")),
86
94
  );
87
95
  if (missing.length > 0) {
88
96
  throw new TypeError(`No handler for the declared capabilities: ${missing.join(", ")}`);
@@ -116,9 +124,15 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
116
124
  let connection: C | null = null;
117
125
  let destroyed = false;
118
126
  let restarts = 0;
127
+ // Until when the frame's next load is another page of its own set, as its content said (P084).
128
+ let pageOfSetUntil = 0;
119
129
  let generation = 0;
120
- // The viewer's answer for this display (P079): asked once, kept across its frames.
121
- const consent = options.consent === undefined ? undefined : onceConsent(options.consent);
130
+ // The viewer's answer for this display (P079): asked once, kept across its frames; or the
131
+ // host's refusal of them all (P080).
132
+ const consent =
133
+ options.consent === undefined || isRefused(options.consent)
134
+ ? options.consent
135
+ : onceConsent(options.consent);
122
136
  let abort: AbortController | null = null;
123
137
  let outcomeWatch: OutcomeWatch | null = null;
124
138
  let themeFrame: number | null = null;
@@ -291,6 +305,9 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
291
305
  });
292
306
  return;
293
307
  }
308
+ case "navigationBlocked":
309
+ emit("navigationBlocked", { url: event.url });
310
+ return;
294
311
  case "error":
295
312
  contentError(event.message);
296
313
  return;
@@ -308,6 +325,7 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
308
325
 
309
326
  const stop = () => {
310
327
  handshaken = false;
328
+ pageOfSetUntil = 0;
311
329
  abort?.abort();
312
330
  abort = null;
313
331
  outcomeWatch?.stop();
@@ -378,6 +396,14 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
378
396
  hostInfo,
379
397
  hostContext,
380
398
  emit: (event) => {
399
+ if (event.type === "navigating") {
400
+ // Only a display whose pages may come with files (P084), for the next load only, and
401
+ // only soon: content can't bank it to skip a restart later (P031).
402
+ if (servesFiles(config)) {
403
+ pageOfSetUntil = Date.now() + PAGE_OF_SET_MS;
404
+ }
405
+ return;
406
+ }
381
407
  if (event.type === "initialized") {
382
408
  watch.initialized();
383
409
  if (!handshaken) {
@@ -394,6 +420,13 @@ export function createHost<C extends AdapterConnection = ShellConnection>(
394
420
  (opened as unknown as Record<string, (...each: unknown[]) => unknown>)[name]?.(...args);
395
421
  }
396
422
  created.onNavigated(() => {
423
+ // Another page of the content's own set (P084): the same content, still connected (the
424
+ // new page's shell says hello again on the same transport). Not a restart.
425
+ const ofSet = pageOfSetUntil > Date.now();
426
+ pageOfSetUntil = 0;
427
+ if (ofSet) {
428
+ return;
429
+ }
397
430
  emit("navigated", undefined);
398
431
  if (restarts < MAX_RESTARTS) {
399
432
  restarts += 1;
package/src/host/types.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { AnnotateMode, AnnotationMark, AnnotationReport } from "../annotate/types.ts";
2
+ import type { Refused } from "../bridge/refusal.ts";
2
3
  import type { Confirm, CapabilityHandlers, Consent, DataCache, Refusal } from "../bridge/types.ts";
3
4
  import type { CompiledConfig } from "../compile/compile.ts";
4
5
  import type { CapabilityName } from "../config/capabilities.ts";
@@ -22,9 +23,11 @@ export interface HostOptions<C extends AdapterConnection = ShellConnection> {
22
23
  /**
23
24
  * Whether a display may make its `consent`-gated calls (read the viewer's data, P079): asked
24
25
  * once per display, before the first, and kept for the display's life (its reloads too).
25
- * Absent: those calls are refused.
26
+ * Absent: those calls are refused. A `Refused` instead of a function refuses every one with its
27
+ * reason, asking nothing, and those capabilities need no handler (a page where live data must
28
+ * not run, P080).
26
29
  */
27
- readonly consent?: Consent;
30
+ readonly consent?: Consent | Refused;
28
31
  /**
29
32
  * What the host last had for a resource (P079): a read of one the content subscribes to is
30
33
  * answered with it at once, marked stale, then with the handler's fresh result.
@@ -154,6 +157,14 @@ export interface DisplayEvents {
154
157
  readonly error: { readonly message: string; readonly source: "content" | "host" };
155
158
  /** The content navigated its frame away; the frame was started again from its content. */
156
159
  readonly navigated: undefined;
160
+ /**
161
+ * The shell stopped the content navigating its frame to `url` (P079, P080): the address whole,
162
+ * as the content gave it (its word: untrusted, may carry data in its query). Only where the
163
+ * config declares `reportError` (it counts as one of the run's reports), and only in frames with
164
+ * an origin of their own (served): an opaque frame's navigations get no events. A
165
+ * `contentError` follows, naming the address without its query or fragment.
166
+ */
167
+ readonly navigationBlocked: { readonly url: string };
157
168
  /** A call didn't run. */
158
169
  readonly refused: { readonly capability: CapabilityName; readonly refusal: Refusal };
159
170
  /** Too many declines: the display stops asking until it runs again. */