@botiverse/porthole 0.12.0 → 0.14.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 (94) hide show
  1. package/dist/annotate/types.d.ts +32 -3
  2. package/dist/annotate/types.js +4 -0
  3. package/dist/annotate/validate.js +19 -2
  4. package/dist/bridge/bridge.d.ts +8 -1
  5. package/dist/bridge/bridge.js +7 -0
  6. package/dist/bridge/unseen.d.ts +8 -0
  7. package/dist/bridge/unseen.js +17 -0
  8. package/dist/check/files.js +14 -10
  9. package/dist/check/lint.js +1 -1
  10. package/dist/check/page-source.js +1 -1
  11. package/dist/check/scroll.d.ts +29 -13
  12. package/dist/check/scroll.js +74 -18
  13. package/dist/compile/policy.d.ts +7 -0
  14. package/dist/compile/policy.js +13 -1
  15. package/dist/config/capabilities.d.ts +16 -3
  16. package/dist/config/capabilities.js +1 -0
  17. package/dist/config/schema.d.ts +11 -0
  18. package/dist/config/validate.js +19 -0
  19. package/dist/conformance/harness-source.js +1 -1
  20. package/dist/displays/displays.js +3 -1
  21. package/dist/guide/limits.js +1 -1
  22. package/dist/guide/runtime.js +1 -1
  23. package/dist/host/create-host.d.ts +2 -0
  24. package/dist/host/create-host.js +100 -3
  25. package/dist/host/pass-on.d.ts +15 -0
  26. package/dist/host/pass-on.js +65 -0
  27. package/dist/host/types.d.ts +37 -0
  28. package/dist/index.d.ts +5 -1
  29. package/dist/index.js +5 -1
  30. package/dist/isolation/types.d.ts +8 -0
  31. package/dist/isolation/types.js +8 -0
  32. package/dist/platform/focus-guard.d.ts +212 -0
  33. package/dist/platform/focus-guard.js +620 -0
  34. package/dist/platform/types.d.ts +25 -0
  35. package/dist/platform/web.js +80 -2
  36. package/dist/presets/presets.d.ts +2 -0
  37. package/dist/presets/presets.js +1 -0
  38. package/dist/react/frame.d.ts +8 -0
  39. package/dist/react/frame.js +4 -0
  40. package/dist/runtime/requests.js +34 -12
  41. package/dist/runtime/types.generated.js +1 -1
  42. package/dist/server/files.js +19 -3
  43. package/dist/server/index.d.ts +1 -0
  44. package/dist/server/index.js +4 -0
  45. package/dist/server/nested.d.ts +37 -0
  46. package/dist/server/nested.js +70 -0
  47. package/dist/server/server.js +57 -7
  48. package/dist/shell/annotate.d.ts +1 -1
  49. package/dist/shell/annotate.js +157 -7
  50. package/dist/shell/frame.d.ts +45 -0
  51. package/dist/shell/frame.js +250 -0
  52. package/dist/shell/plan.js +2 -1
  53. package/dist/shell/runtime.js +49 -14
  54. package/docs/ADOPTING.md +140 -7
  55. package/docs/ARCHITECTURE.md +23 -0
  56. package/docs/DECISIONS.md +564 -5
  57. package/docs/DESIGN.md +18 -2
  58. package/docs/THREAT_MODEL.md +192 -30
  59. package/package.json +1 -1
  60. package/src/annotate/types.ts +28 -3
  61. package/src/annotate/validate.ts +23 -2
  62. package/src/bridge/bridge.ts +17 -1
  63. package/src/bridge/unseen.ts +24 -0
  64. package/src/check/files.ts +14 -10
  65. package/src/check/lint.ts +1 -1
  66. package/src/check/scroll.ts +106 -38
  67. package/src/compile/policy.ts +14 -1
  68. package/src/config/capabilities.ts +16 -3
  69. package/src/config/schema.ts +11 -0
  70. package/src/config/validate.ts +23 -0
  71. package/src/displays/displays.ts +3 -1
  72. package/src/guide/limits.ts +1 -1
  73. package/src/guide/runtime.ts +1 -1
  74. package/src/host/create-host.ts +105 -4
  75. package/src/host/pass-on.ts +73 -0
  76. package/src/host/types.ts +33 -0
  77. package/src/index.ts +5 -1
  78. package/src/isolation/types.ts +12 -0
  79. package/src/platform/focus-guard.ts +815 -0
  80. package/src/platform/types.ts +24 -0
  81. package/src/platform/web.ts +96 -2
  82. package/src/presets/presets.ts +3 -0
  83. package/src/react/frame.tsx +10 -0
  84. package/src/runtime/requests.ts +36 -14
  85. package/src/runtime/types.generated.ts +1 -1
  86. package/src/server/files.ts +19 -3
  87. package/src/server/index.ts +10 -0
  88. package/src/server/nested.ts +86 -0
  89. package/src/server/server.ts +65 -6
  90. package/src/shell/annotate.ts +157 -7
  91. package/src/shell/frame.ts +268 -0
  92. package/src/shell/plan.ts +2 -1
  93. package/src/shell/runtime.ts +49 -14
  94. package/types/runtime/v1/comments.d.ts +8 -4
@@ -24,6 +24,12 @@ export interface SurfaceSpec {
24
24
  readonly fill?: boolean;
25
25
  /** The height to start at (a remembered height, so a frame mounting again doesn't jump). */
26
26
  readonly initialHeightPx: number;
27
+ /**
28
+ * The frame holds a nested page's shell (P111): the host's config says so, never the frame. What
29
+ * the shell says of itself (`porthole/shell/state`) decides moves of focus into it and the
30
+ * gesture its page's calls need; nothing else in that namespace reaches the transport.
31
+ */
32
+ readonly nested?: boolean;
27
33
  }
