@botiverse/porthole 0.7.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 (153) hide show
  1. package/README.md +9 -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 +25 -5
  6. package/dist/bridge/bridge.js +311 -73
  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.js +1 -0
  12. package/dist/bridge/types.d.ts +32 -1
  13. package/dist/check/page-source.js +1 -1
  14. package/dist/check/page.js +2 -0
  15. package/dist/compile/compile.d.ts +6 -0
  16. package/dist/compile/compile.js +3 -1
  17. package/dist/compile/policy.d.ts +38 -2
  18. package/dist/compile/policy.js +122 -7
  19. package/dist/config/capabilities.d.ts +23 -4
  20. package/dist/config/capabilities.js +12 -2
  21. package/dist/config/schema.d.ts +11 -0
  22. package/dist/config/validate.d.ts +8 -2
  23. package/dist/config/validate.js +28 -6
  24. package/dist/config/warnings.d.ts +20 -0
  25. package/dist/config/warnings.js +25 -0
  26. package/dist/conformance/behavior.js +46 -1
  27. package/dist/conformance/cookies.d.ts +15 -0
  28. package/dist/conformance/cookies.js +80 -0
  29. package/dist/conformance/harness/page.d.ts +1 -0
  30. package/dist/conformance/harness/page.js +9 -2
  31. package/dist/conformance/harness-source.js +1 -1
  32. package/dist/conformance/host-kit.js +5 -1
  33. package/dist/conformance/index.d.ts +10 -0
  34. package/dist/conformance/limits.js +38 -1
  35. package/dist/conformance/runtime.js +10 -0
  36. package/dist/conformance/served.d.ts +2 -0
  37. package/dist/conformance/served.js +737 -4
  38. package/dist/files/paths.js +4 -0
  39. package/dist/guide/gates.d.ts +7 -1
  40. package/dist/guide/gates.js +12 -0
  41. package/dist/guide/guide.js +2 -2
  42. package/dist/guide/runtime.js +11 -3
  43. package/dist/host/create-host.js +49 -37
  44. package/dist/host/pages-of-set.d.ts +43 -0
  45. package/dist/host/pages-of-set.js +196 -0
  46. package/dist/host/types.d.ts +8 -1
  47. package/dist/index.d.ts +5 -4
  48. package/dist/index.js +3 -2
  49. package/dist/mcp/adapter.js +11 -15
  50. package/dist/node/index.d.ts +36 -4
  51. package/dist/node/index.js +402 -101
  52. package/dist/presets/presets.d.ts +16 -8
  53. package/dist/presets/presets.js +39 -8
  54. package/dist/protocol/live-data.d.ts +6 -2
  55. package/dist/protocol/live-data.js +20 -1
  56. package/dist/protocol/mcp-apps.d.ts +13 -2
  57. package/dist/protocol/mcp-apps.js +10 -2
  58. package/dist/protocol/message-text.d.ts +8 -0
  59. package/dist/protocol/message-text.js +29 -0
  60. package/dist/protocol/runtime-calls.js +3 -0
  61. package/dist/protocol/shell-adapter.js +16 -22
  62. package/dist/react/context-notice.d.ts +32 -0
  63. package/dist/react/context-notice.js +28 -0
  64. package/dist/react/dialog.js +62 -18
  65. package/dist/react/frame.d.ts +12 -1
  66. package/dist/react/frame.js +79 -2
  67. package/dist/react/index.d.ts +2 -1
  68. package/dist/react/index.js +2 -1
  69. package/dist/runtime/contract.d.ts +9 -1
  70. package/dist/runtime/contract.js +31 -2
  71. package/dist/runtime/db.d.ts +41 -6
  72. package/dist/runtime/db.js +120 -16
  73. package/dist/runtime/declaration.d.ts +15 -1
  74. package/dist/runtime/declaration.js +184 -87
  75. package/dist/runtime/requests.js +27 -11
  76. package/dist/runtime/types.generated.js +1 -1
  77. package/dist/server/files.d.ts +5 -0
  78. package/dist/server/files.js +22 -7
  79. package/dist/server/host.d.ts +18 -1
  80. package/dist/server/host.js +132 -2
  81. package/dist/server/index.d.ts +1 -1
  82. package/dist/server/index.js +1 -1
  83. package/dist/server/peer.d.ts +4 -0
  84. package/dist/server/peer.js +19 -0
  85. package/dist/server/proxy.d.ts +6 -0
  86. package/dist/server/proxy.js +12 -3
  87. package/dist/server/server.js +113 -26
  88. package/dist/server/types.d.ts +6 -3
  89. package/dist/shell/document.d.ts +8 -0
  90. package/dist/shell/document.js +3 -0
  91. package/dist/shell/runtime.js +361 -14
  92. package/docs/ADOPTING.md +119 -14
  93. package/docs/ARCHITECTURE.md +13 -3
  94. package/docs/DECISIONS.md +1455 -8
  95. package/docs/DESIGN.md +79 -25
  96. package/docs/THREAT_MODEL.md +616 -0
  97. package/package.json +14 -3
  98. package/src/bridge/bounded-text.ts +240 -0
  99. package/src/bridge/bridge.ts +373 -84
  100. package/src/bridge/json-data.ts +95 -0
  101. package/src/bridge/navigation.ts +10 -0
  102. package/src/bridge/refusal.ts +1 -0
  103. package/src/bridge/types.ts +30 -1
  104. package/src/check/page.ts +2 -0
  105. package/src/compile/compile.ts +9 -1
  106. package/src/compile/policy.ts +130 -7
  107. package/src/config/capabilities.ts +22 -3
  108. package/src/config/schema.ts +11 -0
  109. package/src/config/validate.ts +43 -5
  110. package/src/config/warnings.ts +42 -0
  111. package/src/conformance/behavior.ts +54 -1
  112. package/src/conformance/cookies.ts +93 -0
  113. package/src/conformance/harness/page.ts +11 -2
  114. package/src/conformance/host-kit.ts +10 -1
  115. package/src/conformance/index.ts +10 -0
  116. package/src/conformance/limits.ts +39 -1
  117. package/src/conformance/runtime.ts +21 -0
  118. package/src/conformance/served.ts +888 -4
  119. package/src/files/paths.ts +4 -0
  120. package/src/guide/gates.ts +13 -1
  121. package/src/guide/guide.ts +3 -3
  122. package/src/guide/runtime.ts +12 -3
  123. package/src/host/create-host.ts +54 -36
  124. package/src/host/pages-of-set.ts +226 -0
  125. package/src/host/types.ts +15 -1
  126. package/src/index.ts +5 -0
  127. package/src/mcp/adapter.ts +16 -20
  128. package/src/node/index.ts +507 -116
  129. package/src/presets/presets.ts +60 -17
  130. package/src/protocol/live-data.ts +31 -3
  131. package/src/protocol/mcp-apps.ts +11 -2
  132. package/src/protocol/message-text.ts +36 -0
  133. package/src/protocol/runtime-calls.ts +3 -0
  134. package/src/protocol/shell-adapter.ts +27 -23
  135. package/src/react/context-notice.tsx +95 -0
  136. package/src/react/dialog.tsx +77 -17
  137. package/src/react/frame.tsx +101 -0
  138. package/src/react/index.ts +8 -1
  139. package/src/runtime/contract.ts +36 -2
  140. package/src/runtime/db.ts +140 -20
  141. package/src/runtime/declaration.ts +227 -89
  142. package/src/runtime/requests.ts +27 -11
  143. package/src/runtime/types.generated.ts +1 -1
  144. package/src/server/files.ts +29 -11
  145. package/src/server/host.ts +158 -3
  146. package/src/server/index.ts +1 -0
  147. package/src/server/peer.ts +21 -0
  148. package/src/server/proxy.ts +13 -3
  149. package/src/server/server.ts +139 -36
  150. package/src/server/types.ts +6 -3
  151. package/src/shell/document.ts +8 -0
  152. package/src/shell/runtime.ts +361 -14
  153. package/types/runtime/v1/context.d.ts +13 -2
