@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
@@ -1,10 +1,62 @@
1
- import { FRAME_STATUS_METHOD } from "../isolation/types.js";
1
+ import { FRAME_STATUS_METHOD, SHELL_BEAT_METHOD, SHELL_METHOD_PREFIX, SHELL_STATE_METHOD, } from "../isolation/types.js";
2
2
  import { postMessageTransport } from "../transport/post-message.js";
3
+ import { focusGuard } from "./focus-guard.js";
3
4
  /** A frame-status message (`porthole/notifications/frame-status`), by its method alone. */
4
5
  const isFrameStatus = (data) => data !== null &&
5
6
  typeof data === "object" &&
6
7
  data.jsonrpc === "2.0" &&
7
8
  data.method === FRAME_STATUS_METHOD;
9
+ /** A shell's own message (P111), by its namespace. */
10
+ const isShellWord = (data) => data !== null &&
11
+ typeof data === "object" &&
12
+ typeof data.method === "string" &&
13
+ data.method.startsWith(SHELL_METHOD_PREFIX);
14
+ /**
15
+ * A nested page's transport (P111): the shell's state, checked, to the focus guard; the rest of
16
+ * the shell's namespace dropped; everything else as it came.
17
+ */
18
+ function shellWords(opened, frame, guard) {
19
+ const listeners = new Set();
20
+ opened.listen((message) => {
21
+ if (!isShellWord(message)) {
22
+ for (const listener of listeners) {
23
+ listener(message);
24
+ }
25
+ return;
26
+ }
27
+ const params = message.params;
28
+ if (params === null || typeof params !== "object") {
29
+ return;
30
+ }
31
+ const { supported, ago, focused, gap } = params;
32
+ const span = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0;
33
+ if (message.method === SHELL_BEAT_METHOD) {
34
+ if (span(gap)) {
35
+ guard.beat(frame);
36
+ }
37
+ return;
38
+ }
39
+ if (message.method !== SHELL_STATE_METHOD ||
40
+ typeof supported !== "boolean" ||
41
+ typeof focused !== "boolean" ||
42
+ !(ago === null || span(ago)) ||
43
+ !span(gap)) {
44
+ return;
45
+ }
46
+ guard.shell(frame, { supported, ago: ago, focused, gap: gap });
47
+ });
48
+ return {
49
+ send: (message) => opened.send(message),
50
+ listen(listener) {
51
+ listeners.add(listener);
52
+ return () => listeners.delete(listener);
53
+ },
54
+ close() {
55
+ listeners.clear();
56
+ opened.close();
57
+ },
58
+ };
59
+ }
8
60
  /**
9
61
  * The web platform: an `<iframe>` whose policy attributes are set before its document is given,
10
62
  * talking over `postMessage`. Its first load is the document it was given; any later load is the
@@ -56,12 +108,26 @@ export const webPlatform = {
56
108
  });
57
109
  container.append(frame);
58
110
  const view = container.ownerDocument.defaultView ?? window;
111
+ // The focus guard (P109): a move of the keyboard into this frame from one of the page's text
112
+ // fields that the person didn't make is undone.
113
+ const guard = focusGuard(view);
114
+ const taken = new Set();
115
+ const nested = spec.nested === true && spec.source.kind === "url";
116
+ const unguard = guard.add(frame, (take) => {
117
+ for (const listener of taken) {
118
+ listener(take);
119
+ }
120
+ }, { nested });
59
121
  // A served frame may pass through the host's own pages (a redirect entry's, P068): what they
60
122
  // say of the frame's status is heard too, and nothing else from there.
61
123
  const own = view.origin;
62
- const transport = postMessageTransport(() => frame.contentWindow, origin, view, origin === "null" || own === "null" || own === origin
124
+ const opened = postMessageTransport(() => frame.contentWindow, origin, view, origin === "null" || own === "null" || own === origin
63
125
  ? undefined
64
126
  : { origin: own, accept: isFrameStatus });
127
+ // A nested page's shell (P111): its own words go to the guard, by the frame's window and the
128
+ // content origin (the transport's checks); the page's pass on. The shell drops any page
129
+ // message in its namespace, so there none is the page's.
130
+ const transport = nested ? shellWords(opened, frame, guard) : opened;
65
131
  return {
66
132
  transport,
67
133
  element: frame,
@@ -85,6 +151,16 @@ export const webPlatform = {
85
151
  const activation = view.navigator.userActivation;
86
152
  return activation === undefined ? undefined : activation.isActive;
87
153
  },
154
+ focused() {
155
+ return guard.focused(frame) || (nested && guard.gesture(frame));
156
+ },
157
+ onFocusTaken(listener) {
158
+ taken.add(listener);
159
+ return () => taken.delete(listener);
160
+ },
161
+ focus() {
162
+ guard.focus(frame);
163
+ },
88
164
  onLoad(listener) {
89
165
  loaded.add(listener);
90
166
  return () => loaded.delete(listener);
@@ -96,6 +172,8 @@ export const webPlatform = {
96
172
  destroy() {
97
173
  navigated.clear();
98
174
  loaded.clear();
175
+ taken.clear();
176
+ unguard();
99
177
  transport.close();
100
178
  frame.remove();
101
179
  },
@@ -40,6 +40,8 @@ export interface PresetOptions {
40
40
  * be offered the runtime's own (`user`, `comments`, `artifact`, `assets`, `db`).
41
41
  */
