@itznomo/baileys 0.0.0-stage → 0.0.3

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 (124) hide show
  1. package/BUTTONS.md +153 -0
  2. package/Example/call-bot.mjs +38 -0
  3. package/Example/example.mjs +36 -0
  4. package/Example/full-bot-commands.mjs +319 -0
  5. package/Example/full-bot.mjs +77 -0
  6. package/LICENSE +21 -0
  7. package/README.md +543 -2
  8. package/WAProto/@dnuzi +1 -0
  9. package/WAProto/index.d.ts +15932 -0
  10. package/WAProto/index.js +113300 -0
  11. package/assets/banner.svg +17 -0
  12. package/assets/devider.svg +1 -0
  13. package/assets/features.svg +21 -0
  14. package/docs/CALLS.md +106 -0
  15. package/docs/FEATURES.md +1152 -0
  16. package/engine-requirements.js +19 -0
  17. package/index.d.ts +815 -0
  18. package/package.json +51 -4
  19. package/src/binary/wa-binary-constants.js +1300 -0
  20. package/src/binary/wa-binary.js +627 -0
  21. package/src/constants.js +147 -0
  22. package/src/defaults.js +106 -0
  23. package/src/foundation/ai-rich.js +654 -0
  24. package/src/foundation/audio-duration.js +470 -0
  25. package/src/foundation/audio-samples.js +250 -0
  26. package/src/foundation/boom.js +39 -0
  27. package/src/foundation/builders.js +851 -0
  28. package/src/foundation/cache.js +134 -0
  29. package/src/foundation/concurrency.js +69 -0
  30. package/src/foundation/curve25519.js +189 -0
  31. package/src/foundation/image-thumb.js +65 -0
  32. package/src/foundation/link-preview.js +278 -0
  33. package/src/foundation/logger.js +78 -0
  34. package/src/foundation/long.js +130 -0
  35. package/src/foundation/performance.js +385 -0
  36. package/src/foundation/protobuf-minimal.js +587 -0
  37. package/src/foundation/qrcode-terminal.js +273 -0
  38. package/src/foundation/sql-database.js +716 -0
  39. package/src/foundation/wa-crypto.js +47 -0
  40. package/src/foundation/zip.js +108 -0
  41. package/src/index.js +67 -0
  42. package/src/signal/libsignal.js +996 -0
  43. package/src/signal/signal-group.js +455 -0
  44. package/src/signal/signal-repository.js +635 -0
  45. package/src/socket/business-communities.js +811 -0
  46. package/src/socket/chats.js +702 -0
  47. package/src/socket/groups-newsletter.js +524 -0
  48. package/src/socket/messages-recv.js +1815 -0
  49. package/src/socket/messages-send.js +1526 -0
  50. package/src/socket/socket-builder.js +131 -0
  51. package/src/socket/socket-core.js +913 -0
  52. package/src/socket/usync.js +287 -0
  53. package/src/socket-client/native-websocket.js +344 -0
  54. package/src/socket-client/websocket-client.js +170 -0
  55. package/src/utils/auth-state-core.js +731 -0
  56. package/src/utils/auth-state-storage.js +594 -0
  57. package/src/utils/chat-sync.js +1046 -0
  58. package/src/utils/check-status.js +159 -0
  59. package/src/utils/cstoken.js +17 -0
  60. package/src/utils/media.js +807 -0
  61. package/src/utils/message-compose.js +1747 -0
  62. package/src/utils/message-processing.js +912 -0
  63. package/src/utils/modern-messages.js +435 -0
  64. package/src/utils/nomo-buttons.js +138 -0
  65. package/src/utils/nomo-commands.js +168 -0
  66. package/src/utils/spam-report-utils.js +136 -0
  67. package/src/utils/use-keyv-auth-state.js +307 -0
  68. package/src/utils/username.js +19 -0
  69. package/src/utils/wa-protocol-core.js +1227 -0
  70. package/src/voip/WaVoipCoordinator.js +158 -0
  71. package/src/voip/app-data/WaAppDataStream.js +193 -0
  72. package/src/voip/app-data/protocol.js +172 -0
  73. package/src/voip/auto.js +139 -0
  74. package/src/voip/bytes.js +63 -0
  75. package/src/voip/call/WaCallManager.js +442 -0
  76. package/src/voip/call/WaCallMediaSession.js +1727 -0
  77. package/src/voip/call/call-state.js +203 -0
  78. package/src/voip/crypto/encryption.js +13 -0
  79. package/src/voip/crypto/primitives.js +21 -0
  80. package/src/voip/crypto/rtcp.js +66 -0
  81. package/src/voip/crypto/srtp.js +180 -0
  82. package/src/voip/crypto/ssrc.js +15 -0
  83. package/src/voip/index.js +730 -0
  84. package/src/voip/media/WaAudioEngine.js +486 -0
  85. package/src/voip/media/WaVideoEngine.js +275 -0
  86. package/src/voip/media/audio-codec.js +0 -0
  87. package/src/voip/media/audio-reorder.js +107 -0
  88. package/src/voip/media/h264.js +246 -0
  89. package/src/voip/media/mlow-codec.js +465 -0
  90. package/src/voip/media/rtcp.js +68 -0
  91. package/src/voip/media/rtp.js +242 -0
  92. package/src/voip/protobuf.js +30 -0
  93. package/src/voip/relay/WaManualRelay.js +609 -0
  94. package/src/voip/relay/datachannel/pre-negotiated.js +25 -0
  95. package/src/voip/relay/dtls/aead.js +46 -0
  96. package/src/voip/relay/dtls/cert-builder.js +102 -0
  97. package/src/voip/relay/dtls/der.js +98 -0
  98. package/src/voip/relay/dtls/ecdhe.js +37 -0
  99. package/src/voip/relay/dtls/handshake-framing.js +100 -0
  100. package/src/voip/relay/dtls/handshake-messages.js +158 -0
  101. package/src/voip/relay/dtls/handshake.js +582 -0
  102. package/src/voip/relay/dtls/prf.js +39 -0
  103. package/src/voip/relay/dtls/record.js +56 -0
  104. package/src/voip/relay/relay-ack.js +141 -0
  105. package/src/voip/relay/sctp/association.js +434 -0
  106. package/src/voip/relay/sctp/crc32c.js +21 -0
  107. package/src/voip/relay/sctp/wire.js +226 -0
  108. package/src/voip/relay/stun.js +463 -0
  109. package/src/voip/shim/baileys-resolve.js +7 -0
  110. package/src/voip/shim/core.js +66 -0
  111. package/src/voip/shim/crypto.js +6 -0
  112. package/src/voip/shim/proto.js +10 -0
  113. package/src/voip/shim/protocol.js +130 -0
  114. package/src/voip/shim/transport.js +82 -0
  115. package/src/voip/shim/util.js +207 -0
  116. package/src/voip/signaling/bridge.js +102 -0
  117. package/src/voip/signaling/screen-share.js +60 -0
  118. package/src/voip/signaling/signaling.js +491 -0
  119. package/src/voip/types.js +69 -0
  120. package/src/voip/voip-deps.js +243 -0
  121. package/src/voip/voipClient.js +314 -0
  122. package/src/wam/wam-constants.js +22852 -0
  123. package/src/wam/wam.js +146 -0
  124. package/voip.d.ts +144 -0
