@botiverse/porthole 0.6.0 → 0.8.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 (208) hide show
  1. package/README.md +25 -2
  2. package/THIRD_PARTY_NOTICES.md +421 -0
  3. package/dist/bridge/bounded-text.d.ts +34 -0
  4. package/dist/bridge/bounded-text.js +188 -0
  5. package/dist/bridge/bridge.d.ts +38 -5
  6. package/dist/bridge/bridge.js +469 -39
  7. package/dist/bridge/json-data.d.ts +28 -0
  8. package/dist/bridge/json-data.js +86 -0
  9. package/dist/bridge/navigation.d.ts +5 -0
  10. package/dist/bridge/navigation.js +7 -0
  11. package/dist/bridge/refusal.d.ts +5 -1
  12. package/dist/bridge/refusal.js +17 -0
  13. package/dist/bridge/types.d.ts +73 -5
  14. package/dist/check/check.d.ts +7 -0
  15. package/dist/check/check.js +1 -0
  16. package/dist/check/instrument.d.ts +3 -0
  17. package/dist/check/lint.js +4 -2
  18. package/dist/check/page-source.js +1 -1
  19. package/dist/check/page.js +16 -0
  20. package/dist/check/tools.js +2 -3
  21. package/dist/compile/compile.d.ts +6 -0
  22. package/dist/compile/compile.js +3 -1
  23. package/dist/compile/policy.d.ts +55 -0
  24. package/dist/compile/policy.js +157 -0
  25. package/dist/config/capabilities.d.ts +85 -7
  26. package/dist/config/capabilities.js +32 -2
  27. package/dist/config/schema.d.ts +35 -0
  28. package/dist/config/validate.d.ts +9 -3
  29. package/dist/config/validate.js +92 -8
  30. package/dist/config/warnings.d.ts +20 -0
  31. package/dist/config/warnings.js +25 -0
  32. package/dist/conformance/behavior.js +46 -1
  33. package/dist/conformance/cookies.d.ts +15 -0
  34. package/dist/conformance/cookies.js +80 -0
  35. package/dist/conformance/harness/page.d.ts +1 -0
  36. package/dist/conformance/harness/page.js +9 -2
  37. package/dist/conformance/harness-source.js +1 -1
  38. package/dist/conformance/host-kit.js +5 -1
  39. package/dist/conformance/index.d.ts +11 -0
  40. package/dist/conformance/index.js +2 -0
  41. package/dist/conformance/limits.js +38 -1
  42. package/dist/conformance/runtime.d.ts +58 -0
  43. package/dist/conformance/runtime.js +324 -0
  44. package/dist/conformance/served.d.ts +2 -0
  45. package/dist/conformance/served.js +737 -4
  46. package/dist/files/paths.js +4 -0
  47. package/dist/guide/gates.d.ts +9 -0
  48. package/dist/guide/gates.js +31 -0
  49. package/dist/guide/guide.d.ts +2 -0
  50. package/dist/guide/guide.js +35 -33
  51. package/dist/guide/limits.js +4 -4
  52. package/dist/guide/runtime.d.ts +13 -0
  53. package/dist/guide/runtime.js +210 -0
  54. package/dist/host/create-host.js +73 -37
  55. package/dist/host/locate.js +8 -0
  56. package/dist/host/locator.js +7 -0
  57. package/dist/host/pages-of-set.d.ts +43 -0
  58. package/dist/host/pages-of-set.js +196 -0
  59. package/dist/host/types.d.ts +26 -1
  60. package/dist/index.d.ts +11 -4
  61. package/dist/index.js +11 -2
  62. package/dist/isolation/types.d.ts +8 -0
  63. package/dist/mcp/adapter.js +11 -15
  64. package/dist/node/index.d.ts +36 -4
  65. package/dist/node/index.js +402 -101
  66. package/dist/presets/presets.d.ts +22 -8
  67. package/dist/presets/presets.js +40 -8
  68. package/dist/protocol/live-data.d.ts +6 -2
  69. package/dist/protocol/live-data.js +20 -1
  70. package/dist/protocol/mcp-apps.d.ts +13 -2
  71. package/dist/protocol/mcp-apps.js +10 -2
  72. package/dist/protocol/message-text.d.ts +8 -0
  73. package/dist/protocol/message-text.js +29 -0
  74. package/dist/protocol/runtime-calls.d.ts +28 -0
  75. package/dist/protocol/runtime-calls.js +116 -0
  76. package/dist/protocol/shell-adapter.js +64 -25
  77. package/dist/react/context-notice.d.ts +32 -0
  78. package/dist/react/context-notice.js +28 -0
  79. package/dist/react/dialog.js +91 -16
  80. package/dist/react/frame.d.ts +25 -1
  81. package/dist/react/frame.js +85 -2
  82. package/dist/react/index.d.ts +2 -1
  83. package/dist/react/index.js +2 -1
  84. package/dist/runtime/contract.d.ts +201 -0
  85. package/dist/runtime/contract.js +245 -0
  86. package/dist/runtime/db.d.ts +188 -0
  87. package/dist/runtime/db.js +502 -0
  88. package/dist/runtime/declaration.d.ts +100 -0
  89. package/dist/runtime/declaration.js +363 -0
  90. package/dist/runtime/levels.d.ts +33 -0
  91. package/dist/runtime/levels.js +41 -0
  92. package/dist/runtime/requests.d.ts +125 -0
  93. package/dist/runtime/requests.js +215 -0
  94. package/dist/runtime/segments.d.ts +8 -0
  95. package/dist/runtime/segments.js +14 -0
  96. package/dist/runtime/types.generated.d.ts +1 -0
  97. package/dist/runtime/types.generated.js +19 -0
  98. package/dist/server/files.d.ts +19 -1
  99. package/dist/server/files.js +115 -6
  100. package/dist/server/host.d.ts +24 -2
  101. package/dist/server/host.js +137 -2
  102. package/dist/server/index.d.ts +3 -2
  103. package/dist/server/index.js +2 -1
  104. package/dist/server/peer.d.ts +4 -0
  105. package/dist/server/peer.js +19 -0
  106. package/dist/server/proxy.d.ts +6 -0
  107. package/dist/server/proxy.js +12 -3
  108. package/dist/server/pseudonym.d.ts +9 -0
  109. package/dist/server/pseudonym.js +20 -0
  110. package/dist/server/server.d.ts +0 -5
  111. package/dist/server/server.js +318 -52
  112. package/dist/server/types.d.ts +74 -2
  113. package/dist/shell/document.d.ts +16 -0
  114. package/dist/shell/document.js +19 -2
  115. package/dist/shell/legacy.d.ts +21 -0
  116. package/dist/shell/legacy.js +63 -0
  117. package/dist/shell/plan.d.ts +17 -1
  118. package/dist/shell/plan.js +13 -2
  119. package/dist/shell/runtime.js +390 -56
  120. package/dist/shell/use.d.ts +15 -0
  121. package/dist/shell/use.js +235 -0
  122. package/docs/ADOPTING.md +205 -15
  123. package/docs/ARCHITECTURE.md +34 -5
  124. package/docs/DECISIONS.md +1867 -11
  125. package/docs/DESIGN.md +137 -17
  126. package/docs/THREAT_MODEL.md +616 -0
  127. package/package.json +16 -3
  128. package/src/bridge/bounded-text.ts +240 -0
  129. package/src/bridge/bridge.ts +601 -51
  130. package/src/bridge/json-data.ts +95 -0
  131. package/src/bridge/navigation.ts +10 -0
  132. package/src/bridge/refusal.ts +17 -0
  133. package/src/bridge/types.ts +76 -5
  134. package/src/check/check.ts +8 -0
  135. package/src/check/instrument.ts +3 -0
  136. package/src/check/lint.ts +4 -2
  137. package/src/check/page.ts +16 -0
  138. package/src/check/tools.ts +2 -3
  139. package/src/compile/compile.ts +9 -1
  140. package/src/compile/policy.ts +177 -0
  141. package/src/config/capabilities.ts +71 -5
  142. package/src/config/schema.ts +35 -0
  143. package/src/config/validate.ts +141 -8
  144. package/src/config/warnings.ts +42 -0
  145. package/src/conformance/behavior.ts +54 -1
  146. package/src/conformance/cookies.ts +93 -0
  147. package/src/conformance/harness/page.ts +11 -2
  148. package/src/conformance/host-kit.ts +10 -1
  149. package/src/conformance/index.ts +17 -0
  150. package/src/conformance/limits.ts +39 -1
  151. package/src/conformance/runtime.ts +594 -0
  152. package/src/conformance/served.ts +888 -4
  153. package/src/files/paths.ts +4 -0
  154. package/src/guide/gates.ts +37 -0
  155. package/src/guide/guide.ts +61 -55
  156. package/src/guide/limits.ts +4 -4
  157. package/src/guide/runtime.ts +253 -0
  158. package/src/host/create-host.ts +88 -36
  159. package/src/host/locate.ts +10 -0
  160. package/src/host/locator.ts +11 -0
  161. package/src/host/pages-of-set.ts +226 -0
  162. package/src/host/types.ts +33 -1
  163. package/src/index.ts +94 -0
  164. package/src/isolation/types.ts +8 -0
  165. package/src/mcp/adapter.ts +16 -20
  166. package/src/node/index.ts +507 -116
  167. package/src/presets/presets.ts +67 -17
  168. package/src/protocol/live-data.ts +31 -3
  169. package/src/protocol/mcp-apps.ts +11 -2
  170. package/src/protocol/message-text.ts +36 -0
  171. package/src/protocol/runtime-calls.ts +141 -0
  172. package/src/protocol/shell-adapter.ts +79 -26
  173. package/src/react/context-notice.tsx +95 -0
  174. package/src/react/dialog.tsx +108 -15
  175. package/src/react/frame.tsx +120 -0
  176. package/src/react/index.ts +8 -1
  177. package/src/runtime/contract.ts +339 -0
  178. package/src/runtime/db.ts +650 -0
  179. package/src/runtime/declaration.ts +516 -0
  180. package/src/runtime/levels.ts +69 -0
  181. package/src/runtime/requests.ts +355 -0
  182. package/src/runtime/segments.ts +17 -0
  183. package/src/runtime/types.generated.ts +19 -0
  184. package/src/server/files.ts +138 -7
  185. package/src/server/host.ts +170 -3
  186. package/src/server/index.ts +4 -0
  187. package/src/server/peer.ts +21 -0
  188. package/src/server/proxy.ts +13 -3
  189. package/src/server/pseudonym.ts +21 -0
  190. package/src/server/server.ts +370 -57
  191. package/src/server/types.ts +73 -2
  192. package/src/shell/document.ts +29 -4
  193. package/src/shell/legacy.ts +64 -0
  194. package/src/shell/plan.ts +37 -3
  195. package/src/shell/runtime.ts +390 -56
  196. package/src/shell/use.ts +235 -0
  197. package/types/runtime/v1/artifact.d.ts +50 -0
  198. package/types/runtime/v1/assets.d.ts +43 -0
  199. package/types/runtime/v1/chat.d.ts +13 -0
  200. package/types/runtime/v1/clipboard.d.ts +14 -0
  201. package/types/runtime/v1/comments.d.ts +24 -0
  202. package/types/runtime/v1/context.d.ts +27 -0
  203. package/types/runtime/v1/data.d.ts +29 -0
  204. package/types/runtime/v1/db.d.ts +110 -0
  205. package/types/runtime/v1/downloads.d.ts +22 -0
  206. package/types/runtime/v1/links.d.ts +13 -0
  207. package/types/runtime/v1/porthole.d.ts +44 -0
  208. package/types/runtime/v1/user.d.ts +19 -0
