ccdeck 3.82.4 → 4.0.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 (145) hide show
  1. package/LICENSING.md +42 -4
  2. package/README.md +183 -72
  3. package/THIRD_PARTY_NOTICES.md +243 -17
  4. package/bin/cli/tui.js +58 -4
  5. package/bin/deck.js +27 -1
  6. package/dist/web/assets/AccountBridge-fp-fsMx-.js +1 -0
  7. package/dist/web/assets/AccountSection-Cu-96Q00.js +1 -0
  8. package/dist/web/assets/BrowserWatchModal-CvUx07C6.js +1 -0
  9. package/dist/web/assets/FeedbackConversations-BgVk0nkA.js +1 -0
  10. package/dist/web/assets/IntegrationModal-CEj5oJg4.js +7 -0
  11. package/dist/web/assets/IntegrationSkeleton-DD7YiFgd.js +1 -0
  12. package/dist/web/assets/RadioPanel-BhnzWRCT.js +1 -0
  13. package/dist/web/assets/StageShell-DmJu3dU1.js +4 -0
  14. package/dist/web/assets/TrafficRadar-C8-ieIw5.js +8 -0
  15. package/dist/web/assets/UsageHistoryModal-BThv9Kja.js +1 -0
  16. package/dist/web/assets/addon-unicode-graphemes-DW3WJwyh.js +18 -0
  17. package/dist/web/assets/addon-web-links-BWjmmSgS.js +12 -0
  18. package/dist/web/assets/addon-webgl-CLK4R-_u.js +75 -0
  19. package/dist/web/assets/app-DtosBis5.css +1 -0
  20. package/dist/web/assets/app-ZMmmEHxF.js +361 -0
  21. package/dist/web/assets/{index-B-l-VxLm.js → index-zSxC5ueJ.js} +1 -1
  22. package/dist/web/assets/inspector-status-pane-BgQG0bQi.js +1 -0
  23. package/dist/web/assets/screens-DD0uCtat.js +12 -0
  24. package/dist/web/assets/screens-DUniTTbC.css +1 -0
  25. package/dist/web/assets/stage-board-J2rKA9Pg.js +2 -0
  26. package/dist/web/assets/use-account-DvFObI4M.js +1 -0
  27. package/dist/web/assets/xterm-4jYizCpg.js +27 -0
  28. package/dist/web/assets/xterm-sheet-6GBZ9nXN.css +32 -0
  29. package/dist/web/index.html +16 -6
  30. package/package.json +13 -1
  31. package/release-notes.json +69 -1
  32. package/src/server/account-client.mjs +196 -0
  33. package/src/server/account-connect.mjs +238 -0
  34. package/src/server/account-flag.mjs +106 -0
  35. package/src/server/account-projects.mjs +1 -1
  36. package/src/server/account-service.mjs +532 -0
  37. package/src/server/account-status.mjs +293 -0
  38. package/src/server/account-store.mjs +137 -0
  39. package/src/server/account-sync.mjs +473 -0
  40. package/src/server/account-token-store.mjs +216 -0
  41. package/src/server/account-ui-fields.mjs +126 -0
  42. package/src/server/account-watch.mjs +1 -1
  43. package/src/server/browser-watch-log.mjs +1 -1
  44. package/src/server/browser-watch-store.mjs +1 -1
  45. package/src/server/ccdeck-account-routes.mjs +252 -0
  46. package/src/server/ccusage-install.mjs +2 -2
  47. package/src/server/ccusage-registry.mjs +4 -4
  48. package/src/server/ccusage-session.mjs +11 -0
  49. package/src/server/claude-accounts.mjs +1 -1
  50. package/src/server/claude-recovery.mjs +9 -4
  51. package/src/server/claude-settings-catalog.mjs +6 -6
  52. package/src/server/claude-settings.mjs +1 -1
  53. package/src/server/codex-auto.mjs +1 -1
  54. package/src/server/codex-cost-usage.mjs +7 -2
  55. package/src/server/codex-live-checkpoint.mjs +24 -9
  56. package/src/server/codex-live-engine.mjs +14 -4
  57. package/src/server/codex-live-handoff.mjs +53 -9
  58. package/src/server/codex-names.mjs +49 -0
  59. package/src/server/codex-translate.mjs +1 -1
  60. package/src/server/codex-ultrafast.d.mts +3 -0
  61. package/src/server/codex-ultrafast.mjs +5 -0
  62. package/src/server/codex-watch.mjs +25 -0
  63. package/src/server/command-panel-engine.mjs +300 -0
  64. package/src/server/command-panel-platform.mjs +99 -0
  65. package/src/server/cswap-auto-choice.mjs +1 -1
  66. package/src/server/cswap-auto-loop.mjs +1 -1
  67. package/src/server/cswap-install.mjs +21 -40
  68. package/src/server/deck-home.mjs +6 -0
  69. package/src/server/deck-prefs.mjs +53 -1
  70. package/src/server/detach.mjs +1 -1
  71. package/src/server/engine-download.mjs +277 -0
  72. package/src/server/engine-install.mjs +378 -0
  73. package/src/server/engine-package.mjs +267 -0
  74. package/src/server/event-log.mjs +7 -1
  75. package/src/server/event-pipeline.mjs +29 -1
  76. package/src/server/ghostty-handoff.mjs +81 -0
  77. package/src/server/index.mjs +143 -5
  78. package/src/server/installer.mjs +4 -1
  79. package/src/server/integrations/jira-write-guard.mjs +14 -208
  80. package/src/server/integrations/store.mjs +37 -19
  81. package/src/server/integrations/write-guard.mjs +223 -0
  82. package/src/server/intel-cpu-temperature.mjs +26 -0
  83. package/src/server/lifecycle.mjs +69 -6
  84. package/src/server/log-replay.mjs +4 -0
  85. package/src/server/login-service.mjs +7 -1
  86. package/src/server/macmon.mjs +1 -1
  87. package/src/server/npm-latest.mjs +1 -1
  88. package/src/server/org-telemetry.mjs +1 -1
  89. package/src/server/output-watch.mjs +4 -1
  90. package/src/server/panel-provenance.mjs +390 -0
  91. package/src/server/pinned-build.mjs +14 -0
  92. package/src/server/prefs-refusal.mjs +8 -1
  93. package/src/server/prefs-routes.mjs +60 -11
  94. package/src/server/pro-engine-client.mjs +339 -0
  95. package/src/server/pro-engine-install.mjs +294 -0
  96. package/src/server/pro-engine-terminal.mjs +308 -0
  97. package/src/server/project-discovery.mjs +139 -0
  98. package/src/server/provider-session-name.mjs +58 -0
  99. package/src/server/quota-closes.mjs +1 -1
  100. package/src/server/quota-history.mjs +1 -1
  101. package/src/server/reports.mjs +86 -21
  102. package/src/server/request-gates.mjs +34 -5
  103. package/src/server/restart-note.mjs +1 -1
  104. package/src/server/seed-boundary.mjs +489 -0
  105. package/src/server/session-counts.mjs +244 -0
  106. package/src/server/session-deck-names.mjs +143 -0
  107. package/src/server/session-enrichment.mjs +43 -6
  108. package/src/server/session-name-route.mjs +73 -0
  109. package/src/server/session-summary.mjs +12 -1
  110. package/src/server/session-transcript-routes.mjs +167 -0
  111. package/src/server/swap-log.mjs +1 -1
  112. package/src/server/system-metrics.mjs +57 -0
  113. package/src/server/terminal-bridge.mjs +485 -0
  114. package/src/server/terminal-folder.mjs +61 -0
  115. package/src/server/terminal-js-routes.mjs +752 -0
  116. package/src/server/terminal-routes.mjs +553 -0
  117. package/src/server/terminal-sessions.mjs +759 -0
  118. package/src/server/terminal-socket.mjs +403 -0
  119. package/src/server/terminal-target.mjs +928 -0
  120. package/src/server/thermal-metrics.mjs +13 -9
  121. package/src/server/tmux-control.mjs +1319 -0
  122. package/src/server/tmux-download.mjs +220 -0
  123. package/src/server/tmux.mjs +542 -0
  124. package/src/server/token-redact.mjs +42 -3
  125. package/src/server/tool-audit-report.mjs +44 -6
  126. package/src/server/tool-audit-routes.mjs +12 -1
  127. package/src/server/tool-audit.mjs +42 -8
  128. package/src/server/traffic-radar-monitor.mjs +1 -1
  129. package/src/server/traffic-radar-permission.mjs +1 -1
  130. package/src/server/transcript-gate.mjs +1 -1
  131. package/src/server/transcript-scan.mjs +15 -7
  132. package/src/server/transcript-turns.mjs +154 -0
  133. package/src/server/tui-network.mjs +1 -0
  134. package/src/server/tui-view.mjs +28 -0
  135. package/src/server/utf8-carry.mjs +159 -0
  136. package/src/server/uv-bootstrap.mjs +2 -2
  137. package/src/server/windows-acl.mjs +158 -0
  138. package/src/server/ws-frames.mjs +690 -0
  139. package/dist/web/assets/BrowserWatchModal-CWVooKxD.js +0 -1
  140. package/dist/web/assets/IntegrationModal-DLX43RIK.js +0 -7
  141. package/dist/web/assets/RadioPanel-Cj6PjrvQ.js +0 -1
  142. package/dist/web/assets/TrafficRadar-Bq1YcuHB.js +0 -8
  143. package/dist/web/assets/UsageHistoryModal-CMSCca5_.js +0 -1
  144. package/dist/web/assets/app-BHxsMz3-.js +0 -358
  145. package/dist/web/assets/app-CbXmr9rC.css +0 -1
