@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,99 @@
1
+ import type { Limits, PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * A version made of files (P081): the rules a published path follows, the limits a version is
4
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
5
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
6
+ * only, never on a filesystem.
7
+ */
8
+ /** The most files a version holds, by default. */
9
+ export declare const DEFAULT_MAX_FILES = 1000;
10
+ /** The largest file of a version, bytes, by default (25 MiB). */
11
+ export declare const DEFAULT_MAX_FILE_BYTES: number;
12
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
13
+ export declare const DEFAULT_MAX_VERSION_BYTES: number;
14
+ /** The longest path, characters, and the longest segment of one. */
15
+ export declare const MAX_FILE_PATH_CHARS = 512;
16
+ export declare const MAX_SEGMENT_CHARS = 255;
17
+ /** The page a version opens at by default. */
18
+ export declare const DEFAULT_ENTRY = "index.html";
19
+ /**
20
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
21
+ * origin of its own. Opaque frames have no origin to serve them from.
22
+ */
23
+ export declare const servesFiles: (config: PortholeConfig) => boolean;
24
+ export interface FileLimits {
25
+ readonly maxFiles: number;
26
+ readonly maxFileBytes: number;
27
+ readonly maxVersionBytes: number;
28
+ }
29
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
30
+ export declare function fileLimits(limits?: Partial<Limits> | null): FileLimits;
31
+ /**
32
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
33
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
34
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
35
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
36
+ */
37
+ export declare function filePathProblem(path: unknown): string | null;
38
+ /** A published path's metadata, as far as the checks read it. */
39
+ export interface FileSetEntryLike {
40
+ readonly size: number;
41
+ }
42
+ export interface FileSetProblem {
43
+ /** The path it is about, where it is about one. */
44
+ readonly path?: string;
45
+ readonly code: "path" | "collision" | "count" | "size" | "total" | "entry";
46
+ /** What to change, for the agent or the person publishing. */
47
+ readonly message: string;
48
+ }
49
+ /**
50
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
51
+ * two paths that differ only in case, and no path that is both a file and a directory; the
52
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
53
+ * `fileLimits`). Empty when it may be published.
54
+ */
55
+ export declare function checkFileSet(files: Readonly<Record<string, FileSetEntryLike>>, options?: {
56
+ readonly entry?: string;
57
+ readonly limits?: FileLimits;
58
+ }): FileSetProblem[];
59
+ /**
60
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
61
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
62
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
63
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
64
+ * `/` stays (a directory).
65
+ */
66
+ export declare function requestFilePath(raw: string): string | null;
67
+ /** What a request's path finds in a version's manifest. */
68
+ export type FileLookup =
69
+ /** The file to answer with, and its status (404 for a `404.html`). */
70
+ {
71
+ readonly kind: "file";
72
+ readonly path: string;
73
+ readonly status: 200 | 404;
74
+ }
75
+ /** The canonical address: `dir` → `dir/` (or `page/` → `page`), relative to the base. */
76
+ | {
77
+ readonly kind: "redirect";
78
+ readonly to: string;
79
+ }
80
+ /** Nothing: a plain 404. */
81
+ | {
82
+ readonly kind: "none";
83
+ };
84
+ export interface LookupOptions {
85
+ /** The page the version opens at (default `index.html`). */
86
+ readonly entry?: string;
87
+ /** A single-page app's routes: a navigation that finds nothing answers the entry. */
88
+ readonly spa?: boolean;
89
+ /** Whether the request is a navigation (a page loading), not a subresource. */
90
+ readonly navigation: boolean;
91
+ }
92
+ /**
93
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
94
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
95
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
96
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
97
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
98
+ */
99
+ export declare function lookupFile(has: (path: string) => boolean, path: string, options: LookupOptions): FileLookup;
@@ -0,0 +1,263 @@
1
+ /**
2
+ * A version made of files (P081): the rules a published path follows, the limits a version is
3
+ * held to, and how a request's path finds its file. Pure: any runtime. A host checks a version
4
+ * with `checkFileSet` when it is published; `/server` looks paths up in the version's manifest
5
+ * only, never on a filesystem.
6
+ */
7
+ /** The most files a version holds, by default. */
8
+ export const DEFAULT_MAX_FILES = 1_000;
9
+ /** The largest file of a version, bytes, by default (25 MiB). */
10
+ export const DEFAULT_MAX_FILE_BYTES = 25 * 1024 * 1024;
11
+ /** A version's files together, bytes, by default (100 MiB): a host sets its own. */
12
+ export const DEFAULT_MAX_VERSION_BYTES = 100 * 1024 * 1024;
13
+ /** The longest path, characters, and the longest segment of one. */
14
+ export const MAX_FILE_PATH_CHARS = 512;
15
+ export const MAX_SEGMENT_CHARS = 255;
16
+ /** The page a version opens at by default. */
17
+ export const DEFAULT_ENTRY = "index.html";
18
+ /**
19
+ * Whether a config's pages may come with files of their own (P081): an artifact served on an
20
+ * origin of its own. Opaque frames have no origin to serve them from.
21
+ */
22
+ export const servesFiles = (config) => config.mode === "artifact" && config.isolation === "domain";
23
+ /** A config's file limits (`limits.maxFiles`, …), with the defaults where it names none. */
24
+ export function fileLimits(limits) {
25
+ return {
26
+ maxFiles: limits?.maxFiles ?? DEFAULT_MAX_FILES,
27
+ maxFileBytes: limits?.maxFileBytes ?? DEFAULT_MAX_FILE_BYTES,
28
+ maxVersionBytes: limits?.maxVersionBytes ?? DEFAULT_MAX_VERSION_BYTES,
29
+ };
30
+ }
31
+ /**
32
+ * What a request's path can never hold once decoded, and a published path never holds: control
33
+ * and format characters (`Cc`, `Cf`: a right-to-left override, a zero-width space, a BOM would make
34
+ * a path read as another), and `\ % ? #`.
35
+ */
36
+ // oxlint-disable-next-line no-control-regex -- control characters are what it refuses
37
+ const FORBIDDEN = /[\p{Cc}\p{Cf}\\%?#]/u;
38
+ /**
39
+ * What is wrong with a published path, or null: relative (no leading `/`), `/`-separated, no
40
+ * empty, `.` or `..` segment, none of `\ % ? #` or a control character, in Unicode NFC, no segment
41
+ * starting or ending with a space, at most 512 characters and 255 a segment, not under
42
+ * `__porthole/` (Porthole's own paths at an origin's root). Case-sensitive.
43
+ */
44
+ export function filePathProblem(path) {
45
+ if (typeof path !== "string" || path.length === 0) {
46
+ return "a path is a non-empty string";
47
+ }
48
+ if (path.length > MAX_FILE_PATH_CHARS) {
49
+ return `a path is at most ${MAX_FILE_PATH_CHARS} characters`;
50
+ }
51
+ if (path.startsWith("/")) {
52
+ return "a path is relative: no leading /";
53
+ }
54
+ if (path.endsWith("/")) {
55
+ return "a path names a file: no trailing /";
56
+ }
57
+ const forbidden = FORBIDDEN.exec(path);
58
+ if (forbidden !== null) {
59
+ const char = forbidden[0];
60
+ return `a path holds no ${char === "\\" || char === "%" || char === "?" || char === "#" ? char : "control or format character"}`;
61
+ }
62
+ if (path.normalize("NFC") !== path) {
63
+ return "a path is in Unicode NFC";
64
+ }
65
+ const segments = path.split("/");
66
+ for (const segment of segments) {
67
+ if (segment === "") {
68
+ return "a path has no empty segment (//)";
69
+ }
70
+ if (segment === "." || segment === "..") {
71
+ return `a path has no ${segment} segment`;
72
+ }
73
+ if (segment.length > MAX_SEGMENT_CHARS) {
74
+ return `a path's segment is at most ${MAX_SEGMENT_CHARS} characters`;
75
+ }
76
+ if (segment.startsWith(" ") || segment.endsWith(" ")) {
77
+ return "a path's segment doesn't start or end with a space";
78
+ }
79
+ }
80
+ if (segments[0] === "__porthole") {
81
+ return "__porthole/ is Porthole's own";
82
+ }
83
+ return null;
84
+ }
85
+ const sizeOf = (bytes) => bytes >= 1024 * 1024
86
+ ? `${Math.round((bytes / (1024 * 1024)) * 10) / 10} MiB`
87
+ : bytes >= 1024
88
+ ? `${Math.round(bytes / 1024)} KiB`
89
+ : `${bytes} bytes`;
90
+ /**
91
+ * Checks a version's files before it is published (P081): every path by `filePathProblem`; no
92
+ * two paths that differ only in case, and no path that is both a file and a directory; the
93
+ * entry is one of them; the count, each size and the total within the limits (a config's, see
94
+ * `fileLimits`). Empty when it may be published.
95
+ */
96
+ export function checkFileSet(files, options = {}) {
97
+ const limits = options.limits ?? fileLimits();
98
+ const problems = [];
99
+ const paths = Object.keys(files);
100
+ if (paths.length > limits.maxFiles) {
101
+ problems.push({
102
+ code: "count",
103
+ message: `${paths.length} files: a version holds at most ${limits.maxFiles}`,
104
+ });
105
+ }
106
+ const folded = new Map();
107
+ const directories = new Set();
108
+ let total = 0;
109
+ for (const path of paths) {
110
+ const problem = filePathProblem(path);
111
+ if (problem !== null) {
112
+ problems.push({ path, code: "path", message: `${JSON.stringify(path)}: ${problem}` });
113
+ continue;
114
+ }
115
+ const lower = path.toLowerCase();
116
+ const other = folded.get(lower);
117
+ if (other !== undefined) {
118
+ problems.push({
119
+ path,
120
+ code: "collision",
121
+ message: `${JSON.stringify(path)} and ${JSON.stringify(other)} differ only in case: rename one`,
122
+ });
123
+ }
124
+ else {
125
+ folded.set(lower, path);
126
+ }
127
+ const segments = path.split("/");
128
+ for (let index = 1; index < segments.length; index += 1) {
129
+ directories.add(segments.slice(0, index).join("/"));
130
+ }
131
+ const size = files[path]?.size;
132
+ if (typeof size !== "number" || !Number.isInteger(size) || size < 0) {
133
+ problems.push({ path, code: "size", message: `${JSON.stringify(path)}: no size` });
134
+ continue;
135
+ }
136
+ if (size > limits.maxFileBytes) {
137
+ problems.push({
138
+ path,
139
+ code: "size",
140
+ message: `${JSON.stringify(path)} is ${sizeOf(size)}: a file is at most ${sizeOf(limits.maxFileBytes)}`,
141
+ });
142
+ }
143
+ total += size;
144
+ }
145
+ for (const path of paths) {
146
+ if (directories.has(path)) {
147
+ problems.push({
148
+ path,
149
+ code: "collision",
150
+ message: `${JSON.stringify(path)} is a file and a directory: rename one`,
151
+ });
152
+ }
153
+ }
154
+ if (total > limits.maxVersionBytes) {
155
+ problems.push({
156
+ code: "total",
157
+ message: `The files are ${sizeOf(total)} together: a version holds at most ${sizeOf(limits.maxVersionBytes)}`,
158
+ });
159
+ }
160
+ const entry = options.entry ?? DEFAULT_ENTRY;
161
+ if (!Object.hasOwn(files, entry)) {
162
+ problems.push({
163
+ path: entry,
164
+ code: "entry",
165
+ message: `No ${JSON.stringify(entry)}: the page the version opens at is one of its files`,
166
+ });
167
+ }
168
+ return problems;
169
+ }
170
+ /**
171
+ * A request's path below a version's base, decoded once, as the key it looks up: null where it
172
+ * can name no file (a segment that doesn't decode, or decodes to one holding `/ \ % ? #` or a
173
+ * control character, or is `.` or `..`). The URL parser has already removed the dot segments it
174
+ * sees (`.`, `..`, `%2e`); anything left of that kind is refused rather than resolved. A trailing
175
+ * `/` stays (a directory).
176
+ */
177
+ export function requestFilePath(raw) {
178
+ if (raw.length > MAX_FILE_PATH_CHARS * 3 + 1) {
179
+ return null;
180
+ }
181
+ const segments = raw.split("/");
182
+ const decoded = [];
183
+ for (const [index, segment] of segments.entries()) {
184
+ if (segment === "") {
185
+ // Only the last segment may be empty: a directory's trailing slash (or the base itself).
186
+ if (index !== segments.length - 1) {
187
+ return null;
188
+ }
189
+ decoded.push("");
190
+ continue;
191
+ }
192
+ let value;
193
+ try {
194
+ value = decodeURIComponent(segment);
195
+ }
196
+ catch {
197
+ return null;
198
+ }
199
+ if (value === "." || value === ".." || value.includes("/") || FORBIDDEN.test(value)) {
200
+ return null;
201
+ }
202
+ decoded.push(value);
203
+ }
204
+ return decoded.join("/");
205
+ }
206
+ /**
207
+ * Finds a request's file in a version's manifest (P081), as static hosts do (Cloudflare's
208
+ * `auto-trailing-slash`): `""` is the entry; `dir/` is `dir/index.html`; `name` is `name`, else
209
+ * `name.html`, else `dir/` when `name/index.html` exists; `name/` with no index but a
210
+ * `name.html` goes to `name`. What finds nothing: for a navigation, the entry when the version is
211
+ * a single-page app, else the nearest `404.html` (status 404); otherwise none.
212
+ */
213
+ export function lookupFile(has, path, options) {
214
+ const entry = options.entry ?? DEFAULT_ENTRY;
215
+ if (path === "") {
216
+ if (!has(entry)) {
217
+ return notFound(has, "", options);
218
+ }
219
+ // An entry in a directory opens there, so its relative addresses are its directory's.
220
+ return entry.includes("/")
221
+ ? { kind: "redirect", to: entry }
222
+ : { kind: "file", path: entry, status: 200 };
223
+ }
224
+ if (path.endsWith("/")) {
225
+ const index = `${path}index.html`;
226
+ if (has(index)) {
227
+ return { kind: "file", path: index, status: 200 };
228
+ }
229
+ const page = `${path.slice(0, -1)}.html`;
230
+ if (has(page)) {
231
+ return { kind: "redirect", to: path.slice(0, -1) };
232
+ }
233
+ return notFound(has, path, options);
234
+ }
235
+ if (has(path)) {
236
+ return { kind: "file", path, status: 200 };
237
+ }
238
+ if (has(`${path}.html`)) {
239
+ return { kind: "file", path: `${path}.html`, status: 200 };
240
+ }
241
+ if (has(`${path}/index.html`)) {
242
+ return { kind: "redirect", to: `${path}/` };
243
+ }
244
+ return notFound(has, path, options);
245
+ }
246
+ function notFound(has, path, options) {
247
+ if (!options.navigation) {
248
+ return { kind: "none" };
249
+ }
250
+ const entry = options.entry ?? DEFAULT_ENTRY;
251
+ if (options.spa === true && has(entry)) {
252
+ return { kind: "file", path: entry, status: 200 };
253
+ }
254
+ // The nearest 404.html: in the request's directory, then each one above it.
255
+ const segments = path.split("/").slice(0, -1);
256
+ for (let depth = segments.length; depth >= 0; depth -= 1) {
257
+ const candidate = [...segments.slice(0, depth), "404.html"].join("/");
258
+ if (has(candidate)) {
259
+ return { kind: "file", path: candidate, status: 404 };
260
+ }
261
+ }
262
+ return { kind: "none" };
263
+ }
@@ -0,0 +1,24 @@
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
+ /** How a type is served: a page (in the shell), a script (it may run as a worker), or a file. */
7
+ export type FileRole = "page" | "script" | "file";
8
+ export interface FileType {
9
+ /** The `content-type` header. */
10
+ readonly type: string;
11
+ readonly role: FileRole;
12
+ }
13
+ /** What a file whose extension isn't in the table is served as: a download. */
14
+ export declare const UNKNOWN_TYPE = "application/octet-stream";
15
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
16
+ export declare function extensionOf(path: string): string;
17
+ /** The type a path is served with, and how. */
18
+ export declare function fileTypeOf(path: string): FileType;
19
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
20
+ export declare const knownType: (path: string) => boolean;
21
+ /** Whether a path names a page: an `.html` file. */
22
+ export declare const isPagePath: (path: string) => boolean;
23
+ /** Every extension the table knows, for the manual and tests. */
24
+ export declare const KNOWN_EXTENSIONS: readonly string[];
@@ -0,0 +1,83 @@
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
+ const UTF8 = "; charset=utf-8";
7
+ /** Extension (lowercase, no dot) to media type. Standard web types only. */
8
+ const TABLE = {
9
+ html: `text/html${UTF8}`,
10
+ htm: `text/html${UTF8}`,
11
+ css: `text/css${UTF8}`,
12
+ js: `text/javascript${UTF8}`,
13
+ mjs: `text/javascript${UTF8}`,
14
+ cjs: `text/javascript${UTF8}`,
15
+ json: `application/json${UTF8}`,
16
+ map: `application/json${UTF8}`,
17
+ webmanifest: `application/manifest+json${UTF8}`,
18
+ txt: `text/plain${UTF8}`,
19
+ md: `text/markdown${UTF8}`,
20
+ markdown: `text/markdown${UTF8}`,
21
+ csv: `text/csv${UTF8}`,
22
+ tsv: `text/tab-separated-values${UTF8}`,
23
+ xml: `application/xml${UTF8}`,
24
+ vtt: `text/vtt${UTF8}`,
25
+ svg: "image/svg+xml",
26
+ png: "image/png",
27
+ jpg: "image/jpeg",
28
+ jpeg: "image/jpeg",
29
+ gif: "image/gif",
30
+ webp: "image/webp",
31
+ avif: "image/avif",
32
+ ico: "image/x-icon",
33
+ bmp: "image/bmp",
34
+ woff: "font/woff",
35
+ woff2: "font/woff2",
36
+ ttf: "font/ttf",
37
+ otf: "font/otf",
38
+ mp3: "audio/mpeg",
39
+ wav: "audio/wav",
40
+ ogg: "audio/ogg",
41
+ oga: "audio/ogg",
42
+ opus: "audio/ogg",
43
+ m4a: "audio/mp4",
44
+ flac: "audio/flac",
45
+ aac: "audio/aac",
46
+ mp4: "video/mp4",
47
+ m4v: "video/mp4",
48
+ webm: "video/webm",
49
+ ogv: "video/ogg",
50
+ wasm: "application/wasm",
51
+ pdf: "application/pdf",
52
+ glb: "model/gltf-binary",
53
+ gltf: `model/gltf+json${UTF8}`,
54
+ zip: "application/zip",
55
+ };
56
+ /** What a file whose extension isn't in the table is served as: a download. */
57
+ export const UNKNOWN_TYPE = "application/octet-stream";
58
+ /** The extension of a path's last segment, lowercase, without the dot ("" for none). */
59
+ export function extensionOf(path) {
60
+ const last = path.slice(path.lastIndexOf("/") + 1);
61
+ const dot = last.lastIndexOf(".");
62
+ return dot <= 0 ? "" : last.slice(dot + 1).toLowerCase();
63
+ }
64
+ /** The type a path is served with, and how. */
65
+ export function fileTypeOf(path) {
66
+ const extension = extensionOf(path);
67
+ const type = Object.hasOwn(TABLE, extension) ? TABLE[extension] : undefined;
68
+ if (type === undefined) {
69
+ return { type: UNKNOWN_TYPE, role: "file" };
70
+ }
71
+ const role = extension === "html" || extension === "htm"
72
+ ? "page"
73
+ : type.startsWith("text/javascript")
74
+ ? "script"
75
+ : "file";
76
+ return { type, role };
77
+ }
78
+ /** Whether Porthole's table names the path's extension (else it is served as a download). */
79
+ export const knownType = (path) => fileTypeOf(path).type !== UNKNOWN_TYPE;
80
+ /** Whether a path names a page: an `.html` file. */
81
+ export const isPagePath = (path) => fileTypeOf(path).role === "page";
82
+ /** Every extension the table knows, for the manual and tests. */
83
+ export const KNOWN_EXTENSIONS = Object.keys(TABLE);
@@ -1,6 +1,7 @@
1
1
  import { MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
2
2
  import { BUILT_IN_TOPICS } from "../config/validate.js";
3
3
  import { anyHttps, declaredCapabilities, effectiveGates, egressOrigins, librarySources, } from "../compile/policy.js";
4
+ import { fileLimits, servesFiles } from "../files/paths.js";
4
5
  import { VENDORED_LIBRARIES, libraryPath } from "../libraries/libraries.js";
5
6
  import { shellPlan } from "../shell/plan.js";
6
7
  import { themeDefault } from "../theme/variables.js";
@@ -54,6 +55,15 @@ const sourcesFor = (config, kind) => [
54
55
  ];
55
56
  /** Whether Porthole's own libraries load in the frame (`egress.libraries`, served, P079). */
56
57
  const servesLibraries = (config) => librarySources(config).length > 0;
58
+ /** The manual's lines on a page's own files (P081-P084), where it may have them. */
59
+ function files(config) {
60
+ if (!servesFiles(config)) {
61
+ return null;
62
+ }
63
+ const limits = fileLimits(config.limits);
64
+ const downloads = config.capabilities.downloadFile !== undefined;
65
+ return lines("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.", '- 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))).', `- 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.`, "- 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.", '- A build tool\'s output works when it writes relative paths (Vite: base: "./"). No service workers.', `- 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.`);
66
+ }
57
67
  /** What content may load, in prose, from the same origins the CSP lists. */
58
68
  function network(config) {
59
69
  const kinds = ["script", "style", "font", "img", "media", "connect"];
@@ -148,7 +158,7 @@ function widget(c) {
148
158
  const textSize = themeDefault(config.theme.variables["--font-text-md-size"] ?? "14px", "light").replace(/^(\d+(?:\.\d+)?)px$/u, "$1 px");
149
159
  return lines(`# ${title}${tool}`, "", what, "", `Where it runs: ${fills ? `in a sandboxed frame that fills the app's viewer (often smaller than the window: toolbars and side panels take room), about ${layout.narrowWidthPx} px wide on a phone (${layout.minWidthPx} on a small one) and wider on a desktop` : `in a sandboxed frame as wide as the column it sits in, about ${layout.narrowWidthPx} px on a phone (${layout.minWidthPx} on a small one) and ${layout.wideWidthPx} on a desktop`}; the same ${noun} is read on both, so never write for one of them. Design for ${layout.narrowWidthPx} first; where the layout depends on the width, read it as it runs (the ${fills ? "frame's own innerWidth, again on resize" : "box's clientWidth, again from a ResizeObserver"}). ${said("layout")} ${said("theme")} It runs again each time it is shown${loadsScripts(config) ? ": pin library versions" : ""}.`, "", "Sizes that read on a phone:", c.when(`- Words go in HTML (titles, notes, legends, readouts): it keeps its size and wraps. The frame's text is already ${textSize} --font-sans in --color-text-primary; notes --font-text-sm-size, never under 12 px.`), `- An SVG scales with the frame: its text shows at font-size × frame width ÷ viewBox width, so a 680-wide viewBox turns 12 into 5 px on a phone. Draw it for the phone: viewBox="0 0 ${viewBox} H", no text under 13, width="100%" style="max-width: 400px"; its text then shows at ${smallest} to ${largest} px on every screen. Or draw it 1 unit = 1 px with a script (topic chart).`, `- The frame never scrolls sideways: nothing fixed wider than ${layout.minWidthPx} px; images max-width: 100%; a grid or flex child with long text min-width: 0; a wide table or code block in its own box with overflow-x: auto.`, "- Cards in a row wrap (flex-wrap: wrap; flex: 1 1 100px), or a grid of repeat(auto-fit, minmax(160px, 1fr)): at most 2 columns under 500 px, never a fixed repeat(3, …).", "- Touch: anything clickable is at least 44 px tall. Phones don't hover: what a hover shows, a tap (click) shows too.", fills
150
160
  ? null
151
- : "- No position: fixed: the frame grows with its content, so a fixed element covers it.", "", "The sandbox:", ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`), `Keep it under ${sizeWords(limits.maxBytes)}.`, loadsScripts(config)
161
+ : "- No position: fixed: the frame grows with its content, so a fixed element covers it.", "", "The sandbox:", ...stated.filter((limit) => limit.topic === "sandbox").map((limit) => `- ${limit.text}`), `Keep it under ${sizeWords(limits.maxBytes)}.`, servesFiles(config) ? "" : null, files(config), loadsScripts(config)
152
162
  ? "\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."
153
163
  : null, ...ownCdns(config), ...ownLibraries(config), "", themeless
154
164
  ? `Colors: these variables hold the app's palette; use them, or colors of your own. Give the ${noun} its own background.`
@@ -218,7 +228,7 @@ function chart(c) {
218
228
  function gateWords(gates, effect) {
219
229
  const sentences = [];
220
230
  if (gates.includes("consent")) {
221
- sentences.push("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).");
231
+ sentences.push("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).");
222
232
  }
223
233
  if (gates.includes("confirm")) {
224
234
  sentences.push(`The app shows the person ${effect} first, and nothing happens unless they confirm.`);
@@ -233,6 +243,16 @@ function gateWords(gates, effect) {
233
243
  }
234
244
  return sentences.join(" ");
235
245
  }
246
+ /**
247
+ * What a data refusal tells content (P080): the codes and the sentence, for the author to draw. With
248
+ * the shell's globals they are the error's own fields; without, the JSON-RPC error's data.
249
+ */
250
+ function refusalWords(c, global) {
251
+ const where = global
252
+ ? "The error's code says why"
253
+ : "A refusal is an error whose data is { code, message }; code says why";
254
+ 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(/ {2,}/gu, " ");
255
+ }
236
256
  const ENTRIES = {
237
257
  sendPrompt: (c, gates) => c.global("sendPrompt")
238
258
  ? `- sendPrompt(text): asks to send text to you as the person's message (at most ${c.config.limits.maxPromptChars.toLocaleString("en-US")} characters). Use it for "explain this point", "try these settings". ${gateWords(gates, "the whole text")} It returns a promise: true if it was sent.`
@@ -243,10 +263,10 @@ const ENTRIES = {
243
263
  downloadFile: (_c, gates) => `- Downloads: the MCP Apps request ui/download-file (with the App SDK, app.downloadFile). ${gateWords(gates, "the file")}`,
244
264
  callTool: (_c, gates) => `- Tools: the MCP Apps request tools/call (with the App SDK, app.callServerTool). ${gateWords(gates, "the call")}`,
245
265
  readData: (c, gates) => c.global("readData")
246
- ? `- 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.`
247
- : `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")}`,
266
+ ? `- 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)}`
267
+ : `- Data: the MCP Apps request resources/read (with the App SDK, app.readServerResource). ${gateWords(gates, "the request")} ${refusalWords(c, false)}`,
248
268
  subscribeData: (c, gates) => c.global("subscribeData")
249
- ? `- 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.`
269
+ ? `- 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.`
250
270
  : `- 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")}`,
251
271
  setModelContext: (_c, gates) => `- Context for the agent: the MCP Apps request ui/update-model-context (with the App SDK, app.updateModelContext). ${gateWords(gates, "it")}`,
252
272
  copyText: (c, gates) => c.global("copyText")
@@ -2,7 +2,9 @@ import { ANNOTATE_METHODS, } from "../annotate/types.js";
2
2
  import { annotateMode, checkMarks, parseReport } from "../annotate/validate.js";
3
3
  import { createBridge, onceConsent } from "../bridge/bridge.js";
4
4
  import { compile } from "../compile/compile.js";
5
- import { declaredCapabilities } from "../compile/policy.js";
5
+ import { servesFiles } from "../files/paths.js";
6
+ import { declaredCapabilities, effectiveGates } from "../compile/policy.js";
7
+ import { isRefused } from "../bridge/refusal.js";
6
8
  import { capabilitySpec } from "../config/capabilities.js";
7
9
  import { locateServed } from "./locate.js";
8
10
  import { watchOutcome } from "./outcome.js";
@@ -12,6 +14,8 @@ import { shellAdapter } from "../protocol/shell-adapter.js";
12
14
  import { resolveTheme } from "../theme/variables.js";
13
15
  /** How long a display may take to load before its outcome is a timeout, by default. */
14
16
  const DEFAULT_LOAD_TIMEOUT_MS = 15_000;
17
+ /** How long a set's page said its next load is another of its pages (P084), ms. */
18
+ const PAGE_OF_SET_MS = 10_000;
15
19
  /** How many times a display is started again after its content navigated its frame away. */
16
20
  const MAX_RESTARTS = 3;
17
21
  const BASE_KEYS = new Set(["hostContextChanged", "teardown", "close"]);
@@ -43,8 +47,12 @@ export function createHost(config, options = {}) {
43
47
  compiled,
44
48
  mount(container, mount) {
45
49
  const handlers = { ...options.handlers, ...mount.handlers };
50
+ // A host whose consent is a Refused refuses every consent-gated call before its handler:
51
+ // those need none (P080).
52
+ const refusesAll = isRefused(options.consent);
46
53
  const missing = declaredCapabilities(config).filter((name) => capabilitySpec(name).served === "handler" &&
47
- handlers[name] === undefined);
54
+ handlers[name] === undefined &&
55
+ !(refusesAll && effectiveGates(config, name).includes("consent")));
48
56
  if (missing.length > 0) {
49
57
  throw new TypeError(`No handler for the declared capabilities: ${missing.join(", ")}`);
50
58
  }
@@ -75,9 +83,14 @@ export function createHost(config, options = {}) {
75
83
  let connection = null;
76
84
  let destroyed = false;
77
85
  let restarts = 0;
86
+ // Until when the frame's next load is another page of its own set, as its content said (P084).
87
+ let pageOfSetUntil = 0;
78
88
  let generation = 0;
79
- // The viewer's answer for this display (P079): asked once, kept across its frames.
80
- const consent = options.consent === undefined ? undefined : onceConsent(options.consent);
89
+ // The viewer's answer for this display (P079): asked once, kept across its frames; or the
90
+ // host's refusal of them all (P080).
91
+ const consent = options.consent === undefined || isRefused(options.consent)
92
+ ? options.consent
93
+ : onceConsent(options.consent);
81
94
  let abort = null;
82
95
  let outcomeWatch = null;
83
96
  let themeFrame = null;
@@ -241,6 +254,9 @@ export function createHost(config, options = {}) {
241
254
  });
242
255
  return;
243
256
  }
257
+ case "navigationBlocked":
258
+ emit("navigationBlocked", { url: event.url });
259
+ return;
244
260
  case "error":
245
261
  contentError(event.message);
246
262
  return;
@@ -257,6 +273,7 @@ export function createHost(config, options = {}) {
257
273
  };
258
274
  const stop = () => {
259
275
  handshaken = false;
276
+ pageOfSetUntil = 0;
260
277
  abort?.abort();
261
278
  abort = null;
262
279
  outcomeWatch?.stop();
@@ -326,6 +343,14 @@ export function createHost(config, options = {}) {
326
343
  hostInfo,
327
344
  hostContext,
328
345
  emit: (event) => {
346
+ if (event.type === "navigating") {
347
+ // Only a display whose pages may come with files (P084), for the next load only, and
348
+ // only soon: content can't bank it to skip a restart later (P031).
349
+ if (servesFiles(config)) {
350
+ pageOfSetUntil = Date.now() + PAGE_OF_SET_MS;
351
+ }
352
+ return;
353
+ }
329
354
  if (event.type === "initialized") {
330
355
  watch.initialized();
331
356
  if (!handshaken) {
@@ -342,6 +367,13 @@ export function createHost(config, options = {}) {
342
367
  opened[name]?.(...args);
343
368
  }
344
369
  created.onNavigated(() => {
370
+ // Another page of the content's own set (P084): the same content, still connected (the
371
+ // new page's shell says hello again on the same transport). Not a restart.
372
+ const ofSet = pageOfSetUntil > Date.now();
373
+ pageOfSetUntil = 0;
374
+ if (ofSet) {
375
+ return;
376
+ }
345
377
  emit("navigated", undefined);
346
378
  if (restarts < MAX_RESTARTS) {
347
379
  restarts += 1;