-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmod.ts
351 lines (286 loc) · 9.62 KB
/
mod.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
import { iterateReader } from "https://deno.land/[email protected]/streams/iterate_reader.ts"
import { EventEmitter } from "https://deno.land/x/[email protected]/mod.ts"
enum State {
Connecting, Open, Closing, Closed
}
type WebsocketEvents = {
open: []
close: [number | null, string | null]
textMessage: [string]
binaryMessage: [Uint8Array]
raw: [Uint8Array]
}
type FrameInfo = {
fin: boolean,
srv: [number, number, number],
op: string,
maskExists: boolean,
length: Uint8Array,
mask: Uint8Array,
content: Uint8Array | string | undefined | { code: number, content: string }
}
class FrameTools {
static lastOp = ''
static decode(data: Uint8Array): FrameInfo {
const maskExists = (data[1] & 0b10000000) == 0b10000000
let op = (data[0] & 0b00001111).toString(16)
if (op == '0' && (this.lastOp == '1' || this.lastOp == '2')) {
op = this.lastOp
} else {
this.lastOp = op
}
let length = Uint8Array.from([data[1] & 0b01111111])
let startIndex = 0
if (length[0] === 126) {
length = Uint8Array.from([data[2], data[3]])
startIndex = 2
}
if (length[0] === 127) {
length = Uint8Array.from([data[2], data[3], data[4], data[5], data[6], data[7], data[8], data[9]])
startIndex = 8
}
let mask: Uint8Array = new Uint8Array(0)
if (maskExists) {
mask = Uint8Array.from([data[startIndex], data[1 + startIndex], data[2 + startIndex], data[3 + startIndex]])
startIndex += 4
}
const contentRaw = data.slice(2 + startIndex, 2 + startIndex + length.reduce((sum, acc) => sum + acc, 0))
const content = (length[0] > 0 && op == '1')
? new TextDecoder().decode(contentRaw)
: (length[0] > 0 && op == '2')
? contentRaw
: (length[0] > 0 && op == '8')
? { code: ((contentRaw[0] << 8) + contentRaw[1]), content: new TextDecoder().decode(contentRaw.slice(2)) }
: undefined
return {
fin: (data[0] & 0b10000000) == 0b10000000,
srv: [
data[0] & 0b01000000,
data[0] & 0b00100000,
data[0] & 0b00010000
],
op,
maskExists,
length,
mask,
content
}
}
static encode(data: FrameInfo): Uint8Array {
const firstByte = ((data.fin ? 1 : 0) << 7) | (data.srv[0] << 6) | (data.srv[1] << 5) | (data.srv[2] << 4) | parseInt(data.op, 16)
const length = [(data.maskExists ? 1 : 0) << 7 | data.length[0], ...data.length.slice(1)]
const decodedContent = (typeof data.content == 'string')
? new TextEncoder().encode(data.content)
: (data.content === undefined)
? Uint8Array.from([])
: data.content as Uint8Array
const content = data.maskExists ? decodedContent.map((elt, i) => elt ^ data.mask[i % 4]) : decodedContent
return Uint8Array.from([firstByte, ...length, ...data.mask, ...content])
}
}
export default class SimpleWebSocket extends EventEmitter<WebsocketEvents> {
port = 80
url: URL
#connection: Deno.Conn | undefined
state: State = State.Closed
#isWSMode = false
#sentClosed = false
headers: { [key: string]: string } = {}
public get isSecure(): boolean {
return this.url.protocol === 'wss:'
}
constructor(url: string | undefined, options?: { port?: number, headers?: { [key: string]: string } }) {
super()
this.port = (url?.startsWith('wss://') || url?.startsWith('https://')) ? 443 : 80
if (Number.isInteger(options?.port)) {
this.port = options!.port!
}
this.url = new URL(url === undefined ? 'http://127.0.0.1' : url)
this.headers = options?.headers === undefined ? {} : options.headers
}
async connect() {
const connection = this.isSecure
? Deno.connectTls({ hostname: this.url.hostname, port: this.port })
: Deno.connect({ hostname: this.url.hostname, port: this.port })
await this.setConnection(connection).catch((err) => { this.state = State.Closed; throw err })
await this.upgradeAndListen(this.headers)
for await (const chunk of iterateReader(this.#connection!)) {
this.#isWSMode = !this.handleFrame(FrameTools.decode(chunk))
if (!this.#isWSMode) {
this.#connection!.close()
break
}
}
if (!this.#sentClosed) this.emit('close', null, null)
}
private handleFrame(frame: FrameInfo): boolean {
switch (frame.op) {
case '1':
this.emit('textMessage', frame.content as string)
break
case '2':
this.emit('binaryMessage', frame.content as Uint8Array)
break
case '8':
// deno-lint-ignore no-explicit-any
this.emit('close', (frame.content as any).code, (frame.content as any).content)
this.#sentClosed = true
return true
case '9':
this.pong()
break
case 'a':
break
default:
this.emit('close', 1000, 'Server send invalid opcode')
return true
}
return false
}
private async setConnection(promise: Promise<Deno.Conn>) {
this.state = State.Connecting
this.#connection = await promise.then(content => content)
}
private async upgradeAndListen(additionalHeaders: { [key: string]: string } = {}) {
const headers = {
'Host': this.url.host,
'Upgrade': 'websocket',
'Connection': 'upgrade',
'Sec-WebSocket-Key': btoa((Math.random() + 1).toString(36).substring(0, 17)),
'Sec-WebSocket-Version': 13,
...additionalHeaders
}
// Send raw HTTP GET request.
const request = new TextEncoder().encode(
`GET ${this.url.pathname} HTTP/1.1\r\n` + Object.entries(headers).map(([key, val]) => `${key}: ${val}`).join('\r\n') + '\r\n\r\n'
)
await this.#connection!.write(request)
const buffer = new Uint8Array(1000)
await this.#connection!.read(buffer)
const out = new TextDecoder().decode(buffer).split('\r\n').filter(elt => elt.length > 0 && elt[0] !== '\x00')
const isConnectionValid = out[0].split(' ')[1] == "101"
if (!isConnectionValid) {
console.error("Connection is invalid, check response headers below")
console.error(out)
return
}
this.#isWSMode = true
this.state = State.Open
this.emit('open')
}
/** Send ping frame */
ping() {
if (!this.#isWSMode) return
this.#connection!.write(FrameTools.encode({
fin: true,
srv: [0, 0, 0],
content: Uint8Array.from([]),
length: Uint8Array.from([0]),
mask: self.crypto.getRandomValues(new Uint8Array(4)),
maskExists: true,
op: '9'
}))
}
/** Send pong frame (ping response) */
pong() {
if (!this.#isWSMode) return
this.#connection!.write(FrameTools.encode({
fin: true,
srv: [0, 0, 0],
content: Uint8Array.from([]),
length: Uint8Array.from([0]),
mask: self.crypto.getRandomValues(new Uint8Array(4)),
maskExists: true,
op: 'A'
}))
}
/** Sends close packet effectively cutting off connection */
close(code: number | null, reason: string | undefined) {
if (!this.#isWSMode) return
if (code !== null && !this.isValidStatusCode(code)) {
throw new Error('Invalid code')
} else {
code = 1000
}
if (reason === undefined) {
reason = 'Connection closed'
}
const buffer = new ArrayBuffer(2)
const dataView = new DataView(buffer)
dataView.setUint16(0, code)
// Create a Uint8Array from the buffer
const decodedCode = new Uint8Array(buffer)
this.#connection!.write(FrameTools.encode({
fin: true,
srv: [0, 0, 0],
content: Uint8Array.from([...decodedCode, ...new TextEncoder().encode(reason)]),
length: Uint8Array.from([reason.length + 2]),
mask: self.crypto.getRandomValues(new Uint8Array(4)),
maskExists: true,
op: '8'
}))
this.#isWSMode = false
}
send(data: string | Uint8Array) {
if (data.length < 126) {
this.#connection!.write(FrameTools.encode({
fin: true,
srv: [0, 0, 0],
content: data,
length: Uint8Array.from([data.length]),
mask: self.crypto.getRandomValues(new Uint8Array(4)),
maskExists: true,
op: Array.isArray(data) ? '2' : '1'
}))
return
}
if (data.length < (Math.pow(2, 16) - 1)) {
if (!this.#isWSMode) return
const buffer = new ArrayBuffer(2)
const dataView = new DataView(buffer)
dataView.setUint16(0, data.length)
// Create a Uint8Array from the buffer
const contentLength = new Uint8Array(buffer)
this.#connection!.write(FrameTools.encode({
fin: true,
srv: [0, 0, 0],
content: data,
length: Uint8Array.from([126, ...contentLength]),
mask: self.crypto.getRandomValues(new Uint8Array(4)),
maskExists: true,
op: Array.isArray(data) ? '2' : '1'
}))
return
}
if (data.length > (Math.pow(2, 64) - 1)) {
const buffer = new ArrayBuffer(8)
const dataView = new DataView(buffer)
dataView.setUint32(0, data.length)
dataView.setUint32(4, (data.length - dataView.getUint32(0)) / Math.pow(2, 32))
// Create a Uint8Array from the buffer
const contentLength = new Uint8Array(buffer)
this.#connection!.write(FrameTools.encode({
fin: true,
srv: [0, 0, 0],
content: data,
length: Uint8Array.from([127, ...contentLength]),
mask: self.crypto.getRandomValues(new Uint8Array(4)),
maskExists: true,
op: Array.isArray(data) ? '2' : '1'
}))
return
} else {
throw new Error('Not implemented')
}
}
private isValidStatusCode(code: number) {
return (
(code >= 1000 &&
code <= 1014 &&
code !== 1004 &&
code !== 1005 &&
code !== 1006) ||
(code >= 3000 && code <= 4999)
)
}
}