@botiverse/porthole 0.2.4 → 0.3.1

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 (85) hide show
  1. package/README.md +17 -11
  2. package/dist/check/check.d.ts +100 -0
  3. package/dist/check/check.js +247 -0
  4. package/dist/check/drivers.d.ts +43 -0
  5. package/dist/check/drivers.js +181 -0
  6. package/dist/check/index.d.ts +8 -0
  7. package/dist/check/index.js +8 -0
  8. package/dist/check/instrument.d.ts +71 -0
  9. package/dist/check/instrument.js +84 -0
  10. package/dist/check/lint.d.ts +21 -0
  11. package/dist/check/lint.js +131 -0
  12. package/dist/check/page-source.d.ts +2 -0
  13. package/dist/check/page-source.js +2 -0
  14. package/dist/check/page.d.ts +13 -0
  15. package/dist/check/page.js +170 -0
  16. package/dist/check/tools.d.ts +61 -0
  17. package/dist/check/tools.js +140 -0
  18. package/dist/conformance/host-kit.d.ts +26 -5
  19. package/dist/conformance/host-kit.js +46 -22
  20. package/dist/conformance/index.d.ts +1 -1
  21. package/dist/conformance/reporter.d.ts +14 -0
  22. package/dist/conformance/reporter.js +28 -0
  23. package/dist/displays/displays.d.ts +61 -0
  24. package/dist/displays/displays.js +113 -0
  25. package/dist/host/client.d.ts +110 -0
  26. package/dist/host/client.js +274 -0
  27. package/dist/index.d.ts +4 -0
  28. package/dist/index.js +6 -0
  29. package/dist/node/index.d.ts +26 -1
  30. package/dist/node/index.js +91 -1
  31. package/dist/react/frame.d.ts +79 -3
  32. package/dist/react/frame.js +183 -42
  33. package/dist/react/index.d.ts +2 -1
  34. package/dist/react/index.js +1 -0
  35. package/dist/react/view.d.ts +54 -0
  36. package/dist/react/view.js +151 -0
  37. package/dist/server/bootstrap.d.ts +27 -0
  38. package/dist/server/bootstrap.js +63 -0
  39. package/dist/server/host.d.ts +77 -8
  40. package/dist/server/host.js +268 -11
  41. package/dist/server/index.d.ts +4 -2
  42. package/dist/server/index.js +3 -1
  43. package/dist/server/pages.d.ts +19 -0
  44. package/dist/server/pages.js +8 -0
  45. package/dist/server/proxy.d.ts +24 -0
  46. package/dist/server/proxy.js +67 -0
  47. package/dist/server/server.js +14 -1
  48. package/dist/server/types.d.ts +8 -0
  49. package/docs/ADOPTING.md +278 -108
  50. package/docs/DECISIONS.md +280 -0
  51. package/docs/DESIGN.md +84 -2
  52. package/examples/app.mjs +82 -78
  53. package/examples/conformance/page.spec.mjs +23 -0
  54. package/examples/conformance/playwright.config.mjs +3 -2
  55. package/examples/conformance/porthole.spec.mjs +6 -3
  56. package/examples/displays.mjs +21 -0
  57. package/examples/mcp/server.mjs +121 -0
  58. package/examples/node/server.mjs +16 -34
  59. package/examples/workers/worker.mjs +19 -7
  60. package/package.json +13 -1
  61. package/src/check/check.ts +386 -0
  62. package/src/check/drivers.ts +242 -0
  63. package/src/check/index.ts +22 -0
  64. package/src/check/instrument.ts +138 -0
  65. package/src/check/lint.ts +238 -0
  66. package/src/check/page-source.ts +19 -0
  67. package/src/check/page.ts +230 -0
  68. package/src/check/tools.ts +206 -0
  69. package/src/conformance/host-kit.ts +82 -27
  70. package/src/conformance/index.ts +1 -0
  71. package/src/conformance/reporter.ts +38 -0
  72. package/src/displays/displays.ts +191 -0
  73. package/src/host/client.ts +395 -0
  74. package/src/index.ts +25 -0
  75. package/src/node/index.ts +112 -2
  76. package/src/react/frame.tsx +271 -57
  77. package/src/react/index.ts +9 -0
  78. package/src/react/view.tsx +237 -0
  79. package/src/server/bootstrap.ts +97 -0
  80. package/src/server/host.ts +372 -18
  81. package/src/server/index.ts +11 -1
  82. package/src/server/pages.ts +28 -0
  83. package/src/server/proxy.ts +86 -0
  84. package/src/server/server.ts +26 -2
  85. package/src/server/types.ts +5 -0