28
34
 
29
35
  /** One isolated frame. */
@@ -46,6 +52,24 @@ export interface Surface {
46
52
  * throw (P105).
47
53
  */
48
54
  viewport?(): { readonly width: number; readonly height: number } | undefined;
55
+ /**
56
+ * Whether the embedding page's focus is in this frame now, once the platform's focus guard
57
+ * judged any move into it (P109); undefined, or absent, where the platform can't tell. A gesture
58
+ * gate that asks for the person in the calling frame (`comments`) reads it: false refuses. A
59
+ * nested page's frame (P111) is the person's too while its shell saw their gesture just now.
60
+ */
61
+ focused?(): boolean | undefined;
62
+ /**
63
+ * Each time the content moved the keyboard into its frame from one of the embedding page's text
64
+ * fields without the person (no press on the frame, no Tab) and the platform gave focus back
65
+ * (P109): whether the person was typing then (a key within the last second), and whether focus
66
+ * failed to go back (the frame kept it or took it again). Absent where the platform has no guard.
67
+ */
68
+ onFocusTaken?(
69
+ listener: (take: { readonly typing: boolean; readonly failed: boolean }) => void,
70
+ ): () => void;
71
+ /** The host moves focus into the frame itself: the guard takes it as the person's (P109). */
72
+ focus?(): void;
49
73
  /**
50
74
  * The frame loaded a document other than the one it was given: the content navigated it. The
51
75
  * framework starts it again from its content and reports it.
@@ -1,6 +1,13 @@
1
1
  import type { ColorScheme } from "../config/schema.ts";
2
- import { FRAME_STATUS_METHOD } from "../isolation/types.ts";
2
+ import {
3
+ FRAME_STATUS_METHOD,
4
+ SHELL_BEAT_METHOD,
5
+ SHELL_METHOD_PREFIX,
6
+ SHELL_STATE_METHOD,
7
+ } from "../isolation/types.ts";
3
8
  import { postMessageTransport } from "../transport/post-message.ts";
9
+ import { focusGuard, type FocusGuard, type FocusTake } from "./focus-guard.ts";
10
+ import type { Transport } from "../transport/types.ts";
4
11
  import type { PlatformHost, Surface, SurfaceSpec } from "./types.ts";
5
12
 
6
13
  /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
@@ -10,6 +17,63 @@ const isFrameStatus = (data: unknown): boolean =>
10
17
  (data as { jsonrpc?: unknown }).jsonrpc === "2.0" &&
11
18
  (data as { method?: unknown }).method === FRAME_STATUS_METHOD;
12
19
 
20
+ /** A shell's own message (P111), by its namespace. */
21
+ const isShellWord = (data: unknown): data is { method: string; params?: unknown } =>
22
+ data !== null &&
23
+ typeof data === "object" &&
24
+ typeof (data as { method?: unknown }).method === "string" &&
25
+ (data as { method: string }).method.startsWith(SHELL_METHOD_PREFIX);
26
+
27
+ /**
28
+ * A nested page's transport (P111): the shell's state, checked, to the focus guard; the rest of
29
+ * the shell's namespace dropped; everything else as it came.
30
+ */
31
+ function shellWords(opened: Transport, frame: HTMLIFrameElement, guard: FocusGuard): Transport {
32
+ const listeners = new Set<(message: unknown) => void>();
33
+ opened.listen((message) => {
34
+ if (!isShellWord(message)) {
35
+ for (const listener of listeners) {
36
+ listener(message);
37
+ }
38
+ return;
39
+ }
40
+ const params = message.params;
41
+ if (params === null || typeof params !== "object") {
42
+ return;
43
+ }
44
+ const { supported, ago, focused, gap } = params as Record<string, unknown>;
45
+ const span = (value: unknown) =>
46
+ typeof value === "number" && Number.isFinite(value) && value >= 0;
47
+ if (message.method === SHELL_BEAT_METHOD) {
48
+ if (span(gap)) {
49
+ guard.beat(frame);
50
+ }
51
+ return;
52
+ }
53
+ if (
54
+ message.method !== SHELL_STATE_METHOD ||
55
+ typeof supported !== "boolean" ||
56
+ typeof focused !== "boolean" ||
57
+ !(ago === null || span(ago)) ||
58
+ !span(gap)
59
+ ) {
60
+ return;
61
+ }
62
+ guard.shell(frame, { supported, ago: ago as number | null, focused, gap: gap as number });
63
+ });
64
+ return {
65
+ send: (message) => opened.send(message),
66
+ listen(listener) {
67
+ listeners.add(listener);
68
+ return () => listeners.delete(listener);
69
+ },
70
+ close() {
71
+ listeners.clear();
72
+ opened.close();
73
+ },
74
+ };
75
+ }
76
+
13
77
  /**
14
78
  * The web platform: an `<iframe>` whose policy attributes are set before its document is given,
15
79
  * talking over `postMessage`. Its first load is the document it was given; any later load is the
@@ -62,10 +126,24 @@ export const webPlatform: PlatformHost = {
62
126
  container.append(frame);
63
127
 
64
128
  const view = container.ownerDocument.defaultView ?? window;
129
+ // The focus guard (P109): a move of the keyboard into this frame from one of the page's text
130
+ // fields that the person didn't make is undone.
131
+ const guard = focusGuard(view);
132
+ const taken = new Set<(take: FocusTake) => void>();
133
+ const nested = spec.nested === true && spec.source.kind === "url";
134
+ const unguard = guard.add(
135
+ frame,
136
+ (take) => {
137
+ for (const listener of taken) {
138
+ listener(take);
139
+ }
140
+ },
141
+ { nested },
142
+ );
65
143
  // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
66
144
  // say of the frame's status is heard too, and nothing else from there.
67
145
  const own = view.origin;
68
- const transport = postMessageTransport(
146
+ const opened = postMessageTransport(
69
147
  () => frame.contentWindow,
70
148
  origin,
71
149
  view,
@@ -73,6 +151,10 @@ export const webPlatform: PlatformHost = {
73
151
  ? undefined
74
152
  : { origin: own, accept: isFrameStatus },
75
153
  );
154
+ // A nested page's shell (P111): its own words go to the guard, by the frame's window and the
155
+ // content origin (the transport's checks); the page's pass on. The shell drops any page
156
+ // message in its namespace, so there none is the page's.
157
+ const transport = nested ? shellWords(opened, frame, guard) : opened;
76
158
  return {
77
159
  transport,
78
160
  element: frame,
@@ -100,6 +182,16 @@ export const webPlatform: PlatformHost = {
100
182
  ).userActivation;
101
183
  return activation === undefined ? undefined : activation.isActive;
102
184
  },
185
+ focused() {
186
+ return guard.focused(frame) || (nested && guard.gesture(frame));
187
+ },
188
+ onFocusTaken(listener) {
189
+ taken.add(listener);
190
+ return () => taken.delete(listener);
191
+ },
192
+ focus() {
193
+ guard.focus(frame);
194
+ },
103
195
  onLoad(listener) {
104
196
  loaded.add(listener);
105
197
  return () => loaded.delete(listener);
@@ -111,6 +203,8 @@ export const webPlatform: PlatformHost = {
111
203
  destroy() {
112
204
  navigated.clear();
113
205
  loaded.clear();
206
+ taken.clear();
207
+ unguard();
114
208
  transport.close();
115
209
  frame.remove();
116
210
  },
@@ -56,6 +56,8 @@ export interface PresetOptions {
56
56
  * be offered the runtime's own (`user`, `comments`, `artifact`, `assets`, `db`).
57
57
  */
58
58
  readonly runtime?: RuntimeVersion;
59
+ /** Domain isolation, artifact pages: the page in an opaque child of Porthole's shell (P111). */
60
+ readonly nested?: true;
59
61
  }
