@botiverse/porthole 0.14.7 → 0.14.9

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 (87) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/dist/bridge/bridge.d.ts +6 -0
  3. package/dist/bridge/bridge.js +5 -0
  4. package/dist/check/files.js +2 -0
  5. package/dist/check/lint.js +82 -3
  6. package/dist/check/page-source.js +1 -1
  7. package/dist/compile/policy.d.ts +17 -6
  8. package/dist/compile/policy.js +22 -7
  9. package/dist/config/capabilities.d.ts +16 -2
  10. package/dist/config/capabilities.js +8 -0
  11. package/dist/config/schema.d.ts +13 -0
  12. package/dist/config/validate.js +15 -0
  13. package/dist/conformance/harness-source.js +1 -1
  14. package/dist/conformance/kit.d.ts +5 -0
  15. package/dist/conformance/kit.js +21 -0
  16. package/dist/conformance/limits.js +10 -5
  17. package/dist/conformance/probes.js +139 -28
  18. package/dist/conformance/served.js +25 -4
  19. package/dist/find/types.d.ts +83 -0
  20. package/dist/find/types.js +29 -0
  21. package/dist/find/validate.d.ts +17 -0
  22. package/dist/find/validate.js +82 -0
  23. package/dist/guide/guide.js +2 -1
  24. package/dist/guide/limits.js +8 -1
  25. package/dist/host/create-host.js +249 -4
  26. package/dist/host/pass-on.js +3 -2
  27. package/dist/host/types.d.ts +51 -0
  28. package/dist/index.d.ts +4 -2
  29. package/dist/index.js +4 -1
  30. package/dist/presets/presets.d.ts +6 -0
  31. package/dist/presets/presets.js +6 -0
  32. package/dist/react/frame.d.ts +43 -0
  33. package/dist/react/frame.js +107 -3
  34. package/dist/react/view.js +2 -0
  35. package/dist/runtime/contract.d.ts +1 -1
  36. package/dist/runtime/contract.js +1 -1
  37. package/dist/server/files.js +4 -3
  38. package/dist/server/server.js +4 -1
  39. package/dist/shell/annotate.js +2 -95
  40. package/dist/shell/document.d.ts +3 -3
  41. package/dist/shell/document.js +5 -3
  42. package/dist/shell/find.d.ts +82 -0
  43. package/dist/shell/find.js +725 -0
  44. package/dist/shell/plan.d.ts +5 -0
  45. package/dist/shell/plan.js +2 -0
  46. package/dist/shell/runtime.d.ts +30 -1
  47. package/dist/shell/runtime.js +789 -105
  48. package/dist/shell/text.d.ts +17 -0
  49. package/dist/shell/text.js +140 -0
  50. package/docs/ADOPTING.md +103 -0
  51. package/docs/ARCHITECTURE.md +10 -3
  52. package/docs/DECISIONS.md +513 -1
  53. package/docs/DESIGN.md +40 -4
  54. package/docs/THREAT_MODEL.md +75 -6
  55. package/docs/insertion-entry-points.md +112 -0
  56. package/package.json +1 -1
  57. package/src/bridge/bridge.ts +7 -0
  58. package/src/check/files.ts +2 -0
  59. package/src/check/lint.ts +97 -8
  60. package/src/compile/policy.ts +23 -6
  61. package/src/config/capabilities.ts +13 -1
  62. package/src/config/schema.ts +13 -0
  63. package/src/config/validate.ts +16 -0
  64. package/src/conformance/kit.ts +22 -0
  65. package/src/conformance/limits.ts +10 -5
  66. package/src/conformance/probes.ts +149 -28
  67. package/src/conformance/served.ts +24 -4
  68. package/src/find/types.ts +86 -0
  69. package/src/find/validate.ts +101 -0
  70. package/src/guide/guide.ts +3 -1
  71. package/src/guide/limits.ts +9 -1
  72. package/src/host/create-host.ts +267 -4
  73. package/src/host/pass-on.ts +3 -2
  74. package/src/host/types.ts +52 -0
  75. package/src/index.ts +13 -0
  76. package/src/presets/presets.ts +15 -0
  77. package/src/react/frame.tsx +160 -1
  78. package/src/react/view.tsx +3 -0
  79. package/src/runtime/contract.ts +1 -1
  80. package/src/server/files.ts +8 -2
  81. package/src/server/server.ts +4 -1
  82. package/src/shell/annotate.ts +3 -95
  83. package/src/shell/document.ts +5 -3
  84. package/src/shell/find.ts +731 -0
  85. package/src/shell/plan.ts +7 -0
  86. package/src/shell/runtime.ts +792 -105
  87. package/src/shell/text.ts +140 -0
@@ -5,7 +5,7 @@ What Porthole protects, from whom, and where that protection ends. For each way
5
5
  guaranteed. [ADOPTING.md](ADOPTING.md) says how to set each one up, and
6
6
  [DESIGN.md](DESIGN.md) lists every defense with the test that proves it.
7
7
 