@@ -0,0 +1,71 @@
1
+ import type { ColorScheme, PortholeConfig } from "../config/schema.ts";
2
+ import type { InstanceRef } from "../isolation/types.ts";
3
+ /**
4
+ * What the check puts in the content it runs (P073, P074): a small script first that reports
5
+ * what happens inside to the page that frames it, and a name on each inline script so an error
6
+ * says the line in the content as written. Pure: the check (any runtime) and its page both use it.
7
+ */
8
+ export interface CheckRunSpec {
9
+ readonly config: PortholeConfig;
10
+ readonly content: string;
11
+ /** Where each inline script's text starts in the content as written (file lines), by index. */
12
+ readonly scriptLines: readonly number[];
13
+ /** A served config's instance (located through the check's own server), else opaque. */
14
+ readonly instance?: InstanceRef;
15
+ readonly widthPx: number;
16
+ readonly heightPx?: number;
17
+ readonly scheme: ColorScheme;
18
+ readonly hostTheme?: Readonly<Record<string, string>>;
19
+ }
20
+ /**
21
+ * A host function the content called (P074): `answered` where the call reached the check's stub
22
+ * (which answers no, as a declining host would), else the refusal a host's gates gave it
23
+ * (`no-user-activation` for a call on load, `declined` where a person was asked).
24
+ */
25
+ export interface CheckCall {
26
+ readonly capability: string;
27
+ readonly outcome: string;
28
+ }
29
+ export interface CheckRunData {
30
+ readonly errors: string[];
31
+ readonly calls: CheckCall[];
32
+ readonly blocked: {
33
+ readonly url: string;
34
+ readonly directive: string;
35
+ }[];
36
+ readonly failedLoads: {
37
+ readonly url: string;
38
+ readonly tag: string;
39
+ }[];
40
+ readonly console: {
41
+ readonly level: "error" | "warning";
42
+ readonly text: string;
43
+ }[];
44
+ readonly height: number | null;
45
+ readonly scrollWidth: number | null;
46
+ readonly clientWidth: number | null;
47
+ readonly outcome: string | null;
48
+ }
49
+ /** Each inline script's name (`//# sourceURL`): its index in the content. */
50
+ export declare const SCRIPT_NAME = "porthole-script-";
51
+ /** Put first in the content: it reports to the page that frames it. */
52
+ export declare const INSTRUMENT = "<script>(() => {\n const send = (kind, data) => { try { parent.postMessage({ portholeCheck: kind, data }, \"*\"); } catch (_) {} };\n const text = (value) => { try { return String(value && value.stack ? value.message || value : value); } catch (_) { return \"?\"; } };\n for (const [method, level] of [[\"error\", \"error\"], [\"warn\", \"warning\"]]) {\n const original = console[method];\n console[method] = (...args) => { send(\"console\", { level, text: args.map(text).join(\" \").slice(0, 400) }); return original.apply(console, args); };\n }\n addEventListener(\"error\", (event) => {\n const target = event.target;\n if (target && target !== window && (target.src || target.href)) {\n send(\"load\", { url: String(target.src || target.href).slice(0, 400), tag: String(target.tagName || \"\").toLowerCase() });\n } else if (event.message || event.error) {\n const error = event.error;\n send(\"error\", {\n message: (error && error.message ? (error.name || \"Error\") + \": \" + error.message : String(event.message)).slice(0, 400),\n file: String(event.filename || \"\"),\n line: event.lineno || 0,\n stack: error && error.stack ? String(error.stack).slice(0, 1000) : \"\",\n });\n }\n }, true);\n addEventListener(\"unhandledrejection\", (event) => send(\"error\", {\n message: (\"Unhandled rejection: \" + text(event.reason)).slice(0, 400),\n file: \"\", line: 0,\n stack: event.reason && event.reason.stack ? String(event.reason.stack).slice(0, 1000) : \"\",\n }));\n addEventListener(\"securitypolicyviolation\", (event) => send(\"blocked\", { url: String(event.blockedURI || \"inline\").slice(0, 400), directive: String(event.effectiveDirective) }));\n addEventListener(\"message\", (event) => {\n if (event.source === parent && event.data && event.data.portholeCheck === \"measure\") {\n const root = document.documentElement;\n send(\"measure\", { scrollWidth: Math.max(root.scrollWidth, document.body ? document.body.scrollWidth : 0), clientWidth: root.clientWidth });\n }\n });\n})();</script>";
53
+ /** The content with the instrument first: after a document's <head>, or before a fragment. */
54
+ export declare function instrumented(content: string): string;
55
+ /**
56
+ * The content with each inline script named (`//# sourceURL=porthole-script-<n>`, after its
57
+ * last line, so no line moves), and where each one's text starts in the content as written.
58
+ */
59
+ export declare function namedScripts(content: string): {
60
+ content: string;
61
+ scriptLines: number[];
62
+ };
63
+ /**
64
+ * An error's line in the content as written: from its script's name (the event's file, or its
65
+ * stack's first frame there) and its line in that script; null where it can't be told.
66
+ */
67
+ export declare function contentLine(error: {
68
+ readonly file: string;
69
+ readonly line: number;
70
+ readonly stack: string;
71
+ }, scriptLines: readonly number[]): number | null;
@@ -0,0 +1,84 @@
1
+ /** Each inline script's name (`//# sourceURL`): its index in the content. */
2
+ export const SCRIPT_NAME = "porthole-script-";
3
+ /** Put first in the content: it reports to the page that frames it. */
4
+ export const INSTRUMENT = `<script>(() => {
5
+ const send = (kind, data) => { try { parent.postMessage({ portholeCheck: kind, data }, "*"); } catch (_) {} };
6
+ const text = (value) => { try { return String(value && value.stack ? value.message || value : value); } catch (_) { return "?"; } };
7
+ for (const [method, level] of [["error", "error"], ["warn", "warning"]]) {
8
+ const original = console[method];
9
+ console[method] = (...args) => { send("console", { level, text: args.map(text).join(" ").slice(0, 400) }); return original.apply(console, args); };
10
+ }
11
+ addEventListener("error", (event) => {
12
+ const target = event.target;
13
+ if (target && target !== window && (target.src || target.href)) {
14
+ send("load", { url: String(target.src || target.href).slice(0, 400), tag: String(target.tagName || "").toLowerCase() });
15
+ } else if (event.message || event.error) {
16
+ const error = event.error;
17
+ send("error", {
18
+ message: (error && error.message ? (error.name || "Error") + ": " + error.message : String(event.message)).slice(0, 400),
19
+ file: String(event.filename || ""),
20
+ line: event.lineno || 0,
21
+ stack: error && error.stack ? String(error.stack).slice(0, 1000) : "",
22
+ });
23
+ }
24
+ }, true);
25
+ addEventListener("unhandledrejection", (event) => send("error", {
26
+ message: ("Unhandled rejection: " + text(event.reason)).slice(0, 400),
27
+ file: "", line: 0,
28
+ stack: event.reason && event.reason.stack ? String(event.reason.stack).slice(0, 1000) : "",
29
+ }));
30
+ addEventListener("securitypolicyviolation", (event) => send("blocked", { url: String(event.blockedURI || "inline").slice(0, 400), directive: String(event.effectiveDirective) }));
31
+ addEventListener("message", (event) => {
32
+ if (event.source === parent && event.data && event.data.portholeCheck === "measure") {
33
+ const root = document.documentElement;
34
+ send("measure", { scrollWidth: Math.max(root.scrollWidth, document.body ? document.body.scrollWidth : 0), clientWidth: root.clientWidth });
35
+ }
36
+ });
37
+ })();</script>`;
38
+ /** The content with the instrument first: after a document's <head>, or before a fragment. */
39
+ export function instrumented(content) {
40
+ const head = /<head[^>]*>/iu.exec(content);
41
+ if (head !== null) {
42
+ const at = head.index + head[0].length;
43
+ return `${content.slice(0, at)}${INSTRUMENT}${content.slice(at)}`;
44
+ }
45
+ const html = /<html[^>]*>/iu.exec(content);
46
+ if (html !== null) {
47
+ const at = html.index + html[0].length;
48
+ return `${content.slice(0, at)}<head>${INSTRUMENT}</head>${content.slice(at)}`;
49
+ }
50
+ return /^\s*<!doctype/iu.test(content)
51
+ ? content.replace(/^(\s*<!doctype[^>]*>)/iu, `$1${INSTRUMENT}`)
52
+ : `${INSTRUMENT}${content}`;
53
+ }
54
+ /**
55
+ * The content with each inline script named (`//# sourceURL=porthole-script-<n>`, after its
56
+ * last line, so no line moves), and where each one's text starts in the content as written.
57
+ */
58
+ export function namedScripts(content) {
59
+ const scriptLines = [];
60
+ const named = content.replace(/(<script\b(?![^>]*\bsrc\s*=)[^>]*>)([\s\S]*?)(<\/script>)/giu, (whole, open, body, close, offset) => {
61
+ const index = scriptLines.length;
62
+ scriptLines.push(content.slice(0, offset + open.length).split("\n").length);
63
+ return `${open}${body}\n//# sourceURL=${SCRIPT_NAME}${index}\n${close}`;
64
+ });
65
+ return { content: named, scriptLines };
66
+ }
67
+ /**
68
+ * An error's line in the content as written: from its script's name (the event's file, or its
69
+ * stack's first frame there) and its line in that script; null where it can't be told.
70
+ */
71
+ export function contentLine(error, scriptLines) {
72
+ const named = new RegExp(`${SCRIPT_NAME}(\\d+)(?::(\\d+))?`, "u");
73
+ const fromFile = named.exec(error.file);
74
+ if (fromFile?.[1] !== undefined && error.line > 0) {
75
+ const start = scriptLines[Number(fromFile[1])];
76
+ return start === undefined ? null : start + error.line - 1;
77
+ }
78
+ const fromStack = named.exec(error.stack);
79
+ if (fromStack?.[1] !== undefined && fromStack[2] !== undefined) {
80
+ const start = scriptLines[Number(fromStack[1])];
81
+ return start === undefined ? null : start + Number(fromStack[2]) - 1;
82
+ }
83
+ return null;
84
+ }
@@ -0,0 +1,21 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * What can be told about content without running it (P073), worded as the manual words it, so
4
+ * the agent fixes it before anyone sees it. Pure: any runtime. Errors are only what certainly
5
+ * fails or is cut (`refuseOn: "error"` refuses those); the rest are warnings.
6
+ */
7
+ export type LintRule = "size" | "document" | "nested-frame" | "document-write" | "clipboard" | "dialog" | "form" | "egress" | "unpinned" | "position-fixed" | "new-window";
8
+ export interface Finding {
9
+ readonly rule: LintRule;
10
+ readonly severity: "error" | "warning";
11
+ /** What to change, for the agent. */
12
+ readonly message: string;
13
+ /** Where (1-based), where a line says it. */
14
+ readonly line?: number;
15
+ }
16
+ /**
17
+ * A whole document sent where a fragment is shown (an inline widget), as the fragment it means:
18
+ * its head's styles and scripts, then its body. Null where it has no body to take.
19
+ */
20
+ export declare function fragmentOf(content: string): string | null;
21
+ export declare function lintContent(config: PortholeConfig, content: string): Finding[];
@@ -0,0 +1,131 @@
1
+ import { anyHttps, declaredCapabilities, egressOrigins, } from "../compile/policy.js";
2
+ import { sizeWords } from "../guide/limits.js";
3
+ import { originMatchesSource } from "../isolation/served.js";
4
+ const lineOf = (text, index) => text.slice(0, index).split("\n").length;
5
+ const noun = (config) => config.mode === "artifact" ? "page" : config.mode === "mcp-app" ? "view" : "widget";
6
+ /** A whole document's markers: what a fragment must not have. */
7
+ const DOCUMENT = /<!doctype\b|<html[\s>]|<head[\s>]|<body[\s>]/iu;
8
+ /**
9
+ * A whole document sent where a fragment is shown (an inline widget), as the fragment it means:
10
+ * its head's styles and scripts, then its body. Null where it has no body to take.
11
+ */
12
+ export function fragmentOf(content) {
13
+ const head = /<head[^>]*>([\s\S]*?)<\/head>/iu.exec(content)?.[1] ?? "";
14
+ const kept = [...head.matchAll(/<(style|script)\b[\s\S]*?<\/\1>|<link\b[^>]*>/giu)]
15
+ .map((each) => each[0])
16
+ .join("\n");
17
+ const body = /<body[^>]*>([\s\S]*?)(?:<\/body>|$)/iu.exec(content)?.[1] ??
18
+ content
19
+ .replace(/<!doctype[^>]*>/iu, "")
20
+ .replace(/<\/?html[^>]*>/giu, "")
21
+ .replace(/<head[^>]*>[\s\S]*?<\/head>/iu, "");
22
+ return body.trim() === "" ? null : `${kept}${kept === "" ? "" : "\n"}${body.trim()}`;
23
+ }
24
+ /** Where content reaches out, by the kind of egress each would need. */
25
+ const REACHES = [
26
+ { kind: "script", pattern: /<script\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
27
+ { kind: "script", pattern: /\bimport\s*(?:[\w{}\s*,]+from\s*)?\(?\s*["'](https?:\/\/[^"']+)/gu },
28
+ { kind: "style", pattern: /<link\b[^>]*\bhref\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
29
+ { kind: "style", pattern: /@import\s+(?:url\()?["']?(https?:\/\/[^"')\s]+)/giu },
30
+ { kind: "img", pattern: /<img\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu },
31
+ { kind: "img", pattern: /url\(\s*["']?(https?:\/\/[^"')\s]+)/giu },
32
+ {
33
+ kind: "media",
34
+ pattern: /<(?:video|audio|source)\b[^>]*\bsrc\s*=\s*["']?(https?:\/\/[^"'\s>]+)/giu,
35
+ },
36
+ { kind: "connect", pattern: /\bfetch\s*\(\s*["'`](https?:\/\/[^"'`]+)/gu },
37
+ {
38
+ kind: "connect",
39
+ pattern: /\bnew\s+(?:WebSocket|EventSource)\s*\(\s*["'`]((?:https?|wss?):\/\/[^"'`]+)/gu,
40
+ },
41
+ ];
42
+ const CDN_PACKAGE = /^https:\/\/(?:cdn\.jsdelivr\.net\/npm|unpkg\.com|esm\.sh)\/((?:@[^/]+\/)?[^/@]+)(@[^/]*)?/u;
43
+ export function lintContent(config, content) {
44
+ if (config.mode === "url") {
45
+ return [];
46
+ }
47
+ const findings = [];
48
+ const add = (rule, severity, message, index) => findings.push({
49
+ rule,
50
+ severity,
51
+ message,
52
+ ...(index === undefined ? {} : { line: lineOf(content, index) }),
53
+ });
54
+ const it = noun(config);
55
+ const declared = new Set(declaredCapabilities(config));
56
+ const bytes = new TextEncoder().encode(content).byteLength;
57
+ if (bytes > config.limits.maxBytes) {
58
+ add("size", "error", `It is ${sizeWords(bytes)}; a ${it} may be at most ${sizeWords(config.limits.maxBytes)}: make it smaller (less data inline, no embedded fonts or images it doesn't need).`);
59
+ }
60
+ if (config.mode === "inline") {
61
+ const at = content.search(DOCUMENT);
62
+ if (at >= 0) {
63
+ if (fragmentOf(content) === null) {
64
+ add("document", "error", "Send an HTML fragment (styles, markup, scripts), not a whole document: this one has no body to show.", at);
65
+ }
66
+ else {
67
+ add("document", "warning", "Send an HTML fragment, not a whole document (no <!doctype>, <html>, <head> or <body>): it was taken as its body, with its head's styles and scripts.", at);
68
+ }
69
+ }
70
+ }
71
+ const frame = /<(iframe|frame|object|embed)\b/iu.exec(content);
72
+ if (frame !== null) {
73
+ add("nested-frame", "error", `Remove the <${frame[1]?.toLowerCase()}>: nested frames and plugins are taken out of a ${it} and never run. Draw it inline instead.`, frame.index);
74
+ }
75
+ const write = /\bdocument\s*\.\s*write(?:ln)?\s*\(/u.exec(content);
76
+ if (write !== null) {
77
+ add("document-write", "error", "Remove document.write: it throws here. Build elements with document.createElement, or set innerHTML.", write.index);
78
+ }
79
+ const clipboard = /\bnavigator\s*\.\s*clipboard\b|\bexecCommand\s*\(\s*["'](?:copy|cut)["']/u.exec(content);
80
+ if (clipboard !== null) {
81
+ add("clipboard", "warning", declared.has("copyText")
82
+ ? "The clipboard is closed to content: a copy button calls copyText(text) from its click."
83
+ : "The clipboard is closed to content: copying from a button doesn't work here.", clipboard.index);
84
+ }
85
+ const dialog = /(?:^|[^.\w$])(?:window\s*\.\s*)?(alert|confirm|prompt)\s*\(/u.exec(content);
86
+ if (dialog !== null) {
87
+ add("dialog", "warning", `${dialog[1]}() shows nothing here (confirm returns false, prompt null): show it in the ${it}'s own markup.`, dialog.index);
88
+ }
89
+ const form = /<form\b/iu.exec(content);
90
+ if (form !== null) {
91
+ add("form", "warning", 'Forms never submit here, and some browsers fire no submit event: use <button type="button"> and a click handler.', form.index);
92
+ }
93
+ const reported = new Set();
94
+ for (const { kind, pattern } of REACHES) {
95
+ for (const match of content.matchAll(pattern)) {
96
+ const address = match[1] ?? "";
97
+ let origin;
98
+ try {
99
+ origin = new URL(address.replace(/^ws/u, "http")).origin;
100
+ }
101
+ catch {
102
+ continue;
103
+ }
104
+ const open = (kind !== "script" &&
105
+ kind !== "style" &&
106
+ kind !== "connect" &&
107
+ address.startsWith("https:") &&
108
+ anyHttps(config, kind)) ||
109
+ egressOrigins(config, kind).some((source) => source === origin || originMatchesSource(origin, source));
110
+ if (!open && !reported.has(`${kind} ${origin}`)) {
111
+ reported.add(`${kind} ${origin}`);
112
+ add("egress", "warning", `Nothing loads from ${origin} here (${kind}): ${kind === "script" || kind === "style" ? "write it inline, or use a library from an allowed CDN" : kind === "connect" ? "the content can't call it; work from data in the content" : "put it inline as a data: URL"}.`, match.index);
113
+ }
114
+ const pinned = CDN_PACKAGE.exec(address);
115
+ if (pinned !== null && (pinned[2] === undefined || !/^@\d+\.\d+\.\d+/u.test(pinned[2]))) {
116
+ add("unpinned", "warning", `Pin an exact version of ${pinned[1]} (${pinned[1]}@1.2.3 in its URL), never @latest or a range: the code then can't change under the ${it}.`, match.index);
117
+ }
118
+ }
119
+ }
120
+ if (config.layout.kind !== "fill") {
121
+ const fixed = /position\s*:\s*fixed/iu.exec(content);
122
+ if (fixed !== null) {
123
+ add("position-fixed", "warning", `No position: fixed: the frame grows with the ${it}'s content, so a fixed element covers it. Use position: sticky or normal flow.`, fixed.index);
124
+ }
125
+ }
126
+ const opens = /target\s*=\s*["']?_blank|\bwindow\s*\.\s*open\s*\(/u.exec(content);
127
+ if (opens !== null && !declared.has("openLink")) {
128
+ add("new-window", "warning", "Nothing opens a new window here (window.open returns null, target=_blank does nothing): show it inline.", opens.index);
129
+ }
130
+ return findings;
131
+ }
@@ -0,0 +1,2 @@
1
+ declare const source: string;
2
+ export default source;