@botiverse/porthole 0.5.0 → 0.5.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 (42) hide show
  1. package/dist/bridge/bridge.d.ts +12 -4
  2. package/dist/bridge/bridge.js +58 -26
  3. package/dist/bridge/navigation.d.ts +11 -0
  4. package/dist/bridge/navigation.js +30 -0
  5. package/dist/bridge/refusal.d.ts +53 -0
  6. package/dist/bridge/refusal.js +121 -0
  7. package/dist/bridge/types.d.ts +7 -0
  8. package/dist/check/page-source.js +1 -1
  9. package/dist/check/page.js +5 -0
  10. package/dist/config/capabilities.d.ts +5 -0
  11. package/dist/conformance/harness-source.js +1 -1
  12. package/dist/guide/guide.js +14 -4
  13. package/dist/host/create-host.js +15 -4
  14. package/dist/host/types.d.ts +15 -2
  15. package/dist/index.d.ts +2 -1
  16. package/dist/index.js +3 -1
  17. package/dist/mcp/adapter.js +22 -7
  18. package/dist/protocol/mcp-apps.d.ts +6 -0
  19. package/dist/protocol/mcp-apps.js +6 -0
  20. package/dist/protocol/shell-adapter.js +14 -2
  21. package/dist/react/frame.d.ts +19 -4
  22. package/dist/react/frame.js +37 -9
  23. package/dist/shell/runtime.js +34 -8
  24. package/docs/ADOPTING.md +39 -9
  25. package/docs/DECISIONS.md +92 -0
  26. package/docs/DESIGN.md +12 -7
  27. package/package.json +1 -1
  28. package/src/bridge/bridge.ts +70 -22
  29. package/src/bridge/navigation.ts +34 -0
  30. package/src/bridge/refusal.ts +151 -0
  31. package/src/bridge/types.ts +12 -1
  32. package/src/check/page.ts +7 -0
  33. package/src/config/capabilities.ts +5 -1
  34. package/src/guide/guide.ts +18 -4
  35. package/src/host/create-host.ts +16 -4
  36. package/src/host/types.ts +13 -2
  37. package/src/index.ts +9 -0
  38. package/src/mcp/adapter.ts +26 -6
  39. package/src/protocol/mcp-apps.ts +7 -0
  40. package/src/protocol/shell-adapter.ts +15 -2
  41. package/src/react/frame.tsx +53 -14
  42. package/src/shell/runtime.ts +34 -8
@@ -1,6 +1,7 @@
1
1
  import { type CapabilityName } from "../config/capabilities.ts";
2
2
  import type { AnnotationReport } from "../annotate/types.ts";
3
3
  import type { PortholeConfig } from "../config/schema.ts";
4
+ import { type Refused } from "./refusal.ts";
4
5
  import type { CapabilityHandlers, Confirm, ConfirmDisplay, Consent, DataCache, HostFunctionBridge, Refusal } from "./types.ts";