@@ -0,0 +1,690 @@
1
+ // WebSocket (RFC 6455) from the server's side: the opening handshake, the frame
2
+ // codec, and the life of one connection — as much of the protocol as the
3
+ // terminal panel needs and nothing beyond it.
4
+ //
5
+ // The terminal panel streams a pane's bytes to the page and the keys typed
6
+ // there back again. That traffic gets a socket of its own rather than riding
7
+ // the event stream the deck already has, for three reasons: concurrent POSTs
8
+ // can land out of order, which turns fast typing into transposed letters
9
+ // rather than into lag; the one SSE channel carries a resume window and
10
+ // backpressure accounting that a firehose of terminal output would disturb;
11
+ // and SSE is text, so every byte a TUI writes would be escaped on its way out.
12
+ // A WebSocket is ordered, binary, and touches nothing else.
13
+ //
14
+ // HAND-WRITTEN BECAUSE THE SERVER TAKES NO RUNTIME DEPENDENCIES. Everything
15
+ // here is node:crypto, node:buffer and node:http, and it must run on the
16
+ // Node 18 floor the packed tarball is booted on. The browser is the only
17
+ // client, so this speaks exactly what a browser speaks when nothing is
18
+ // negotiated: no extensions (every browser offers permessage-deflate, and it
19
+ // is declined by not answering it), no subprotocol, version 13 only.
20
+ //
21
+ // THE PARSER IS STRICT, AND A REFUSAL ENDS THE CONNECTION. Every frame read
22
+ // here came off the network before anybody was trusted, so anything the RFC
23
+ // says a client must not send — an unmasked frame, a reserved bit or opcode, a
24
+ // control frame that is long or fragmented, a close code that is never sent on
25
+ // the wire — is a protocol error (1002); a message over the cap is refused as
26
+ // its header arrives, before its payload is buffered (1009); a text message or
27
+ // close reason that is not UTF-8 is refused once it is whole (1007). The
28
+ // connection answers a refusal with a close frame carrying that code and stops
29
+ // reading, which is what "fail the WebSocket connection" means in RFC 6455 §7.
30
+ //
31
+ // NOTHING HERE THROWS OUT OF A SOCKET EVENT. An exception inside a socket's
32
+ // 'data' or 'close' event has nothing above it to catch it, so it would take
33
+ // the whole deck down with every other terminal and count towards the
34
+ // supervisor's crash ceiling. A message handler that throws ends its own
35
+ // connection (1011); an onClose that throws is swallowed.
36
+ import { createHash } from "node:crypto";
37
+ // A namespace import, not `{ isUtf8 }`: the named export arrived in Node 18.14,
38
+ // and on an older 18 a named import of a missing export fails the whole module
39
+ // at link time. Read off the namespace it is merely undefined, and the
40
+ // hand-written check below stands in.
41
+ import * as nodeBuffer from "node:buffer";
42
+ import { STATUS_CODES } from "node:http";
43
+
44
+ /** The GUID RFC 6455 §1.3 appends to the client's key before hashing it. */
45
+ const HANDSHAKE_GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
46
+
47
+ /** Opcodes (RFC 6455 §5.2). Every other value is reserved and refused. */
48
+ export const OP = Object.freeze({ CONTINUATION: 0x0, TEXT: 0x1, BINARY: 0x2, CLOSE: 0x8, PING: 0x9, PONG: 0xa });
49
+ const KNOWN_OPCODES = new Set(Object.values(OP));
50
+
51
+ /** The most one message may be unless the caller says otherwise. A terminal's
52
+ * input is keystrokes and the odd paste, so a mebibyte is far above anything
53
+ * legitimate and low enough that a page cannot make the deck hold much. */
54
+ export const DEFAULT_MAX_MESSAGE_BYTES = 1 << 20;
55
+
56
+ /** The most frames one message may arrive in. The byte cap alone does not
57
+ * bound what assembling a message costs: an empty fragment adds no bytes, and
58
+ * a one-byte fragment costs a buffer of its own, so a client could hold the
59
+ * deck's memory far past the cap a byte or none at a time. A browser sends a
60
+ * message in one frame; a thousand is room for any client that splits. */
61
+ export const MAX_FRAGMENTS = 1024;
62
+
63
+ /** How long a closing connection waits for the other side before the socket is
64
+ * destroyed. A browser echoes a close within a round trip; a peer that has not
65
+ * in two seconds is gone or not listening, and its socket is not worth more. */
66
+ export const CLOSE_TIMEOUT_MS = 2_000;
67
+
68
+ /** A control frame carries at most 125 bytes (§5.5), and a close frame spends
69
+ * two of them on its code — so a close reason is at most 123 bytes. */
70
+ const MAX_CONTROL_PAYLOAD = 125;
71
+ const MAX_CLOSE_REASON = MAX_CONTROL_PAYLOAD - 2;
72
+
73
+ const EMPTY = Buffer.alloc(0);
74
+
75
+ /**
76
+ * The Sec-WebSocket-Accept value for a client's Sec-WebSocket-Key: the key and
77
+ * the RFC's GUID, SHA-1'd and base64'd. It proves to the browser that this
78
+ * server read its handshake rather than replaying a cached response.
79
+ */
80
+ export function acceptKey(secKey) {
81
+ return createHash("sha1").update(`${secKey}${HANDSHAKE_GUID}`).digest("base64");
82
+ }
83
+
84
+ /**
85
+ * Whether an HTTP request is a WebSocket opening handshake this server can
86
+ * answer, read from its method, version and headers alone (Node lower-cases
87
+ * header names and trims their values).
88
+ *
89
+ * Answers `{ ok: true, key }` with the client's key, or `{ ok: false, status,
90
+ * reason }` with the HTTP status to refuse with. A version mismatch is 426 and
91
+ * also carries `headers` naming the one version spoken here, which §4.4 asks
92
+ * for so a client can retry with it. This checks the protocol only: the Host,
93
+ * Origin and ticket checks that decide WHO may connect are the caller's.
94
+ */
95
+ export function validateUpgrade(req) {
96
+ const headers = req?.headers ?? {};
97
+ if (req?.method !== "GET") return refusal(405, "a WebSocket handshake is a GET");
98
+ if (olderThanHttp11(req)) return refusal(400, "a WebSocket handshake needs HTTP/1.1");
99
+ if (headerText(headers.upgrade).toLowerCase() !== "websocket") return refusal(400, "not a WebSocket upgrade");
100
+ if (!headerTokens(headers.connection).includes("upgrade")) {
101
+ return refusal(400, "the Connection header does not ask to upgrade");
102
+ }
103
+ if (headerText(headers["sec-websocket-version"]) !== "13") {
104
+ return { ...refusal(426, "only WebSocket version 13 is spoken here"), headers: { "Sec-WebSocket-Version": "13" } };
105
+ }
106
+ const key = headerText(headers["sec-websocket-key"]);
107
+ if (!isHandshakeNonce(key)) return refusal(400, "the Sec-WebSocket-Key is not 16 bytes of base64");
108
+ return { ok: true, key };
109
+ }
110
+
111
+ function refusal(status, reason) {
112
+ return { ok: false, status, reason };
113
+ }
114
+
115
+ /** Only when the request says which version it is: Node always does, and a
116
+ * hand-built request in a test that leaves it out is not refused for that. */
117
+ function olderThanHttp11(req) {
118
+ const major = req?.httpVersionMajor;
119
+ const minor = req?.httpVersionMinor;
120
+ if (typeof major !== "number" || typeof minor !== "number") return false;
121
+ return major < 1 || (major === 1 && minor < 1);
122
+ }
123
+
124
+ function headerText(value) {
125
+ return String(value ?? "").trim();
126
+ }
127
+
128
+ /** A comma-separated header as lower-cased tokens. Firefox sends
129
+ * `Connection: keep-alive, Upgrade`, so a plain equality would refuse it. */
130
+ function headerTokens(value) {
131
+ return headerText(value).toLowerCase().split(",").map(token => token.trim());
132
+ }
133
+
134
+ /** The key must be base64 of exactly 16 bytes (§4.1). The pattern pins the
135
+ * shape; the round trip refuses the non-canonical spellings Buffer would
136
+ * otherwise decode leniently (stray bits in the last character). Two keys
137
+ * that Node joined with ", " fail both. */
138
+ function isHandshakeNonce(key) {
139
+ return /^[A-Za-z0-9+/]{22}==$/.test(key) && Buffer.from(key, "base64").toString("base64") === key;
140
+ }
141
+
142
+ /**
143
+ * The exact 101 response that completes the handshake for a client key: no
144
+ * extensions and no subprotocol, so a browser that offered either goes on
145
+ * without it, as §4.2.2 provides. Write it to the socket, then hand the socket
146
+ * to wsConnection.
147
+ */
148
+ export function upgradeResponse(key) {
149
+ return "HTTP/1.1 101 Switching Protocols\r\n"
150
+ + "Upgrade: websocket\r\n"
151
+ + "Connection: Upgrade\r\n"
152
+ + `Sec-WebSocket-Accept: ${acceptKey(key)}\r\n`
153
+ + "\r\n";
154
+ }
155
+
156
+ /**
157
+ * A plain HTTP refusal to write on an upgrade socket before destroying it —
158
+ * the only answer an upgrade request that will not be accepted gets, since no
159
+ * http.ServerResponse exists for it. `headers` is a refusal's own extra
160
+ * headers (validateUpgrade's 426 names the version). With none, a 404 is
161
+ * exactly `HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n`.
162
+ */
163
+ export function httpRefusal(status, headers = {}) {
164
+ const extra = Object.entries(headers).map(([name, value]) => `${name}: ${value}\r\n`).join("");
165
+ return `HTTP/1.1 ${status} ${STATUS_CODES[status] ?? "Error"}\r\nConnection: close\r\n${extra}\r\n`;
166
+ }
167
+
168
+ /**
169
+ * One frame as the server writes it: never masked (§5.1 forbids a server to
170
+ * mask), with the payload length in 7, 16 or 64 bits — always the shortest
171
+ * that holds it, as §5.2 requires. `payload` is a Buffer, any typed-array
172
+ * view, or a string (written as UTF-8). Throws on an unknown opcode or a
173
+ * control frame that is fragmented or over 125 bytes: those are bugs in the
174
+ * caller, and a peer would fail the connection over them anyway.
175
+ */
176
+ export function encodeFrame(opcode, payload = EMPTY, { fin = true } = {}) {
177
+ if (!KNOWN_OPCODES.has(opcode)) throw new RangeError(`unknown WebSocket opcode ${opcode}`);
178
+ const body = asBuffer(payload);
179
+ if (opcode >= 0x8 && !fin) throw new RangeError("a control frame cannot be fragmented");
180
+ if (opcode >= 0x8 && body.length > MAX_CONTROL_PAYLOAD) {
181
+ throw new RangeError(`a control frame carries at most ${MAX_CONTROL_PAYLOAD} bytes`);
182
+ }
183
+ const length = body.length;
184
+ const headerBytes = length < 126 ? 2 : length < 0x10000 ? 4 : 10;
185
+ const frame = Buffer.allocUnsafe(headerBytes + length);
186
+ frame[0] = (fin ? 0x80 : 0) | opcode;
187
+ if (length < 126) {
188
+ frame[1] = length;
189
+ } else if (length < 0x10000) {
190
+ frame[1] = 126;
191
+ frame.writeUInt16BE(length, 2);
192
+ } else {
193
+ // Two 32-bit halves rather than writeBigUInt64BE, so no BigInt is made per
194
+ // frame; `>>> 0` keeps the low 32 bits of any length a Buffer can have.
195
+ frame[1] = 127;
196
+ frame.writeUInt32BE(Math.floor(length / 0x100000000), 2);
197
+ frame.writeUInt32BE(length >>> 0, 6);
198
+ }
199
+ body.copy(frame, headerBytes);
200
+ return frame;
201
+ }
202
+
203
+ function asBuffer(payload) {
204
+ if (payload == null) return EMPTY;
205
+ if (typeof payload === "string") return Buffer.from(payload, "utf8");
206
+ if (Buffer.isBuffer(payload)) return payload;
207
+ if (ArrayBuffer.isView(payload)) return Buffer.from(payload.buffer, payload.byteOffset, payload.byteLength);
208
+ if (payload instanceof ArrayBuffer) return Buffer.from(payload);
209
+ throw new TypeError("a frame's payload is a Buffer, a typed array or a string");
210
+ }
211
+
212
+ /**
213
+ * Whether a close code may appear in a close frame (§7.4): the defined codes
214
+ * other than 1004 (reserved) and 1005/1006 (which only ever describe a close
215
+ * locally), the IANA-registered 1012–1014, and the 3000–4999 ranges left to
216
+ * libraries and applications.
217
+ */
218
+ function isSendableCloseCode(code) {
219
+ return Number.isInteger(code)
220
+ && ((code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006)
221
+ || (code >= 3000 && code <= 4999));
222
+ }
223
+
224
+ /**
225
+ * Whether bytes are well-formed UTF-8 in the strict sense RFC 3629 gives it:
226
+ * no overlong forms, no UTF-16 surrogates, nothing past U+10FFFF. This is the
227
+ * stand-in for Node's native `buffer.isUtf8` on a Node 18 older than 18.14,
228
+ * and is exported so a test holds the two to the same answers.
229
+ */
230
+ export function isValidUtf8(bytes) {
231
+ const length = bytes.length;
232
+ let i = 0;
233
+ while (i < length) {
234
+ const lead = bytes[i];
235
+ if (lead < 0x80) { i += 1; continue; }
236
+ if (lead >= 0xc2 && lead <= 0xdf) {
237
+ if (i + 1 >= length || !isContinuation(bytes[i + 1])) return false;
238
+ i += 2;
239
+ continue;
240
+ }
241
+ if (lead >= 0xe0 && lead <= 0xef) {
242
+ if (i + 2 >= length) return false;
243
+ const second = bytes[i + 1];
244
+ if (!isContinuation(second) || !isContinuation(bytes[i + 2])) return false;
245
+ if (lead === 0xe0 && second < 0xa0) return false; // overlong
246
+ if (lead === 0xed && second > 0x9f) return false; // a UTF-16 surrogate
247
+ i += 3;
248
+ continue;
249
+ }
250
+ if (lead >= 0xf0 && lead <= 0xf4) {
251
+ if (i + 3 >= length) return false;
252
+ const second = bytes[i + 1];
253
+ if (!isContinuation(second) || !isContinuation(bytes[i + 2]) || !isContinuation(bytes[i + 3])) return false;
254
+ if (lead === 0xf0 && second < 0x90) return false; // overlong
255
+ if (lead === 0xf4 && second > 0x8f) return false; // past U+10FFFF
256
+ i += 4;
257
+ continue;
258
+ }
259
+ return false;
260
+ }
261
+ return true;
262
+ }
263
+
264
+ function isContinuation(byte) {
265
+ return (byte & 0xc0) === 0x80;
266
+ }
267
+
268
+ const isUtf8 = typeof nodeBuffer.isUtf8 === "function" ? nodeBuffer.isUtf8 : isValidUtf8;
269
+
270
+ /**
271
+ * A parser for the frames a client sends, fed whatever the socket hands over.
272
+ *
273
+ * `push(chunk)` takes the next bytes, in pieces of any size, and answers an
274
+ * array of the MESSAGES they completed, in order: `{ type: "text" | "binary",
275
+ * data }` once every fragment of a message is in, and `{ type: "ping" |
276
+ * "pong", data }` or `{ type: "close", data, code, reason }` as each control
277
+ * frame arrives — so a ping between two fragments comes out before the message
278
+ * it interrupted, which is what §5.4 means control frames to be able to do.
279
+ * `data` is always a Buffer, unmasked. A close with no code reports 1005,
280
+ * which is how §7.1.5 says to describe it.
281
+ *
282
+ * A refusal comes out as `{ type: "error", code, reason }`, after any message
283
+ * completed before it, and the parser reads nothing more. Nor does it after a
284
+ * close: §5.5.1 has a client send nothing once it has sent one.
285
+ *
286
+ * Bytes are queued as they come and copied once, when a frame's payload is
287
+ * whole, so a mebibyte arriving in many small reads is not re-copied per read.
288
+ * The queue never holds more than one frame's header and payload, and a
289
+ * payload over the cap is refused from its header, before it is buffered.
290
+ */
291
+ export function createFrameParser({ maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES } = {}) {
292
+ const queue = [];
293
+ let queued = 0;
294
+ let finished = false;
295
+
296
+ // The frame being read: which part of it comes next and how many bytes that
297
+ // part needs.
298
+ let step = "header";
299
+ let need = 2;
300
+ let fin = false;
301
+ let opcode = 0;
302
+ let length = 0;
303
+ let mask = EMPTY;
304
+
305
+ // The message being assembled from fragments; `messageOpcode` is 0 between
306
+ // messages, TEXT or BINARY while one is open.
307
+ let messageOpcode = 0;
308
+ let fragments = [];
309
+ let fragmentBytes = 0;
310
+ let fragmentCount = 0;
311
+
312
+ /** Consume exactly `n` queued bytes: a view when one chunk holds them all,
313
+ * one copy when they span chunks.
314
+ *
315
+ * The chunks used up are dropped with one splice at the end, NOT a shift
316
+ * per chunk: shift moves every element behind it, so a payload that came
317
+ * in as a million one-byte reads — which a client can arrange by dripping
318
+ * it — cost a million moves of a million-long array. */
319
+ function take(n) {
320
+ if (n === 0) return EMPTY;
321
+ const first = queue[0];
322
+ if (first.length >= n) {
323
+ queued -= n;
324
+ if (first.length === n) { queue.shift(); return first; }
325
+ queue[0] = first.subarray(n);
326
+ return first.subarray(0, n);
327
+ }
328
+ const out = Buffer.allocUnsafe(n);
329
+ let offset = 0;
330
+ let used = 0;
331
+ while (offset < n) {
332
+ const chunk = queue[used];
333
+ const wanted = n - offset;
334
+ if (chunk.length <= wanted) {
335
+ chunk.copy(out, offset);
336
+ offset += chunk.length;
337
+ used += 1;
338
+ } else {
339
+ chunk.copy(out, offset, 0, wanted);
340
+ queue[used] = chunk.subarray(wanted);
341
+ offset += wanted;
342
+ }
343
+ }
344
+ queue.splice(0, used);
345
+ queued -= n;
346
+ return out;
347
+ }
348
+
349
+ function stop() {
350
+ finished = true;
351
+ queue.length = 0;
352
+ queued = 0;
353
+ fragments = [];
354
+ fragmentBytes = 0;
355
+ fragmentCount = 0;
356
+ }
357
+
358
+ function fail(out, code, reason) {
359
+ out.push({ type: "error", code, reason });
360
+ stop();
361
+ }
362
+
363
+ function readHeader(bytes, out) {
364
+ const first = bytes[0];
365
+ const second = bytes[1];
366
+ fin = (first & 0x80) !== 0;
367
+ opcode = first & 0x0f;
368
+ length = second & 0x7f;
369
+ if (first & 0x70) return fail(out, 1002, "reserved bits set with no extension agreed");
370
+ if (!KNOWN_OPCODES.has(opcode)) return fail(out, 1002, `reserved opcode ${opcode}`);
371
+ if (!(second & 0x80)) return fail(out, 1002, "a client frame must be masked");
372
+ if (opcode >= 0x8) {
373
+ if (!fin) return fail(out, 1002, "a control frame cannot be fragmented");
374
+ if (length > MAX_CONTROL_PAYLOAD) return fail(out, 1002, "a control frame carries at most 125 bytes");
375
+ } else if (opcode === OP.CONTINUATION) {
376
+ if (!messageOpcode) return fail(out, 1002, "a continuation with no message to continue");
377
+ } else if (messageOpcode) {
378
+ return fail(out, 1002, "a new message before the last one finished");
379
+ }
380
+ if (length === 126) { step = "length16"; need = 2; return; }
381
+ if (length === 127) { step = "length64"; need = 8; return; }
382
+ lengthKnown(out);
383
+ }
384
+
385
+ function readLength64(bytes, out) {
386
+ const high = bytes.readUInt32BE(0);
387
+ // §5.2: the most significant bit of a 64-bit length MUST be 0.
388
+ if (high >= 0x80000000) return fail(out, 1002, "a 64-bit length with its top bit set");
389
+ length = high * 0x100000000 + bytes.readUInt32BE(4);
390
+ lengthKnown(out);
391
+ }
392
+
393
+ /** The cap is checked here, from the header, so a peer that announces a
394
+ * gigabyte is refused before it has sent one. Fragments count together. */
395
+ function lengthKnown(out) {
396
+ if (opcode < 0x8 && fragmentBytes + length > maxMessageBytes) {
397
+ return fail(out, 1009, `a message over ${maxMessageBytes} bytes`);
398
+ }
399
+ if (opcode < 0x8 && fragmentCount >= MAX_FRAGMENTS) {
400
+ return fail(out, 1009, `a message in more than ${MAX_FRAGMENTS} frames`);
401
+ }
402
+ step = "mask";
403
+ need = 4;
404
+ }
405
+
406
+ function readPayload(masked, out) {
407
+ // Unmasked into a fresh buffer rather than in place: `masked` may be a view
408
+ // of the caller's own chunk, which is not this parser's to rewrite.
409
+ const payload = Buffer.allocUnsafe(masked.length);
410
+ for (let i = 0; i < masked.length; i++) payload[i] = masked[i] ^ mask[i & 3];
411
+ step = "header";
412
+ need = 2;
413
+ if (opcode >= 0x8) return controlFrame(payload, out);
414
+ if (opcode !== OP.CONTINUATION) messageOpcode = opcode;
415
+ fragmentCount += 1;
416
+ // An empty fragment is counted, never kept: it adds nothing to the message.
417
+ if (payload.length) fragments.push(payload);
418
+ fragmentBytes += payload.length;
419
+ if (!fin) return;
420
+ const data = fragments.length === 1 ? fragments[0] : Buffer.concat(fragments, fragmentBytes);
421
+ const type = messageOpcode === OP.TEXT ? "text" : "binary";
422
+ messageOpcode = 0;
423
+ fragments = [];
424
+ fragmentBytes = 0;
425
+ fragmentCount = 0;
426
+ // Checked once the message is whole, not per fragment: a character may be
427
+ // split across two fragments, and only the joined bytes say whether it is.
428
+ if (type === "text" && !isUtf8(data)) return fail(out, 1007, "a text message that is not UTF-8");
429
+ out.push({ type, data });
430
+ }
431
+
432
+ function controlFrame(payload, out) {
433
+ if (opcode === OP.PING) return void out.push({ type: "ping", data: payload });
434
+ if (opcode === OP.PONG) return void out.push({ type: "pong", data: payload });
435
+ if (payload.length === 1) return fail(out, 1002, "a close frame with a one-byte payload");
436
+ if (payload.length === 0) {
437
+ out.push({ type: "close", data: payload, code: 1005, reason: "" });
438
+ } else {
439
+ const code = payload.readUInt16BE(0);
440
+ if (!isSendableCloseCode(code)) return fail(out, 1002, `close code ${code} is never sent`);
441
+ const reason = payload.subarray(2);
442
+ if (!isUtf8(reason)) return fail(out, 1007, "a close reason that is not UTF-8");
443
+ out.push({ type: "close", data: payload, code, reason: reason.toString("utf8") });
444
+ }
445
+ stop();
446
+ }
447
+
448
+ return {
449
+ push(chunk) {
450
+ const out = [];
451
+ if (finished || !chunk || chunk.length === 0) return out;
452
+ queue.push(chunk);
453
+ queued += chunk.length;
454
+ while (!finished && queued >= need) {
455
+ if (step === "header") readHeader(take(2), out);
456
+ else if (step === "length16") { length = take(2).readUInt16BE(0); lengthKnown(out); }
457
+ else if (step === "length64") readLength64(take(8), out);
458
+ else if (step === "mask") { mask = take(4); step = "payload"; need = length; }
459
+ else readPayload(take(length), out);
460
+ }
461
+ return out;
462
+ },
463
+ };
464
+ }
465
+
466
+ /** A close frame's payload: the code and a reason cut to the 123 bytes there is
467
+ * room for — on a character boundary, so the cut never makes the reason
468
+ * invalid UTF-8 (which the browser would fail the connection over). */
469
+ function closePayload(code, reason) {
470
+ if (code == null) return EMPTY;
471
+ const text = Buffer.from(String(reason ?? ""), "utf8");
472
+ let end = Math.min(text.length, MAX_CLOSE_REASON);
473
+ if (end < text.length) while (end > 0 && isContinuation(text[end])) end -= 1;
474
+ const payload = Buffer.allocUnsafe(2 + end);
475
+ payload.writeUInt16BE(code, 0);
476
+ text.copy(payload, 2, 0, end);
477
+ return payload;
478
+ }
479
+
480
+ /**
481
+ * Run one accepted WebSocket over `socket` — call it after writing
482
+ * upgradeResponse(key) to the socket. `head` is the bytes Node read past the
483
+ * handshake (the 'upgrade' event's third argument); they are the start of the
484
+ * first frame and are read before anything later.
485
+ *
486
+ * `onMessage({ type: "text" | "binary", data })` gets each data message while
487
+ * the connection is open; control frames are handled here. Pings are answered
488
+ * with a pong carrying the same bytes. A close from the client is echoed with
489
+ * its code and the socket ended. `close(code, reason)` starts the close
490
+ * handshake from this side; a socket whose peer has not finished it within
491
+ * CLOSE_TIMEOUT_MS is destroyed. Every `pingMs` (0 turns it off) the client is
492
+ * pinged, and a connection whose ping has gone unanswered for two intervals is
493
+ * closed 1001 — a laptop that slept or a tunnel that stalled never says
494
+ * goodbye, and its socket would otherwise sit there for good.
495
+ *
496
+ * `onClose(code, reason)` fires exactly once, as soon as the connection is
497
+ * over: with the code of whichever side closed first (1005 for a client close
498
+ * with no code), the refusal's code when this side failed the connection, and
499
+ * 1006 when the socket went away with no close frame either way.
500
+ *
501
+ * Answers `{ sendBinary(bytes), sendText(string), close(code = 1000, reason =
502
+ * ""), bufferedAmount, open }`. The two senders answer false and drop the
503
+ * frame once the connection is no longer open. `bufferedAmount` is the bytes
504
+ * the socket has yet to flush, for the caller's backpressure.
505
+ */
506
+ export function wsConnection(socket, head, {
507
+ maxMessageBytes = DEFAULT_MAX_MESSAGE_BYTES,
508
+ pingMs = 30_000,
509
+ onMessage,
510
+ onClose,
511
+ } = {}) {
512
+ const parser = createFrameParser({ maxMessageBytes });
513
+ // "open" until either side sends a close; "closing" while this side waits
514
+ // for the client to answer its close; "closed" once nothing more is read.
515
+ let state = "open";
516
+ let closedWith = null;
517
+ let notified = false;
518
+ let unanswered = 0;
519
+ let destroyTimer = null;
520
+ let pingTimer = null;
521
+
522
+ // Typing is a stream of tiny frames, and Nagle would hold each keystroke's
523
+ // echo back waiting for the last one's ACK.
524
+ socket.setNoDelay?.(true);
525
+ // An error is always followed by 'close', which is where the connection's end
526
+ // is handled; the listener is here so the error is not thrown.
527
+ socket.on("error", () => {});
528
+ // The client closed its half, after a close handshake or without one.
529
+ // Upgrade sockets come from an http.Server, which allows half-open sockets,
530
+ // so this half is ended here or the socket would wait for good.
531
+ socket.on("end", () => endSocket());
532
+ socket.on("close", socketGone);
533
+
534
+ if (pingMs > 0) {
535
+ pingTimer = setInterval(keepalive, pingMs);
536
+ pingTimer.unref?.();
537
+ }
538
+
539
+ // The head and the 'data' listener wait one tick, so onMessage is never
540
+ // called before this function has returned the connection a handler may
541
+ // want to answer through. Attaching 'data' in the same tick as reading the
542
+ // head keeps them in order: until a listener is attached the upgrade socket
543
+ // is not flowing, so anything that arrived meanwhile is still buffered.
544
+ process.nextTick(() => {
545
+ // A client that vanished between the upgrade and this call left a socket
546
+ // whose 'close' may already have fired, before anything here listened —
547
+ // and onClose is promised exactly once, not "unless it was quick".
548
+ if (socket.destroyed) return socketGone();
549
+ if (head && head.length) receive(head);
550
+ socket.on("data", receive);
551
+ // So may a client that only closed its half. An upgrade socket goes on
552
+ // reading after the upgrade, so its 'end' can fire while a handler is
553
+ // still deciding (the engine's attach waits for its answer), before the
554
+ // 'end' listener above existed. Its half is ended here, as that listener
555
+ // would have, or the socket stays half-open for good.
556
+ if (socket.readableEnded) endSocket();
557
+ });
558
+
559
+ function socketGone() {
560
+ clearTimeout(destroyTimer);
561
+ finish(closedWith?.code ?? 1006, closedWith?.reason ?? "");
562
+ }
563
+
564
+ function receive(chunk) {
565
+ if (state === "closed") return;
566
+ for (const message of parser.push(chunk)) handle(message);
567
+ }
568
+
569
+ function handle(message) {
570
+ switch (message.type) {
571
+ case "text":
572
+ case "binary":
573
+ if (state !== "open") return;
574
+ try {
575
+ onMessage?.(message);
576
+ } catch {
577
+ close(1011, "the server could not handle a message");
578
+ }
579
+ return;
580
+ case "ping":
581
+ if (state === "open") write(encodeFrame(OP.PONG, message.data));
582
+ return;
583
+ case "pong":
584
+ unanswered = 0;
585
+ return;
586
+ case "close":
587
+ peerClosed(message.code, message.reason);
588
+ return;
589
+ case "error":
590
+ failConnection(message.code, message.reason);
591
+ return;
592
+ }
593
+ }
594
+
595
+ function peerClosed(code, reason) {
596
+ if (state === "closed") return;
597
+ if (state === "open") {
598
+ // §5.5.1: answer with a close, typically echoing the code received. A
599
+ // close that carried no code is answered with none.
600
+ write(encodeFrame(OP.CLOSE, closePayload(code === 1005 ? null : code, "")));
601
+ closedWith = { code, reason };
602
+ }
603
+ state = "closed";
604
+ // §7.1.1: once both closes have crossed, the server closes the TCP
605
+ // connection first, so the client is not left in TIME_WAIT.
606
+ endSocket();
607
+ finish(closedWith.code, closedWith.reason);
608
+ }
609
+
610
+ function failConnection(code, reason) {
611
+ if (state === "closed") return;
612
+ // While this side waits for its own close to be answered it has already
613
+ // sent the one close frame it may send; the refusal only ends the socket.
614
+ if (state === "open") {
615
+ const payload = closePayload(code, reason);
616
+ write(encodeFrame(OP.CLOSE, payload));
617
+ closedWith = { code, reason: payload.subarray(2).toString("utf8") };
618
+ }
619
+ state = "closed";
620
+ endSocket();
621
+ finish(closedWith.code, closedWith.reason);
622
+ }
623
+
624
+ function close(code = 1000, reason = "") {
625
+ if (!isSendableCloseCode(code)) throw new RangeError(`${code} is not a close code that can be sent`);
626
+ if (state !== "open") return;
627
+ state = "closing";
628
+ const payload = closePayload(code, reason);
629
+ closedWith = { code, reason: payload.subarray(2).toString("utf8") };
630
+ write(encodeFrame(OP.CLOSE, payload));
631
+ armDestroy();
632
+ }
633
+
634
+ function keepalive() {
635
+ if (state !== "open") return;
636
+ if (unanswered >= 2) {
637
+ close(1001, "no answer to ping");
638
+ return;
639
+ }
640
+ unanswered += 1;
641
+ write(encodeFrame(OP.PING));
642
+ }
643
+
644
+ function endSocket() {
645
+ try { socket.end(); } catch { /* already gone */ }
646
+ armDestroy();
647
+ }
648
+
649
+ function armDestroy() {
650
+ if (destroyTimer) return;
651
+ destroyTimer = setTimeout(() => socket.destroy(), CLOSE_TIMEOUT_MS);
652
+ destroyTimer.unref?.();
653
+ }
654
+
655
+ function write(frame) {
656
+ if (socket.destroyed || socket.writableEnded) return false;
657
+ try {
658
+ socket.write(frame);
659
+ return true;
660
+ } catch {
661
+ return false;
662
+ }
663
+ }
664
+
665
+ function finish(code, reason) {
666
+ if (notified) return;
667
+ notified = true;
668
+ state = "closed";
669
+ clearInterval(pingTimer);
670
+ try { onClose?.(code, reason); } catch { /* see the header: nothing throws out of a socket event */ }
671
+ }
672
+
673
+ return {
674
+ sendBinary(bytes) {
675
+ if (state !== "open") return false;
676
+ return write(encodeFrame(OP.BINARY, bytes));
677
+ },
678
+ sendText(text) {
679
+ if (state !== "open") return false;
680
+ return write(encodeFrame(OP.TEXT, String(text)));
681
+ },
682
+ close,
683
+ get bufferedAmount() {
684
+ return socket.writableLength ?? 0;
685
+ },
686
+ get open() {
687
+ return state === "open";
688
+ },
689
+ };
690
+ }