package/src/node/index.ts CHANGED
@@ -8,20 +8,31 @@
8
8
  * const server = http.createServer(porthole.request);
9
9
  * server.on("upgrade", porthole.upgrade);
10
10
  * server.listen(8080, () => content.start());
11
+ *
12
+ * Nothing a request does throws out of these listeners or ends the process (S01, P092): what fetch
13
+ * can't take is 405 or 400; what fails on the app's side (a handler, a listener, an answer Node
14
+ * can't write) is 500, and `onError` hears it.
11
15
  */
12
16
  import type { IncomingMessage, Server, ServerResponse } from "node:http";
13
- import { createServer as createHttpServer, request as httpRequest } from "node:http";
17
+ import { createServer as createHttpServer, request as httpRequest, STATUS_CODES } from "node:http";
14
18
  import { request as httpsRequest } from "node:https";
15
19
  import type { LookupFunction } from "node:net";
16
20
  import type { Duplex } from "node:stream";
17
- import { Readable } from "node:stream";
18
21
  import type { ContentHost, HealthProbe } from "../server/host.ts";
22
+ import { withPeerAddress } from "../server/peer.ts";
19
23
  import { withoutPortholeCookies } from "../server/proxy.ts";
20
24
  import type { Access } from "../server/types.ts";
21
25
 
22
26
  type RequestListener = (request: IncomingMessage, response: ServerResponse) => void;
23
27
  type UpgradeListener = (request: IncomingMessage, socket: Duplex, head: Buffer) => void;
24
28
 
29
+ /**
30
+ * Hears what failed on the app's side while serving a request (its handler or listener threw or
31
+ * rejected, an answer Node can't write), once the client has its 500. Default: a process warning
32
+ * (`process.emitWarning`). Never the client's to read.
33
+ */
34
+ export type NodeErrorListener = (error: unknown, request: IncomingMessage) => void;
35
+
25
36
  export interface NodeHostOptions {
26
37
  /** The app's own request listener (Express, Hono's `getRequestListener`, a router). */
27
38
  readonly request: RequestListener;
@@ -34,6 +45,7 @@ export interface NodeHostOptions {
34
45
  socket: Duplex,
35
46
  head: Buffer,
36
47
  ) => void;
48
+ readonly onError?: NodeErrorListener;
37
49
  }
38
50
 
39
51
  export interface NodeHost {
@@ -41,9 +53,142 @@ export interface NodeHost {
41
53
  readonly upgrade: UpgradeListener;
42
54
  }
43
55
 
56
+ /** Tells the app what failed (`onError`, or a process warning); a report never fails a request. */
57
+ function report(onError: NodeErrorListener | undefined, error: unknown, request: IncomingMessage) {
58
+ try {
59
+ if (onError === undefined) {
60
+ process.emitWarning(error instanceof Error ? error : new Error(String(error)));
61
+ } else {
62
+ onError(error, request);
63
+ }
64
+ } catch {
65
+ // The report's own failure is not the request's.
66
+ }
67
+ }
68
+
69
+ /** The most of a body no one reads that is dropped before the connection closes (P092). */
70
+ const DROP_BYTES = 1_048_576;
71
+ /** How long an answered request's unread body is dropped before the connection closes (P092). */
72
+ const DROP_MS = 5_000;
73
+ const dropping = new WeakSet<IncomingMessage>();
74
+
75
+ /**
76
+ * Reads and drops what is left of a request's body no one will read, at most `DROP_BYTES`, then
77
+ * closes the connection (P092). A client still sending its body gets the answer this way: closed
78
+ * at once with the body unread, the connection is reset, and the answer with it.
79
+ */
80
+ function drop(request: IncomingMessage): void {
81
+ if (request.complete || dropping.has(request)) {
82
+ return;
83
+ }
84
+ dropping.add(request);
85
+ let dropped = 0;
86
+ const count = (chunk: Buffer) => {
87
+ dropped += chunk.byteLength;
88
+ if (dropped > DROP_BYTES) {
89
+ request.off("data", count);
90
+ request.socket.destroy();
91
+ }
92
+ };
93
+ request.on("data", count);
94
+ request.resume();
95
+ }
96
+
97
+ /**
98
+ * Once an answer is out, what its request's body still holds is dropped for at most `DROP_MS`
99
+ * (and `DROP_BYTES`), then the connection closes: never left waiting on a body no one reads, and
100
+ * a body dropped whole leaves the connection to go on (P092).
101
+ */
102
+ function dropAfter(response: ServerResponse): void {
103
+ response.once("finish", () => {
104
+ const request = (response.req as IncomingMessage | undefined) ?? null;
105
+ if (request === null || request.complete) {
106
+ return;
107
+ }
108
+ drop(request);
109
+ const socket = request.socket;
110
+ const timer = setTimeout(() => socket.destroy(), DROP_MS);
111
+ timer.unref();
112
+ const stop = () => clearTimeout(timer);
113
+ request.once("end", stop);
114
+ socket.once("close", stop);
115
+ });
116
+ }
117
+
118
+ /**
119
+ * A Node request's body as a stream, read only as it is pulled (a body no one reads is never
120
+ * taken: the app's listener gets it whole, P092). Cancelled, the rest is dropped (`drop`), not
121
+ * the connection: the answer still goes out.
122
+ */
123
+ function bodyOf(request: IncomingMessage): ReadableStream<Uint8Array> {
124
+ let listening = false;
125
+ let settled = false;
126
+ let stop = () => {};
127
+ return new ReadableStream<Uint8Array>(
128
+ {
129
+ pull(controller) {
130
+ if (settled) {
131
+ return;
132
+ }
133
+ if (!listening) {
134
+ listening = true;
135
+ const settle = () => {
136
+ settled = true;
137
+ stop();
138
+ };
139
+ const data = (chunk: Buffer) => {
140
+ if (!settled) {
141
+ controller.enqueue(new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength));
142
+ request.pause();
143
+ }
144
+ };
145
+ const end = () => {
146
+ if (!settled) {
147
+ settle();
148
+ controller.close();
149
+ }
150
+ };
151
+ const fail = () => {
152
+ if (!settled) {
153
+ settle();
154
+ controller.error(new Error("The request's body broke off"));
155
+ }
156
+ };
157
+ const close = () => {
158
+ if (!request.complete) {
159
+ fail();
160
+ }
161
+ };
162
+ request.on("data", data);
163
+ request.on("end", end);
164
+ request.on("error", fail);
165
+ request.on("close", close);
166
+ stop = () => {
167
+ request.off("data", data);
168
+ request.off("end", end);
169
+ request.off("error", fail);
170
+ request.off("close", close);
171
+ };
172
+ }
173
+ request.resume();
174
+ },
175
+ cancel() {
176
+ settled = true;
177
+ stop();
178
+ drop(request);
179
+ },
180
+ },
181
+ { highWaterMark: 0 },
182
+ );
183
+ }
184
+
44
185
  /**
45
186
  * The Node request as a fetch `Request`: an absolute-form target kept as it came (P056). `signal`
46
- * (`nodeHost` gives one, aborted when the client goes away) lets an upstream stop its work.
187
+ * (`nodeHost` gives one, aborted when the client goes away) lets an upstream stop its work. The
188
+ * body is read only as it is pulled; cancelled, the rest is dropped (bounded), not the connection.
189
+ * The socket's peer goes with it, for the issue endpoint's rate limit (P092).
190
+ * Throws where fetch can't take the request: a method it can't carry (`TRACE`), a Host or a
191
+ * target that is no URL. `nodeListener`, `nodeHost` and `nodeServer` answer those 405 and 400.
47
192
  */
48
193
  export function toRequest(
49
194
  request: IncomingMessage,
@@ -61,24 +206,21 @@ export function toRequest(
61
206
  ? `${scheme}://${request.headers.host ?? "localhost"}${target}`
62
207
  : target;
63
208
  const method = request.method ?? "GET";
64
- const body =
65
- method === "GET" || method === "HEAD" ? null : (Readable.toWeb(request) as ReadableStream);
66
- return new Request(url, {
67
- method,
68
- headers,
69
- body,
70
- duplex: "half",
71
- ...(signal === undefined ? {} : { signal }),
72
- } as RequestInit);
209
+ const body = method === "GET" || method === "HEAD" ? null : bodyOf(request);
210
+ return withPeerAddress(
211
+ new Request(url, {
212
+ method,
213
+ headers,
214
+ body,
215
+ duplex: "half",
216
+ ...(signal === undefined ? {} : { signal }),
217
+ } as RequestInit),
218
+ request.socket.remoteAddress,
219
+ );
73
220
  }
74
221
 
75
- /**
76
- * Writes a fetch `Response` to a Node response, cookies one header each (P070): it waits for the
77
- * socket to drain before reading on (a slow client never makes it buffer the body), cancels the
78
- * body when the client goes away (an event stream ends with the page that asked for it), and on
79
- * an error mid-body destroys the response rather than end it looking complete.
80
- */
81
- export async function sendResponse(response: ServerResponse, answer: Response): Promise<void> {
222
+ /** A fetch Response's head for Node, cookies one header each (P070). Throws for no Response. */
223
+ function headOf(answer: Response): Record<string, string | string[]> {
82
224
  const headers: Record<string, string | string[]> = {};
83
225
  for (const [name, value] of answer.headers) {
84
226
  if (name !== "set-cookie") {
@@ -89,8 +231,53 @@ export async function sendResponse(response: ServerResponse, answer: Response):
89
231
  if (cookies.length > 0) {
90
232
  headers["set-cookie"] = cookies;
91
233
  }
92
- response.writeHead(answer.status, headers);
93
- if (answer.body === null) {
234
+ if (answer.bodyUsed || answer.body?.locked === true) {
235
+ throw new TypeError("The answer's body is already being read");
236
+ }
237
+ return headers;
238
+ }
239
+
240
+ /**
241
+ * Writes a fetch `Response` to a Node response, cookies one header each (P070): it waits for the
242
+ * socket to drain before reading on (a slow client never makes it buffer the body), cancels the
243
+ * body when the client goes away, before the answer or during it (an event stream ends with the
244
+ * page that asked for it), and on an error mid-body destroys the response rather than end it
245
+ * looking complete. A HEAD gets the head and its body is cancelled. Never rejects (P092): an
246
+ * answer it can't write (no Response, a body already read, a header value fetch takes and Node
247
+ * doesn't) is a 500, and `onError` hears why. Once the answer is out, a request body no one read
248
+ * is dropped, bounded, before the connection closes.
249
+ */
250
+ export async function sendResponse(
251
+ response: ServerResponse,
252
+ answer: Response,
253
+ onError?: (error: unknown) => void,
254
+ ): Promise<void> {
255
+ const cancel = () => {
256
+ try {
257
+ answer.body?.cancel().catch(() => undefined);
258
+ } catch {
259
+ // No Response, or a body already taken: nothing of it to stop.
260
+ }
261
+ };
262
+ // The client went away before the answer: nothing to write, and the body's source is told.
263
+ if (response.destroyed) {
264
+ cancel();
265
+ return;
266
+ }
267
+ try {
268
+ const headers = headOf(answer);
269
+ dropAfter(response);
270
+ response.writeHead(answer.status, headers);
271
+ } catch (error) {
272
+ cancel();
273
+ onError?.(error);
274
+ answerPlain(response, 500, "The answer couldn't be written.");
275
+ return;
276
+ }
277
+ const request = (response.req as IncomingMessage | undefined) ?? null;
278
+ if (answer.body === null || request?.method === "HEAD") {
279
+ // Node writes no body for HEAD: the head goes out with the end, and the body is never read.
280
+ cancel();
94
281
  response.end();
95
282
  return;
96
283
  }
@@ -109,10 +296,10 @@ export async function sendResponse(response: ServerResponse, answer: Response):
109
296
  try {
110
297
  for (;;) {
111
298
  const { done, value } = await reader.read();
112
- if (done || gone) {
299
+ if (done || gone || response.destroyed) {
113
300
  break;
114
301
  }
115
- if (!response.write(value)) {
302
+ if (!response.write(value) && !response.destroyed) {
116
303
  await new Promise<void>((resolve) => {
117
304
  const on = () => {
118
305
  response.off("drain", on);
@@ -130,11 +317,159 @@ export async function sendResponse(response: ServerResponse, answer: Response):
130
317
  response.destroy(error instanceof Error ? error : new Error(String(error)));
131
318
  return;
132
319
  }
133
- if (!gone) {
320
+ if (response.destroyed) {
321
+ leave();
322
+ } else if (!gone) {
134
323
  response.end();
135
324
  }
136
325
  }
137
326
 
327
+ /** The methods a fetch `Request` can't carry (the Fetch standard's forbidden methods). */
328
+ const FORBIDDEN_METHODS = new Set(["CONNECT", "TRACE", "TRACK"]);
329
+
330
+ /**
331
+ * `toRequest`, or the status for a request fetch can't take (S01, P092): 405 for a method it
332
+ * can't carry, 400 for anything else (a Host or a target that is no URL). Never throws: the
333
+ * conversion runs in a listener, where a throw would end the process.
334
+ */
335
+ function convert(
336
+ request: IncomingMessage,
337
+ scheme: "https" | "http",
338
+ signal?: AbortSignal,
339
+ ): Request | 400 | 405 {
340
+ try {
341
+ return toRequest(request, scheme, signal);
342
+ } catch {
343
+ return FORBIDDEN_METHODS.has((request.method ?? "").toUpperCase()) ? 405 : 400;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * A plain answer of the adapter's own. A response already started is cut off, never made to look
349
+ * whole; one already ended is left be. Never throws: it answers from the listeners' catches.
350
+ */
351
+ function answerPlain(response: ServerResponse, status: number, text: string): void {
352
+ try {
353
+ if (response.writableEnded || response.destroyed) {
354
+ return;
355
+ }
356
+ if (response.headersSent) {
357
+ response.destroy();
358
+ return;
359
+ }
360
+ dropAfter(response);
361
+ // The reason given: a head Node refused to write leaves its own behind.
362
+ response.writeHead(status, STATUS_CODES[status], {
363
+ "content-type": "text/plain; charset=utf-8",
364
+ });
365
+ response.end(text);
366
+ } catch {
367
+ response.destroy();
368
+ }
369
+ }
370
+
371
+ const REFUSED: Record<400 | 405, string> = {
372
+ 400: "Bad request.",
373
+ 405: "That method isn't served here.",
374
+ };
375
+
376
+ /** A request's signal: aborted when the client goes away before the answer is out (P070). */
377
+ function goneSignal(response: ServerResponse): AbortSignal {
378
+ const gone = new AbortController();
379
+ response.once("close", () => {
380
+ if (!response.writableFinished) {
381
+ gone.abort();
382
+ }
383
+ });
384
+ return gone.signal;
385
+ }
386
+
387
+ const isThenable = (value: unknown): value is PromiseLike<unknown> =>
388
+ (typeof value === "object" || typeof value === "function") &&
389
+ value !== null &&
390
+ typeof (value as { then?: unknown }).then === "function";
391
+
392
+ /**
393
+ * Calls one of the app's own listeners: what it throws, or an async one's rejection, is reported
394
+ * and ends in `failed` (a 500, a closed socket), never out of the listener (S01, P092).
395
+ */
396
+ function callApp(
397
+ call: () => unknown,
398
+ failed: () => void,
399
+ onError: NodeErrorListener | undefined,
400
+ request: IncomingMessage,
401
+ ): void {
402
+ const fail = (error: unknown) => {
403
+ report(onError, error, request);
404
+ failed();
405
+ };
406
+ try {
407
+ const returned = call();
408
+ if (isThenable(returned)) {
409
+ returned.then(undefined, fail);
410
+ }
411
+ } catch (error) {
412
+ fail(error);
413
+ }
414
+ }
415
+
416
+ /**
417
+ * Writes what a fetch-style handler answers (null: `otherwise`, the app's own listener). Whatever
418
+ * fails, the handler (thrown or rejected), `otherwise`, or the writing (a header fetch takes and
419
+ * Node doesn't), answers 500, or cuts off a response already started, and is reported: nothing
420
+ * escapes (S01, P092).
421
+ */
422
+ function serve(
423
+ request: IncomingMessage,
424
+ response: ServerResponse,
425
+ handle: () => Response | null | Promise<Response | null>,
426
+ failed: string,
427
+ onError: NodeErrorListener | undefined,
428
+ otherwise?: () => void,
429
+ ): void {
430
+ const fail = (error: unknown) => {
431
+ report(onError, error, request);
432
+ answerPlain(response, 500, failed);
433
+ };
434
+ new Promise<Response | null>((resolve) => resolve(handle()))
435
+ .then((answer) => {
436
+ if (answer === null && otherwise !== undefined) {
437
+ otherwise();
438
+ return undefined;
439
+ }
440
+ // Anything that isn't a Response (an app's null or undefined) fails in it, as a 500.
441
+ return sendResponse(response, answer as Response, (error) => report(onError, error, request));
442
+ })
443
+ .catch(fail);
444
+ }
445
+
446
+ export interface NodeListenerOptions {
447
+ /** The requests' URLs' scheme (default `http`; `https` behind a TLS edge). */
448
+ readonly scheme?: "https" | "http";
449
+ readonly onError?: NodeErrorListener;
450
+ }
451
+
452
+ /**
453
+ * A fetch-style handler (Hono's `app.fetch`, the app's own) as a Node request listener: what
454
+ * `toRequest` can't convert is 405 or 400, what the handler throws or the answer's writing fails
455
+ * is 500 (`onError` hears it); nothing it does ends the process (S01, P092). The request's
456
+ * `signal` aborts when the client goes away before the answer is out.
457
+ */
458
+ export function nodeListener(
459
+ app: (request: Request) => Response | Promise<Response>,
460
+ options: NodeListenerOptions = {},
461
+ ): RequestListener {
462
+ const scheme = options.scheme ?? "http";
463
+ return (incoming, response) => {
464
+ const asked = convert(incoming, scheme, goneSignal(response));
465
+ if (typeof asked === "number") {
466
+ answerPlain(response, asked, REFUSED[asked]);
467
+ return;
468
+ }
469
+ serve(incoming, response, () => app(asked), "Something went wrong.", options.onError);
470
+ };
471
+ }
472
+
138
473
  /** Whether a Node request's Host (or absolute-form target) is under the content domain. */
139
474
  function forContent<V>(content: ContentHost<V>, request: IncomingMessage): boolean {
140
475
  const domain = content.domain;
@@ -151,87 +486,139 @@ function forContent<V>(content: ContentHost<V>, request: IncomingMessage): boole
151
486
  return domain.isContentHost(host) || (target !== "" && domain.isContentHost(target));
152
487
  }
153
488
 
154
- /** Refuses a WebSocket on the content domain with a plain 404, and closes it. */
155
- function refuseSocket(socket: Duplex): void {
156
- socket.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n");
489
+ /** Refuses a WebSocket with a plain status (404: on the content domain), and closes it. */
490
+ function refuseSocket(socket: Duplex, status = 404): void {
491
+ socket.end(
492
+ `HTTP/1.1 ${status} ${STATUS_CODES[status] ?? ""}\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`,
493
+ );
494
+ }
495
+
496
+ const guarded = new WeakSet<Duplex>();
497
+
498
+ /**
499
+ * Node takes its own error listener off an upgrade's socket before the `upgrade` event: a reset
500
+ * there would be an unhandled `error` and end the process (P092). The socket is closed instead.
501
+ */
502
+ function guardSocket(socket: Duplex): void {
503
+ if (!guarded.has(socket)) {
504
+ guarded.add(socket);
505
+ socket.on("error", () => socket.destroy());
506
+ }
157
507
  }
158
508
 
159
509
  export function nodeHost<V>(content: ContentHost<V>, app: NodeHostOptions): NodeHost {
160
510
  const scheme = () => content.domain?.scheme ?? "http";
511
+ const toApp = (request: IncomingMessage, response: ServerResponse) =>
512
+ callApp(
513
+ () => app.request(request, response),
514
+ () => answerPlain(response, 500, "Something went wrong."),
515
+ app.onError,
516
+ request,
517
+ );
518
+ const toAppSocket = (request: IncomingMessage, socket: Duplex, head: Buffer) => {
519
+ const upgrade = app.upgrade;
520
+ if (upgrade === undefined) {
521
+ refuseSocket(socket);
522
+ return;
523
+ }
524
+ callApp(
525
+ () => upgrade(request, socket, head),
526
+ () => socket.destroy(),
527
+ app.onError,
528
+ request,
529
+ );
530
+ };
531
+ // Nothing in either listener throws out of it, the app's own listeners included (S01, P092):
532
+ // a request ends in an answer, a socket in a refusal or closed.
161
533
  return {
162
534
  request(request, response) {
163
- if (!forContent(content, request)) {
164
- app.request(request, response);
165
- return;
166
- }
167
- // Aborted when the client goes away first, so an upstream (a proxied app's event stream)
168
- // stops with it.
169
- const gone = new AbortController();
170
- response.once("close", () => {
171
- if (!response.writableFinished) {
172
- gone.abort();
535
+ try {
536
+ if (!forContent(content, request)) {
537
+ toApp(request, response);
538
+ return;
173
539
  }
174
- });
175
- content.fetch(toRequest(request, scheme(), gone.signal)).then(
176
- (answer) => {
177
- if (answer === null) {
178
- // A label the app routes itself.
179
- app.request(request, response);
180
- return;
181
- }
182
- return sendResponse(response, answer);
183
- },
184
- () => {
185
- if (response.headersSent) {
186
- response.destroy();
187
- return;
188
- }
189
- response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
190
- response.end("Content couldn't be served.");
191
- },
192
- );
540
+ // Aborted when the client goes away first, so an upstream (a proxied app's event stream)
541
+ // stops with it.
542
+ const asked = convert(request, scheme(), goneSignal(response));
543
+ if (typeof asked === "number") {
544
+ answerPlain(response, asked, REFUSED[asked]);
545
+ return;
546
+ }
547
+ // A label the app routes itself: its request untouched, body and all (P092).
548
+ if (!content.owns(asked)) {
549
+ toApp(request, response);
550
+ return;
551
+ }
552
+ serve(
553
+ request,
554
+ response,
555
+ () => content.fetch(asked),
556
+ "Content couldn't be served.",
557
+ app.onError,
558
+ () => toApp(request, response),
559
+ );
560
+ } catch (error) {
561
+ report(app.onError, error, request);
562
+ answerPlain(response, 500, "Something went wrong.");
563
+ }
193
564
  },
194
565
  upgrade(request, socket, head) {
195
- if (!forContent(content, request)) {
196
- if (app.upgrade === undefined) {
197
- refuseSocket(socket);
198
- } else {
199
- app.upgrade(request, socket, head);
566
+ guardSocket(socket);
567
+ try {
568
+ if (!forContent(content, request)) {
569
+ toAppSocket(request, socket, head);
570
+ return;
200
571
  }
201
- return;
202
- }
203
- const asked = toRequest(request, scheme());
204
- // A reserved label's socket is the app's.
205
- if (!content.owns(asked)) {
206
- if (app.upgrade === undefined) {
572
+ const asked = convert(request, scheme());
573
+ if (typeof asked === "number") {
574
+ refuseSocket(socket, asked);
575
+ return;
576
+ }
577
+ // A reserved label's socket is the app's.
578
+ if (!content.owns(asked)) {
579
+ toAppSocket(request, socket, head);
580
+ return;
581
+ }
582
+ const appSocket = app.appSocket;
583
+ if (appSocket === undefined) {
207
584
  refuseSocket(socket);
208
- } else {
209
- app.upgrade(request, socket, head);
585
+ return;
210
586
  }
211
- return;
212
- }
213
- const appSocket = app.appSocket;
214
- if (appSocket === undefined) {
215
- refuseSocket(socket);
216
- return;
217
- }
218
- content.access(asked).then(
219
- (access) => {
220
- if (access === null) {
221
- refuseSocket(socket);
222
- } else {
223
- // The app's socket never sees Porthole's own cookies, as its HTTP requests don't (P072).
587
+ const settled = content.access(asked).then(
588
+ (access) => {
589
+ if (access === null) {
590
+ refuseSocket(socket);
591
+ return;
592
+ }
593
+ // The app's socket never sees Porthole's own cookies, as its HTTP requests don't
594
+ // (P072).
224
595
  const cookie = withoutPortholeCookies(request.headers.cookie);
225
596
  if (cookie === null) {
226
597
  delete request.headers.cookie;
227
598
  } else {
228
599
  request.headers.cookie = cookie;
229
600
  }
230
- appSocket(access, request, socket, head);
231
- }
232
- },
233
- () => refuseSocket(socket),
234
- );
601
+ callApp(
602
+ () => appSocket(access, request, socket, head),
603
+ () => socket.destroy(),
604
+ app.onError,
605
+ request,
606
+ );
607
+ },
608
+ (error: unknown) => {
609
+ report(app.onError, error, request);
610
+ refuseSocket(socket);
611
+ },
612
+ );
613
+ // Neither branch above throws (callApp catches the app's); should one, the socket closes.
614
+ settled.catch((error: unknown) => {
615
+ report(app.onError, error, request);
616
+ socket.destroy();
617
+ });
618
+ } catch (error) {
619
+ report(app.onError, error, request);
620
+ socket.destroy();
621
+ }
235
622
  },
236
623
  };
237
624
  }
@@ -311,6 +698,7 @@ export interface NodeServerOptions {
311
698
  readonly appSocket?: NodeHostOptions["appSocket"];
312
699
  /** Whether the app's own requests came over https (behind a TLS edge): their URL's scheme. */
313
700
  readonly scheme?: "https" | "http";
701
+ readonly onError?: NodeErrorListener;
314
702
  }
315
703
 
316
704
  /**
@@ -321,24 +709,12 @@ export interface NodeServerOptions {
321
709
  */
322
710
  export function nodeServer(options: NodeServerOptions): Server {
323
711
  const scheme = options.scheme ?? "http";
324
- const fromFetch = options.app;
712
+ const onError = options.onError;
325
713
  const request: RequestListener | undefined =
326
714
  options.request ??
327
- (fromFetch === undefined
715
+ (options.app === undefined
328
716
  ? undefined
329
- : (incoming, response) => {
330
- Promise.resolve(fromFetch(toRequest(incoming, scheme))).then(
331
- (answer) => sendResponse(response, answer),
332
- () => {
333
- if (response.headersSent) {
334
- response.destroy();
335
- return;
336
- }
337
- response.writeHead(500, { "content-type": "text/plain; charset=utf-8" });
338
- response.end("Something went wrong.");
339
- },
340
- );
341
- });
717
+ : nodeListener(options.app, { scheme, ...(onError === undefined ? {} : { onError }) }));
342
718
  if (request === undefined) {
343
719
  throw new TypeError("nodeServer needs the app: app (fetch-style) or request (a Node listener)");
344
720
  }
@@ -358,6 +734,7 @@ export function nodeServer(options: NodeServerOptions): Server {
358
734
  request,
359
735
  ...(options.upgrade === undefined ? {} : { upgrade: options.upgrade }),
360
736
  ...(options.appSocket === undefined ? {} : { appSocket: options.appSocket }),
737
+ ...(onError === undefined ? {} : { onError }),
361
738
  });
362
739
  adapters.set(host, adapter);
363
740
  }
@@ -367,23 +744,37 @@ export function nodeServer(options: NodeServerOptions): Server {
367
744
  }
368
745
  return adapter;
369
746
  };
747
+ // The host function, the app's listeners: nothing throws out of the server's events (S01).
370
748
  const server = createHttpServer((incoming, response) => {
371
- const adapter = current();
372
- if (adapter === null) {
373
- request(incoming, response);
374
- } else {
375
- adapter.request(incoming, response);
376
- }
749
+ callApp(
750
+ () => {
751
+ const adapter = current();
752
+ return adapter === null ? request(incoming, response) : adapter.request(incoming, response);
753
+ },
754
+ () => answerPlain(response, 500, "Something went wrong."),
755
+ onError,
756
+ incoming,
757
+ );
377
758
  });
378
759
  server.on("upgrade", (incoming: IncomingMessage, socket: Duplex, head: Buffer) => {
379
- const adapter = current();
380
- if (adapter !== null) {
381
- adapter.upgrade(incoming, socket, head);
382
- } else if (options.upgrade !== undefined) {
383
- options.upgrade(incoming, socket, head);
384
- } else {
385
- refuseSocket(socket);
386
- }
760
+ guardSocket(socket);
761
+ callApp(
762
+ () => {
763
+ const adapter = current();
764
+ if (adapter !== null) {
765
+ adapter.upgrade(incoming, socket, head);
766
+ return undefined;
767
+ }
768
+ if (options.upgrade === undefined) {
769
+ refuseSocket(socket);
770
+ return undefined;
771
+ }
772
+ return options.upgrade(incoming, socket, head);
773
+ },
774
+ () => socket.destroy(),
775
+ onError,
776
+ incoming,
777
+ );
387
778
  });
388
779
  server.on("listening", () => {
389
780
  listening = true;