5
6
  /**
6
7
  * The host-function bridge: every capability call from a frame passes here, and nowhere else
@@ -15,6 +16,11 @@ export type BridgeEvent = {
15
16
  } | {
16
17
  readonly type: "error";
17
18
  readonly message: string;
19
+ }
20
+ /** The shell cancelled a navigation of the frame to `url` (P080): the content's word. */
21
+ | {
22
+ readonly type: "navigationBlocked";
23
+ readonly url: string;
18
24
  } | {
19
25
  readonly type: "annotation";
20
26
  readonly report: AnnotationReport;
@@ -32,9 +38,10 @@ export interface BridgeOptions {
32
38
  readonly confirm?: Confirm;
33
39
  /**
34
40
  * Asked before a `consent`-gated call (P079). The host's, made to ask once per display by the
35
- * caller (`createHost` keeps the answer across the display's frames).
41
+ * caller (`createHost` keeps the answer across the display's frames). A `Refused` refuses every
42
+ * such call with it, asking nothing (P080).
36
43
  */
37
- readonly consent?: Consent;
44
+ readonly consent?: Consent | Refused;
38
45
  /** The host's cache, for reads that may be answered stale (`CallOptions.stale`, P079). */
39
46
  readonly cached?: DataCache;
40
47
  /** Whether the embedding page has user activation now; undefined where it can't tell. */
@@ -47,8 +54,9 @@ export interface BridgeOptions {
47
54
  export declare function linkTarget(value: unknown): string | null;
48
55
  /**
49
56
  * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
50
- * for as long as the returned function is kept (`createHost` keeps one per display). A consent
51
- * function that fails is a no for that call, and is asked again at the next.
57
+ * for as long as the returned function is kept (`createHost` keeps one per display). A `Refused`
58
+ * it throws is an answer, kept and thrown again at every call (P080); anything else it throws is
59
+ * no answer: thrown for that call, and the next asks again.
52
60
  */
53
61
  export declare function onceConsent(consent: Consent): Consent;
54
62
  export declare function createBridge(options: BridgeOptions): HostFunctionBridge;
@@ -1,6 +1,8 @@
1
1
  import { MAX_COPY_CHARS, capabilitySpec, } from "../config/capabilities.js";
2
2
  import { parseReport } from "../annotate/validate.js";
3
3
  import { effectiveGates } from "../compile/policy.js";
4
+ import { blockedNavigationMessage } from "./navigation.js";
5
+ import { defaultReason, isRefused, pendingReason, reasonOf, } from "./refusal.js";
4
6
  const isRecord = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
5
7
  const MAX_URL = 4_096;
6
8
  /** An http(s) URL without credentials in it (`https://bank.example@evil.example` reads as a lie). */
@@ -72,7 +74,15 @@ const VALIDATORS = {
72
74
  ...(structuredContent === undefined ? {} : { structuredContent }),
73
75
  };
74
76
  },
75
- reportError: (args) => {
77
+ reportError: (args, config) => {
78
+ // A navigation the shell cancelled (P080): Porthole words it, naming the address without its
79
+ // query; the address itself goes to the host whole.
80
+ const blocked = isRecord(args) ? args.navigationBlocked : undefined;
81
+ if (blocked !== undefined) {
82
+ return typeof blocked === "string" && blocked !== "" && blocked.length <= MAX_URL
83
+ ? { message: blockedNavigationMessage(blocked, config), navigationBlocked: blocked }
84
+ : null;
85
+ }
76
86
  const message = isRecord(args) ? args.message : undefined;
77
87
  return typeof message === "string" && message !== ""
78
88
  ? { message: message.slice(0, 2_000) }
@@ -100,19 +110,30 @@ const VALIDATORS = {
100
110
  };
101
111
  /**
102
112
  * The host's `consent`, asked once (P079): the first call asks, every later one gets that answer,
103
- * for as long as the returned function is kept (`createHost` keeps one per display). A consent
104
- * function that fails is a no for that call, and is asked again at the next.
113
+ * for as long as the returned function is kept (`createHost` keeps one per display). A `Refused`
114
+ * it throws is an answer, kept and thrown again at every call (P080); anything else it throws is
115
+ * no answer: thrown for that call, and the next asks again.
105
116
  */
106
117
  export function onceConsent(consent) {
107
118
  let answer = null;
108
- return (request) => (answer ??= Promise.resolve()
109
- .then(() => consent(request))
110
- .then(
111
- // Only a real yes: anything else a host's function gives is a no (fail closed).
112
- (allowed) => allowed === true, () => {
113
- answer = null;
114
- return false;
115
- }));
119
+ return async (request) => {
120
+ const asked = (answer ??= Promise.resolve()
121
+ .then(() => consent(request))
122
+ .then(
123
+ // Only a real yes: anything else a host's function gives is a no (fail closed).
124
+ (allowed) => allowed === true, (error) => {
125
+ if (isRefused(error)) {
126
+ return error;
127
+ }
128
+ answer = null;
129
+ throw error;
130
+ }));
131
+ const given = await asked;
132
+ if (typeof given !== "boolean") {
133
+ throw given;
134
+ }
135
+ return given;
136
+ };
116
137
  }
117
138
  export function createBridge(options) {
118
139
  const { config, display, handlers, onEvent } = options;
@@ -120,9 +141,14 @@ export function createBridge(options) {
120
141
  const calls = new Map();
121
142
  let declines = 0;
122
143
  let muted = false;
123
- const refuse = (capability, refusal, message) => {
144
+ const refuse = (capability, refusal, message, reason) => {
124
145
  onEvent({ type: "refused", capability, refusal });
125
- return { ok: false, refusal, ...(message === undefined ? {} : { message }) };
146
+ return {
147
+ ok: false,
148
+ refusal,
149
+ ...(message === undefined ? {} : { message }),
150
+ reason: reason ?? defaultReason(capability, refusal),
151
+ };
126
152
  };
127
153
  const withinRate = (capability, perMinute) => {
128
154
  const at = now();
@@ -162,22 +188,23 @@ export function createBridge(options) {
162
188
  }
163
189
  }
164
190
  if (gates.includes("consent")) {
165
- if (options.consent === undefined) {
191
+ const consent = options.consent;
192
+ if (consent === undefined) {
166
193
  return refuse(capability, "no-consent");
167
194
  }
168
- let allowed = false;
195
+ // The host's policy, known before any call: every one refused with its reason (P080).
196
+ if (isRefused(consent)) {
197
+ return refuse(capability, "denied", undefined, reasonOf(consent));
198
+ }
199
+ let answer = false;
169
200
  try {
170
- const answer = await options.consent({
171
- capability,
172
- args,
173
- display,
174
- });
175
- allowed = answer === true;
201
+ answer = await consent({ capability, args, display });
176
202
  }
177
- catch {
178
- allowed = false;
203
+ catch (error) {
204
+ // A Refused is the host's no, with its reason; any other failure is no answer yet.
205
+ return refuse(capability, "denied", undefined, isRefused(error) ? reasonOf(error) : pendingReason(capability));
179
206
  }
180
- if (!allowed) {
207
+ if (answer !== true) {
181
208
  return refuse(capability, "denied");
182
209
  }
183
210
  }
@@ -224,7 +251,11 @@ export function createBridge(options) {
224
251
  onEvent({ type: "annotation", report: args });
225
252
  }
226
253
  else {
227
- onEvent({ type: "error", message: args.message });
254
+ const report = args;
255
+ if (report.navigationBlocked !== undefined) {
256
+ onEvent({ type: "navigationBlocked", url: report.navigationBlocked });
257
+ }
258
+ onEvent({ type: "error", message: report.message });
228
259
  }
229
260
  return { ok: true, value: undefined };
230
261
  }
@@ -255,7 +286,8 @@ export function createBridge(options) {
255
286
  return { ok: true, value: value };
256
287
  }
257
288
  catch (error) {
258
- return refuse(capability, "failed", error instanceof Error ? error.message : String(error));
289
+ // A host's Refused tells content its reason (P080); any other error stays the host's.
290
+ return refuse(capability, "failed", error instanceof Error ? error.message : String(error), isRefused(error) ? reasonOf(error) : undefined);
259
291
  }
260
292
  }
261
293
  }
@@ -0,0 +1,11 @@
1
+ import type { PortholeConfig } from "../config/schema.ts";
2
+ /**
3
+ * A navigation the shell cancelled (P079), as the host is told it (P080): the address, whole, on
4
+ * the `navigationBlocked` event (the host's to keep), and a sentence for the content's errors
5
+ * (`contentError`, which a host may give the agent that wrote it) that names the address without
6
+ * its query or fragment, where a viewer's data would be.
7
+ */
8
+ /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
9
+ export declare function addressWithoutQuery(url: string): string;
10
+ /** What the content's errors say about a navigation the shell cancelled. */
11
+ export declare function blockedNavigationMessage(url: string, config: PortholeConfig): string;
@@ -0,0 +1,30 @@
1
+ /**
2
+ * A navigation the shell cancelled (P079), as the host is told it (P080): the address, whole, on
3
+ * the `navigationBlocked` event (the host's to keep), and a sentence for the content's errors
4
+ * (`contentError`, which a host may give the agent that wrote it) that names the address without
5
+ * its query or fragment, where a viewer's data would be.
6
+ */
7
+ /** An address without what could carry data: an http(s) one's origin and path, else its scheme. */
8
+ export function addressWithoutQuery(url) {
9
+ let parsed;
10
+ try {
11
+ parsed = new URL(url);
12
+ }
13
+ catch {
14
+ return "another address";
15
+ }
16
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
17
+ return `a ${parsed.protocol} address`;
18
+ }
19
+ const rest = parsed.search !== "" || parsed.hash !== "" ? "?…" : "";
20
+ return `${parsed.origin}${parsed.pathname}${rest}`;
21
+ }
22
+ /** What the content's errors say about a navigation the shell cancelled. */
23
+ export function blockedNavigationMessage(url, config) {
24
+ const links = config.capabilities.openLink === undefined
25
+ ? ""
26
+ : config.mode === "mcp-app"
27
+ ? " Open links with ui/open-link (a new tab)."
28
+ : " Open links with openLink(url) or an <a href> (a new tab).";
29
+ return `It tried to navigate its frame to ${addressWithoutQuery(url)}, and was stopped: content never leaves its page.${links}`;
30
+ }
@@ -0,0 +1,53 @@
1
+ import type { CapabilityName } from "../config/capabilities.ts";
2
+ import type { Refusal } from "./types.ts";
3
+ /**
4
+ * Why a call was refused, as content is told (P080): a code it can branch on and a sentence it can
5
+ * show the person viewing it. Carried in a refused request's JSON-RPC error, as its `data`; the
6
+ * shell's globals reject with an error that has both (`error.code`, `error.message`).
7
+ *
8
+ * - `consent_required`: the viewer hasn't allowed it yet (their answer is still to come).
9
+ * - `denied`: the viewer (or the person asked to confirm) said no.
10
+ * - `rate_limited`: too many calls this minute.
11
+ * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
12
+ * serve, a page where data never runs).
13
+ * - `failed`: the host tried and couldn't.
14
+ */
15
+ export declare const REFUSAL_CODES: readonly ["consent_required", "denied", "rate_limited", "not_allowed", "failed"];
16
+ export type RefusalCode = (typeof REFUSAL_CODES)[number];
17
+ /** What content is told about a refusal: the JSON-RPC error's `data`. */
18
+ export interface RefusalReason {
19
+ readonly code: RefusalCode;
20
+ /** A sentence for the person viewing the content: the host's, else Porthole's. */
21
+ readonly message: string;
22
+ }
23
+ export declare function isRefusalCode(value: unknown): value is RefusalCode;
24
+ /**
25
+ * A refusal the host gives, with the reason content is told (P080). Throw it from a handler (this
26
+ * URI isn't one you serve: `not_allowed`; the viewer didn't allow this kind of data: `denied`), or
27
+ * from a `consent` function (kept as the display's answer, as `false` is). Or pass one as
28
+ * `HostOptions.consent` itself: every `consent`-gated call is refused with it, and those
29
+ * capabilities need no handler (a page where data never runs).
30
+ *
31
+ * Any other error a handler throws is `failed` with Porthole's words: its message stays the host's.
32
+ */
33
+ export declare class Refused extends Error {
34
+ readonly code: RefusalCode;
35
+ /** `message`: a sentence for the viewer; absent, Porthole's for the code. */
36
+ constructor(code: RefusalCode, message?: string);
37
+ }
38
+ /**
39
+ * Whether `value` is a `Refused`: by class, or by shape where two copies of Porthole meet (a
40
+ * host's bundle and a library's).
41
+ */
42
+ export declare function isRefused(value: unknown): value is Refused;
43
+ /** The reason a host's `Refused` gives content. */
44
+ export declare function reasonOf(refused: Refused): RefusalReason;
45
+ /** What content is told about a refusal Porthole made (the host gave no `Refused`). */
46
+ export declare function defaultReason(capability: CapabilityName, refusal: Refusal): RefusalReason;
47
+ /** What content is told about a refused call: the bridge's reason, else Porthole's for it. */
48
+ export declare function reasonFor(capability: CapabilityName, outcome: {
49
+ readonly refusal: Refusal;
50
+ readonly reason?: RefusalReason;
51
+ }): RefusalReason;
52
+ /** A consent function that failed (threw, rejected): not an answer, so asked again at the next. */
53
+ export declare function pendingReason(capability: CapabilityName): RefusalReason;
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Why a call was refused, as content is told (P080): a code it can branch on and a sentence it can
3
+ * show the person viewing it. Carried in a refused request's JSON-RPC error, as its `data`; the
4
+ * shell's globals reject with an error that has both (`error.code`, `error.message`).
5
+ *
6
+ * - `consent_required`: the viewer hasn't allowed it yet (their answer is still to come).
7
+ * - `denied`: the viewer (or the person asked to confirm) said no.
8
+ * - `rate_limited`: too many calls this minute.
9
+ * - `not_allowed`: the host doesn't let this content have it, here or at all (a URI it doesn't
10
+ * serve, a page where data never runs).
11
+ * - `failed`: the host tried and couldn't.
12
+ */
13
+ export const REFUSAL_CODES = [
14
+ "consent_required",
15
+ "denied",
16
+ "rate_limited",
17
+ "not_allowed",
18
+ "failed",
19
+ ];
20
+ /** The most a refusal's message carries to content. */
21
+ const MAX_MESSAGE = 500;
22
+ export function isRefusalCode(value) {
23
+ return typeof value === "string" && REFUSAL_CODES.includes(value);
24
+ }
25
+ /**
26
+ * A refusal the host gives, with the reason content is told (P080). Throw it from a handler (this
27
+ * URI isn't one you serve: `not_allowed`; the viewer didn't allow this kind of data: `denied`), or
28
+ * from a `consent` function (kept as the display's answer, as `false` is). Or pass one as
29
+ * `HostOptions.consent` itself: every `consent`-gated call is refused with it, and those
30
+ * capabilities need no handler (a page where data never runs).
31
+ *
32
+ * Any other error a handler throws is `failed` with Porthole's words: its message stays the host's.
33
+ */
34
+ export class Refused extends Error {
35
+ code;
36
+ /** `message`: a sentence for the viewer; absent, Porthole's for the code. */
37
+ constructor(code, message) {
38
+ if (!isRefusalCode(code)) {
39
+ throw new TypeError(`Refused: code must be one of ${REFUSAL_CODES.join(", ")}`);
40
+ }
41
+ super(message === undefined || message.trim() === "" ? DEFAULT_MESSAGES[code] : message);
42
+ this.name = "Refused";
43
+ this.code = code;
44
+ }
45
+ }
46
+ /**
47
+ * Whether `value` is a `Refused`: by class, or by shape where two copies of Porthole meet (a
48
+ * host's bundle and a library's).
49
+ */
50
+ export function isRefused(value) {
51
+ return (value instanceof Refused ||
52
+ (value instanceof Error &&
53
+ value.name === "Refused" &&
54
+ isRefusalCode(value.code)));
55
+ }
56
+ /** The reason a host's `Refused` gives content. */
57
+ export function reasonOf(refused) {
58
+ const message = refused.message.trim();
59
+ return {
60
+ code: refused.code,
61
+ message: (message === "" ? DEFAULT_MESSAGES[refused.code] : message).slice(0, MAX_MESSAGE),
62
+ };
63
+ }
64
+ /** Porthole's sentence for each code, where the host gave none. */
65
+ const DEFAULT_MESSAGES = {
66
+ consent_required: "This needs your permission first.",
67
+ denied: "You didn't allow this.",
68
+ rate_limited: "Too many requests: try again in a minute.",
69
+ not_allowed: "This isn't available here.",
70
+ failed: "The app couldn't do this.",
71
+ };
72
+ /** Where a data capability's words differ: they name the data. */
73
+ const DATA_MESSAGES = {
74
+ consent_required: "Reading this data needs your permission first.",
75
+ denied: "You didn't allow this to read your data.",
76
+ rate_limited: "Too many data requests: try again in a minute.",
77
+ not_allowed: "This data isn't available here.",
78
+ failed: "The app couldn't get this data.",
79
+ };
80
+ /** Each refusal's code, as content is told it. */
81
+ const CODES = {
82
+ "not-declared": "not_allowed",
83
+ invalid: "not_allowed",
84
+ "no-user-activation": "not_allowed",
85
+ "no-confirm": "not_allowed",
86
+ declined: "denied",
87
+ redirected: "denied",
88
+ muted: "denied",
89
+ "no-consent": "not_allowed",
90
+ denied: "denied",
91
+ "rate-limited": "rate_limited",
92
+ failed: "failed",
93
+ };
94
+ /** Refusals whose own words say more than their code's. */
95
+ const OWN_MESSAGES = {
96
+ "no-user-activation": "This needs a click.",
97
+ invalid: "The app can't take this request.",
98
+ muted: "You declined this too often: it isn't asked again until it runs again.",
99
+ };
100
+ /** What content is told about a refusal Porthole made (the host gave no `Refused`). */
101
+ export function defaultReason(capability, refusal) {
102
+ const code = CODES[refusal];
103
+ const data = capability === "readData" || capability === "subscribeData";
104
+ return {
105
+ code,
106
+ message: OWN_MESSAGES[refusal] ?? (data ? DATA_MESSAGES : DEFAULT_MESSAGES)[code],
107
+ };
108
+ }
109
+ /** What content is told about a refused call: the bridge's reason, else Porthole's for it. */
110
+ export function reasonFor(capability, outcome) {
111
+ const reason = outcome.reason ?? defaultReason(capability, outcome.refusal);
112
+ return { code: reason.code, message: reason.message };
113
+ }
114
+ /** A consent function that failed (threw, rejected): not an answer, so asked again at the next. */
115
+ export function pendingReason(capability) {
116
+ const data = capability === "readData" || capability === "subscribeData";
117
+ return {
118
+ code: "consent_required",
119
+ message: (data ? DATA_MESSAGES : DEFAULT_MESSAGES).consent_required,
120
+ };
121
+ }
@@ -1,5 +1,6 @@
1
1
  import type { CapabilityArgs, CapabilityName, CapabilityResults, HandledCapability } from "../config/capabilities.ts";
2
2
  import type { InstanceRef } from "../isolation/types.ts";
3
+ import type { RefusalReason } from "./refusal.ts";
3
4
  /**
4
5
  * The host-function bridge (ARCHITECTURE § Framework layer): carries a capability call from the
5
6
  * frame to the host's handler and its result back, checking at the boundary that the capability
@@ -36,6 +37,9 @@ export type CapabilityHandlers = {
36
37
  * Asked once per display before its first call of a `consent`-gated capability (P079): may this
37
38
  * content have them (read the viewer's data)? The request is that first call. A host remembers
38
39
  * the answer where it likes (per viewer, per widget); Porthole keeps it for the display's life.
40
+ * `false` is a no (content is told `denied`); a thrown `Refused` is a no with its reason, kept
41
+ * the same way (P080); anything else it throws is no answer yet (`consent_required`), and the next
42
+ * call asks again.
39
43
  */
40
44
  export type Consent = (request: ConfirmRequest) => boolean | Promise<boolean>;
41
45
  /**
@@ -111,7 +115,10 @@ export type CallOutcome<T> =
111
115
  } | {
112
116
  readonly ok: false;
113
117
  readonly refusal: Refusal;
118
+ /** What the host's handler threw: the host's own words, never sent to content. */
114
119
  readonly message?: string;
120
+ /** What content is told (P080): the host's `Refused`, else Porthole's for the refusal. */
121
+ readonly reason?: RefusalReason;
115
122
  };
116
123
  /** What an adapter adds to a call, beyond what the content sent. */
117
124
  export interface CallOptions {