@@ -1,10 +1,137 @@
1
- import { createServer as createHttpServer, request as httpRequest } from "node:http";
1
+ import { createServer as createHttpServer, request as httpRequest, STATUS_CODES } from "node:http";
2
2
  import { request as httpsRequest } from "node:https";
3
- import { Readable } from "node:stream";
3
+ import { withPeerAddress } from "../server/peer.js";
4
4
  import { withoutPortholeCookies } from "../server/proxy.js";
5
+ /** Tells the app what failed (`onError`, or a process warning); a report never fails a request. */
6
+ function report(onError, error, request) {
7
+ try {
8
+ if (onError === undefined) {
9
+ process.emitWarning(error instanceof Error ? error : new Error(String(error)));
10
+ }
11
+ else {
12
+ onError(error, request);
13
+ }
14
+ }
15
+ catch {
16
+ // The report's own failure is not the request's.
17
+ }
18
+ }
19
+ /** The most of a body no one reads that is dropped before the connection closes (P092). */
20
+ const DROP_BYTES = 1_048_576;
21
+ /** How long an answered request's unread body is dropped before the connection closes (P092). */
22
+ const DROP_MS = 5_000;
23
+ const dropping = new WeakSet();
24
+ /**
25
+ * Reads and drops what is left of a request's body no one will read, at most `DROP_BYTES`, then
26
+ * closes the connection (P092). A client still sending its body gets the answer this way: closed
27
+ * at once with the body unread, the connection is reset, and the answer with it.
28
+ */
29
+ function drop(request) {
30
+ if (request.complete || dropping.has(request)) {
31
+ return;
32
+ }
33
+ dropping.add(request);
34
+ let dropped = 0;
35
+ const count = (chunk) => {
36
+ dropped += chunk.byteLength;
37
+ if (dropped > DROP_BYTES) {
38
+ request.off("data", count);
39
+ request.socket.destroy();
40
+ }
41
+ };
42
+ request.on("data", count);
43
+ request.resume();
44
+ }
45
+ /**
46
+ * Once an answer is out, what its request's body still holds is dropped for at most `DROP_MS`
47
+ * (and `DROP_BYTES`), then the connection closes: never left waiting on a body no one reads, and
48
+ * a body dropped whole leaves the connection to go on (P092).
49
+ */
50
+ function dropAfter(response) {
51
+ response.once("finish", () => {
52
+ const request = response.req ?? null;
53
+ if (request === null || request.complete) {
54
+ return;
55
+ }
56
+ drop(request);
57
+ const socket = request.socket;
58
+ const timer = setTimeout(() => socket.destroy(), DROP_MS);
59
+ timer.unref();
60
+ const stop = () => clearTimeout(timer);
61
+ request.once("end", stop);
62
+ socket.once("close", stop);
63
+ });
64
+ }
65
+ /**
66
+ * A Node request's body as a stream, read only as it is pulled (a body no one reads is never
67
+ * taken: the app's listener gets it whole, P092). Cancelled, the rest is dropped (`drop`), not
68
+ * the connection: the answer still goes out.
69
+ */
70
+ function bodyOf(request) {
71
+ let listening = false;
72
+ let settled = false;
73
+ let stop = () => { };
74
+ return new ReadableStream({
75
+ pull(controller) {
76
+ if (settled) {
77
+ return;
78
+ }
79
+ if (!listening) {
80
+ listening = true;
81
+ const settle = () => {
82
+ settled = true;
83
+ stop();
84
+ };
85
+ const data = (chunk) => {
86
+ if (!settled) {
87
+ controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
88
+ request.pause();
89
+ }
90
+ };
91
+ const end = () => {
92
+ if (!settled) {
93
+ settle();
94
+ controller.close();
95
+ }
96
+ };
97
+ const fail = () => {
98
+ if (!settled) {
99
+ settle();
100
+ controller.error(new Error("The request's body broke off"));
101
+ }
102
+ };
103
+ const close = () => {
104
+ if (!request.complete) {
105
+ fail();
106
+ }
107
+ };
108
+ request.on("data", data);
109
+ request.on("end", end);
110
+ request.on("error", fail);
111
+ request.on("close", close);
112
+ stop = () => {
113
+ request.off("data", data);
114
+ request.off("end", end);
115
+ request.off("error", fail);
116
+ request.off("close", close);
117
+ };
118
+ }
119
+ request.resume();
120
+ },
121
+ cancel() {
122
+ settled = true;
123
+ stop();
124
+ drop(request);
125
+ },
126
+ }, { highWaterMark: 0 });
127
+ }
5
128
  /**
6
129
  * The Node request as a fetch `Request`: an absolute-form target kept as it came (P056). `signal`
7
- * (`nodeHost` gives one, aborted when the client goes away) lets an upstream stop its work.
130
+ * (`nodeHost` gives one, aborted when the client goes away) lets an upstream stop its work. The
131
+ * body is read only as it is pulled; cancelled, the rest is dropped (bounded), not the connection.
132
+ * The socket's peer goes with it, for the issue endpoint's rate limit (P092).
133
+ * Throws where fetch can't take the request: a method it can't carry (`TRACE`), a Host or a
134
+ * target that is no URL. `nodeListener`, `nodeHost` and `nodeServer` answer those 405 and 400.
8
135
  */