@@ -0,0 +1,287 @@
1
+ import { assertNodeErrorFree, getBinaryNodeChild, getBinaryNodeChildren, getBinaryNodeChildString } from '../binary/wa-binary.js'
2
+
3
+ export class USyncUser {
4
+ withId(id) {
5
+ this.id = id
6
+ return this
7
+ }
8
+ withLid(lid) {
9
+ this.lid = lid
10
+ return this
11
+ }
12
+ withPhone(phone) {
13
+ this.phone = phone
14
+ return this
15
+ }
16
+ withUsername(username) {
17
+ this.username = username
18
+ return this
19
+ }
20
+ withUsernameKey(usernameKey) {
21
+ this.usernameKey = usernameKey
22
+ return this
23
+ }
24
+ withType(type) {
25
+ this.type = type
26
+ return this
27
+ }
28
+ withPersonaId(personaId) {
29
+ this.personaId = personaId
30
+ return this
31
+ }
32
+ }
33
+
34
+ export class USyncContactProtocol {
35
+ constructor() {
36
+ this.name = 'contact'
37
+ }
38
+ getQueryElement() {
39
+ return { tag: 'contact', attrs: {} }
40
+ }
41
+ getUserElement(user) {
42
+ if (user.phone) return { tag: 'contact', attrs: {}, content: user.phone }
43
+ if (user.username) {
44
+ return {
45
+ tag: 'contact',
46
+ attrs: { username: user.username, ...(user.usernameKey ? { pin: user.usernameKey } : {}), ...(user.lid ? { lid: user.lid } : {}) }
47
+ }
48
+ }
49
+ if (user.type) return { tag: 'contact', attrs: { type: user.type } }
50
+ return { tag: 'contact', attrs: {} }
51
+ }
52
+ parser(node) {
53
+ if (node.tag === 'contact') {
54
+ assertNodeErrorFree(node)
55
+ return node?.attrs?.type === 'in'
56
+ }
57
+ return false
58
+ }
59
+ }
60
+
61
+ export class USyncDeviceProtocol {
62
+ constructor() {
63
+ this.name = 'devices'
64
+ }
65
+ getQueryElement() {
66
+ return { tag: 'devices', attrs: { version: '2' } }
67
+ }
68
+ getUserElement() {
69
+
70
+ return null
71
+ }
72
+ parser(node) {
73
+ const deviceList = []
74
+ let keyIndex
75
+ if (node.tag === 'devices') {
76
+ assertNodeErrorFree(node)
77
+ const deviceListNode = getBinaryNodeChild(node, 'device-list')
78
+ const keyIndexNode = getBinaryNodeChild(node, 'key-index-list')
79
+ if (Array.isArray(deviceListNode?.content)) {
80
+ for (const { tag, attrs } of deviceListNode.content) {
81
+ const id = +attrs.id
82
+ const ki = +attrs['key-index']
83
+ if (tag === 'device') deviceList.push({ id, keyIndex: ki, isHosted: !!(attrs['is_hosted'] && attrs['is_hosted'] === 'true') })
84
+ }
85
+ }
86
+ if (keyIndexNode?.tag === 'key-index-list') {
87
+ keyIndex = {
88
+ timestamp: +keyIndexNode.attrs['ts'],
89
+ signedKeyIndex: keyIndexNode?.content,
90
+ expectedTimestamp: keyIndexNode.attrs['expected_ts'] ? +keyIndexNode.attrs['expected_ts'] : undefined
91
+ }
92
+ }
93
+ }
94
+ return { deviceList, keyIndex }
95
+ }
96
+ }
97
+
98
+ export class USyncDisappearingModeProtocol {
99
+ constructor() {
100
+ this.name = 'disappearing_mode'
101
+ }
102
+ getQueryElement() {
103
+ return { tag: 'disappearing_mode', attrs: {} }
104
+ }
105
+ getUserElement() {
106
+ return null
107
+ }
108
+ parser(node) {
109
+ if (node.tag === 'disappearing_mode') {
110
+ assertNodeErrorFree(node)
111
+ const duration = +node?.attrs.duration
112
+ const setAt = new Date(+(node?.attrs.t || 0) * 1000)
113
+ return { duration, setAt }
114
+ }
115
+ }
116
+ }
117
+
118
+ export class USyncStatusProtocol {
119
+ constructor() {
120
+ this.name = 'status'
121
+ }
122
+ getQueryElement() {
123
+ return { tag: 'status', attrs: {} }
124
+ }
125
+ getUserElement() {
126
+ return null
127
+ }
128
+ parser(node) {
129
+ if (node.tag === 'status') {
130
+ assertNodeErrorFree(node)
131
+ let status = node?.content?.toString() ?? null
132
+ const setAt = new Date(+(node?.attrs.t || 0) * 1000)
133
+ if (!status) status = node.attrs?.code && +node.attrs.code === 401 ? '' : null
134
+ else if (typeof status === 'string' && status.length === 0) status = null
135
+ return { status, setAt }
136
+ }
137
+ }
138
+ }
139
+
140
+ export class USyncUsernameProtocol {
141
+ constructor() {
142
+ this.name = 'username'
143
+ }
144
+ getQueryElement() {
145
+ return { tag: 'username', attrs: {} }
146
+ }
147
+ getUserElement() {
148
+ return null
149
+ }
150
+ parser(node) {
151
+ if (node.tag === 'username') {
152
+ assertNodeErrorFree(node)
153
+ return typeof node.content === 'string' ? node.content : null
154
+ }
155
+ return null
156
+ }
157
+ }
158
+
159
+ export class USyncBotProfileProtocol {
160
+ constructor() {
161
+ this.name = 'bot'
162
+ }
163
+ getQueryElement() {
164
+ return { tag: 'bot', attrs: {}, content: [{ tag: 'profile', attrs: { v: '1' } }] }
165
+ }
166
+ getUserElement(user) {
167
+ return { tag: 'bot', attrs: {}, content: [{ tag: 'profile', attrs: { persona_id: user.personaId } }] }
168
+ }
169
+ parser(node) {
170
+ const botNode = getBinaryNodeChild(node, 'bot')
171
+ const profile = getBinaryNodeChild(botNode, 'profile')
172
+ const commandsNode = getBinaryNodeChild(profile, 'commands')
173
+ const promptsNode = getBinaryNodeChild(profile, 'prompts')
174
+ const commands = []
175
+ const prompts = []
176
+ for (const command of getBinaryNodeChildren(commandsNode, 'command')) {
177
+ commands.push({ name: getBinaryNodeChildString(command, 'name'), description: getBinaryNodeChildString(command, 'description') })
178
+ }
179
+ for (const prompt of getBinaryNodeChildren(promptsNode, 'prompt')) {
180
+ prompts.push(`${getBinaryNodeChildString(prompt, 'emoji')} ${getBinaryNodeChildString(prompt, 'text')}`)
181
+ }
182
+ return {
183
+ isDefault: !!getBinaryNodeChild(profile, 'default'),
184
+ jid: node.attrs.jid,
185
+ name: getBinaryNodeChildString(profile, 'name'),
186
+ attributes: getBinaryNodeChildString(profile, 'attributes'),
187
+ description: getBinaryNodeChildString(profile, 'description'),
188
+ category: getBinaryNodeChildString(profile, 'category'),
189
+ personaId: profile.attrs['persona_id'],
190
+ commandsDescription: getBinaryNodeChildString(commandsNode, 'description'),
191
+ commands,
192
+ prompts
193
+ }
194
+ }
195
+ }
196
+
197
+ export class USyncLIDProtocol {
198
+ constructor() {
199
+ this.name = 'lid'
200
+ }
201
+ getQueryElement() {
202
+ return { tag: 'lid', attrs: {} }
203
+ }
204
+ getUserElement(user) {
205
+ return user.lid ? { tag: 'lid', attrs: { jid: user.lid } } : null
206
+ }
207
+ parser(node) {
208
+ return node.tag === 'lid' ? node.attrs.val : null
209
+ }
210
+ }
211
+
212
+ export class USyncQuery {
213
+ constructor() {
214
+ this.protocols = []
215
+ this.users = []
216
+ this.context = 'interactive'
217
+ this.mode = 'query'
218
+ }
219
+ withMode(mode) {
220
+ this.mode = mode
221
+ return this
222
+ }
223
+ withContext(context) {
224
+ this.context = context
225
+ return this
226
+ }
227
+ withUser(user) {
228
+ this.users.push(user)
229
+ return this
230
+ }
231
+ parseUSyncQueryResult(result) {
232
+ if (result?.attrs.type !== 'result') return
233
+ const protocolMap = Object.fromEntries(this.protocols.map(protocol => [protocol.name, protocol.parser]))
234
+ const queryResult = { list: [], sideList: [] }
235
+ const usyncNode = getBinaryNodeChild(result, 'usync')
236
+ const listNode = usyncNode ? getBinaryNodeChild(usyncNode, 'list') : undefined
237
+ if (listNode?.content && Array.isArray(listNode.content)) {
238
+ queryResult.list = listNode.content.reduce((acc, node) => {
239
+ const id = node?.attrs.jid
240
+ if (id) {
241
+ const data = Array.isArray(node?.content)
242
+ ? Object.fromEntries(
243
+ node.content
244
+ .map(content => {
245
+ const protocol = content.tag
246
+ const parser = protocolMap[protocol]
247
+ return parser ? [protocol, parser(content)] : [protocol, null]
248
+ })
249
+ .filter(([, b]) => b !== null)
250
+ )
251
+ : {}
252
+ acc.push({ ...data, id })
253
+ }
254
+ return acc
255
+ }, [])
256
+ }
257
+ return queryResult
258
+ }
259
+ withDeviceProtocol() {
260
+ this.protocols.push(new USyncDeviceProtocol())
261
+ return this
262
+ }
263
+ withContactProtocol() {
264
+ this.protocols.push(new USyncContactProtocol())
265
+ return this
266
+ }
267
+ withStatusProtocol() {
268
+ this.protocols.push(new USyncStatusProtocol())
269
+ return this
270
+ }
271
+ withDisappearingModeProtocol() {
272
+ this.protocols.push(new USyncDisappearingModeProtocol())
273
+ return this
274
+ }
275
+ withBotProfileProtocol() {
276
+ this.protocols.push(new USyncBotProfileProtocol())
277
+ return this
278
+ }
279
+ withLIDProtocol() {
280
+ this.protocols.push(new USyncLIDProtocol())
281
+ return this
282
+ }
283
+ withUsernameProtocol() {
284
+ this.protocols.push(new USyncUsernameProtocol())
285
+ return this
286
+ }
287
+ }
@@ -0,0 +1,344 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { isIP, connect as connectTcp } from 'node:net'
3
+ import { connect as connectTls } from 'node:tls'
4
+
5
+ const GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
6
+ const MAX_MESSAGE_BYTES = 64 * 1024 * 1024
7
+ const MAX_HANDSHAKE_BYTES = 16 * 1024
8
+ const CLOSE_TIMEOUT_MS = 5000
9
+ const TOKEN = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/
10
+ const FORBIDDEN_HEADERS = new Set([
11
+ 'host', 'upgrade', 'connection', 'content-length', 'transfer-encoding',
12
+ 'sec-websocket-key', 'sec-websocket-version', 'sec-websocket-accept', 'sec-websocket-extensions', 'sec-websocket-protocol'
13
+ ])
14
+ const OPCODE_CONTINUATION = 0x0
15
+ const OPCODE_TEXT = 0x1
16
+ const OPCODE_BINARY = 0x2
17
+ const OPCODE_CLOSE = 0x8
18
+ const OPCODE_PING = 0x9
19
+ const OPCODE_PONG = 0xa
20
+ const TEXT_DECODER = new TextDecoder('utf-8', { fatal: true })
21
+
22
+ const isValidCloseCode = code => (code >= 1000 && code <= 1014 && code !== 1004 && code !== 1005 && code !== 1006) || (code >= 3000 && code <= 4999)
23
+
24
+ const toArrayBuffer = buf => buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength)
25
+
26
+ const encodeFrame = (opcode, payload) => {
27
+ const length = payload.length
28
+ let header
29
+ if (length < 126) {
30
+ header = Buffer.alloc(2)
31
+ header[1] = 0x80 | length
32
+ } else if (length <= 0xffff) {
33
+ header = Buffer.alloc(4)
34
+ header[1] = 0x80 | 126
35
+ header.writeUInt16BE(length, 2)
36
+ } else {
37
+ header = Buffer.alloc(10)
38
+ header[1] = 0x80 | 127
39
+ header.writeBigUInt64BE(BigInt(length), 2)
40
+ }
41
+ header[0] = 0x80 | opcode
42
+ const mask = randomBytes(4)
43
+ const masked = Buffer.allocUnsafe(length)
44
+ for (let i = 0; i < length; i++) masked[i] = payload[i] ^ mask[i & 3]
45
+ return Buffer.concat([header, mask, masked])
46
+ }
47
+
48
+ export class NativeWebSocket {
49
+ static CONNECTING = 0
50
+ static OPEN = 1
51
+ static CLOSING = 2
52
+ static CLOSED = 3
53
+
54
+ #readyState = NativeWebSocket.CONNECTING
55
+ #socket = null
56
+ #buffer = Buffer.alloc(0)
57
+ #handshakeDone = false
58
+ #expectedAccept = ''
59
+ #fragments = null
60
+ #fragmentBytes = 0
61
+ #fragmentOpcode = 0
62
+ #closeSent = false
63
+ #closeTimer = null
64
+ #remoteClose = null
65
+ #failCode = null
66
+
67
+ constructor(url, options = {}) {
68
+ const target = new URL(url)
69
+ if (target.protocol !== 'ws:' && target.protocol !== 'wss:') throw new SyntaxError(`Unsupported WebSocket protocol: ${target.protocol}`)
70
+ this.url = target.href
71
+ this.binaryType = 'arraybuffer'
72
+ this.onopen = null
73
+ this.onmessage = null
74
+ this.onerror = null
75
+ this.onclose = null
76
+ this.#connect(target, options.headers ?? {})
77
+ }
78
+
79
+ get readyState() {
80
+ return this.#readyState
81
+ }
82
+
83
+ send(data) {
84
+ if (this.#readyState === NativeWebSocket.CONNECTING) throw new Error('InvalidStateError: Still in CONNECTING state')
85
+ if (this.#readyState !== NativeWebSocket.OPEN) return
86
+ const isText = typeof data === 'string'
87
+ let payload
88
+ if (isText) payload = Buffer.from(data, 'utf8')
89
+ else if (ArrayBuffer.isView(data)) payload = Buffer.from(data.buffer, data.byteOffset, data.byteLength)
90
+ else payload = Buffer.from(data)
91
+ this.#socket.write(encodeFrame(isText ? OPCODE_TEXT : OPCODE_BINARY, payload))
92
+ }
93
+
94
+ close(code, reason = '') {
95
+ if (this.#readyState === NativeWebSocket.CLOSING || this.#readyState === NativeWebSocket.CLOSED) return
96
+ if (code !== undefined && code !== 1000 && !(code >= 3000 && code <= 4999)) throw new TypeError(`InvalidAccessError: invalid close code ${code}`)
97
+ if (Buffer.byteLength(reason) > 123) throw new SyntaxError('Reason must be less than 123 bytes')
98
+ if (this.#readyState === NativeWebSocket.CONNECTING) {
99
+ this.#fire('onerror', { type: 'error', error: new Error('WebSocket was closed before the connection was established'), message: 'WebSocket was closed before the connection was established' })
100
+ this.#readyState = NativeWebSocket.CLOSING
101
+ this.#socket.destroy()
102
+ return
103
+ }
104
+ this.#readyState = NativeWebSocket.CLOSING
105
+ this.#sendClose(code, reason)
106
+ this.#scheduleDestroy()
107
+ }
108
+
109
+ #connect(target, headers) {
110
+ const secure = target.protocol === 'wss:'
111
+ const host = target.hostname.replace(/^\[(.*)\]$/, '$1')
112
+ const port = Number(target.port) || (secure ? 443 : 80)
113
+ const key = randomBytes(16).toString('base64')
114
+ this.#expectedAccept = createHash('sha1').update(key + GUID).digest('base64')
115
+ const lines = [
116
+ `GET ${target.pathname || '/'}${target.search} HTTP/1.1`,
117
+ `Host: ${target.port ? `${target.hostname}:${target.port}` : target.hostname}`,
118
+ 'Upgrade: websocket',
119
+ 'Connection: Upgrade',
120
+ `Sec-WebSocket-Key: ${key}`,
121
+ 'Sec-WebSocket-Version: 13'
122
+ ]
123
+ for (const [name, value] of Object.entries(headers)) {
124
+ if (value === undefined || value === null) continue
125
+ if (!TOKEN.test(name)) throw new TypeError(`Invalid header name: ${name}`)
126
+ const text = String(value)
127
+ if (/[\r\n\0]/.test(text)) throw new TypeError(`Invalid header value for ${name}`)
128
+ if (FORBIDDEN_HEADERS.has(name.toLowerCase())) continue
129
+ lines.push(`${name}: ${text}`)
130
+ }
131
+ const socket = secure
132
+ ? connectTls({ host, port, servername: isIP(host) ? undefined : host, ALPNProtocols: ['http/1.1'] })
133
+ : connectTcp({ host, port })
134
+ socket.setNoDelay(true)
135
+ socket.on('data', chunk => this.#onData(chunk))
136
+ socket.on('error', error => this.#onSocketError(error))
137
+ socket.on('close', () => this.#onSocketClose())
138
+ this.#socket = socket
139
+ socket.write(`${lines.join('\r\n')}\r\n\r\n`)
140
+ }
141
+
142
+ #onData(chunk) {
143
+ this.#buffer = this.#buffer.length ? Buffer.concat([this.#buffer, chunk]) : chunk
144
+ if (!this.#handshakeDone) {
145
+ const end = this.#buffer.indexOf('\r\n\r\n')
146
+ if (end === -1) {
147
+ if (this.#buffer.length > MAX_HANDSHAKE_BYTES) this.#abortHandshake(new Error('Handshake response too large'))
148
+ return
149
+ }
150
+ const head = this.#buffer.subarray(0, end).toString('latin1')
151
+ this.#buffer = this.#buffer.subarray(end + 4)
152
+ if (!this.#completeHandshake(head)) return
153
+ }
154
+ this.#parseFrames()
155
+ }
156
+
157
+ #completeHandshake(head) {
158
+ const [statusLine, ...headerLines] = head.split('\r\n')
159
+ const status = /^HTTP\/1\.[01] (\d{3})/.exec(statusLine)?.[1]
160
+ const reject = message => {
161
+ this.#abortHandshake(new Error(message))
162
+ return false
163
+ }
164
+ if (status !== '101') return reject(`Unexpected server response: ${status ?? 'invalid'}`)
165
+ const headers = new Map()
166
+ for (const line of headerLines) {
167
+ const i = line.indexOf(':')
168
+ if (i > 0) headers.set(line.slice(0, i).trim().toLowerCase(), line.slice(i + 1).trim())
169
+ }
170
+ const connection = (headers.get('connection') ?? '').toLowerCase().split(',').map(token => token.trim())
171
+ if (headers.get('upgrade')?.toLowerCase() !== 'websocket') return reject('Server did not set Upgrade header to "websocket".')
172
+ if (!connection.includes('upgrade')) return reject('Server did not set Connection header to "upgrade".')
173
+ if (headers.get('sec-websocket-accept') !== this.#expectedAccept) return reject('Incorrect hash received in Sec-WebSocket-Accept header.')
174
+ if (headers.get('sec-websocket-extensions')) return reject('Server negotiated an extension that was not requested.')
175
+ if (headers.get('sec-websocket-protocol')) return reject('Server negotiated a subprotocol that was not requested.')
176
+ this.#handshakeDone = true
177
+ this.#readyState = NativeWebSocket.OPEN
178
+ this.#fire('onopen', { type: 'open' })
179
+ return true
180
+ }
181
+
182
+ #abortHandshake(error) {
183
+ this.#fire('onerror', { type: 'error', error, message: error.message })
184
+ this.#socket.destroy()
185
+ }
186
+
187
+ #parseFrames() {
188
+ while (this.#buffer.length >= 2 && this.#readyState !== NativeWebSocket.CLOSED) {
189
+ const first = this.#buffer[0]
190
+ const second = this.#buffer[1]
191
+ const fin = (first & 0x80) !== 0
192
+ const opcode = first & 0x0f
193
+ const masked = (second & 0x80) !== 0
194
+ let length = second & 0x7f
195
+ let offset = 2
196
+ if (length === 126) {
197
+ if (this.#buffer.length < 4) return
198
+ length = this.#buffer.readUInt16BE(2)
199
+ offset = 4
200
+ } else if (length === 127) {
201
+ if (this.#buffer.length < 10) return
202
+ const big = this.#buffer.readBigUInt64BE(2)
203
+ if (big > BigInt(MAX_MESSAGE_BYTES)) return this.#failConnection(1009, 'Payload size exceeds maximum allowed size')
204
+ length = Number(big)
205
+ offset = 10
206
+ }
207
+ if (first & 0x70) return this.#failConnection(1002, 'RSV1, RSV2, RSV3 must be clear')
208
+ if (masked) return this.#failConnection(1002, 'Server frames must not be masked')
209
+ if (opcode >= 0x8 && (!fin || length > 125)) return this.#failConnection(1002, 'Invalid control frame')
210
+ if (length > MAX_MESSAGE_BYTES) return this.#failConnection(1009, 'Payload size exceeds maximum allowed size')
211
+ if (this.#buffer.length < offset + length) return
212
+ const payload = Buffer.from(this.#buffer.subarray(offset, offset + length))
213
+ this.#buffer = this.#buffer.subarray(offset + length)
214
+ this.#handleFrame(fin, opcode, payload)
215
+ }
216
+ }
217
+
218
+ #handleFrame(fin, opcode, payload) {
219
+ if (opcode === OPCODE_CONTINUATION && !this.#fragments) return this.#failConnection(1002, 'Unexpected continuation frame')
220
+ if ((opcode === OPCODE_TEXT || opcode === OPCODE_BINARY) && this.#fragments) return this.#failConnection(1002, 'Expected continuation frame')
221
+ switch (opcode) {
222
+ case OPCODE_CONTINUATION:
223
+ case OPCODE_TEXT:
224
+ case OPCODE_BINARY:
225
+ return this.#appendData(opcode, fin, payload)
226
+ case OPCODE_CLOSE:
227
+ return this.#handleClose(payload)
228
+ case OPCODE_PING:
229
+ if (this.#readyState === NativeWebSocket.OPEN) this.#socket.write(encodeFrame(OPCODE_PONG, payload))
230
+ return
231
+ case OPCODE_PONG:
232
+ return
233
+ default:
234
+ return this.#failConnection(1002, 'Invalid opcode received')
235
+ }
236
+ }
237
+
238
+ #appendData(opcode, fin, payload) {
239
+ if (opcode !== OPCODE_CONTINUATION) {
240
+ this.#fragments = []
241
+ this.#fragmentBytes = 0
242
+ this.#fragmentOpcode = opcode
243
+ }
244
+ this.#fragments.push(payload)
245
+ this.#fragmentBytes += payload.length
246
+ if (this.#fragmentBytes > MAX_MESSAGE_BYTES) return this.#failConnection(1009, 'Payload size exceeds maximum allowed size')
247
+ if (!fin) return
248
+ const message = this.#fragments.length === 1 ? this.#fragments[0] : Buffer.concat(this.#fragments, this.#fragmentBytes)
249
+ const messageOpcode = this.#fragmentOpcode
250
+ this.#fragments = null
251
+ this.#fragmentBytes = 0
252
+ if (messageOpcode === OPCODE_TEXT) {
253
+ let text
254
+ try {
255
+ text = TEXT_DECODER.decode(message)
256
+ } catch {
257
+ return this.#failConnection(1007, 'Invalid UTF-8')
258
+ }
259
+ this.#fire('onmessage', { type: 'message', data: text })
260
+ return
261
+ }
262
+ this.#fire('onmessage', { type: 'message', data: toArrayBuffer(message) })
263
+ }
264
+
265
+ #handleClose(payload) {
266
+ if (payload.length === 1) return this.#failConnection(1002, 'Received close frame with a 1-byte body.')
267
+ let code = 1005
268
+ let reason = ''
269
+ if (payload.length >= 2) {
270
+ code = payload.readUInt16BE(0)
271
+ if (!isValidCloseCode(code)) return this.#failConnection(1002, 'Invalid status code')
272
+ try {
273
+ reason = TEXT_DECODER.decode(payload.subarray(2))
274
+ } catch {
275
+ return this.#failConnection(1007, 'Invalid UTF-8')
276
+ }
277
+ }
278
+ this.#remoteClose = { code, reason }
279
+ this.#buffer = Buffer.alloc(0)
280
+ if (this.#readyState === NativeWebSocket.OPEN) this.#readyState = NativeWebSocket.CLOSING
281
+ this.#sendClose(payload.length >= 2 ? code : undefined, reason)
282
+ this.#socket.end()
283
+ this.#scheduleDestroy()
284
+ }
285
+
286
+ #failConnection(code, reason) {
287
+ if (this.#readyState === NativeWebSocket.CLOSED || this.#failCode !== null) return
288
+ this.#fire('onerror', { type: 'error', error: new Error(reason), message: reason })
289
+ this.#failCode = code
290
+ this.#buffer = Buffer.alloc(0)
291
+ this.#readyState = NativeWebSocket.CLOSING
292
+ this.#sendClose(code, reason)
293
+ this.#socket.end()
294
+ this.#scheduleDestroy()
295
+ }
296
+
297
+ #sendClose(code, reason = '') {
298
+ if (this.#closeSent || !this.#socket) return
299
+ this.#closeSent = true
300
+ let payload = Buffer.alloc(0)
301
+ if (code !== undefined) {
302
+ const text = Buffer.from(reason, 'utf8')
303
+ payload = Buffer.alloc(2 + text.length)
304
+ payload.writeUInt16BE(code, 0)
305
+ text.copy(payload, 2)
306
+ }
307
+ this.#socket.write(encodeFrame(OPCODE_CLOSE, payload))
308
+ }
309
+
310
+ #scheduleDestroy() {
311
+ if (this.#closeTimer || !this.#socket) return
312
+ this.#closeTimer = setTimeout(() => this.#socket?.destroy(), CLOSE_TIMEOUT_MS)
313
+ this.#closeTimer.unref?.()
314
+ }
315
+
316
+ #onSocketError(error) {
317
+ if (this.#readyState === NativeWebSocket.CLOSED) return
318
+ this.#fire('onerror', { type: 'error', error, message: error.message })
319
+ }
320
+
321
+ #onSocketClose() {
322
+ clearTimeout(this.#closeTimer)
323
+ this.#closeTimer = null
324
+ const code = this.#failCode ?? this.#remoteClose?.code ?? 1006
325
+ const reason = this.#failCode !== null ? '' : this.#remoteClose?.reason ?? ''
326
+ const wasClean = this.#remoteClose !== null && this.#failCode === null && this.#closeSent
327
+ this.#readyState = NativeWebSocket.CLOSED
328
+ this.#socket = null
329
+ this.#buffer = Buffer.alloc(0)
330
+ this.#fire('onclose', { type: 'close', code, reason, wasClean })
331
+ }
332
+
333
+ #fire(name, event) {
334
+ const handler = this[name]
335
+ if (typeof handler !== 'function') return
336
+ try {
337
+ handler.call(this, event)
338
+ } catch (error) {
339
+ queueMicrotask(() => {
340
+ throw error
341
+ })
342
+ }
343
+ }
344
+ }