60
62
 
61
63
  /** What a live widget may say about a capability (P103): anything but origins of its own. */
@@ -241,6 +243,7 @@ function build(
241
243
  ...(options.storage === undefined ? {} : { storage: options.storage }),
242
244
  ...(options.errors === undefined ? {} : { errors: options.errors }),
243
245
  ...(options.runtime === undefined ? {} : { runtime: options.runtime }),
246
+ ...(options.nested === undefined ? {} : { nested: options.nested }),
244
247
  });
245
248
  }
246
249
 
@@ -564,6 +564,12 @@ export interface PortholeFrameProps {
564
564
  readonly onRefused?: (capability: CapabilityName, refusal: Refusal) => void;
565
565
  /** Too many declines: the display stops asking until it runs again. */
566
566
  readonly onMuted?: () => void;
567
+ /**
568
+ * The content moved the keyboard into its frame from one of the page's text fields without the
569
+ * person, and focus went back (P109); `typing`: the person was typing on the page. A display
570
+ * that keeps doing it is stopped (`onContentError` says so).
571
+ */
572
+ readonly onFocusTaken?: (taken: { readonly typing: boolean }) => void;
567
573
  /**
568
574
  * How the frame's first document went: loaded, blocked (and why), or a timeout. A host shows its
569
575
  * own fallback (a url-mode app "Open in a new tab") on anything but loaded.
@@ -839,6 +845,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
839
845
  case "muted":
840
846
  frame.onMuted?.();
841
847
  return;
848
+ case "focusTaken":
849
+ frame.onFocusTaken?.(detail as DisplayEvents["focusTaken"]);
850
+ return;
842
851
  case "outcome":
843
852
  frame.onOutcome?.(detail as DisplayEvents["outcome"]);
844
853
  return;
@@ -967,6 +976,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }: MountProps):
967
976
  "navigationBlocked",
968
977
  "refused",
969
978
  "muted",
979
+ "focusTaken",
970
980
  "outcome",
971
981
  "annotation",
972
982
  "contentError",
@@ -1,4 +1,4 @@
1
- import { unseen } from "../bridge/unseen.ts";
1
+ import { unseenStrict, withoutUnseen } from "../bridge/unseen.ts";
2
2
  import type { Limits } from "../config/schema.ts";
3
3
  import { fileLimits, filePathProblem } from "../files/paths.ts";
4
4
  import { fileTypeOf } from "../files/types.ts";
@@ -70,18 +70,42 @@ export interface CommentRequest {
70
70
  readonly draft?: string;
71
71
  }
72
72
 
73
+ /** Characters that draw as a blank: spaces of every kind, tabs, new lines, the braille blank. */
74
+ const BLANK = /^[\p{White_Space}\u2800]*$/u;
75
+ /** More than 32 blanks in a row on a line, or more than two blank lines in a row (P109). */
76
+ const BLANK_RUN = /[\p{Zs}\t\u2800]{33}|\n(?:[\p{Zs}\t\u2800]*\n){3}/u;
77
+ /** Line and paragraph separators: a line break a person may see as nothing (Firefox, WebKit). */
78
+ const SEPARATORS = /[\u2028\u2029]/u;
79
+
73
80
  /**
74
- * A draft (P108): text the person will post in their own name, so all of it must be text they can
75
- * see: at most 2,000 characters, well-formed, not blank, and nothing `unseen` (P100: no zero-width
76
- * or bidi characters, no tags, no controls but a new line and a tab), which a host would show as
77
- * nothing and an agent would read as the person's words. Lines and tabs are fine: a checklist.
81
+ * A draft (P108, P109): text the person will post in their own name, so all of it must be text
82
+ * they can see: at most 2,000 characters, well-formed, and nothing invisible (`unseenStrict`: no
83
+ * zero-width characters, bidi or tag characters, controls but a new line and a tab; a joiner or
84
+ * non-joiner only between two letters or marks, a variation selector only after a pictograph), no line or paragraph
85
+ * separator, not blank-looking, at most 32 blanks in a row and two blank lines in a row (so that
86
+ * "whole" is something a host can show). Lines and tabs are fine: a checklist.
78
87
  */
79
88
  const draftText = (value: unknown): value is string =>
80
89
  typeof value === "string" &&
81
- value.trim() !== "" &&
82
90
  value.length <= 2_000 &&
83
91
  value.isWellFormed() &&
84
- !unseen(value);
92
+ !BLANK.test(value) &&
93
+ !unseenStrict(value) &&
94
+ !SEPARATORS.test(value) &&
95
+ !BLANK_RUN.test(value);
96
+
97
+ /**
98
+ * An anchor's label or quote, shown beside the draft (P109): the page's short text, without what a
99
+ * person can't see (P105's `withoutUnseen`, line and paragraph separators too), or null if nothing
100
+ * visible is left. Shown, never posted as the person's words, so cleaned rather than refused.
101
+ */
102
+ const shownText = (value: unknown, max: number): string | null => {
103
+ if (!shortText(value, max)) {
104
+ return null;
105
+ }
106
+ const seen = withoutUnseen(value).replace(/[\u2028\u2029]/gu, "");
107
+ return BLANK.test(seen) ? null : seen;
108
+ };
85
109
 
86
110
  export function parseCommentRequest(args: unknown): CommentRequest | null {
87
111
  const anchor = isRecord(args) ? args.anchor : undefined;
@@ -89,18 +113,16 @@ export function parseCommentRequest(args: unknown): CommentRequest | null {
89
113
  return null;
90
114
  }
91
115
  const draft = isRecord(args) ? args.draft : undefined;
92
- if (
93
- (anchor.label !== undefined && !shortText(anchor.label, 200)) ||
94
- (anchor.quote !== undefined && !shortText(anchor.quote, 2_000)) ||
95
- (draft !== undefined && !draftText(draft))
96
- ) {
116
+ const label = anchor.label === undefined ? undefined : shownText(anchor.label, 200);
117
+ const quote = anchor.quote === undefined ? undefined : shownText(anchor.quote, 2_000);
118
+ if (label === null || quote === null || (draft !== undefined && !draftText(draft))) {
97
119
  return null;
98
120
  }
99
121
  return {
100
122
  anchor: {
101
123
  name: anchor.name,
102
- ...(anchor.label === undefined ? {} : { label: anchor.label }),
103
- ...(anchor.quote === undefined ? {} : { quote: anchor.quote }),
124
+ ...(label === undefined ? {} : { label }),
125
+ ...(quote === undefined ? {} : { quote }),
104
126
  },
105
127
  ...(draft === undefined ? {} : { draft }),
106
128
  };
@@ -7,7 +7,7 @@ export const RUNTIME_TYPES: Readonly<Record<string, Readonly<Record<string, stri
7
7
  "assets": "// Porthole capability runtime, contract 1: assets (the artifact's asset library). Declare it: { assets: {} }.\n// Assets live outside every version, at \"/_blob/<id>\" on the page's own origin: keep that url (or\n// the id) in your data, and show it with assets.url(id). Images, media and fonts load; scripts and\n// stylesheets only where the app lets only admins upload, and only those an admin added. Not for\n// files that version with the page: publish those with it.\n\ninterface PortholeAsset {\n /** 32 hex characters. */\n readonly id: string;\n /** \"/_blob/<id>\": use it as given. */\n readonly url: string;\n readonly name: string;\n /** Porthole's type for the name's extension. */\n readonly type: string;\n readonly size: number;\n}\n\ninterface PortholeAssets {\n /** The library, people's uploads through the page included. Level: view. */\n list(): Promise<readonly PortholeAsset[]>;\n /**\n * Adds a file (a File from an <input type=\"file\">, a Blob, bytes) under its name (a File's own,\n * or options.name): an image, media, a font, a PDF, text or data, never HTML; a script or a\n * stylesheet only where uploads are the admins'. The app may ask the person first. Level: admin,\n * unless the app lets people who interact upload.\n */\n upload(\n file: Blob | ArrayBuffer | ArrayBufferView,\n options?: { readonly name?: string },\n ): Promise<PortholeAsset>;\n /**\n * The address that loads an asset in this page now: put it in src or href when you show it.\n * Store the id (or \"/_blob/<id>\"), never this: it carries this page's access. A \"/_blob/<id>\"\n * written in the page loads too, except in some browsers' frames (Safari's); this always does.\n */\n url(id: string): string;\n /** Removes one, from a click; the app asks the person first. Level: admin. */\n delete(id: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n assets: PortholeAssets;\n}\n",
8
8
  "chat": "// Porthole capability runtime, contract 1: chat. Declare it: { chat: {} }.\n\ninterface PortholeChat {\n /**\n * Sends text to the agent as the person's message (\"explain this point\"). Call it from a click.\n * Resolves true if it was sent. Level: interact.\n */\n send(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n chat: PortholeChat;\n}\n",
9
9
  "clipboard": "// Porthole capability runtime, contract 1: clipboard. Built in: never declare it.\n\ninterface PortholeClipboard {\n /**\n * Copies text to the person's clipboard (at most 20,000 characters); the app shows them what\n * was copied. Nothing else in the page can write the clipboard. Call it from a click.\n * Resolves true if it was copied. Level: view.\n */\n copy(text: string): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n clipboard: PortholeClipboard;\n}\n",
10
- "comments": "// Porthole capability runtime, contract 1: comments. Built in: never declare it.\n\n/** Where a comment goes, in the page's own words. */\ninterface PortholeCommentAnchor {\n /** A stable name the page chose: \"slide-3\", \"refs/a.md#L12\" (at most 256 characters). */\n readonly name: string;\n /** What the app shows for it (at most 200). */\n readonly label?: string;\n /** The text the comment is about (at most 2,000). */\n readonly quote?: string;\n}\n\n/** How the composer opens. */\ninterface PortholeCommentOptions {\n /**\n * Text the composer starts with (at most 2,000 characters): a draft the person edits, posts\n * or discards in the app. It is never posted without them. Visible text only: new lines and\n * tabs are fine; a draft with zero-width, bidi or tag characters is refused.\n */\n readonly draft?: string;\n}\n\ninterface PortholeComments {\n /**\n * Opens the app's comment composer at the anchor (a name alone is { name }), starting with\n * `options.draft` if given. The person writes and posts it in the app. Resolves true if the\n * composer opened. Write-only: a page never reads comments. Call it from a click. Level: view.\n */\n open(anchor: PortholeCommentAnchor | string, options?: PortholeCommentOptions): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n comments: PortholeComments;\n}\n",
10
+ "comments": "// Porthole capability runtime, contract 1: comments. Built in: never declare it.\n\n/** Where a comment goes, in the page's own words. */\ninterface PortholeCommentAnchor {\n /** A stable name the page chose: \"slide-3\", \"refs/a.md#L12\" (at most 256 characters). */\n readonly name: string;\n /** What the app shows for it (at most 200; what a person can't see is taken out). */\n readonly label?: string;\n /** The text the comment is about (at most 2,000; what a person can't see is taken out). */\n readonly quote?: string;\n}\n\n/** How the composer opens. */\ninterface PortholeCommentOptions {\n /**\n * Text the composer starts with (at most 2,000 characters): a draft the person edits, posts\n * or discards in the app. It is never posted without them. Visible text only: new lines and\n * tabs are fine (at most 32 blanks in a row, two blank lines in a row), and so are U+200C and\n * U+200D between two letters or marks (Persian, the Indic scripts); a draft with zero-width\n * characters, a joiner anywhere else (an emoji joined with U+200D too; ❤️ is fine), bidi or tag\n * characters, or a line or paragraph separator (U+2028, U+2029) is refused.\n */\n readonly draft?: string;\n}\n\ninterface PortholeComments {\n /**\n * Opens the app's comment composer at the anchor (a name alone is { name }), starting with\n * `options.draft` if given. The person writes and posts it in the app. Resolves true if the\n * composer opened, false if it didn't (the app may refuse while the person is writing).\n * Write-only: a page never reads comments. Call it from a click in the page. Level: view.\n */\n open(anchor: PortholeCommentAnchor | string, options?: PortholeCommentOptions): Promise<boolean>;\n}\n\ninterface PortholeCapabilities {\n comments: PortholeComments;\n}\n",
11
11
  "context": "// Porthole capability runtime, contract 1: context. Declare it: { context: {} }.\n\ninterface PortholeContextUpdate {\n /**\n * MCP text blocks only: [{ type: \"text\", text: \"…\" }]. Visible characters only, here and in\n * structuredContent: no zero-width or bidi controls, variation selectors, tag or private-use\n * characters, or controls other than new lines and tabs (refused), but the selectors and\n * joiners inside real emoji (☀️, 👨‍👩‍👧, 1️⃣), and a joiner or non-joiner between two letters of\n * a script it shapes (Arabic, Persian, the Indic scripts, Myanmar…).\n */\n readonly content?: readonly unknown[];\n /** Plain JSON. With the text, at most 20,000 characters. */\n readonly structuredContent?: Record<string, unknown>;\n}\n\ninterface PortholeContext {\n /**\n * Tells the agent, at its next turns, what the page says the person is looking at (replaces the\n * last). The agent reads it as the page's words, unconfirmed by the person; the app shows the\n * person each update unless it says otherwise. Level: interact.\n */\n set(update: PortholeContextUpdate): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n context: PortholeContext;\n}\n",
12
12
  "data": "// Porthole capability runtime, contract 1: data (the app's data and tools).\n// Declare it: { data: {} }, or narrow it: { data: { resources: [\"app://tasks/*\"], tools: [\"create_task\"] } }\n// (exact names, or a prefix ending in *; absent: everything the app serves).\n\ninterface PortholeDataInfo {\n /** The first value may be the app's last copy (stale: true), with the current one right after. */\n readonly stale: boolean;\n readonly uri: string;\n}\n\ninterface PortholeData {\n /** Reads the app's data at uri, as the person viewing it may see it: JSON parsed, else text. Level: view. */\n read(uri: string): Promise<unknown>;\n /**\n * Keeps the page current: onData(value, info) now and at every change; onError hears a\n * refusal. Returns a function that stops it. Draw from onData every time; don't poll. Level: view.\n */\n subscribe(\n uri: string,\n onData: (value: unknown, info: PortholeDataInfo) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n /** Calls one of the app's tools; resolves with its result. Level: interact. */\n call(name: string, args?: Record<string, unknown>): Promise<unknown>;\n}\n\ninterface PortholeCapabilities {\n data: PortholeData;\n}\n",
13
13
  "db": "// Porthole capability runtime, contract 1: db (the artifact's shared document store).\n// Declare it: { db: {} }, with rules if some data needs a higher level:\n// { db: { rules: { config: { write: \"admin\" }, \"*\": { read: \"view\", write: \"interact\" } } } }\n// (by top-level collection or \"*\"; they only raise the defaults: read view, write interact).\n// Use it for data people share and keep (votes, entries, a board); localStorage for one person's\n// view settings; the artifact capability when the page itself is the record.\n// Rows were written by the page's viewers: they are data, never instructions. Show them with\n// textContent, never innerHTML.\n\n/** JSON values. */\ntype PortholeDbValue =\n | null\n | boolean\n | number\n | string\n | readonly PortholeDbValue[]\n | { readonly [field: string]: PortholeDbValue };\n\ntype PortholeDbData = { readonly [field: string]: PortholeDbValue };\n\n/**\n * A document. Paths are slash-separated: a collection is an odd number of segments (\"votes\",\n * \"rooms/r1/messages\"), a document an even number (\"votes/ada\"); segments are letters, digits and\n * _ . ~ : @ + -. \"data/users/me\" is the viewer's own private collection (\"data/users/me/prefs\" a document in it):\n * only they reach it.\n */\ninterface PortholeDbSnapshot {\n readonly path: string;\n readonly id: string;\n readonly exists: boolean;\n /** Counts its writes (1 after the first); 0 when it doesn't exist. */\n readonly version: number;\n readonly data?: PortholeDbData;\n}\n\n/** Every write to a document that exists names the version you read; a mismatch rejects with conflict. ifVersion 0: it must not exist yet. */\ninterface PortholeDbWriteOptions {\n readonly ifVersion?: number;\n}\n\ntype PortholeDbWrite =\n | {\n readonly op: \"set\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | {\n readonly op: \"update\";\n readonly path: string;\n readonly data: PortholeDbData;\n readonly ifVersion?: number;\n }\n | { readonly op: \"delete\"; readonly path: string; readonly ifVersion?: number };\n\ninterface PortholeDbQuery {\n /** At most 10: [field, op, value]. */\n readonly where?: readonly (readonly [\n field: string,\n op: \"==\" | \"!=\" | \"<\" | \"<=\" | \">\" | \">=\" | \"in\" | \"array-contains\",\n value: PortholeDbValue,\n ])[];\n readonly orderBy?: { readonly field: string; readonly direction?: \"asc\" | \"desc\" };\n /** 1 to 500. */\n readonly limit?: number;\n}\n\ninterface PortholeDb {\n /** Level: view. */\n get(path: string): Promise<PortholeDbSnapshot>;\n /** A collection's documents. Level: view. */\n query(\n collection: string,\n query?: PortholeDbQuery,\n ): Promise<{ readonly docs: readonly PortholeDbSnapshot[] }>;\n /** Writes a whole document (at most 1 MiB of JSON). Level: interact. */\n set(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Merges fields over a document's. Level: interact. */\n update(\n path: string,\n data: PortholeDbData,\n options?: PortholeDbWriteOptions,\n ): Promise<{ readonly version: number }>;\n /** Level: interact. */\n delete(path: string, options?: PortholeDbWriteOptions): Promise<null>;\n /**\n * Up to 50 writes to different documents, all or none. Each write's new version (null for a\n * delete). Each write at its own level.\n */\n batch(\n writes: readonly PortholeDbWrite[],\n ): Promise<{ readonly versions: readonly (number | null)[] }>;\n /**\n * Follows a document (a snapshot) or a collection ({ docs }) now and at every change. Returns a\n * function that stops it. Draw from onData; don't poll. Level: view.\n */\n onSnapshot(\n path: string,\n onData: (state: PortholeDbSnapshot | { readonly docs: readonly PortholeDbSnapshot[] }) => void,\n onError?: (error: PortholeError) => void,\n ): () => void;\n}\n\ninterface PortholeCapabilities {\n db: PortholeDb;\n}\n",
@@ -11,6 +11,7 @@ import { DEFAULT_ENTRY, lookupFile, requestFilePath, type FileLookup } from "../
11
11
  import { fileTypeOf } from "../files/types.ts";
12
12
  import { isCodeAsset } from "../runtime/requests.ts";
13
13
  import { sha256, utf8 } from "./crypto.ts";
14
+ import { NESTED_FILE_HEADERS } from "./nested.ts";
14
15
  import type { FileBody, StoredAsset, StoredFiles } from "./types.ts";
15
16
 
16
17
  /**
@@ -226,6 +227,8 @@ export async function serveFile(serving: FileServing): Promise<Response> {
226
227
  return nothing(serving, 404, method);
227
228
  }
228
229
  const { type, role } = fileTypeOf(found.path);
230
+ // A nested page (P111): in its shell's child, an opaque origin.
231
+ const nested = serving.compiled.config.nested === true;
229
232
  // In a frame, the version's files are at a sealed address (P083), which their own loads of the
230
233
  // artifact's assets carry as their `Referer` (P091): to this origin only, never another.
231
234
  const referrer =
@@ -242,12 +245,18 @@ export async function serveFile(serving: FileServing): Promise<Response> {
242
245
  // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
243
246
  // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
244
247
  // its own.
248
+ // A nested page's files are on its shell's origin (P111, after the review): every one carries a
249
+ // sandbox, so none opened as a document on its own (a tab, "open image in new tab") runs on that
250
+ // origin. Pages run their scripts, opaque; anything else runs nothing (a file's is inert already,
251
+ // a script's gets one too).
245
252
  const csp =
246
253
  role === "file"
247
254
  ? INERT_FILE_CSP
248
255
  : role === "page"
249
256
  ? servedDocumentCsp(serving.compiled.config, directives)
250
- : serializeCsp(directives);
257
+ : nested
258
+ ? `${serializeCsp(directives)}; sandbox`
259
+ : serializeCsp(directives);
251
260
  const headers = new Headers({
252
261
  "content-type": type,
253
262
  "x-content-type-options": "nosniff",
@@ -263,7 +272,8 @@ export async function serveFile(serving: FileServing): Promise<Response> {
263
272
  if (role === "page") {
264
273
  // Every page of the set in the shell (P081): its hardening, its host functions, its theme.
265
274
  const html = serving.compiled.shellDocument({
266
- origins: serving.hostOrigins,
275
+ // A nested page hears its shell, on its own origin, never the host (P111).
276
+ origins: nested ? [serving.origin] : serving.hostOrigins,
267
277
  document: await textOf(body),
268
278
  cspMeta: false,
269
279
  ...(referrer === "same-origin" ? { referrer } : {}),
@@ -303,8 +313,14 @@ export async function serveFile(serving: FileServing): Promise<Response> {
303
313
  serving.pinned ? `private, max-age=${YEAR}, immutable` : "private, no-cache",
304
314
  );
305
315
  // Only this origin's own pages load it: no other content origin (a sibling, same-site without
306
- // the public suffix list) can embed it with the viewer's cookie.
316
+ // the public suffix list) can embed it with the viewer's cookie. A nested page's origin is
317
+ // opaque, and its files carry their access in their path, never a cookie (P111).
307
318
  headers.set("cross-origin-resource-policy", "same-origin");
319
+ if (nested) {
320
+ for (const [name, value] of Object.entries(NESTED_FILE_HEADERS)) {
321
+ headers.set(name, value);
322
+ }
323
+ }
308
324
  headers.set("accept-ranges", "bytes");
309
325
  if (role === "file" && type === "application/octet-stream") {
310
326
  headers.set("content-disposition", "attachment");
@@ -70,6 +70,16 @@ export {
70
70
  type D1StatementLike,
71
71
  } from "./tickets.ts";
72
72
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
73
+ // A nested page (P111): Porthole's shell at the framed address, the page and its files below the
74
+ // sealed prefix. `/server` serves them for a config with `nested`; a content Worker of its own
75
+ // answers the same (docs/ADOPTING.md, "Nested pages").
76
+ export {
77
+ NESTED_FILE_HEADERS,
78
+ NESTED_FILES_PREFIX,
79
+ nestedAncestors,
80
+ nestedShellCsp,
81
+ nestedShellResponse,
82
+ } from "./nested.ts";
73
83
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
74
84
  // The page an app serves in conformance test mode (P071).
75
85
  export { conformancePage } from "../conformance/page.ts";
@@ -0,0 +1,86 @@
1
+ import type { CompiledConfig } from "../compile/compile.ts";
2
+ import { servedPermissionsPolicy, serializeCsp, type CspDirective } from "../compile/policy.ts";
3
+ import { frameShellDocument, frameShellScript, type FrameShellOptions } from "../shell/frame.ts";
4
+ import { sha256, utf8 } from "./crypto.ts";
5
+
6
+ /**
7
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
8
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
9
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
10
+ * a host serving its own content origin (its own Worker) answers the same.
11
+ */
12
+
13
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
14
+ export const NESTED_FILES_PREFIX = "/__porthole/f/";
15
+
16
+ const base64 = (bytes: Uint8Array): string => btoa(String.fromCharCode(...bytes));
17
+
18
+ /**
19
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
20
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
21
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
22
+ * this (a framed URL's document never does).
23
+ */
24
+ export function nestedShellCsp(
25
+ script: string,
26
+ origin: string,
27
+ hostOrigins: readonly string[],
28
+ ): string {
29
+ const files = `${origin}${NESTED_FILES_PREFIX}`;
30
+ const directives: CspDirective[] = [
31
+ ["default-src", "'none'"],
32
+ ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
33
+ ["frame-src", files],
34
+ ["connect-src", files],
35
+ ["base-uri", "'none'"],
36
+ ["form-action", "'none'"],
37
+ ["frame-ancestors", ...hostOrigins],
38
+ ];
39
+ return serializeCsp(directives);
40
+ }
41
+
42
+ /**
43
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
44
+ * stored (it carries the page's sealed address), its page at `options.page`.
45
+ */
46
+ export function nestedShellResponse(
47
+ compiled: CompiledConfig,
48
+ options: FrameShellOptions & { readonly origin: string; readonly method?: string },
49
+ ): Response {
50
+ const script = frameShellScript(options);
51
+ const headers = new Headers({
52
+ "content-type": "text/html; charset=utf-8",
53
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
54
+ "cache-control": "no-store",
55
+ "referrer-policy": "no-referrer",
56
+ "x-content-type-options": "nosniff",
57
+ "x-robots-tag": "noindex, nofollow",
58
+ });
59
+ // Denied to the shell, so to its child too (a frame's features are its parent's at most).
60
+ const permissions = servedPermissionsPolicy(compiled.config);
61
+ if (permissions !== null) {
62
+ headers.set("permissions-policy", permissions);
63
+ }
64
+ return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
65
+ status: 200,
66
+ headers,
67
+ });
68
+ }
69
+
70
+ /**
71
+ * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
72
+ * it, the host origins (`frame-ancestors` names every ancestor).
73
+ */
74
+ export const nestedAncestors = (origin: string, frameAncestors: string): string =>
75
+ `${origin} ${frameAncestors}`;
76
+
77
+ /**
78
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
79
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
80
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
81
+ * is their access, never the request's origin.
82
+ */
83
+ export const NESTED_FILE_HEADERS: Readonly<Record<string, string>> = {
84
+ "cross-origin-resource-policy": "cross-origin",
85
+ "access-control-allow-origin": "*",
86
+ };
@@ -13,7 +13,9 @@ import { randomBytes } from "./crypto.ts";
13
13
  import { isHostLabel, reservedLabels } from "./naming.ts";
14
14
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.ts";
15
15
  import { libraryFile } from "./libraries.ts";
16
- import { ownLoad, serveAsset, serveFile } from "./files.ts";
16
+ import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.ts";
17
+ import { nestedAncestors, nestedShellResponse } from "./nested.ts";
18
+ import { DEFAULT_ENTRY } from "../files/paths.ts";
17
19
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.ts";
18
20
  import {
19
21
  assetCodeRuns,
@@ -520,6 +522,8 @@ export function createServer(options: ServerOptions): PortholeServer {
520
522
  async function documentOf(instance: InstanceRef): Promise<
521
523
  | {
522
524
  readonly html: string;
525
+ /** An artifact's own page, before the shell (a nested page's is made apart, P111). */
526
+ readonly document?: string;
523
527
  readonly compiled: CompiledConfig;
524
528
  /** Whether its CSP opens its artifact's asset library (P089): an artifact's page. */
525
529
  readonly assets: boolean;
@@ -554,6 +558,7 @@ export function createServer(options: ServerOptions): PortholeServer {
554
558
  }
555
559
  return {
556
560
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
561
+ document: stored.html,
557
562
  compiled: config,
558
563
  assets: true,
559
564
  };
@@ -807,10 +812,14 @@ export function createServer(options: ServerOptions): PortholeServer {
807
812
  }
808
813
  }
809
814
 
810
- function documentHeaders(csp: string, permissions: string | null): Headers {
815
+ function documentHeaders(
816
+ csp: string,
817
+ permissions: string | null,
818
+ ancestors: string = frameAncestors,
819
+ ): Headers {
811
820
  return new Headers({
812
821
  "content-type": "text/html; charset=utf-8",
813
- "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
822
+ "content-security-policy": `${csp}; frame-ancestors ${ancestors}`,
814
823
  // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
815
824
  ...(permissions === null ? {} : { "permissions-policy": permissions }),
816
825
  "cache-control": "no-store",
@@ -905,12 +914,16 @@ export function createServer(options: ServerOptions): PortholeServer {
905
914
  }
906
915
  const access = await sealedAccess(request, label, token);
907
916
  if (access === null) {
908
- return page(
917
+ // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
918
+ // config without nesting never frames this address but at the host.
919
+ return statusPage(
909
920
  401,
910
921
  "This has ended",
911
922
  "Content here opens for a while. Open it again from the app that showed it.",
923
+ nestedAncestors(origin, frameAncestors),
912
924
  method,
913
925
  "session",
926
+ [...options.hostOrigins, origin],
914
927
  );
915
928
  }
916
929
  // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
@@ -1021,6 +1034,43 @@ export function createServer(options: ServerOptions): PortholeServer {
1021
1034
  if (served === null) {
1022
1035
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
1023
1036
  }
1037
+ // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
1038
+ // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
1039
+ // that address, below the sealed prefix, answers the page and its files, without a cookie.
1040
+ const nested = served.compiled.config.nested === true;
1041
+ const sealedAt = at !== undefined && at.base.startsWith(FILES_PREFIX);
1042
+ if (nested && !sealedAt) {
1043
+ if (!isNavigation(request)) {
1044
+ return page(404, "Not found", "This page's files are at its own address.", method);
1045
+ }
1046
+ const sealed = await sealFiles(access);
1047
+ let rest = "";
1048
+ if ("files" in served) {
1049
+ const entry = served.files.entry ?? DEFAULT_ENTRY;
1050
+ rest =
1051
+ at !== undefined && at.rest !== ""
1052
+ ? at.rest
1053
+ : entry.includes("/")
1054
+ ? entry
1055
+ .split("/")
1056
+ .map((segment) => encodeURIComponent(segment))
1057
+ .join("/")
1058
+ : "";
1059
+ }
1060
+ const shell = nestedShellResponse(served.compiled, {
1061
+ origin: access.origin,
1062
+ origins: options.hostOrigins,
1063
+ page: `${access.origin}${sealed.base}${rest}`,
1064
+ renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
1065
+ method,
1066
+ });
1067
+ if (cookie !== null) {
1068
+ shell.headers.set("set-cookie", cookie);
1069
+ }
1070
+ return shell;
1071
+ }
1072
+ // Below the sealed prefix, a nested page and its files are framed by its shell too.
1073
+ const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
1024
1074
  if ("files" in served) {
1025
1075
  if (at !== undefined) {
1026
1076
  return serveFile({
@@ -1034,7 +1084,7 @@ export function createServer(options: ServerOptions): PortholeServer {
1034
1084
  source: at.source,
1035
1085
  compiled: served.compiled,
1036
1086
  hostOrigins: options.hostOrigins,
1037
- frameAncestors,
1087
+ frameAncestors: ancestors,
1038
1088
  ...versionOf(access.instance),
1039
1089
  });
1040
1090
  }
@@ -1071,11 +1121,20 @@ export function createServer(options: ServerOptions): PortholeServer {
1071
1121
  served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives,
1072
1122
  ),
1073
1123
  servedPermissionsPolicy(config),
1124
+ ancestors,
1074
1125
  );
1075
1126
  if (cookie !== null) {
1076
1127
  headers.set("set-cookie", cookie);
1077
1128
  }
1078
- return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
1129
+ // A nested page's document takes messages from its shell, on its own origin (P111).
1130
+ const html = nested
1131
+ ? served.compiled.shellDocument({
1132
+ origins: [access.origin],
1133
+ document: served.document ?? "",
1134
+ cspMeta: false,
1135
+ })
1136
+ : served.html;
1137
+ return new Response(method === "HEAD" ? null : html, { status: 200, headers });
1079
1138
  }
1080
1139
 
1081
1140
  /**