8
- **Status.** This describes Porthole 0.14.7 (2026-10-30). A review on 2026-10-19 found gaps, and every decision it led to
8
+ **Status.** This describes Porthole 0.14.9 (2026-11-04). A review on 2026-10-19 found gaps, and every decision it led to
9
9
  has merged ([§8](#8-fixes-in-flight) lists them). P096 changed the negative-control runner and CI,
10
10
  and the shipped conformance probes' messages and timing, not what they check. P104 (0.9.0's
11
11
  annotation markers) had a review of its own, and P105, in 0.10.0, is what it led to. 0.11.0 was
@@ -22,7 +22,13 @@ person, not the page, pressed in it (§7 "The keyboard", `comments`); and P112's
22
22
  additions for a host's comment modes (hints, as every report is, §7). 0.14.1: P114
23
23
  (porthole#56) serves a nested page's shell on a label of its own, on which nothing but nested
24
24
  pages' shells, their pages, those pages' files and status pages is ever served, so no other
25
- display of the scope is same-origin with the shell (S3).
25
+ display of the scope is same-origin with the shell (S3). 0.14.8: P128 lets a host opt a config
26
+ into a page's own nested frames (`nestedFrames: "own"`, off by default): its `srcdoc` frames and
27
+ frames of its own files load and run, in realms the shell's hardening never reaches (WebRTC, the
28
+ clipboard's guards: S1, S3); frames of other sites stay out. 0.14.9: P131 adds find
29
+ in page (`find`, off unless a config declares it): the host's find bar sends the person's query
30
+ into the frame, where the content can read it, and takes counts, a box and the find shortcut back
31
+ as the content's word (§6, §7 "Find in page"); no wall moves.
26
32
 
27
33
  ## 1. Two layers
28
34
 
@@ -77,7 +83,9 @@ the agent, but it is not a wall.
77
83
  Isolation doesn't stop content from sending out what it was given, or from drawing a fake. So:
78
84
  - its network is closed by default: the frame's CSP, the shell's defenses for channels a CSP
79
85
  doesn't cover (WebRTC, nested frames, resource hints), and the embedding page's `frame-src`
80
- against the frame navigating itself away;
86
+ against the frame navigating itself away. A host that opts into a page's own frames
87
+ (`nestedFrames: "own"`, P128) gives up the shell's defenses inside them: there, the CSP alone
88
+ closes the network;
81
89
  - everything beyond drawing is a host function the config declares, behind gates: a user
82
90
  gesture, a person's confirmation, consent, a rate;
83
91
  - the host draws its confirmations and consent outside the frame, where content can't draw over
@@ -186,6 +194,10 @@ Whatever the use:
186
194
  log them, show nothing for them. A url-mode app can still say any outcome (S6).
187
195
  - Take what the frame reports about annotations as UI hints (where to draw, what to open), never
188
196
  as permissions, and put nothing in a mark the page may not know (§7).
197
+ - Under `find` (P131), know that the page reads every query your find bar sends it, and declare
198
+ `find` only for displays whose pages may learn what the person searches for (not a third-party
199
+ app with egress, S5, unless you accept it). Take its counts as the bar's numbers, and open your
200
+ bar on `findRequested`, nothing more (§7 "Find in page").
189
201
  - Guard a view that a frame's report opens or moves (`activated`, `anchored`, `selected`,
190
202
  `tracked`: a comment's bubble, a composer, a card that follows its mark, which the page moves
191
203
  at will, up to 60 times a second). The content chooses when it appears and where, so it can bring it
@@ -231,7 +243,10 @@ Whatever the use:
231
243
  capability or the egress config names an origin), `form-action 'none'`, `frame-src 'none'`,
232
244
  `base-uri 'none'`, `object-src 'none'` and `webrtc 'block'`, and no `'self'` anywhere. Before
233
245
  content runs, the shell removes the `RTC*` constructors, drops nested frames, plugins and
234
- resource hints as they are inserted, and makes `document.open` and `write` throw.
246
+ resource hints as they are inserted, and makes `document.open` and `write` throw. Where the host
247
+ opts into the content's own frames (`nestedFrames: "own"`, P128; off by default), the shell keeps
248
+ `srcdoc` iframes (an inline widget has no files of its own) and drops every other frame and
249
+ plugin as before, a kept frame included once a change would point it elsewhere.
235
250
  - While it streams, drafts are drawn inert (no scripts, handlers or navigation); the whole runs
236
251
  once.
237
252
  - Only the host functions the config declares exist, each behind its default gates:
@@ -278,6 +293,11 @@ Whatever the use:
278
293
  **Not guaranteed**
279
294
 
280
295
  - On a page without that `frame-src`, a widget can send out whatever it was shown.
296
+ - With `nestedFrames: "own"` (P128, the host's choice), a widget's `srcdoc` frame is a realm where
297
+ none of the shell's defenses ran: it has WebRTC (a way out past `connect-src`, closed only where
298
+ an engine honors `webrtc 'block'`), resource hints, `document.write`, and `execCommand("copy")`
299
+ and copy listeners from a click in it (text the person didn't choose on their clipboard, with no
300
+ notice). The frame's CSP, which it inherits, still holds for everything else.
281
301
  - `copyText` needs only a gesture, not a confirmation: a widget can put text the person didn't
282
302
  choose on their clipboard when they click in it (pastejacking). The notice above is what tells
283
303
  them.
@@ -360,10 +380,17 @@ encrypted into the path, since WebKit keeps no cookie in a frame (P083).
360
380
  no other label can set; the entered mark names its label. A session names its scope, signed, so
361
381
  another label's session is never read as this one's, under https or on loopback (P101).
362
382
  - Pages, files and status pages carry their CSP in headers and `X-Robots-Tag: noindex`, and
363
- `frame-ancestors` names the app's origins only.
383
+ `frame-ancestors` names the app's origins only (with `nestedFrames: "own"`, P128, a file set's
384
+ files below its base name the page's own origin too, so its pages frame them).
364
385
  - Files: from the version's manifest only, typed by Porthole's table, `nosniff`; files other than
365
386
  pages are `Cross-Origin-Resource-Policy: same-origin`; a file set never registers a service
366
387
  worker; a page's CSP opens its own version's path, not its whole origin.
388
+ - A page's nested frames are removed, a `srcdoc` one and one of its own files alike, unless the
389
+ host opts in (`nestedFrames: "own"`, P128). Then an iframe of one of its version's own files or
390
+ with `srcdoc` loads and runs (a page of the set with its own shell), and every other frame
391
+ (another site, another path of the origin, a scheme, an empty one) and plugin is removed: the
392
+ page's `frame-src` opens its version's path alone, which also governs every navigation of its
393
+ frames. Not for a nested page (refused).
367
394
  - With a per-request check (`authorize`), the host decides again on every request; a deny is a