9
136
  export function toRequest(request, scheme, signal) {
10
137
  const headers = new Headers();
@@ -18,22 +145,17 @@ export function toRequest(request, scheme, signal) {
18
145
  ? `${scheme}://${request.headers.host ?? "localhost"}${target}`
19
146
  : target;
20
147
  const method = request.method ?? "GET";
21
- const body = method === "GET" || method === "HEAD" ? null : Readable.toWeb(request);
22
- return new Request(url, {
148
+ const body = method === "GET" || method === "HEAD" ? null : bodyOf(request);
149
+ return withPeerAddress(new Request(url, {
23
150
  method,
24
151
  headers,
25
152
  body,
26
153
  duplex: "half",
27
154
  ...(signal === undefined ? {} : { signal }),
28
- });
155
+ }), request.socket.remoteAddress);
29
156
  }
30
- /**
31
- * Writes a fetch `Response` to a Node response, cookies one header each (P070): it waits for the
32
- * socket to drain before reading on (a slow client never makes it buffer the body), cancels the
33
- * body when the client goes away (an event stream ends with the page that asked for it), and on
34
- * an error mid-body destroys the response rather than end it looking complete.
35
- */
36
- export async function sendResponse(response, answer) {
157
+ /** A fetch Response's head for Node, cookies one header each (P070). Throws for no Response. */
158
+ function headOf(answer) {
37
159
  const headers = {};
38
160
  for (const [name, value] of answer.headers) {
39
161
  if (name !== "set-cookie") {
@@ -44,8 +166,50 @@ export async function sendResponse(response, answer) {
44
166
  if (cookies.length > 0) {
45
167
  headers["set-cookie"] = cookies;
46
168
  }
47
- response.writeHead(answer.status, headers);
48
- if (answer.body === null) {
169
+ if (answer.bodyUsed || answer.body?.locked === true) {
170
+ throw new TypeError("The answer's body is already being read");
171
+ }
172
+ return headers;
173
+ }
174
+ /**
175
+ * Writes a fetch `Response` to a Node response, cookies one header each (P070): it waits for the
176
+ * socket to drain before reading on (a slow client never makes it buffer the body), cancels the
177
+ * body when the client goes away, before the answer or during it (an event stream ends with the
178
+ * page that asked for it), and on an error mid-body destroys the response rather than end it
179
+ * looking complete. A HEAD gets the head and its body is cancelled. Never rejects (P092): an
180
+ * answer it can't write (no Response, a body already read, a header value fetch takes and Node
181
+ * doesn't) is a 500, and `onError` hears why. Once the answer is out, a request body no one read
182
+ * is dropped, bounded, before the connection closes.
183
+ */
184
+ export async function sendResponse(response, answer, onError) {
185
+ const cancel = () => {
186
+ try {
187
+ answer.body?.cancel().catch(() => undefined);
188
+ }
189
+ catch {
190
+ // No Response, or a body already taken: nothing of it to stop.
191
+ }
192
+ };
193
+ // The client went away before the answer: nothing to write, and the body's source is told.
194
+ if (response.destroyed) {
195
+ cancel();
196
+ return;
197
+ }
198
+ try {
199
+ const headers = headOf(answer);
200
+ dropAfter(response);
201
+ response.writeHead(answer.status, headers);
202
+ }
203
+ catch (error) {
204
+ cancel();
205
+ onError?.(error);
206
+ answerPlain(response, 500, "The answer couldn't be written.");
207
+ return;
208
+ }
209
+ const request = response.req ?? null;
210
+ if (answer.body === null || request?.method === "HEAD") {
211
+ // Node writes no body for HEAD: the head goes out with the end, and the body is never read.
212
+ cancel();
49
213
  response.end();
50
214
  return;
51
215
  }
@@ -64,10 +228,10 @@ export async function sendResponse(response, answer) {
64
228
  try {
65
229
  for (;;) {
66
230
  const { done, value } = await reader.read();
67
- if (done || gone) {
231
+ if (done || gone || response.destroyed) {
68
232
  break;
69
233
  }
70
- if (!response.write(value)) {
234
+ if (!response.write(value) && !response.destroyed) {
71
235
  await new Promise((resolve) => {
72
236
  const on = () => {
73
237
  response.off("drain", on);
@@ -86,10 +250,127 @@ export async function sendResponse(response, answer) {
86
250
  response.destroy(error instanceof Error ? error : new Error(String(error)));
87
251
  return;
88
252
  }
89
- if (!gone) {
253
+ if (response.destroyed) {
254
+ leave();
255
+ }
256
+ else if (!gone) {
90
257
  response.end();
91
258
  }
92
259
  }
260
+ /** The methods a fetch `Request` can't carry (the Fetch standard's forbidden methods). */
261
+ const FORBIDDEN_METHODS = new Set(["CONNECT", "TRACE", "TRACK"]);
262
+ /**
263
+ * `toRequest`, or the status for a request fetch can't take (S01, P092): 405 for a method it
264
+ * can't carry, 400 for anything else (a Host or a target that is no URL). Never throws: the
265
+ * conversion runs in a listener, where a throw would end the process.
266
+ */
267
+ function convert(request, scheme, signal) {
268
+ try {
269
+ return toRequest(request, scheme, signal);
270
+ }
271
+ catch {
272
+ return FORBIDDEN_METHODS.has((request.method ?? "").toUpperCase()) ? 405 : 400;
273
+ }
274
+ }
275
+ /**
276
+ * A plain answer of the adapter's own. A response already started is cut off, never made to look
277
+ * whole; one already ended is left be. Never throws: it answers from the listeners' catches.
278
+ */
279
+ function answerPlain(response, status, text) {
280
+ try {
281
+ if (response.writableEnded || response.destroyed) {
282
+ return;
283
+ }
284
+ if (response.headersSent) {
285
+ response.destroy();
286
+ return;
287
+ }
288
+ dropAfter(response);
289
+ // The reason given: a head Node refused to write leaves its own behind.
290
+ response.writeHead(status, STATUS_CODES[status], {
291
+ "content-type": "text/plain; charset=utf-8",
292
+ });
293
+ response.end(text);
294
+ }
295
+ catch {
296
+ response.destroy();
297
+ }
298
+ }
299
+ const REFUSED = {
300
+ 400: "Bad request.",
301
+ 405: "That method isn't served here.",
302
+ };
303
+ /** A request's signal: aborted when the client goes away before the answer is out (P070). */
304
+ function goneSignal(response) {
305
+ const gone = new AbortController();
306
+ response.once("close", () => {
307
+ if (!response.writableFinished) {
308
+ gone.abort();
309
+ }
310
+ });
311
+ return gone.signal;
312
+ }
313
+ const isThenable = (value) => (typeof value === "object" || typeof value === "function") &&
314
+ value !== null &&
315
+ typeof value.then === "function";
316
+ /**
317
+ * Calls one of the app's own listeners: what it throws, or an async one's rejection, is reported
318
+ * and ends in `failed` (a 500, a closed socket), never out of the listener (S01, P092).
319
+ */
320
+ function callApp(call, failed, onError, request) {
321
+ const fail = (error) => {
322
+ report(onError, error, request);
323
+ failed();
324
+ };
325
+ try {
326
+ const returned = call();
327
+ if (isThenable(returned)) {
328
+ returned.then(undefined, fail);
329
+ }
330
+ }
331
+ catch (error) {
332
+ fail(error);
333
+ }
334
+ }
335
+ /**
336
+ * Writes what a fetch-style handler answers (null: `otherwise`, the app's own listener). Whatever
337
+ * fails, the handler (thrown or rejected), `otherwise`, or the writing (a header fetch takes and
338
+ * Node doesn't), answers 500, or cuts off a response already started, and is reported: nothing
339
+ * escapes (S01, P092).
340
+ */
341
+ function serve(request, response, handle, failed, onError, otherwise) {
342
+ const fail = (error) => {
343
+ report(onError, error, request);
344
+ answerPlain(response, 500, failed);
345
+ };
346
+ new Promise((resolve) => resolve(handle()))
347
+ .then((answer) => {
348
+ if (answer === null && otherwise !== undefined) {
349
+ otherwise();
350
+ return undefined;
351
+ }
352
+ // Anything that isn't a Response (an app's null or undefined) fails in it, as a 500.
353
+ return sendResponse(response, answer, (error) => report(onError, error, request));
354
+ })
355
+ .catch(fail);
356
+ }
357
+ /**
358
+ * A fetch-style handler (Hono's `app.fetch`, the app's own) as a Node request listener: what
359
+ * `toRequest` can't convert is 405 or 400, what the handler throws or the answer's writing fails
360
+ * is 500 (`onError` hears it); nothing it does ends the process (S01, P092). The request's
361
+ * `signal` aborts when the client goes away before the answer is out.
362
+ */
363
+ export function nodeListener(app, options = {}) {
364
+ const scheme = options.scheme ?? "http";
365
+ return (incoming, response) => {
366
+ const asked = convert(incoming, scheme, goneSignal(response));
367
+ if (typeof asked === "number") {
368
+ answerPlain(response, asked, REFUSED[asked]);
369
+ return;
370
+ }
371
+ serve(incoming, response, () => app(asked), "Something went wrong.", options.onError);
372
+ };
373
+ }
93
374
  /** Whether a Node request's Host (or absolute-form target) is under the content domain. */
94
375
  function forContent(content, request) {
95
376
  const domain = content.domain;
@@ -106,74 +387,89 @@ function forContent(content, request) {
106
387
  }
107
388
  return domain.isContentHost(host) || (target !== "" && domain.isContentHost(target));
108
389
  }
109
- /** Refuses a WebSocket on the content domain with a plain 404, and closes it. */
110
- function refuseSocket(socket) {
111
- socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
390
+ /** Refuses a WebSocket with a plain status (404: on the content domain), and closes it. */
391
+ function refuseSocket(socket, status = 404) {
392
+ socket.end(`HTTP/1.1 ${status} ${STATUS_CODES[status] ?? ""}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
393
+ }
394
+ const guarded = new WeakSet();
395
+ /**
396
+ * Node takes its own error listener off an upgrade's socket before the `upgrade` event: a reset
397
+ * there would be an unhandled `error` and end the process (P092). The socket is closed instead.
398
+ */
399
+ function guardSocket(socket) {
400
+ if (!guarded.has(socket)) {
401
+ guarded.add(socket);
402
+ socket.on("error", () => socket.destroy());
403
+ }
112
404
  }
113
405
  export function nodeHost(content, app) {
114
406
  const scheme = () => content.domain?.scheme ?? "http";
407
+ const toApp = (request, response) => callApp(() => app.request(request, response), () => answerPlain(response, 500, "Something went wrong."), app.onError, request);
408
+ const toAppSocket = (request, socket, head) => {
409
+ const upgrade = app.upgrade;
410
+ if (upgrade === undefined) {
411
+ refuseSocket(socket);
412
+ return;
413
+ }
414
+ callApp(() => upgrade(request, socket, head), () => socket.destroy(), app.onError, request);
415
+ };
416
+ // Nothing in either listener throws out of it, the app's own listeners included (S01, P092):
417
+ // a request ends in an answer, a socket in a refusal or closed.
115
418
  return {
116
419
  request(request, response) {
117
- if (!forContent(content, request)) {
118
- app.request(request, response);
119
- return;
120
- }
121
- // Aborted when the client goes away first, so an upstream (a proxied app's event stream)
122
- // stops with it.
123
- const gone = new AbortController();
124
- response.once("close", () => {
125
- if (!response.writableFinished) {
126
- gone.abort();
420
+ try {
421
+ if (!forContent(content, request)) {
422
+ toApp(request, response);
423
+ return;
127
424
  }
128
- });
129
- content.fetch(toRequest(request, scheme(), gone.signal)).then((answer) => {
130
- if (answer === null) {
131
- // A label the app routes itself.
132
- app.request(request, response);
425
+ // Aborted when the client goes away first, so an upstream (a proxied app's event stream)
426
+ // stops with it.
427
+ const asked = convert(request, scheme(), goneSignal(response));
428
+ if (typeof asked === "number") {
429
+ answerPlain(response, asked, REFUSED[asked]);
133
430
  return;
134
431
  }
135
- return sendResponse(response, answer);
136
- }, () => {
137
- if (response.headersSent) {
138
- response.destroy();
432
+ // A label the app routes itself: its request untouched, body and all (P092).
433
+ if (!content.owns(asked)) {
434
+ toApp(request, response);
139
435
  return;
140
436
  }
141
- response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
142
- response.end("Content couldn't be served.");
143
- });
437
+ serve(request, response, () => content.fetch(asked), "Content couldn't be served.", app.onError, () => toApp(request, response));
438
+ }
439
+ catch (error) {
440
+ report(app.onError, error, request);
441
+ answerPlain(response, 500, "Something went wrong.");
442
+ }
144
443
  },
145
444
  upgrade(request, socket, head) {
146
- if (!forContent(content, request)) {
147
- if (app.upgrade === undefined) {
148
- refuseSocket(socket);
149
- }
150
- else {
151
- app.upgrade(request, socket, head);
445
+ guardSocket(socket);
446
+ try {
447
+ if (!forContent(content, request)) {
448
+ toAppSocket(request, socket, head);
449
+ return;
152
450
  }
153
- return;
154
- }
155
- const asked = toRequest(request, scheme());
156
- // A reserved label's socket is the app's.
157
- if (!content.owns(asked)) {
158
- if (app.upgrade === undefined) {
159
- refuseSocket(socket);
451
+ const asked = convert(request, scheme());
452
+ if (typeof asked === "number") {
453
+ refuseSocket(socket, asked);
454
+ return;
160
455
  }
161
- else {
162
- app.upgrade(request, socket, head);
456
+ // A reserved label's socket is the app's.
457
+ if (!content.owns(asked)) {
458
+ toAppSocket(request, socket, head);
459
+ return;
163
460
  }
164
- return;
165
- }
166
- const appSocket = app.appSocket;
167
- if (appSocket === undefined) {
168
- refuseSocket(socket);
169
- return;
170
- }
171
- content.access(asked).then((access) => {
172
- if (access === null) {
461
+ const appSocket = app.appSocket;
462
+ if (appSocket === undefined) {
173
463
  refuseSocket(socket);
464
+ return;
174
465
  }
175
- else {
176
- // The app's socket never sees Porthole's own cookies, as its HTTP requests don't (P072).
466
+ const settled = content.access(asked).then((access) => {
467
+ if (access === null) {
468
+ refuseSocket(socket);
469
+ return;
470
+ }
471
+ // The app's socket never sees Porthole's own cookies, as its HTTP requests don't
472
+ // (P072).
177
473
  const cookie = withoutPortholeCookies(request.headers.cookie);
178
474
  if (cookie === null) {
179
475
  delete request.headers.cookie;
@@ -181,9 +477,21 @@ export function nodeHost(content, app) {
181
477
  else {
182
478
  request.headers.cookie = cookie;
183
479
  }
184
- appSocket(access, request, socket, head);
185
- }
186
- }, () => refuseSocket(socket));
480
+ callApp(() => appSocket(access, request, socket, head), () => socket.destroy(), app.onError, request);
481
+ }, (error) => {
482
+ report(app.onError, error, request);
483
+ refuseSocket(socket);
484
+ });
485
+ // Neither branch above throws (callApp catches the app's); should one, the socket closes.
486
+ settled.catch((error) => {
487
+ report(app.onError, error, request);
488
+ socket.destroy();
489
+ });
490
+ }
491
+ catch (error) {
492
+ report(app.onError, error, request);
493
+ socket.destroy();
494
+ }
187
495
  },
188
496
  };
189
497
  }
@@ -235,20 +543,11 @@ export function nodeProbe() {
235
543
  */
236
544
  export function nodeServer(options) {
237
545
  const scheme = options.scheme ?? "http";
238
- const fromFetch = options.app;
546
+ const onError = options.onError;
239
547
  const request = options.request ??
240
- (fromFetch === undefined
548
+ (options.app === undefined
241
549
  ? undefined
242
- : (incoming, response) => {
243
- Promise.resolve(fromFetch(toRequest(incoming, scheme))).then((answer) => sendResponse(response, answer), () => {
244
- if (response.headersSent) {
245
- response.destroy();
246
- return;
247
- }
248
- response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
249
- response.end("Something went wrong.");
250
- });
251
- });
550
+ : nodeListener(options.app, { scheme, ...(onError === undefined ? {} : { onError }) }));
252
551
  if (request === undefined) {
253
552
  throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
254
553
  }
@@ -268,6 +567,7 @@ export function nodeServer(options) {
268
567
  request,
269
568
  ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
270
569
  ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
570
+ ...(onError === undefined ? {} : { onError }),
271
571
  });
272
572
  adapters.set(host, adapter);
273
573
  }
@@ -277,26 +577,27 @@ export function nodeServer(options) {
277
577
  }
278
578
  return adapter;
279
579
  };
580
+ // The host function, the app's listeners: nothing throws out of the server's events (S01).
280
581
  const server = createHttpServer((incoming, response) => {
281
- const adapter = current();
282
- if (adapter === null) {
283
- request(incoming, response);
284
- }
285
- else {
286
- adapter.request(incoming, response);
287
- }
582
+ callApp(() => {
583
+ const adapter = current();
584
+ return adapter === null ? request(incoming, response) : adapter.request(incoming, response);
585
+ }, () => answerPlain(response, 500, "Something went wrong."), onError, incoming);
288
586
  });
289
587
  server.on("upgrade", (incoming, socket, head) => {
290
- const adapter = current();
291
- if (adapter !== null) {
292
- adapter.upgrade(incoming, socket, head);
293
- }
294
- else if (options.upgrade !== undefined) {
295
- options.upgrade(incoming, socket, head);
296
- }
297
- else {
298
- refuseSocket(socket);
299
- }
588
+ guardSocket(socket);
589
+ callApp(() => {
590
+ const adapter = current();
591
+ if (adapter !== null) {
592
+ adapter.upgrade(incoming, socket, head);
593
+ return undefined;
594
+ }
595
+ if (options.upgrade === undefined) {
596
+ refuseSocket(socket);
597
+ return undefined;
598
+ }
599
+ return options.upgrade(incoming, socket, head);
600
+ }, () => socket.destroy(), onError, incoming);
300
601
  });
301
602
  server.on("listening", () => {
302
603
  listening = true;
@@ -1,3 +1,4 @@
1
+ import type { RuntimeVersion } from "../runtime/contract.ts";
1
2
  import type { CapabilityName } from "../config/capabilities.ts";
2
3
  import type { CapabilityConfig, EgressConfig, EmbedderConfig, GuideConfig, IsolationKind, LayoutConfig, Limits, PortholeConfig, StorageConfig, ThemeValue, UrlPermission, UrlSandboxExtra } from "../config/schema.ts";
3
4
  /**
@@ -34,12 +35,24 @@ export interface PresetOptions {
34
35
  readonly storage?: StorageConfig;
35
36
  /** Where the content's errors go (`PortholeConfig.errors`); `none` drops `reportError`. */
36
37
  readonly errors?: "agent" | "host" | "none";
38
+ /**
39
+ * The capability runtime (P085): content reaches capabilities through `porthole.use`, and may
40
+ * be offered the runtime's own (`user`, `comments`, `artifact`, `assets`, `db`).
41
+ */
42
+ readonly runtime?: RuntimeVersion;
37
43
  }
44
+ /** What a live widget may say about a capability (P103): anything but origins of its own. */
45
+ export type LiveCapabilityConfig = Omit<CapabilityConfig, "connect" | "resource">;
38
46
  /**
39
47
  * The live widget's options (P079): a widget's, less egress, which stays closed (Porthole's own
40
- * libraries come with domain isolation). A host adds capabilities, or changes the data ones' gates.
48
+ * libraries come with domain isolation), and less a capability's own origins, which are egress
49
+ * too (P103). A host adds capabilities, or changes the data ones' gates.
41
50
  */
42
- export type LiveWidgetOptions = Omit<PresetOptions, "egress">;
51
+ export type LiveWidgetOptions = Omit<PresetOptions, "egress" | "capabilities"> & {
52
+ readonly capabilities?: {
53
+ readonly [N in CapabilityName]?: LiveCapabilityConfig | false;
54
+ };
55
+ };
43
56
  /** The url preset's options: where the app is served, and the embedding page's extra frames. */
44
57
  export interface UrlPresetOptions {
45
58
  readonly contentOrigins: readonly string[];
@@ -66,12 +79,13 @@ export declare const presets: {
66
79
  readonly inlineWidget: (options?: PresetOptions) => PortholeConfig;
67
80
  /**
68
81
  * A widget that shows its host's data, live, and has no network of its own (P079): an inline
69
- * widget whose egress stays closed (no option opens it). It reads the host's data (`readData`,
70
- * MCP `resources/read`) and subscribes to it (`subscribeData`, `resources/subscribe`), each
71
- * behind the viewer's consent (the host's `consent`, asked once per display) and a rate. In
72
- * domain isolation its scripts load from Porthole's own libraries on its origin
73
- * (`egress.libraries`: Chart.js, D3), and nowhere else. A host adds what any widget may have (a
74
- * link, a copy button), or changes the data capabilities' gates.
82
+ * widget whose egress stays closed (no option opens it: neither `egress` nor a capability's own
83
+ * `connect` or `resource`, P103). It reads the host's data (`readData`, MCP `resources/read`)
84
+ * and subscribes to it (`subscribeData`, `resources/subscribe`), each behind the viewer's
85
+ * consent (the host's `consent`, asked once per display) and a rate. In domain isolation its
86
+ * scripts load from Porthole's own libraries on its origin (`egress.libraries`: Chart.js, D3),
87
+ * and nowhere else. A host adds what any widget may have (a link, a copy button), or changes the
88
+ * data capabilities' gates.
75
89
  */
76
90
  readonly liveWidget: (options?: LiveWidgetOptions) => PortholeConfig;
77
91
  /**