42
42
  readonly runtime?: RuntimeVersion;
43
+ /** Domain isolation, artifact pages: the page in an opaque child of Porthole's shell (P111). */
44
+ readonly nested?: true;
43
45
  }
44
46
  /** What a live widget may say about a capability (P103): anything but origins of its own. */
45
47
  export type LiveCapabilityConfig = Omit<CapabilityConfig, "connect" | "resource">;
@@ -141,6 +141,7 @@ function build(mode, defaults, options) {
141
141
  ...(options.storage === undefined ? {} : { storage: options.storage }),
142
142
  ...(options.errors === undefined ? {} : { errors: options.errors }),
143
143
  ...(options.runtime === undefined ? {} : { runtime: options.runtime }),
144
+ ...(options.nested === undefined ? {} : { nested: options.nested }),
144
145
  });
145
146
  }
146
147
  export const presets = {
@@ -229,6 +229,14 @@ export interface PortholeFrameProps {
229
229
  readonly onRefused?: (capability: CapabilityName, refusal: Refusal) => void;
230
230
  /** Too many declines: the display stops asking until it runs again. */
231
231
  readonly onMuted?: () => void;
232
+ /**
233
+ * The content moved the keyboard into its frame from one of the page's text fields without the
234
+ * person, and focus went back (P109); `typing`: the person was typing on the page. A display
235
+ * that keeps doing it is stopped (`onContentError` says so).
236
+ */
237
+ readonly onFocusTaken?: (taken: {
238
+ readonly typing: boolean;
239
+ }) => void;
232
240
  /**
233
241
  * How the frame's first document went: loaded, blocked (and why), or a timeout. A host shows its
234
242
  * own fallback (a url-mode app "Open in a new tab") on anything but loaded.
@@ -415,6 +415,9 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
415
415
  case "muted":
416
416
  frame.onMuted?.();
417
417
  return;
418
+ case "focusTaken":
419
+ frame.onFocusTaken?.(detail);
420
+ return;
418
421
  case "outcome":
419
422
  frame.onOutcome?.(detail);
420
423
  return;
@@ -532,6 +535,7 @@ function Mount({ frame, page, initialHeightPx, placeholder, run }) {
532
535
  "navigationBlocked",
533
536
  "refused",
534
537
  "muted",
538
+ "focusTaken",
535
539
  "outcome",
536
540
  "annotation",
537
541
  "contentError",
@@ -1,4 +1,4 @@
1
- import { unseen } from "../bridge/unseen.js";
1
+ import { unseenStrict, withoutUnseen } from "../bridge/unseen.js";
2
2
  import { fileLimits, filePathProblem } from "../files/paths.js";
3
3
  import { fileTypeOf } from "../files/types.js";
4
4
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
@@ -21,33 +21,55 @@ export function base64Bytes(value) {
21
21
  return (value.length / 4) * 3 - padding;
22
22
  }
23
23
  const encoder = new TextEncoder();
24
+ /** Characters that draw as a blank: spaces of every kind, tabs, new lines, the braille blank. */
25
+ const BLANK = /^[\p{White_Space}\u2800]*$/u;
26
+ /** More than 32 blanks in a row on a line, or more than two blank lines in a row (P109). */
27
+ const BLANK_RUN = /[\p{Zs}\t\u2800]{33}|\n(?:[\p{Zs}\t\u2800]*\n){3}/u;
28
+ /** Line and paragraph separators: a line break a person may see as nothing (Firefox, WebKit). */
29
+ const SEPARATORS = /[\u2028\u2029]/u;
24
30
  /**
25
- * A draft (P108): text the person will post in their own name, so all of it must be text they can
26
- * see: at most 2,000 characters, well-formed, not blank, and nothing `unseen` (P100: no zero-width
27
- * or bidi characters, no tags, no controls but a new line and a tab), which a host would show as
28
- * nothing and an agent would read as the person's words. Lines and tabs are fine: a checklist.
31
+ * A draft (P108, P109): text the person will post in their own name, so all of it must be text
32
+ * they can see: at most 2,000 characters, well-formed, and nothing invisible (`unseenStrict`: no
33
+ * zero-width characters, bidi or tag characters, controls but a new line and a tab; a joiner or
34
+ * non-joiner only between two letters or marks, a variation selector only after a pictograph), no line or paragraph
35
+ * separator, not blank-looking, at most 32 blanks in a row and two blank lines in a row (so that
36
+ * "whole" is something a host can show). Lines and tabs are fine: a checklist.
29
37
  */
30
38
  const draftText = (value) => typeof value === "string" &&
31
- value.trim() !== "" &&
32
39
  value.length <= 2_000 &&
33
40
  value.isWellFormed() &&
34
- !unseen(value);
41
+ !BLANK.test(value) &&
42
+ !unseenStrict(value) &&
43
+ !SEPARATORS.test(value) &&
44
+ !BLANK_RUN.test(value);
45
+ /**
46
+ * An anchor's label or quote, shown beside the draft (P109): the page's short text, without what a
47
+ * person can't see (P105's `withoutUnseen`, line and paragraph separators too), or null if nothing
48
+ * visible is left. Shown, never posted as the person's words, so cleaned rather than refused.
49
+ */
50
+ const shownText = (value, max) => {
51
+ if (!shortText(value, max)) {
52
+ return null;
53
+ }
54
+ const seen = withoutUnseen(value).replace(/[\u2028\u2029]/gu, "");
55
+ return BLANK.test(seen) ? null : seen;
56
+ };
35
57
  export function parseCommentRequest(args) {
36
58
  const anchor = isRecord(args) ? args.anchor : undefined;
37
59
  if (!isRecord(anchor) || !shortText(anchor.name, 256)) {
38
60
  return null;
39
61
  }
40
62
  const draft = isRecord(args) ? args.draft : undefined;
41
- if ((anchor.label !== undefined && !shortText(anchor.label, 200)) ||
42
- (anchor.quote !== undefined && !shortText(anchor.quote, 2_000)) ||
43
- (draft !== undefined && !draftText(draft))) {
63
+ const label = anchor.label === undefined ? undefined : shownText(anchor.label, 200);
64
+ const quote = anchor.quote === undefined ? undefined : shownText(anchor.quote, 2_000);
65
+ if (label === null || quote === null || (draft !== undefined && !draftText(draft))) {
44
66
  return null;
45
67
  }
46
68
  return {
47
69
  anchor: {
48
70
  name: anchor.name,
49
- ...(anchor.label === undefined ? {} : { label: anchor.label }),
50
- ...(anchor.quote === undefined ? {} : { quote: anchor.quote }),
71
+ ...(label === undefined ? {} : { label }),
72
+ ...(quote === undefined ? {} : { quote }),
51
73
  },
52
74
  ...(draft === undefined ? {} : { draft }),
53
75
  };
@@ -7,7 +7,7 @@ export const RUNTIME_TYPES = {
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",
@@ -3,6 +3,7 @@ import { DEFAULT_ENTRY, lookupFile, requestFilePath } from "../files/paths.js";
3
3
  import { fileTypeOf } from "../files/types.js";
4
4
  import { isCodeAsset } from "../runtime/requests.js";
5
5
  import { sha256, utf8 } from "./crypto.js";
6
+ import { NESTED_FILE_HEADERS } from "./nested.js";
6
7
  const HEX = /^[0-9a-f]{64}$/u;
7
8
  const YEAR = 31_536_000;
8
9
  const hex = (bytes) => Array.from(bytes, (byte) => byte.toString(16).padStart(2, "0")).join("");
@@ -156,6 +157,8 @@ export async function serveFile(serving) {
156
157
  return nothing(serving, 404, method);
157
158
  }
158
159
  const { type, role } = fileTypeOf(found.path);
160
+ // A nested page (P111): in its shell's child, an opaque origin.
161
+ const nested = serving.compiled.config.nested === true;
159
162
  // In a frame, the version's files are at a sealed address (P083), which their own loads of the
160
163
  // artifact's assets carry as their `Referer` (P091): to this origin only, never another.
161
164
  const referrer = serving.base.startsWith("/__porthole/f/") &&
@@ -167,11 +170,17 @@ export async function serveFile(serving) {
167
170
  // A page and a script (a worker's policy is its script's) get the page's CSP, a page with its
168
171
  // frame's sandbox, on a tab of its own too (P099); anything else runs nothing when opened on
169
172
  // its own.
173
+ // A nested page's files are on its shell's origin (P111, after the review): every one carries a
174
+ // sandbox, so none opened as a document on its own (a tab, "open image in new tab") runs on that
175
+ // origin. Pages run their scripts, opaque; anything else runs nothing (a file's is inert already,
176
+ // a script's gets one too).
170
177
  const csp = role === "file"
171
178
  ? INERT_FILE_CSP
172
179
  : role === "page"
173
180
  ? servedDocumentCsp(serving.compiled.config, directives)
174
- : serializeCsp(directives);
181
+ : nested
182
+ ? `${serializeCsp(directives)}; sandbox`
183
+ : serializeCsp(directives);
175
184
  const headers = new Headers({
176
185
  "content-type": type,
177
186
  "x-content-type-options": "nosniff",
@@ -186,7 +195,8 @@ export async function serveFile(serving) {
186
195
  if (role === "page") {
187
196
  // Every page of the set in the shell (P081): its hardening, its host functions, its theme.
188
197
  const html = serving.compiled.shellDocument({
189
- origins: serving.hostOrigins,
198
+ // A nested page hears its shell, on its own origin, never the host (P111).
199
+ origins: nested ? [serving.origin] : serving.hostOrigins,
190
200
  document: await textOf(body),
191
201
  cspMeta: false,
192
202
  ...(referrer === "same-origin" ? { referrer } : {}),
@@ -222,8 +232,14 @@ export async function serveFile(serving) {
222
232
  }
223
233
  headers.set("cache-control", serving.pinned ? `private, max-age=${YEAR}, immutable` : "private, no-cache");
224
234
  // Only this origin's own pages load it: no other content origin (a sibling, same-site without
225
- // the public suffix list) can embed it with the viewer's cookie.
235
+ // the public suffix list) can embed it with the viewer's cookie. A nested page's origin is
236
+ // opaque, and its files carry their access in their path, never a cookie (P111).
226
237
  headers.set("cross-origin-resource-policy", "same-origin");
238
+ if (nested) {
239
+ for (const [name, value] of Object.entries(NESTED_FILE_HEADERS)) {
240
+ headers.set(name, value);
241
+ }
242
+ }
227
243
  headers.set("accept-ranges", "bytes");
228
244
  if (role === "file" && type === "application/octet-stream") {
229
245
  headers.set("content-disposition", "attachment");
@@ -37,6 +37,7 @@ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, type ContentHealthVie
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, type ContentDomainInfo, type ContentDomainProblem, } from "./domain.ts";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, type D1Like, type D1StatementLike, } from "./tickets.ts";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.ts";
40
+ export { NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedShellCsp, nestedShellResponse, } from "./nested.ts";
40
41
  export { isHostLabel, prefixedName, type Naming } from "./naming.ts";
41
42
  export { conformancePage } from "../conformance/page.ts";
42
43
  export type { PortholeConfig } from "../config/schema.ts";
@@ -37,6 +37,10 @@ export { createContentHost, HEALTH_PATH, ISSUE_BODY_BYTES, ASSET_LIBRARY_PATH, i
37
37
  export { clashOf, contentDomain, ContentDomainError, hostnameOf, } from "./domain.js";
38
38
  export { d1TicketSchema, d1TicketStore, memoryTicketStore, } from "./tickets.js";
39
39
  export { FRAME_STATUS_METHOD } from "../isolation/types.js";
40
+ // A nested page (P111): Porthole's shell at the framed address, the page and its files below the
41
+ // sealed prefix. `/server` serves them for a config with `nested`; a content Worker of its own
42
+ // answers the same (docs/ADOPTING.md, "Nested pages").
43
+ export { NESTED_FILE_HEADERS, NESTED_FILES_PREFIX, nestedAncestors, nestedShellCsp, nestedShellResponse, } from "./nested.js";
40
44
  export { isHostLabel, prefixedName } from "./naming.js";
41
45
  // The page an app serves in conformance test mode (P071).
42
46
  export { conformancePage } from "../conformance/page.js";
@@ -0,0 +1,37 @@
1
+ import type { CompiledConfig } from "../compile/compile.ts";
2
+ import { type FrameShellOptions } from "../shell/frame.ts";
3
+ /**
4
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
5
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
6
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
7
+ * a host serving its own content origin (its own Worker) answers the same.
8
+ */
9
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
10
+ export declare const NESTED_FILES_PREFIX = "/__porthole/f/";
11
+ /**
12
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
13
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
14
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
15
+ * this (a framed URL's document never does).
16
+ */
17
+ export declare function nestedShellCsp(script: string, origin: string, hostOrigins: readonly string[]): string;
18
+ /**
19
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
20
+ * stored (it carries the page's sealed address), its page at `options.page`.
21
+ */
22
+ export declare function nestedShellResponse(compiled: CompiledConfig, options: FrameShellOptions & {
23
+ readonly origin: string;
24
+ readonly method?: string;
25
+ }): Response;
26
+ /**
27
+ * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
28
+ * it, the host origins (`frame-ancestors` names every ancestor).
29
+ */
30
+ export declare const nestedAncestors: (origin: string, frameAncestors: string) => string;
31
+ /**
32
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
33
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
34
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
35
+ * is their access, never the request's origin.
36
+ */
37
+ export declare const NESTED_FILE_HEADERS: Readonly<Record<string, string>>;
@@ -0,0 +1,70 @@
1
+ import { servedPermissionsPolicy, serializeCsp } from "../compile/policy.js";
2
+ import { frameShellDocument, frameShellScript } from "../shell/frame.js";
3
+ import { sha256, utf8 } from "./crypto.js";
4
+ /**
5
+ * A nested page's serving (P111): what the address the host frames answers (Porthole's shell,
6
+ * `nestedShellResponse`), and what changes on the page and its files below the sealed prefix
7
+ * (`nestedAncestors`, `NESTED_FILE_HEADERS`). `/server` serves both for a config with `nested`;
8
+ * a host serving its own content origin (its own Worker) answers the same.
9
+ */
10
+ /** Where every page and file of a nested page is, on its origin: its sealed files' prefix. */
11
+ export const NESTED_FILES_PREFIX = "/__porthole/f/";
12
+ const base64 = (bytes) => btoa(String.fromCharCode(...bytes));
13
+ /**
14
+ * The shell's CSP (a header): its own script alone runs (by its hash), it frames and fetches
15
+ * nothing but its origin's sealed files (the page, the renewal), and only the host origins frame
16
+ * it. Nothing of the page's runs here: the page is a document of its own, which inherits none of
17
+ * this (a framed URL's document never does).
18
+ */
19
+ export function nestedShellCsp(script, origin, hostOrigins) {
20
+ const files = `${origin}${NESTED_FILES_PREFIX}`;
21
+ const directives = [
22
+ ["default-src", "'none'"],
23
+ ["script-src", `'sha256-${base64(sha256(utf8(script)))}'`],
24
+ ["frame-src", files],
25
+ ["connect-src", files],
26
+ ["base-uri", "'none'"],
27
+ ["form-action", "'none'"],
28
+ ["frame-ancestors", ...hostOrigins],
29
+ ];
30
+ return serializeCsp(directives);
31
+ }
32
+ /**
33
+ * The answer at the address the host frames, for a nested page (P111): Porthole's shell, never
34
+ * stored (it carries the page's sealed address), its page at `options.page`.
35
+ */
36
+ export function nestedShellResponse(compiled, options) {
37
+ const script = frameShellScript(options);
38
+ const headers = new Headers({
39
+ "content-type": "text/html; charset=utf-8",
40
+ "content-security-policy": nestedShellCsp(script, options.origin, options.origins),
41
+ "cache-control": "no-store",
42
+ "referrer-policy": "no-referrer",
43
+ "x-content-type-options": "nosniff",
44
+ "x-robots-tag": "noindex, nofollow",
45
+ });
46
+ // Denied to the shell, so to its child too (a frame's features are its parent's at most).
47
+ const permissions = servedPermissionsPolicy(compiled.config);
48
+ if (permissions !== null) {
49
+ headers.set("permissions-policy", permissions);
50
+ }
51
+ return new Response(options.method === "HEAD" ? null : frameShellDocument(script), {
52
+ status: 200,
53
+ headers,
54
+ });
55
+ }
56
+ /**
57
+ * Who may frame a nested page and its files' answers: its shell (the content origin) and, above
58
+ * it, the host origins (`frame-ancestors` names every ancestor).
59
+ */
60
+ export const nestedAncestors = (origin, frameAncestors) => `${origin} ${frameAncestors}`;
61
+ /**
62
+ * What a nested page's files (not its pages) carry beyond a served file's (P111): its page's
63
+ * origin is opaque, so a same-origin resource policy would refuse its own images and scripts, and
64
+ * its fetches, modules and fonts are CORS requests from `null`. The sealed address in their path
65
+ * is their access, never the request's origin.
66
+ */
67
+ export const NESTED_FILE_HEADERS = {
68
+ "cross-origin-resource-policy": "cross-origin",
69
+ "access-control-allow-origin": "*",
70
+ };
@@ -6,7 +6,9 @@ import { randomBytes } from "./crypto.js";
6
6
  import { isHostLabel, reservedLabels } from "./naming.js";
7
7
  import { enterPage, pageScript, SESSION_PATH, statusPage } from "./pages.js";
8
8
  import { libraryFile } from "./libraries.js";
9
- import { ownLoad, serveAsset, serveFile } from "./files.js";
9
+ import { isNavigation, ownLoad, serveAsset, serveFile } from "./files.js";
10
+ import { nestedAncestors, nestedShellResponse } from "./nested.js";
11
+ import { DEFAULT_ENTRY } from "../files/paths.js";
10
12
  import { isPortholeCookie, setsPortholeCookie } from "./proxy.js";
11
13
  import { assetCodeRuns, assetCspDirectives, INERT_FILE_CSP, servedDocumentCsp, servedPermissionsPolicy, } from "../compile/policy.js";
12
14
  import { parseViewer } from "../runtime/levels.js";
@@ -425,6 +427,7 @@ export function createServer(options) {
425
427
  }
426
428
  return {
427
429
  html: config.shellDocument({ origins, document: stored.html, cspMeta: false }),
430
+ document: stored.html,
428
431
  compiled: config,
429
432
  assets: true,
430
433
  };
@@ -648,10 +651,10 @@ export function createServer(options) {
648
651
  return null;
649
652
  }
650
653
  }
651
- function documentHeaders(csp, permissions) {
654
+ function documentHeaders(csp, permissions, ancestors = frameAncestors) {
652
655
  return new Headers({
653
656
  "content-type": "text/html; charset=utf-8",
654
- "content-security-policy": `${csp}; frame-ancestors ${frameAncestors}`,
657
+ "content-security-policy": `${csp}; frame-ancestors ${ancestors}`,
655
658
  // What the frame's `allow` doesn't grant, denied on a tab of its own too (P099).
656
659
  ...(permissions === null ? {} : { "permissions-policy": permissions }),
657
660
  "cache-control": "no-store",
@@ -730,7 +733,9 @@ export function createServer(options) {
730
733
  }
731
734
  const access = await sealedAccess(request, label, token);
732
735
  if (access === null) {
733
- return page(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", method, "session");
736
+ // In a nested page's frame (P111) its shell frames it and hears it, on this origin; a
737
+ // config without nesting never frames this address but at the host.
738
+ return statusPage(401, "This has ended", "Content here opens for a while. Open it again from the app that showed it.", nestedAncestors(origin, frameAncestors), method, "session", [...options.hostOrigins, origin]);
734
739
  }
735
740
  // An asset of this artifact's library, at the frame's own sealed address (P091): every engine
736
741
  // sends a frame's path, where some send no Referer that names it.
@@ -815,6 +820,43 @@ export function createServer(options) {
815
820
  if (served === null) {
816
821
  return page(404, "Not found", "This page, or this version of it, doesn't exist.", method);
817
822
  }
823
+ // A nested page (P111): the address the host frames (a ticket's, a cookie's, an entered
824
+ // one's) answers Porthole's shell, which frames the page at its sealed files' address; only
825
+ // that address, below the sealed prefix, answers the page and its files, without a cookie.
826
+ const nested = served.compiled.config.nested === true;
827
+ const sealedAt = at !== undefined && at.base.startsWith(FILES_PREFIX);
828
+ if (nested && !sealedAt) {
829
+ if (!isNavigation(request)) {
830
+ return page(404, "Not found", "This page's files are at its own address.", method);
831
+ }
832
+ const sealed = await sealFiles(access);
833
+ let rest = "";
834
+ if ("files" in served) {
835
+ const entry = served.files.entry ?? DEFAULT_ENTRY;
836
+ rest =
837
+ at !== undefined && at.rest !== ""
838
+ ? at.rest
839
+ : entry.includes("/")
840
+ ? entry
841
+ .split("/")
842
+ .map((segment) => encodeURIComponent(segment))
843
+ .join("/")
844
+ : "";
845
+ }
846
+ const shell = nestedShellResponse(served.compiled, {
847
+ origin: access.origin,
848
+ origins: options.hostOrigins,
849
+ page: `${access.origin}${sealed.base}${rest}`,
850
+ renew: { url: `${access.origin}${sealed.base}__porthole/renew`, expires: sealed.expires },
851
+ method,
852
+ });
853
+ if (cookie !== null) {
854
+ shell.headers.set("set-cookie", cookie);
855
+ }
856
+ return shell;
857
+ }
858
+ // Below the sealed prefix, a nested page and its files are framed by its shell too.
859
+ const ancestors = nested ? nestedAncestors(access.origin, frameAncestors) : frameAncestors;
818
860
  if ("files" in served) {
819
861
  if (at !== undefined) {
820
862
  return serveFile({
@@ -828,7 +870,7 @@ export function createServer(options) {
828
870
  source: at.source,
829
871
  compiled: served.compiled,
830
872
  hostOrigins: options.hostOrigins,
831
- frameAncestors,
873
+ frameAncestors: ancestors,
832
874
  ...versionOf(access.instance),
833
875
  });
834
876
  }
@@ -859,11 +901,19 @@ export function createServer(options) {
859
901
  // A page that may use its artifact's assets loads them from its own origin (P089); every
860
902
  // served page carries its frame's sandbox, a tab of its own included (P099).
861
903
  const { config, cspDirectives } = served.compiled;
862
- const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config));
904
+ const headers = documentHeaders(servedDocumentCsp(config, served.assets ? assetCspDirectives(config, cspDirectives, access.origin) : cspDirectives), servedPermissionsPolicy(config), ancestors);
863
905
  if (cookie !== null) {
864
906
  headers.set("set-cookie", cookie);
865
907
  }
866
- return new Response(method === "HEAD" ? null : served.html, { status: 200, headers });
908
+ // A nested page's document takes messages from its shell, on its own origin (P111).
909
+ const html = nested
910
+ ? served.compiled.shellDocument({
911
+ origins: [access.origin],
912
+ document: served.document ?? "",
913
+ cspMeta: false,
914
+ })
915
+ : served.html;
916
+ return new Response(method === "HEAD" ? null : html, { status: 200, headers });
867
917
  }
868
918
  /**
869
919
  * An asset at `/_blob/<id>` (P089, after the review): a request carrying an access to an
@@ -8,7 +8,7 @@
8
8
  * (`porthole/annotate.selected|unselected|cancelled|anchored|activated`):
9
9
  * - picking an element: the element under the pointer (or finger) is outlined with its name; a
10
10
  * click or tap picks it, and the content's own handlers never see that click (unless the content
11
- * patched the DOM's built-ins, P105); Escape cancels;
11
+ * patched the DOM's built-ins, P105); Escape cancels (while selecting text too, P112);
12
12
  * - selecting text: each selection that settles is reported, with where it is, and its clearing;
13
13
  * - marks: each anchor is found in the content as it is now (its CSS selector, its text where it
14
14
  * was, its text anywhere, its words with any spacing) and drawn over it, in a layer of the