368
395
  403 that says `denied`.
369
396
  - A nested page (`nested: true`, P111): the framed address answers Porthole's shell alone, its
@@ -444,6 +471,11 @@ encrypted into the path, since WebKit keeps no cookie in a frame (P083).
444
471
  - A revocation reaches the next request. It doesn't reach a page already running, an open
445
472
  WebSocket, pinned files the browser cached (immutable for a year), or assets in bearer mode
446
473
  (§7).
474
+ - With `nestedFrames: "own"` (P128), a page has WebRTC: every iframe it keeps starts as an
475
+ `about:blank` of its own origin, which it reaches before anything loads there, and a `srcdoc`
476
+ frame runs none of the shell's defenses (resource hints, `document.write`, and a click's
477
+ `execCommand("copy")` and copy listeners, which put text on the clipboard with no notice). Its
478
+ frames can't navigate out of its version's path, and their sandbox is the page's.
447
479
 
448
480
  ### S4. Public links, and pages that are apps
449
481
 
@@ -667,7 +699,8 @@ fallback (a sign-in prompt with a link out): that is the door's wall (P125).
667
699
 
668
700
  What it is: the presets, the isolation, the egress walls, the shell, the bridge for the display's
669
701
  host functions (`sendPrompt`, `openLink`, `downloadFile`, `copyText`, `callTool`, `readData`,
670
- `subscribeData`, `setModelContext`, `reportError`, annotations) and the generated manual.
702
+ `subscribeData`, `setModelContext`, `reportError`, annotations, find in page) and the generated
703
+ manual.
671
704
 
672
705
  **Porthole guarantees** the two lines of [§4](#4-two-lines-of-defense) for each display except url
673
706
  mode (S6), with S1–S5's open items: isolation, closed egress, the gates. One config generates the
@@ -830,6 +863,42 @@ own frame, below the shell, P111), so:
830
863
  resolve, delete or reply); an anchor or a rect decides where something is drawn, never who may
831
864
  see or do anything.
832
865
 
