@open-artifact/server-sdk 0.0.0-stage → 0.2.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.
package/src/ws.d.ts ADDED
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A small WebSocket server side (RFC 6455) on Node built-ins only: text
3
+ * frames, ping/pong and close. Type servers use it for the event streams of
4
+ * mounted sites and for their own upgrades.
5
+ */
6
+ import type { IncomingMessage } from 'node:http';
7
+ import type { Duplex } from 'node:stream';
8
+ /** What a {@link WebSocketConnection} calls back. */
9
+ export interface WebSocketHandlers {
10
+ /** A complete text (or binary, decoded as UTF-8) message arrived. */
11
+ message?: (text: string) => void;
12
+ /** The connection closed, from either side. Called once. */
13
+ close?: () => void;
14
+ }
15
+ /** The `Sec-WebSocket-Accept` value for a client's `Sec-WebSocket-Key`. */
16
+ export declare function acceptKey(key: string): string;
17
+ /**
18
+ * Accepts an HTTP upgrade as a WebSocket. Answers `protocol` as the
19
+ * subprotocol when the client asked for it. Returns the connection, or `null`
20
+ * after refusing a request that is not a WebSocket handshake.
21
+ */
22
+ export declare function acceptWebSocket(request: IncomingMessage, socket: Duplex, head: Buffer, protocol?: string): WebSocketConnection | null;
23
+ /** One accepted WebSocket connection (server side: frames it sends are unmasked). */
24
+ export declare class WebSocketConnection {
25
+ /** The underlying socket. */
26
+ readonly socket: Duplex;
27
+ /** Set once the connection closed. */
28
+ closed: boolean;
29
+ /** Callbacks; assign them right after accepting. */
30
+ handlers: WebSocketHandlers;
31
+ private buffer;
32
+ private fragments;
33
+ private readonly pinger;
34
+ /** Wraps an upgraded socket; `head` is what the upgrade event already read. */
35
+ constructor(socket: Duplex, head?: Buffer);
36
+ /** Parses every complete frame in the buffer. */
37
+ private read;
38
+ /** Sends one unfragmented frame. */
39
+ private frame;
40
+ /** Sends a text message. */
41
+ sendText(text: string): void;
42
+ /** Sends a close frame with `code` and ends the connection. */
43
+ close(code?: number): void;
44
+ /** Ends the socket and calls the close handler once. */
45
+ private finish;
46
+ }
package/src/ws.js ADDED
@@ -0,0 +1,182 @@
1
+ /**
2
+ * A small WebSocket server side (RFC 6455) on Node built-ins only: text
3
+ * frames, ping/pong and close. Type servers use it for the event streams of
4
+ * mounted sites and for their own upgrades.
5
+ */
6
+ import { createHash } from 'node:crypto';
7
+ /** The GUID RFC 6455 appends to the client key. */
8
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
9
+ /** Largest frame accepted, bytes. Bigger frames close the connection with 1009. */
10
+ const MAX_FRAME = 16 * 1024 * 1024;
11
+ /** Interval of keep-alive pings, ms. */
12
+ const PING_MS = 25_000;
13
+ /** The `Sec-WebSocket-Accept` value for a client's `Sec-WebSocket-Key`. */
14
+ export function acceptKey(key) {
15
+ return createHash('sha1').update(key + GUID).digest('base64');
16
+ }
17
+ /**
18
+ * Accepts an HTTP upgrade as a WebSocket. Answers `protocol` as the
19
+ * subprotocol when the client asked for it. Returns the connection, or `null`
20
+ * after refusing a request that is not a WebSocket handshake.
21
+ */
22
+ export function acceptWebSocket(request, socket, head, protocol) {
23
+ const key = request.headers['sec-websocket-key'];
24
+ if (typeof key !== 'string' || String(request.headers.upgrade).toLowerCase() !== 'websocket') {
25
+ socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
26
+ return null;
27
+ }
28
+ const asked = String(request.headers['sec-websocket-protocol'] ?? '')
29
+ .split(',')
30
+ .map((p) => p.trim())
31
+ .filter(Boolean);
32
+ const lines = ['HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket', 'Connection: Upgrade', `Sec-WebSocket-Accept: ${acceptKey(key)}`];
33
+ if (protocol && asked.includes(protocol))
34
+ lines.push(`Sec-WebSocket-Protocol: ${protocol}`);
35
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`);
36
+ return new WebSocketConnection(socket, head);
37
+ }
38
+ /** One accepted WebSocket connection (server side: frames it sends are unmasked). */
39
+ export class WebSocketConnection {
40
+ /** The underlying socket. */
41
+ socket;
42
+ /** Set once the connection closed. */
43
+ closed = false;
44
+ /** Callbacks; assign them right after accepting. */
45
+ handlers = {};
46
+ buffer;
47
+ fragments = [];
48
+ pinger;
49
+ /** Wraps an upgraded socket; `head` is what the upgrade event already read. */
50
+ constructor(socket, head) {
51
+ this.socket = socket;
52
+ this.buffer = head && head.length ? Buffer.from(head) : Buffer.alloc(0);
53
+ socket.setNoDelay?.(true);
54
+ socket.on('data', (chunk) => {
55
+ this.buffer = Buffer.concat([this.buffer, chunk]);
56
+ this.read();
57
+ });
58
+ const end = () => this.finish();
59
+ socket.on('close', end);
60
+ socket.on('end', end);
61
+ socket.on('error', end);
62
+ if (this.buffer.length)
63
+ setImmediate(() => this.read());
64
+ this.pinger = setInterval(() => this.frame(0x9, Buffer.alloc(0)), PING_MS);
65
+ this.pinger.unref();
66
+ }
67
+ /** Parses every complete frame in the buffer. */
68
+ read() {
69
+ for (;;) {
70
+ const b = this.buffer;
71
+ if (b.length < 2)
72
+ return;
73
+ const fin = (b[0] & 0x80) !== 0;
74
+ const op = b[0] & 0x0f;
75
+ const masked = (b[1] & 0x80) !== 0;
76
+ let len = b[1] & 0x7f;
77
+ let at = 2;
78
+ if (len === 126) {
79
+ if (b.length < 4)
80
+ return;
81
+ len = b.readUInt16BE(2);
82
+ at = 4;
83
+ }
84
+ else if (len === 127) {
85
+ if (b.length < 10)
86
+ return;
87
+ len = Number(b.readBigUInt64BE(2));
88
+ at = 10;
89
+ }
90
+ if (len > MAX_FRAME)
91
+ return this.close(1009);
92
+ const maskAt = at;
93
+ if (masked)
94
+ at += 4;
95
+ if (b.length < at + len)
96
+ return;
97
+ let payload = b.subarray(at, at + len);
98
+ if (masked) {
99
+ const mask = b.subarray(maskAt, maskAt + 4);
100
+ payload = Buffer.from(payload);
101
+ for (let i = 0; i < payload.length; i++)
102
+ payload[i] = payload[i] ^ mask[i & 3];
103
+ }
104
+ this.buffer = b.subarray(at + len);
105
+ if (op === 0x8)
106
+ return this.close(1000);
107
+ if (op === 0x9) {
108
+ this.frame(0xa, payload);
109
+ continue;
110
+ }
111
+ if (op === 0xa)
112
+ continue;
113
+ if (op === 0x1 || op === 0x2 || op === 0x0) {
114
+ this.fragments.push(payload);
115
+ if (fin) {
116
+ const text = Buffer.concat(this.fragments).toString('utf8');
117
+ this.fragments = [];
118
+ try {
119
+ this.handlers.message?.(text);
120
+ }
121
+ catch {
122
+ // A handler's error is its own.
123
+ }
124
+ }
125
+ }
126
+ }
127
+ }
128
+ /** Sends one unfragmented frame. */
129
+ frame(op, payload) {
130
+ if (this.closed)
131
+ return;
132
+ const len = payload.length;
133
+ let header;
134
+ if (len < 126)
135
+ header = Buffer.from([0x80 | op, len]);
136
+ else if (len < 65536) {
137
+ header = Buffer.alloc(4);
138
+ header[0] = 0x80 | op;
139
+ header[1] = 126;
140
+ header.writeUInt16BE(len, 2);
141
+ }
142
+ else {
143
+ header = Buffer.alloc(10);
144
+ header[0] = 0x80 | op;
145
+ header[1] = 127;
146
+ header.writeBigUInt64BE(BigInt(len), 2);
147
+ }
148
+ try {
149
+ this.socket.write(Buffer.concat([header, payload]));
150
+ }
151
+ catch {
152
+ this.finish();
153
+ }
154
+ }
155
+ /** Sends a text message. */
156
+ sendText(text) {
157
+ this.frame(0x1, Buffer.from(text, 'utf8'));
158
+ }
159
+ /** Sends a close frame with `code` and ends the connection. */
160
+ close(code = 1000) {
161
+ if (this.closed)
162
+ return;
163
+ const payload = Buffer.alloc(2);
164
+ payload.writeUInt16BE(code, 0);
165
+ this.frame(0x8, payload);
166
+ this.finish();
167
+ }
168
+ /** Ends the socket and calls the close handler once. */
169
+ finish() {
170
+ if (this.closed)
171
+ return;
172
+ this.closed = true;
173
+ clearInterval(this.pinger);
174
+ try {
175
+ this.socket.end();
176
+ }
177
+ catch {
178
+ // Already gone.
179
+ }
180
+ this.handlers.close?.();
181
+ }
182
+ }