866
+ **Find in page** (`find`, P131). The host draws its own find bar; the shell finds the query in the
867
+ content's text (annotations' text index) and highlights the matches in a layer of its own (a closed
868
+ shadow root, as annotations' marks; never the CSS Custom Highlight API, which is the content's to
869
+ read and rewrite). It shares its realm with the content, so:
870
+
871
+ - *What content learns.* The query (`porthole/find.query`, posted into the frame's window), each
872
+ time the host sends it (a bar that searches as the person types sends their typing, key by key),
873
+ whether it is case-sensitive, each move to the next or previous match, when the bar clears, and
874
+ whether the host draws its own bar (`porthole/find.handled`). The query is the person's words,
875
+ typed in the host's own UI: a page with a way out (an MCP App's `connectDomains`, S5; egress a
876
+ host opened; a carrier such as `db`, `mayPassOn`) can send what the person searched for to its
877
+ author. That is why `find` is a capability a config declares, in no preset by default; accepted
878
+ by the product owner, with hosts sending queries on a pause or Enter rather than at every key
879
+ (P131). A query holds only for the content it was asked of: a new run or other content forgets
880
+ it, so another page is never searched with it (it would learn the words from what matched).
881
+ - *What content can say.* Any count and current match (bounded: at most 1,000, whole numbers, the
882
+ current one among them), any box inside its frame (clamped to the frame's viewport, as
883
+ annotations' boxes, P104), and an `updated` while a query is shown. The host takes an answer only
884
+ for a query it asked, under that query's id; anything malformed is `"unsupported"` or a refusal.
885
+ A find bar's numbers, never a fact about the content.
886
+ - *The shortcut.* While the host draws its own bar (`find.takeShortcut(true)`), the shell cancels
887
+ the browser's find on Cmd+F (Apple) or Ctrl+F (elsewhere) in the frame and says `requested`; a
888
+ page that handles the key itself keeps it. The page can say `requested` without the key, or keep
889
+ the key from the shell. The host takes it only while the platform says the page's focus is in
890
+ the frame (a press on it or a Tab put it there, P109; control `find-requested-focus`): a page
891
+ can't open the host's bar, which takes focus, while the person types in the host's composer, so
892
+ their next keys can't be steered into the bar and from there into the frame as queries. With the
893
+ person already in the frame the page has their keys anyway, and the bar moves the keyboard out of
894
+ it. Where a platform can't tell, it passes, as the gesture gate does. Open the bar, nothing more.
895
+ - *What content can always do.* Hide, cover or move the layer, change its words so the count
896
+ changes, reach the layer through built-ins it patched (as annotations' layer, P105), or make the
897
+ search dear: linear in its text, at most 1,000 matches kept and 10,000 looked at, a query of 256
898
+ characters, found again at most once a second while the content changes, and of a burst of
899
+ queries only the latest searched (the others answered superseded); in an opaque frame that
900
+ shares the host's process that time is the host's too ([§5](#5-out-of-scope)).
901
+
833
902
  **The keyboard** (P109). Any display, of any kind and any version, can move the keyboard into its
834
903
  frame: `element.focus()` runs in the content's realm, where nothing of Porthole can stop it, and on
835
904
  Chromium and WebKit it needs no gesture. What the person goes on typing then goes to the page,
@@ -0,0 +1,112 @@
1
+ # Insertion entry points the frame guard covers
2
+
3
+ The shell's frame guard (step 3 of the runtime, `src/shell/runtime.ts`; P030, P128, P129, P130)
4
+ keeps frame-like elements (`FRAMES`: `iframe`, `frame`, `frameset`, `object`, `embed`, `portal`,
5
+ `fencedframe`) and the resource hints a CSP doesn't govern (`HINTS`) out of every tree content can
6
+ reach. This page lists every way content can put a node into a document, or get a subtree it can
7
+ put in later, and how each is guarded. `test/shell.test.ts` checks each row against the runtime.
8
+
9
+ The invariant (P130): **every insertion entry point is guarded, every subtree producer strips
10
+ before it returns, and under the default configuration no frame-capable element can exist in a
11
+ content-reachable tree.** The mutation observer stays behind all of it as the backstop.
12
+
13
+ Statuses:
14
+
15
+ - **wrapped**: the method or setter runs every node argument through `admit`/`strip` (built-ins
16
+ captured before content runs, called through `callOf`) before the platform connects anything.
17
+ This holds whatever the parent is, connected or detached.
18
+ - **parsed and stripped**: the markup is parsed in a detached element of the same kind (`parseIn`)
19
+ or by the platform's own parser, stripped, then moved in through a wrapped method or returned.
20
+ - **producer stripped**: an API that hands content a subtree strips that subtree synchronously
21
+ before content gets it.
22
+ - **refused**: the call throws a neutral error, as `document.write` does, and nothing is made.
23
+ - **text only**: the entry point inserts text, never elements.
24
+ - **nothing to guard**: the entry point makes only empty elements of fixed kinds, or copies or
25
+ moves nodes that already went through the guard (and, under the default configuration, can't
26
+ hold a frame-like element).
27
+
28
+ `strip` walks a node's own tree (what `querySelectorAll` reaches) and also what that never enters:
29
+ each template's content and each open shadow root's tree, however deeply they nest (a work list,
30
+ not recursion). A shadow root it finds is also watched by the observer.
31
+
32
+ ## Putting nodes into a document
33
+
34
+ | # | Entry point | Status | How |
35
+ | --- | --- | --- | --- |
36
+ | A1 | `Node.appendChild` / `insertBefore` / `replaceChild` | wrapped | the node argument is admitted; a refused one goes in as an empty text node |
37
+ | A2 | `append` / `prepend` / `replaceChildren` on Element, Document, DocumentFragment (ShadowRoot inherits them) | wrapped | every argument is admitted |
38
+ | A3 | `before` / `after` / `replaceWith` on Element, CharacterData, DocumentType | wrapped | every argument is admitted |
39
+ | A4 | `Element.insertAdjacentElement` | wrapped | the element argument is admitted |
40
+ | A5 | `insertAdjacentText`, `innerText`, `outerText`, `textContent`, `nodeValue` | text only | `textContent` and `nodeValue` also go through the attribute-turn guard |
41
+ | A6 | `Range.insertNode` / `surroundContents` | wrapped | the node argument is admitted |
42
+ | A7 | `innerHTML` setter (Element, ShadowRoot) | parsed and stripped | parsed in a detached element of the same kind; on an HTML `<template>` the markup goes into its content, which is stripped before the setter returns |
43
+ | A8 | `outerHTML` setter | parsed and stripped | parsed in the parent's kind; where the parent is a document the platform's setter refuses |
44
+ | A9 | `insertAdjacentHTML` | parsed and stripped | the position is read once; the nodes go in through the wrapped methods |
45
+ | A10 | `setHTML` (Sanitizer API; Element, ShadowRoot) | parsed and stripped | sent to the `innerHTML` path |
46
+ | A11 | `setHTMLUnsafe` (Element, ShadowRoot) | parsed and stripped | sent to the `innerHTML` path (no declarative shadow DOM) |
47
+ | A12 | `document.open` / `write` / `writeln` | refused | throw |
48
+ | A13 | `execCommand("insertHTML")` (and `copy`, `cut`, `paste`) | refused | the command name is read once |
49
+ | A14 | `document.body` setter | wrapped | the value is admitted; a refused one refuses the set (`HierarchyRequestError`) |
50
+ | A15 | `HTMLTableElement` `tHead` / `tFoot` / `caption` setters | wrapped | as A14 |
51
+ | A16 | `createTHead` / `createTFoot` / `createCaption` / `createTBody` / `insertRow` / `insertCell` | nothing to guard | they make empty elements of fixed kinds; anything put into them goes through A1–A3 |
52
+ | A17 | `HTMLSelectElement.add`, `HTMLOptionsCollection.add` | wrapped | the element argument is admitted |
53
+ | A18 | `select[i] = option`, `options[i] = option`, the `length` setters (indexed setters can't be wrapped) | nothing to guard | under the default configuration no frame-like element can be made (A21, A25) or parsed into a subtree content gets (section B), so a detached option can't hold one |
54
+ | A19 | `Element.attachShadow` | wrapped | `init` is read once, field by field, into a fresh object with no prototype, which is all the platform is given; the new root is guarded |
55
+ | A20 | Declarative shadow DOM | parsed and stripped | the parser entry points that would build it are closed (A11, A12) or sent to `DOMParser`'s parse (`Document.parseHTMLUnsafe`, `Document.parseHTML`), which builds none |
56
+ | A21 | `createElement` / `createElementNS` (Document; ShadowRoot where an engine has them), and what copies nodes: `cloneNode`, `importNode`, `Range.cloneContents` | nothing to guard | under the default configuration a `FRAMES` name is refused at creation, in any case and any namespace (the local name after a prefix included); the name is read once and that reading is what the platform gets. Nothing else makes a frame-like element: `new Option(…)`, `new Image()` and `new Audio()` make their own kinds, and a copy is of a tree that already holds none |
57
+ | A22 | `src` / `srcdoc` and other attribute setters on an iframe | wrapped | under the default configuration no iframe exists to set; under `nestedFrames: "own"` a kept iframe leaves the document before a change would make it any other (P128) |
58
+ | A23 | `<object>` / `<embed>` and the other `FRAMES` elements | refused | refused at creation under the default configuration; removed on every guarded insertion and by the observer under any configuration; never kept, not even under `"own"` |
59
+ | A24 | `moveBefore` (where an engine has it) | wrapped | the node argument is admitted |
60
+ | A25 | `CustomElementRegistry.define` with `extends` naming a `FRAMES` element | refused | under the default configuration; the options are read once into a fresh object |
61
+ | A26 | A markup method on Element, ShadowRoot, Document, DocumentFragment or Range not named above (one a later engine adds) | refused | any own method whose name contains `HTML`, other than those above, throws |
62
+
63
+ ## Producers: APIs that hand content a subtree it can insert later
64
+
65
+ | # | Producer | Status | How |
66
+ | --- | --- | --- | --- |
67
+ | B1 | `DOMParser.parseFromString`, every MIME type | producer stripped | the platform's parse, then `strip` of the document |
68
+ | B2 | `HTMLTemplateElement.content` | producer stripped | the getter strips the content before it returns it (and A7 strips what the template's `innerHTML` fills) |
69
+ | B3 | `Document.parseHTMLUnsafe`, `Document.parseHTML` | producer stripped | the platform's `DOMParser` parse, stripped |
70
+ | B4 | `document.implementation.createHTMLDocument` | producer stripped | the new document is stripped |
71
+ | B5 | `document.implementation.createDocument` | producer stripped | the new document is stripped (its document element included) |
72
+ | B6 | `Range.createContextualFragment` | producer stripped | the fragment is stripped |
73
+ | B7 | `XSLTProcessor.transformToFragment` / `transformToDocument` (where an engine has them) | producer stripped | the result is stripped |
74
+ | B8 | `XMLHttpRequest` `responseXML`, and `response` when it is a document | producer stripped | each getter strips the document before it returns it |
75
+ | B9 | `Document.importNode` / `adoptNode` | producer stripped | the clone (importNode) or the node (adoptNode) is stripped; one that is itself a frame-like element is refused |
76
+ | B10 | HTML inside SVG `<foreignObject>` and MathML `<annotation-xml>`, and markup that crosses namespaces while parsing | parsed and stripped | the walk matches HTML-namespace frame-like elements wherever they are in the subtree |
77
+ | B11 | Inert documents' own `body` setter, and nodes moved into the live document | wrapped | the same prototypes, so A14 and B9 apply |
78
+ | B12 | Template contents and open shadow roots inside any subtree the guard walks | producer stripped | `strip` enters each template's content and each open shadow root's tree, recursively |
79
+
80
+ ## Editing
81
+
82
+ | # | Entry point | Status | How |
83
+ | --- | --- | --- | --- |
84
+ | E1 | Paste, drop, replacement text and yank into editable content (`beforeinput` with `insertFromPaste`, `insertFromPasteAsQuotation`, `insertFromDrop`, `insertReplacementText`, `insertFromYank`) | text only | the shell's own `beforeinput` listener (on `window`, capturing, registered before content runs) cancels one whose data carries any type but `text/plain`, and inserts only its plain text through the editor's `insertText`, which carries no markup. Only the browser's own events are acted on. Composition (`insertCompositionText`) can't be cancelled, and carries text alone |
85
+
86
+ A drop or paste of formatted content into an editable region goes in as plain text. A text field
87
+ (`<input>`, `<textarea>`) takes text only and is unaffected.
88
+
89
+ ## The shell's own layers
90
+
91
+ Find in page (P131), where a config declares `find`, draws its highlights in a layer of the
92
+ shell's own: an element over the content holding a closed shadow root. It adds no entry point. It
93
+ is spliced into the runtime after step 3, takes the methods below then (the guarded ones), and
94
+ calls each through `callOf` (P129), so its nodes go in the way any node does:
95
+
96
+ - `createElement` for the layer, its style element and each highlight box (A21);
97
+ - `attachShadow` for the layer's closed root (A19);
98
+ - `appendChild` of the layer into the document element (A1);
99
+ - `replaceChildren` on the shadow root and on the element holding the boxes (A2);
100
+ - the `textContent` setter for its style sheet's text (A5).
101
+
102
+ It inserts nothing into the content's own trees: no element wraps or splits the content's text, and
103
+ the matches are ranges, read for their boxes only. Its inline styles are set through CSSOM
104
+ (`cssText`), and it doesn't use the CSS Custom Highlight API.
105
+
106
+ ## Under `nestedFrames: "own"`
107
+
108
+ The configuration that keeps a page's own iframes (P128) keeps creation open: an `iframe` can be
109
+ made, and the guards above decide when it is connected or changed (a kept frame leaves the
110
+ document before a change would make it any other). Elements that are never kept (`frame`,
111
+ `frameset`, `object`, `embed`, `portal`, `fencedframe`, an iframe that isn't the page's own) are
112
+ removed on every guarded insertion and by the observer. The trade-offs P128 records stand.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@botiverse/porthole",
3
- "version": "0.14.7",
3
+ "version": "0.14.9",
4
4
  "description": "A host-side sandbox for agent-made HTML: isolation, egress hardening, a themed shell, gated host functions, and the agent manual, from one config.",
5
5
  "homepage": "https://github.com/botiverse/porthole#readme",
6
6
  "bugs": {
@@ -8,6 +8,8 @@ import {
8
8
  } from "../config/capabilities.ts";
9
9
  import type { AnnotationReport } from "../annotate/types.ts";
10
10
  import { parseReport } from "../annotate/validate.ts";
11
+ import type { FindReport } from "../find/types.ts";
12
+ import { parseFindReport } from "../find/validate.ts";
11
13
  import type { PortholeConfig } from "../config/schema.ts";
12
14
  import { callGates, effectiveGates } from "../compile/policy.ts";
13
15
  import { boundedText } from "./bounded-text.ts";
@@ -84,6 +86,8 @@ export type BridgeEvent =
84
86
  /** The shell cancelled a navigation of the frame to `url` (P080): the content's word. */
85
87
  | { readonly type: "navigationBlocked"; readonly url: string }
86
88
  | { readonly type: "annotation"; readonly report: AnnotationReport }
89
+ /** What the frame said of find in page unasked (P131), checked. */
90
+ | { readonly type: "find"; readonly report: FindReport }
87
91
  | { readonly type: "refused"; readonly capability: CapabilityName; readonly refusal: Refusal }
88
92
  | { readonly type: "muted" };
89
93
 
@@ -319,6 +323,7 @@ const VALIDATORS: { readonly [N in CapabilityName]: Validator<N> } = {
319
323
  : null;
320
324
  },
321
325
  annotate: (args) => parseReport(args),
326
+ find: (args) => parseFindReport(args),
322
327
  // The runtime's own (P088-P090): their shapes and limits, before any gate.
323
328
  user: (args) => (args === undefined || isRecord(args) ? {} : null),
324
329
  comments: (args) => parseCommentRequest(args),
@@ -819,6 +824,8 @@ export function createBridge(options: BridgeOptions): DisplayBridge {
819
824
  onEvent({ type: "resize", ...size });
820
825
  } else if (capability === "annotate") {
821
826
  onEvent({ type: "annotation", report: args as CapabilityArgs["annotate"] });
827
+ } else if (capability === "find") {
828
+ onEvent({ type: "find", report: args as CapabilityArgs["find"] });
822
829
  } else {
823
830
  const report = args as CapabilityArgs["reportError"];
824
831
  if (report.navigationBlocked !== undefined) {
@@ -75,6 +75,8 @@ const REFERENCE_ATTRIBUTES: Readonly<Record<string, readonly string[]>> = {
75
75
  audio: ["src"],
76
76
  track: ["src"],
77
77
  embed: ["src"],
78
+ // A page's own frame (P128, `nestedFrames: "own"`): a file of the set, looked up as the rest.
79
+ iframe: ["src"],
78
80
  input: ["src"],
79
81
  link: ["href"],
80
82
  a: ["href"],
package/src/check/lint.ts CHANGED
@@ -6,8 +6,10 @@ import {
6
6
  librarySources,
7
7
  } from "../compile/policy.ts";
8
8
  import type { PortholeConfig } from "../config/schema.ts";
9
+ import { servesFiles } from "../files/paths.ts";
9
10
  import { sizeWords } from "../guide/limits.ts";
10
11
  import { originMatchesSource } from "../isolation/served.ts";
12
+ import { attributesOf } from "./markup.ts";
11
13
  import { scrollLock } from "./scroll.ts";
12
14
 
13
15
  /**
@@ -124,6 +126,72 @@ const OWN_CDN: readonly {
124
126
  { name: "Plotly", host: /^https:\/\/cdn\.plot\.ly\/plotly/u, pinned: /\d+\.\d+\.\d+/u },
125
127
  ];
126
128
 
129
+ /** The most of a tag's text a frame's attributes are read from: a `srcdoc` may hold markup. */
130
+ const MOST_TAG_CHARS = 65_536;
131
+
132
+ /** The most frame-like tags read for `strayFrame`: past them, the rest isn't looked at. */
133
+ const MOST_FRAMES = 200;
134
+
135
+ /**
136
+ * A tag's attributes' text, from just past its name to its closing `>` outside any quoted value
137
+ * (a `srcdoc` holds `<` and `>`), read at most `MOST_TAG_CHARS` far: linear in what it reads.
138
+ */
139
+ function tagText(content: string, from: number): string {
140
+ const end = Math.min(content.length, from + MOST_TAG_CHARS);
141
+ let quote = "";
142
+ for (let at = from; at < end; at += 1) {
143
+ const char = content[at];
144
+ if (quote !== "") {
145
+ if (char === quote) {
146
+ quote = "";
147
+ }
148
+ } else if (char === '"' || char === "'") {
149
+ quote = char;
150
+ } else if (char === ">") {
151
+ return content.slice(from, at);
152
+ }
153
+ }
154
+ return content.slice(from, end);
155
+ }
156
+
157
+ /**
158
+ * Under `nestedFrames: "own"` (P128), the first frame-like element that never loads, and why: a
159
+ * `<frame>`, `<object>` or `<embed>`; an `<iframe>` of another site (any scheme, `//`), of the
160
+ * origin's root (`/`), or with neither `src` nor `srcdoc`; one with a relative `src` where there
161
+ * are no files to frame (`relative`: false). Null where every frame is the page's own.
162
+ */
163
+ function strayFrame(
164
+ content: string,
165
+ relative: boolean,
166
+ ): { readonly tag: string; readonly src: string; readonly index: number } | null {
167
+ let read = 0;
168
+ for (const match of content.matchAll(/<(iframe|frame|object|embed)\b/giu)) {
169
+ read += 1;
170
+ if (read > MOST_FRAMES) {
171
+ break;
172
+ }
173
+ const tag = (match[1] ?? "").toLowerCase();
174
+ if (tag !== "iframe") {
175
+ return { tag, src: "", index: match.index };
176
+ }
177
+ const attributes = attributesOf(tagText(content, match.index + match[0].length));
178
+ if (attributes.some((each) => each.name === "srcdoc")) {
179
+ continue;
180
+ }
181
+ const src = (attributes.find((each) => each.name === "src")?.value ?? "").trim();
182
+ const elsewhere =
183
+ src === "" ||
184
+ /^[a-z][a-z0-9+.-]*:/iu.test(src) ||
185
+ src.startsWith("/") ||
186
+ src.startsWith("\\") ||
187
+ !relative;
188
+ if (elsewhere) {
189
+ return { tag, src, index: match.index };
190
+ }
191
+ }
192
+ return null;
193
+ }
194
+
127
195
  export function lintContent(config: PortholeConfig, content: string): Finding[] {
128
196
  return lintPage(config, content, { scrollLock: true });
129
197
  }
@@ -179,14 +247,35 @@ export function lintPage(
179
247
  }
180
248
  }
181
249
  }
182
- const frame = /<(iframe|frame|object|embed)\b/iu.exec(content);
183
- if (frame !== null) {
184
- add(
185
- "nested-frame",
186
- "error",
187
- `Remove the <${frame[1]?.toLowerCase()}>: nested frames and plugins are taken out of a ${it} and never run. Draw it inline instead.`,
188
- frame.index,
189
- );
250
+ if (config.nestedFrames === "own") {
251
+ // A page's own frames load (P128): only what never does is said.
252
+ const files = servesFiles(config);
253
+ const own = files
254
+ ? 'an <iframe> of one of its own files (a relative src, src="chart.html") or with srcdoc does'
255
+ : "an <iframe> with srcdoc does";
256
+ const stray = strayFrame(content, files);
257
+ if (stray !== null) {
258
+ add(
259
+ "nested-frame",
260
+ "error",
261
+ stray.tag !== "iframe"
262
+ ? `Remove the <${stray.tag}>: <frame>, <object> and <embed> are taken out of a ${it} and never run; ${own}.`
263
+ : stray.src === ""
264
+ ? `This <iframe> has neither src nor srcdoc, and is taken out of the ${it}: ${own}.`
265
+ : `Remove the <iframe src="${stray.src.slice(0, 200)}">: ${files ? "frames of other sites (or of another path of the address) are" : "frames of an address are"} taken out of a ${it} and never load; ${own}.`,
266
+ stray.index,
267
+ );
268
+ }
269
+ } else {
270
+ const frame = /<(iframe|frame|object|embed)\b/iu.exec(content);
271
+ if (frame !== null) {
272
+ add(
273
+ "nested-frame",
274
+ "error",
275
+ `Remove the <${frame[1]?.toLowerCase()}>: nested frames and plugins are taken out of a ${it} and never run. Draw it inline instead.`,
276
+ frame.index,
277
+ );
278
+ }
190
279
  }
191
280
  const write = /\bdocument\s*\.\s*write(?:ln)?\s*\(/u.exec(content);
192
281
  if (write !== null) {
@@ -139,20 +139,37 @@ export const FILE_SET_DIRECTIVES = [
139
139
  "worker-src",
140
140
  ] as const;
141
141
 
142
+ /**
143
+ * The directives a page of a file set opens to its version's own files under `config` (P082):
144
+ * `FILE_SET_DIRECTIVES`, and `frame-src` too where the config lets content frame its own files
145
+ * (`nestedFrames: "own"`, P128). Never `child-src`: every engine Porthole supports reads frames
146
+ * from `frame-src` (P038), and `child-src` is only its fallback (and workers', which have
147
+ * `worker-src`).
148
+ */
149
+ export function fileSetDirectives(config: PortholeConfig): readonly string[] {
150
+ return config.nestedFrames === "own"
151
+ ? [...FILE_SET_DIRECTIVES, "frame-src"]
152
+ : FILE_SET_DIRECTIVES;
153
+ }
154
+
142
155
  /**
143
156
  * A served page's CSP when it comes with files (P082): the frame's, with its version's own files
144
- * opened for each kind that loads (`FILE_SET_DIRECTIVES`), by `source`, the files' path on the
145
- * content origin (`https://a-x.example-usercontent.com/v/3/`). Never `'self'`: the origin's other
146
- * paths (other versions, Porthole's own) stay closed, and frames, plugins, forms and `<base>` stay
147
- * `'none'`. Opaque frames have no files, and keep P022's rule whole.
157
+ * opened for each kind that loads (`opened`: `FILE_SET_DIRECTIVES` by default, a server's
158
+ * `fileSetDirectives(config)`), by `source`, the files' path on the content origin
159
+ * (`https://a-x.example-usercontent.com/v/3/`).
160
+ * Never `'self'`: the origin's other paths (other versions, Porthole's own) stay closed, and
161
+ * plugins, forms and `<base>` stay `'none'`, frames too unless the config opts into its own
162
+ * (P128: `frame-src` its version's path, never another origin). Opaque frames have no files, and
163
+ * keep P022's rule whole.
148
164
  */
149
165
  export function fileSetCspDirectives(
150
166
  directives: readonly CspDirective[],
151
167
  source: string,
168
+ opened: readonly string[] = FILE_SET_DIRECTIVES,
152
169
  ): CspDirective[] {
153
- const opened = new Set<string>(FILE_SET_DIRECTIVES);
170
+ const open = new Set<string>(opened);
154
171
  return directives.map(([name, ...sources]) => {
155
- if (!opened.has(name)) {
172
+ if (!open.has(name)) {
156
173
  return [name, ...sources];
157
174
  }
158
175
  const kept = sources.filter((each) => each !== "'none'");
@@ -1,4 +1,5 @@
1
1
  import type { AnnotationReport } from "../annotate/types.ts";
2
+ import type { FindReport } from "../find/types.ts";
2
3
  import type { DbRequest, DbResult } from "../runtime/db.ts";
3
4
  import type {
4
5
  ArtifactInfo,
@@ -32,6 +33,7 @@ export const CAPABILITY_NAMES = [
32
33
  "resize",
33
34
  "copyText",
34
35
  "annotate",
36
+ "find",
35
37
  // The capability runtime's own (P085, `config.runtime`): reached through `porthole.use`.
36
38
  "user",
37
39
  "comments",
@@ -84,7 +86,7 @@ export interface CapabilitySpec {
84
86
  /**
85
87
  * How content reaches it without the shell's global: the MCP Apps request (or Porthole's own,
86
88
  * `porthole/…`, where the standard has none), and the official App SDK's method for it, if any.
87
- * Absent for what the shell does by itself (sizes, errors, annotations).
89
+ * Absent for what the shell does by itself (sizes, errors, annotations, find).
88
90
  */
89
91
  readonly request?: { readonly method: string; readonly sdk?: string };
90
92
  /**
@@ -175,6 +177,13 @@ export const CAPABILITIES = {
175
177
  * (it shares the realm): UI hints for the host, never permissions.
176
178
  */
177
179
  annotate: { defaultGates: [rate(120)], served: "event" },
180
+ /**
181
+ * Find in page (P131): the host's find bar asks the shell to find the person's words in the
182
+ * content and highlight them; the shell answers how many and which is current, and says when
183
+ * the person pressed the find shortcut in the frame. The query goes into the content's realm,
184
+ * which can read it; what the frame says back is the content's word: a find bar's numbers.
185
+ */
186
+ find: { defaultGates: [rate(120)], served: "event" },
178
187
  /** Who is viewing (P087): answered from the viewer the host gave the display. */
179
188
  user: { defaultGates: [rate(60)], served: "viewer", request: { method: "porthole/call" } },
180
189
  /** Opens the host's comment composer at the page's anchor (P090): write-only. */
@@ -221,6 +230,8 @@ export interface CapabilityArgs {
221
230
  readonly copyText: { readonly text: string };
222
231
  /** What the frame reported, once checked (`AnnotationReport`). */
223
232
  readonly annotate: AnnotationReport;
233
+ /** What the frame said unasked, once checked (`FindReport`): the shortcut, a changed count. */
234
+ readonly find: FindReport;
224
235
  readonly user: Readonly<Record<string, never>>;
225
236
  readonly comments: CommentRequest;
226
237
  readonly artifact: ArtifactRequest;
@@ -247,6 +258,7 @@ export interface CapabilityResults {
247
258
  /** Whether the text was copied. */
248
259
  readonly copyText: boolean;
249
260
  readonly annotate: undefined;
261
+ readonly find: undefined;
250
262
  readonly user: UserInfo;
251
263
  /** Whether the composer opened. Never a thread: content doesn't read comments (P090). */
252
264
  readonly comments: boolean;
@@ -269,6 +269,19 @@ export interface PortholeConfig {
269
269
  * page has no storage of its own (an in-memory stand-in) and fetches nothing with a cookie.
270
270
  */
271
271
  readonly nested?: true;
272
+ /**
273
+ * Which nested frames content may make (P128). `none` (default, and absent): the shell removes
274
+ * every frame-like element content adds, and the CSP's `frame-src` is `'none'`. `own`: an
275
+ * `<iframe>` of one of the page's own files (its `src` under its version's own address, P082)
276
+ * and a `srcdoc` one load and run; frames of other sites, `<frame>`, `<object>` and `<embed>`
277
+ * are still removed, and a served file set's `frame-src` opens its version's own path only.
278
+ * A weakening, opted into: a child frame is a realm of its own, where the shell's WebRTC
279
+ * removal, clipboard guards and navigation cancel never ran (a page of the set framed there has
280
+ * its own shell; a `srcdoc` frame, or the `about:blank` a new frame starts as, has none), so
281
+ * content reaches WebRTC and the clipboard's events there. Not for url mode, a live widget
282
+ * (no network of its own, P079) or a nested page (P111).
283
+ */
284
+ readonly nestedFrames?: "none" | "own";
272
285
  }
273
286
 
274
287
  export interface StorageConfig {
@@ -325,6 +325,7 @@ export function validateConfig(
325
325
  "errors",
326
326
  "runtime",
327
327
  "nested",
328
+ "nestedFrames",
328
329
  ],
329
330
  "config",
330
331
  );
@@ -710,6 +711,21 @@ export function validateConfig(
710
711
  }
711
712
  }
712
713
 
714
+ // A page's own nested frames (P128): opted into, never a default.
715
+ if (config.nestedFrames !== undefined) {
716
+ if (config.nestedFrames !== "none" && config.nestedFrames !== "own") {
717
+ fail("config.nestedFrames", 'must be "none" or "own", or left out');
718
+ }
719
+ if (config.nestedFrames === "own" && config.mode === "url") {
720
+ fail("config.nestedFrames", "url mode has no shell: its app's frames are its own");
721
+ }
722
+ // A nested page's frames have an opaque ancestor, which no frame-ancestors source matches:
723
+ // none of its own files would load in one. Not measured yet.
724
+ if (config.nestedFrames === "own" && config.nested === true) {
725
+ fail("config.nestedFrames", 'a nested page (P111) has no "own" frames yet: leave it out');
726
+ }
727
+ }
728
+
713
729
  if (config.errors !== undefined) {
714
730
  if (config.errors !== "agent" && config.errors !== "host" && config.errors !== "none") {
715
731
  fail("config.errors", 'must be "agent", "host" or "none"');
@@ -66,6 +66,17 @@ export function attack(code: string, markup = ""): string {
66
66
  document.removeEventListener("securitypolicyviolation", seen);
67
67
  return blocked;
68
68
  };
69
+ // An element of \`tag\`, or null where the shell refuses to make one (P130: a frame-like element,
70
+ // under the default config): the guard held, and \`r.refused\` lists what was refused at creation.
71
+ const created = (tag) => {
72
+ try {
73
+ return document.createElement(tag);
74
+ } catch (error) {
75
+ if (!error || error.name !== "NotSupportedError") throw error;
76
+ r.refused = (r.refused || []).concat(tag);
77
+ return null;
78
+ }
79
+ };
69
80
  try {
70
81
  ${code}
71
82
  } catch (error) {
@@ -78,3 +89,14 @@ ${code}
78
89
  }
79
90
 
80
91
  export const inline = (options: PresetOptions = {}) => presets.inlineWidget(options);
92
+
93
+ /**
94
+ * Records, as a measured fact, the frame-like elements a probe's verdict says the shell refused
95
+ * at creation (`created` in `attack`; P130): the guard held, and nothing was there to remove.
96
+ */
97
+ export function noteRefused(context: ProbeContext, verdict: Record<string, unknown>): void {
98
+ const refused = verdict.refused;
99
+ if (Array.isArray(refused) && refused.length > 0) {
100
+ context.measured(`${context.engine}: ${refused.join(", ")} refused at creation`);
101
+ }
102
+ }