@elysionjs/dylive-ws 0.0.0-stage → 0.1.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/LICENSE +22 -0
- package/README.md +71 -2
- package/dist/client-BJv32cEp.d.mts +63 -0
- package/dist/client-CQjW_f9V.mjs +188 -0
- package/dist/client-CQjW_f9V.mjs.map +1 -0
- package/dist/electron.d.mts +27 -0
- package/dist/electron.mjs +86 -0
- package/dist/electron.mjs.map +1 -0
- package/dist/index.d.mts +27 -0
- package/dist/index.mjs +336 -0
- package/dist/index.mjs.map +1 -0
- package/dist/parser-B2hsJb39.d.mts +30 -0
- package/dist/parser.d.mts +2 -0
- package/dist/parser.mjs +59 -0
- package/dist/parser.mjs.map +1 -0
- package/dist/protobuf-Dwp5TIr1.mjs +80 -0
- package/dist/protobuf-Dwp5TIr1.mjs.map +1 -0
- package/dist/protocol-B2FdR4E9.d.mts +16 -0
- package/dist/protocol.d.mts +2 -0
- package/dist/protocol.mjs +64 -0
- package/dist/protocol.mjs.map +1 -0
- package/package.json +85 -4
package/dist/index.mjs
ADDED
|
@@ -0,0 +1,336 @@
|
|
|
1
|
+
import { decodeCdpPayload, decodeFrame, decodeMessages } from "./protocol.mjs";
|
|
2
|
+
import { parseEvent } from "./parser.mjs";
|
|
3
|
+
import { n as timerDuration, t as LiveClient } from "./client-CQjW_f9V.mjs";
|
|
4
|
+
import { WebSocket } from "ws";
|
|
5
|
+
import { createHash, randomInt } from "node:crypto";
|
|
6
|
+
// src/api.ts
|
|
7
|
+
const liveOrigin = "https://live.douyin.com";
|
|
8
|
+
const webcastEndpoint = "wss://webcast100-ws-web-lf.douyin.com/webcast/im/push/v2/";
|
|
9
|
+
const browserVersion = "5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36";
|
|
10
|
+
const sdkVersion = "1.0.15";
|
|
11
|
+
const requestHeaders = {
|
|
12
|
+
"user-agent": `Mozilla/${browserVersion}`,
|
|
13
|
+
referer: `${liveOrigin}/`
|
|
14
|
+
};
|
|
15
|
+
async function resolveConnection(options) {
|
|
16
|
+
const pageUrl = new URL(`/${options.webRoomId}`, liveOrigin);
|
|
17
|
+
const headers = options.cookie ? {
|
|
18
|
+
...requestHeaders,
|
|
19
|
+
cookie: options.cookie
|
|
20
|
+
} : requestHeaders;
|
|
21
|
+
let response;
|
|
22
|
+
try {
|
|
23
|
+
response = await options.fetch(pageUrl, {
|
|
24
|
+
headers,
|
|
25
|
+
signal: options.signal,
|
|
26
|
+
redirect: "error"
|
|
27
|
+
});
|
|
28
|
+
} catch {
|
|
29
|
+
throw new Error("Could not request the Douyin live room page");
|
|
30
|
+
}
|
|
31
|
+
if (!response.ok) throw new Error(`Douyin live room page returned HTTP ${response.status}`);
|
|
32
|
+
const page = readLivePage(await response.text(), options.webRoomId);
|
|
33
|
+
const cookie = sessionCookie(options.cookie, response.headers);
|
|
34
|
+
const url = buildSocketUrl(page, options.sign);
|
|
35
|
+
return {
|
|
36
|
+
roomId: page.roomId,
|
|
37
|
+
url,
|
|
38
|
+
headers: {
|
|
39
|
+
...requestHeaders,
|
|
40
|
+
origin: liveOrigin,
|
|
41
|
+
...cookie ? { cookie } : {}
|
|
42
|
+
}
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function readLivePage(html, webRoomId) {
|
|
46
|
+
const state = html.replaceAll(/\\+"/g, "\"");
|
|
47
|
+
const room = /"roomInfo"\s*:\s*\{\s*"room"\s*:\s*\{\s*"id_str"\s*:\s*"([1-9]\d*)"\s*,\s*"status"\s*:\s*(\d+)/.exec(state);
|
|
48
|
+
const roomId = [...state.matchAll(/"roomId"\s*:\s*"([1-9]\d*)"\s*,\s*"web_rid"\s*:\s*"([1-9]\d*)"/g)].find((match) => match[2] === webRoomId)?.[1] ?? room?.[1];
|
|
49
|
+
if (!roomId) throw new Error("Douyin live room page did not return an internal room ID");
|
|
50
|
+
if (room && room[1] === roomId && room[2] === "4") throw new Error("Douyin live room is offline");
|
|
51
|
+
const userId = /"user_unique_id"\s*:\s*"?([1-9]\d*)/.exec(state)?.[1];
|
|
52
|
+
if (!userId) throw new Error("Douyin live room page did not return a viewer ID");
|
|
53
|
+
return {
|
|
54
|
+
roomId,
|
|
55
|
+
userId
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
function sessionCookie(cookie, headers) {
|
|
59
|
+
if (/(?:^|;\s*)ttwid=/.test(cookie)) return cookie;
|
|
60
|
+
const guest = headers.getSetCookie().find((value) => value.startsWith("ttwid="))?.split(";", 1)[0];
|
|
61
|
+
if (!guest) return cookie;
|
|
62
|
+
return cookie ? `${cookie}; ${guest}` : guest;
|
|
63
|
+
}
|
|
64
|
+
function buildSocketUrl({ roomId, userId }, sign) {
|
|
65
|
+
const url = new URL(webcastEndpoint);
|
|
66
|
+
const now = Date.now();
|
|
67
|
+
url.search = new URLSearchParams({
|
|
68
|
+
app_name: "douyin_web",
|
|
69
|
+
version_code: "180800",
|
|
70
|
+
webcast_sdk_version: sdkVersion,
|
|
71
|
+
update_version_code: sdkVersion,
|
|
72
|
+
compress: "gzip",
|
|
73
|
+
device_platform: "web",
|
|
74
|
+
cookie_enabled: "true",
|
|
75
|
+
screen_width: "1920",
|
|
76
|
+
screen_height: "1080",
|
|
77
|
+
browser_language: "zh-CN",
|
|
78
|
+
browser_platform: "Win32",
|
|
79
|
+
browser_name: "Mozilla",
|
|
80
|
+
browser_version: browserVersion,
|
|
81
|
+
browser_online: "true",
|
|
82
|
+
tz_name: "Asia/Shanghai",
|
|
83
|
+
cursor: `d-1_u-1_fh-0_t-${now}_r-1`,
|
|
84
|
+
internal_ext: `internal_src:dim|wss_push_room_id:${roomId}|wss_push_did:${userId}|first_req_ms:${now}|fetch_time:${now}|seq:1|wss_info:0-${now}-0-0`,
|
|
85
|
+
host: liveOrigin,
|
|
86
|
+
aid: "6383",
|
|
87
|
+
live_id: "1",
|
|
88
|
+
did_rule: "3",
|
|
89
|
+
endpoint: "live_pc",
|
|
90
|
+
support_wrds: "1",
|
|
91
|
+
user_unique_id: userId,
|
|
92
|
+
im_path: "/webcast/im/fetch/",
|
|
93
|
+
identity: "audience",
|
|
94
|
+
need_persist_msg_count: "15",
|
|
95
|
+
insert_task_id: "",
|
|
96
|
+
live_reason: "",
|
|
97
|
+
room_id: roomId,
|
|
98
|
+
heartbeatDuration: "0"
|
|
99
|
+
}).toString();
|
|
100
|
+
url.searchParams.set("signature", sign(url.searchParams));
|
|
101
|
+
return url.href;
|
|
102
|
+
}
|
|
103
|
+
// src/signature.ts
|
|
104
|
+
const signatureFields = [
|
|
105
|
+
"live_id",
|
|
106
|
+
"aid",
|
|
107
|
+
"version_code",
|
|
108
|
+
"webcast_sdk_version",
|
|
109
|
+
"room_id",
|
|
110
|
+
"sub_room_id",
|
|
111
|
+
"sub_channel_id",
|
|
112
|
+
"did_rule",
|
|
113
|
+
"user_unique_id",
|
|
114
|
+
"device_platform",
|
|
115
|
+
"device_type",
|
|
116
|
+
"ac",
|
|
117
|
+
"identity"
|
|
118
|
+
];
|
|
119
|
+
const base64Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
|
120
|
+
const webcastAlphabet = "Dkdpgh4ZKsQB80/Mfvw36XI1R25+WUAlEi7NLboqYTOPuzmFjJnryx9HVGcaStCe";
|
|
121
|
+
const emptyDigest = digest(digest(""));
|
|
122
|
+
function digest(value) {
|
|
123
|
+
return createHash("md5").update(value).digest();
|
|
124
|
+
}
|
|
125
|
+
function createWebcastSigner() {
|
|
126
|
+
let counter = 0;
|
|
127
|
+
return (query) => {
|
|
128
|
+
const stub = digest(signatureFields.map((name) => `${name}=${query.get(name) ?? ""}`).join(","));
|
|
129
|
+
counter = counter + 1 & 63;
|
|
130
|
+
return encodeSignature(stub, counter, randomInt(2) === 1, randomInt(255), randomInt(255));
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
function encodeSignature(stub, counter, flag, payloadRandom, key) {
|
|
134
|
+
const stubDigest = digest(stub);
|
|
135
|
+
const payload = Uint8Array.of(counter & 63, 0, 1, 14, emptyDigest[14], emptyDigest[15], stubDigest[14], stubDigest[15], payloadRandom, 0);
|
|
136
|
+
payload[9] = payload.reduce((checksum, byte) => checksum ^ byte, 0);
|
|
137
|
+
return Buffer.from([
|
|
138
|
+
flag ? 80 : 64,
|
|
139
|
+
key,
|
|
140
|
+
...legacyStreamCipher(payload, key)
|
|
141
|
+
]).toString("base64").replaceAll(/[A-Za-z0-9+/]/g, (char) => {
|
|
142
|
+
return webcastAlphabet[base64Alphabet.indexOf(char)];
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
function legacyStreamCipher(input, key) {
|
|
146
|
+
const state = Uint8Array.from({ length: 256 }, (_, index) => index);
|
|
147
|
+
let position = 0;
|
|
148
|
+
for (let index = 0; index < state.length; index++) {
|
|
149
|
+
position = position + state[index] + key & 255;
|
|
150
|
+
[state[index], state[position]] = [state[position], state[index]];
|
|
151
|
+
}
|
|
152
|
+
let index = 0;
|
|
153
|
+
position = 0;
|
|
154
|
+
return input.map((byte) => {
|
|
155
|
+
index = index + 1 & 255;
|
|
156
|
+
position = position + state[index] & 255;
|
|
157
|
+
[state[index], state[position]] = [state[position], state[index]];
|
|
158
|
+
return byte ^ state[state[index] + state[position] & 255];
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
// src/ws.ts
|
|
162
|
+
function createClient(options) {
|
|
163
|
+
const roomId = normalizeRoomId(options.roomId);
|
|
164
|
+
const { url } = options;
|
|
165
|
+
const connectTimeout = timerDuration(options.connectTimeout ?? 15e3, "connectTimeout");
|
|
166
|
+
const heartbeatInterval = timerDuration(options.heartbeatInterval ?? 5e3, "heartbeatInterval");
|
|
167
|
+
const sign = createWebcastSigner();
|
|
168
|
+
const fetcher = options.fetch ?? fetch;
|
|
169
|
+
if (roomId === void 0 && url === void 0) throw new TypeError("Provide a Douyin live room ID or WebSocket URL");
|
|
170
|
+
return new LiveClient({
|
|
171
|
+
...options,
|
|
172
|
+
roomId
|
|
173
|
+
}, async (session) => {
|
|
174
|
+
const preparation = AbortSignal.any([session.signal, AbortSignal.timeout(connectTimeout)]);
|
|
175
|
+
const cookie = await readCookie(options.cookie, preparation);
|
|
176
|
+
const connection = url === void 0 && roomId !== void 0 ? await abortable(resolveConnection({
|
|
177
|
+
webRoomId: roomId,
|
|
178
|
+
cookie,
|
|
179
|
+
fetch: fetcher,
|
|
180
|
+
signal: preparation,
|
|
181
|
+
sign
|
|
182
|
+
}), preparation) : await resolveUrl(url, cookie, preparation);
|
|
183
|
+
preparation.throwIfAborted();
|
|
184
|
+
session.onRoom(connection.roomId);
|
|
185
|
+
let socket;
|
|
186
|
+
try {
|
|
187
|
+
socket = options.createWebSocket ? options.createWebSocket(connection.url, { headers: connection.headers }) : new WebSocket(connection.url, {
|
|
188
|
+
headers: connection.headers,
|
|
189
|
+
handshakeTimeout: connectTimeout,
|
|
190
|
+
maxPayload: 16777216
|
|
191
|
+
});
|
|
192
|
+
} catch {
|
|
193
|
+
throw new Error("Could not create the Douyin WebSocket");
|
|
194
|
+
}
|
|
195
|
+
await openSocket(socket, session, connectTimeout, heartbeatInterval);
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
function normalizeRoomId(value) {
|
|
199
|
+
if (value === void 0) return;
|
|
200
|
+
if (typeof value === "number" && !Number.isSafeInteger(value)) throw new TypeError("roomId must use a string for integers outside the safe range");
|
|
201
|
+
const text = String(value);
|
|
202
|
+
if (!/^[1-9]\d{0,19}$/.test(text)) throw new TypeError("roomId must be a positive decimal ID");
|
|
203
|
+
return text;
|
|
204
|
+
}
|
|
205
|
+
async function readCookie(source, signal) {
|
|
206
|
+
try {
|
|
207
|
+
signal.throwIfAborted();
|
|
208
|
+
const value = typeof source === "function" ? source(signal) : source;
|
|
209
|
+
const cookie = await abortable(Promise.resolve(value), signal) ?? "";
|
|
210
|
+
if (typeof cookie !== "string" || /[\r\n\0]/.test(cookie)) throw new Error("Invalid Cookie");
|
|
211
|
+
return cookie;
|
|
212
|
+
} catch {
|
|
213
|
+
throw new Error("Douyin Cookie provider failed or was cancelled");
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
async function resolveUrl(source, cookie, signal) {
|
|
217
|
+
try {
|
|
218
|
+
signal.throwIfAborted();
|
|
219
|
+
const input = typeof source === "function" ? source(signal) : source;
|
|
220
|
+
const value = await abortable(Promise.resolve(input), signal);
|
|
221
|
+
const url = value && URL.parse(value);
|
|
222
|
+
if (!url || url.protocol !== "ws:" && url.protocol !== "wss:") throw new Error("Invalid WebSocket URL");
|
|
223
|
+
const headers = {};
|
|
224
|
+
if (cookie && url.protocol === "wss:" && url.hostname.endsWith(".douyin.com")) headers.cookie = cookie;
|
|
225
|
+
return {
|
|
226
|
+
url: url.href,
|
|
227
|
+
headers
|
|
228
|
+
};
|
|
229
|
+
} catch {
|
|
230
|
+
throw new Error("Could not resolve the Douyin WebSocket URL");
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
async function abortable(promise, signal) {
|
|
234
|
+
const abort = Promise.withResolvers();
|
|
235
|
+
const cancel = () => abort.reject(signal.reason);
|
|
236
|
+
const result = Promise.race([promise, abort.promise]);
|
|
237
|
+
signal.addEventListener("abort", cancel, { once: true });
|
|
238
|
+
if (signal.aborted) cancel();
|
|
239
|
+
try {
|
|
240
|
+
return await result;
|
|
241
|
+
} finally {
|
|
242
|
+
signal.removeEventListener("abort", cancel);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
async function openSocket(socket, session, timeout, heartbeatInterval) {
|
|
246
|
+
const done = Promise.withResolvers();
|
|
247
|
+
const deadline = setTimeout(() => done.reject(/* @__PURE__ */ new Error("WebSocket connection timed out")), timeout);
|
|
248
|
+
let heartbeat;
|
|
249
|
+
let awaitingPong = false;
|
|
250
|
+
function onOpen() {
|
|
251
|
+
clearTimeout(deadline);
|
|
252
|
+
session.onConnected();
|
|
253
|
+
session.onReady();
|
|
254
|
+
if (session.signal.aborted) return;
|
|
255
|
+
heartbeat = setInterval(() => {
|
|
256
|
+
if (awaitingPong) {
|
|
257
|
+
done.reject(/* @__PURE__ */ new Error("Douyin heartbeat timed out"));
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
awaitingPong = true;
|
|
261
|
+
socket.ping(Buffer.from([
|
|
262
|
+
58,
|
|
263
|
+
2,
|
|
264
|
+
104,
|
|
265
|
+
98
|
|
266
|
+
]), true, (error) => {
|
|
267
|
+
if (error) done.reject(/* @__PURE__ */ new Error("Could not send the Douyin heartbeat"));
|
|
268
|
+
});
|
|
269
|
+
}, heartbeatInterval);
|
|
270
|
+
}
|
|
271
|
+
function onMessage(data, isBinary) {
|
|
272
|
+
if (!isBinary || session.signal.aborted) return;
|
|
273
|
+
try {
|
|
274
|
+
const bytes = Array.isArray(data) ? Buffer.concat(data) : new Uint8Array(data);
|
|
275
|
+
const { messages, ack } = decodeFrame(bytes);
|
|
276
|
+
if (ack) socket.send(encodeAck(ack.logId, ack.payload));
|
|
277
|
+
session.onMessages(messages);
|
|
278
|
+
} catch {
|
|
279
|
+
session.onError(/* @__PURE__ */ new Error("Could not process the Douyin WebSocket message"));
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const onPong = () => {
|
|
283
|
+
awaitingPong = false;
|
|
284
|
+
};
|
|
285
|
+
const onClose = (code) => done.reject(/* @__PURE__ */ new Error(`WebSocket closed (code ${code})`));
|
|
286
|
+
const onError = () => done.reject(/* @__PURE__ */ new Error("Douyin WebSocket transport failed"));
|
|
287
|
+
const stop = () => done.resolve();
|
|
288
|
+
socket.on("open", onOpen);
|
|
289
|
+
socket.on("message", onMessage);
|
|
290
|
+
socket.on("pong", onPong);
|
|
291
|
+
socket.on("close", onClose);
|
|
292
|
+
socket.on("error", onError);
|
|
293
|
+
session.signal.addEventListener("abort", stop, { once: true });
|
|
294
|
+
if (session.signal.aborted) stop();
|
|
295
|
+
try {
|
|
296
|
+
await done.promise;
|
|
297
|
+
} finally {
|
|
298
|
+
clearTimeout(deadline);
|
|
299
|
+
clearInterval(heartbeat);
|
|
300
|
+
session.signal.removeEventListener("abort", stop);
|
|
301
|
+
socket.off("open", onOpen);
|
|
302
|
+
socket.off("message", onMessage);
|
|
303
|
+
socket.off("pong", onPong);
|
|
304
|
+
socket.off("close", onClose);
|
|
305
|
+
socket.off("error", onError);
|
|
306
|
+
socket.on("error", () => void 0);
|
|
307
|
+
socket.terminate();
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
function encodeAck(logId, payload) {
|
|
311
|
+
const header = Buffer.from([
|
|
312
|
+
16,
|
|
313
|
+
...varint(logId),
|
|
314
|
+
58,
|
|
315
|
+
3,
|
|
316
|
+
97,
|
|
317
|
+
99,
|
|
318
|
+
107,
|
|
319
|
+
66,
|
|
320
|
+
...varint(BigInt(payload.length))
|
|
321
|
+
]);
|
|
322
|
+
return Buffer.concat([header, payload]);
|
|
323
|
+
}
|
|
324
|
+
function varint(input) {
|
|
325
|
+
let value = input;
|
|
326
|
+
const bytes = [];
|
|
327
|
+
while (value > 127n) {
|
|
328
|
+
bytes.push(Number(value & 127n) | 128);
|
|
329
|
+
value >>= 7n;
|
|
330
|
+
}
|
|
331
|
+
bytes.push(Number(value));
|
|
332
|
+
return bytes;
|
|
333
|
+
}
|
|
334
|
+
export { LiveClient, createClient, decodeCdpPayload, decodeFrame, decodeMessages, parseEvent };
|
|
335
|
+
|
|
336
|
+
//# sourceMappingURL=index.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/api.ts","../src/signature.ts","../src/ws.ts"],"sourcesContent":["export type Fetcher = (url: string | URL, options?: RequestInit) => Promise<Response>;\n\nexport type CookieSource =\n | string\n | ((signal: AbortSignal) => string | null | undefined | Promise<string | null | undefined>);\n\ninterface RoomConnection {\n roomId: string;\n url: string;\n headers: Record<string, string>;\n}\n\ninterface ResolveOptions {\n webRoomId: string;\n cookie: string;\n fetch: Fetcher;\n signal: AbortSignal;\n sign: (query: URLSearchParams) => string;\n}\n\nconst liveOrigin = 'https://live.douyin.com';\nconst webcastEndpoint = 'wss://webcast100-ws-web-lf.douyin.com/webcast/im/push/v2/';\n\nconst browserVersion =\n '5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/142.0.0.0 Safari/537.36';\n\nconst sdkVersion = '1.0.15';\n\nconst requestHeaders = {\n 'user-agent': `Mozilla/${browserVersion}`,\n referer: `${liveOrigin}/`,\n};\n\nexport async function resolveConnection(options: ResolveOptions): Promise<RoomConnection> {\n const pageUrl = new URL(`/${options.webRoomId}`, liveOrigin);\n\n const headers = options.cookie ? { ...requestHeaders, cookie: options.cookie } : requestHeaders;\n\n let response: Response;\n\n try {\n response = await options.fetch(pageUrl, {\n headers,\n signal: options.signal,\n redirect: 'error',\n });\n } catch {\n throw new Error('Could not request the Douyin live room page');\n }\n\n if (!response.ok) {\n throw new Error(`Douyin live room page returned HTTP ${response.status}`);\n }\n\n const page = readLivePage(await response.text(), options.webRoomId);\n const cookie = sessionCookie(options.cookie, response.headers);\n const url = buildSocketUrl(page, options.sign);\n\n return {\n roomId: page.roomId,\n url,\n headers: { ...requestHeaders, origin: liveOrigin, ...(cookie ? { cookie } : {}) },\n };\n}\n\nexport function readLivePage(html: string, webRoomId: string): { roomId: string; userId: string } {\n // 抖音直播间将 SSR 状态装在带转义的脚本字符串中。\n const state = html.replaceAll(/\\\\+\"/g, '\"');\n\n const room =\n /\"roomInfo\"\\s*:\\s*\\{\\s*\"room\"\\s*:\\s*\\{\\s*\"id_str\"\\s*:\\s*\"([1-9]\\d*)\"\\s*,\\s*\"status\"\\s*:\\s*(\\d+)/.exec(\n state,\n );\n\n const adjacentRoom = /\"roomId\"\\s*:\\s*\"([1-9]\\d*)\"\\s*,\\s*\"web_rid\"\\s*:\\s*\"([1-9]\\d*)\"/g;\n const matched = [...state.matchAll(adjacentRoom)].find(match => match[2] === webRoomId);\n const roomId = matched?.[1] ?? room?.[1];\n\n if (!roomId) {\n throw new Error('Douyin live room page did not return an internal room ID');\n }\n\n if (room && room[1] === roomId && room[2] === '4') {\n throw new Error('Douyin live room is offline');\n }\n\n const userId = /\"user_unique_id\"\\s*:\\s*\"?([1-9]\\d*)/.exec(state)?.[1];\n\n if (!userId) {\n throw new Error('Douyin live room page did not return a viewer ID');\n }\n\n return { roomId, userId };\n}\n\nfunction sessionCookie(cookie: string, headers: Headers): string {\n if (/(?:^|;\\s*)ttwid=/.test(cookie)) {\n return cookie;\n }\n\n const guest = headers\n .getSetCookie()\n .find(value => value.startsWith('ttwid='))\n ?.split(';', 1)[0];\n\n if (!guest) {\n return cookie;\n }\n\n return cookie ? `${cookie}; ${guest}` : guest;\n}\n\nfunction buildSocketUrl(\n { roomId, userId }: { roomId: string; userId: string },\n sign: ResolveOptions['sign'],\n): string {\n const url = new URL(webcastEndpoint);\n const now = Date.now();\n\n url.search = new URLSearchParams({\n app_name: 'douyin_web',\n version_code: '180800',\n webcast_sdk_version: sdkVersion,\n update_version_code: sdkVersion,\n compress: 'gzip',\n device_platform: 'web',\n cookie_enabled: 'true',\n screen_width: '1920',\n screen_height: '1080',\n browser_language: 'zh-CN',\n browser_platform: 'Win32',\n browser_name: 'Mozilla',\n browser_version: browserVersion,\n browser_online: 'true',\n tz_name: 'Asia/Shanghai',\n cursor: `d-1_u-1_fh-0_t-${now}_r-1`,\n internal_ext: `internal_src:dim|wss_push_room_id:${roomId}|wss_push_did:${userId}|first_req_ms:${now}|fetch_time:${now}|seq:1|wss_info:0-${now}-0-0`,\n host: liveOrigin,\n aid: '6383',\n live_id: '1',\n did_rule: '3',\n endpoint: 'live_pc',\n support_wrds: '1',\n user_unique_id: userId,\n im_path: '/webcast/im/fetch/',\n identity: 'audience',\n need_persist_msg_count: '15',\n insert_task_id: '',\n live_reason: '',\n room_id: roomId,\n heartbeatDuration: '0',\n }).toString();\n url.searchParams.set('signature', sign(url.searchParams));\n\n return url.href;\n}\n","import { createHash, randomInt } from 'node:crypto';\n\n// 兼容网页端 Webcast 握手格式。参考 douyinLive/v2.3.2 的 MIT 实现。\nconst signatureFields = [\n 'live_id',\n 'aid',\n 'version_code',\n 'webcast_sdk_version',\n 'room_id',\n 'sub_room_id',\n 'sub_channel_id',\n 'did_rule',\n 'user_unique_id',\n 'device_platform',\n 'device_type',\n 'ac',\n 'identity',\n];\n\nconst base64Alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\nconst webcastAlphabet = 'Dkdpgh4ZKsQB80/Mfvw36XI1R25+WUAlEi7NLboqYTOPuzmFjJnryx9HVGcaStCe';\nconst emptyDigest = digest(digest(''));\n\nfunction digest(value: string | Uint8Array): Buffer {\n return createHash('md5').update(value).digest();\n}\n\nexport function createWebcastSigner(): (query: URLSearchParams) => string {\n let counter = 0;\n\n return query => {\n const fields = signatureFields.map(name => `${name}=${query.get(name) ?? ''}`);\n const stub = digest(fields.join(','));\n counter = (counter + 1) & 0x3f;\n\n return encodeSignature(stub, counter, randomInt(2) === 1, randomInt(255), randomInt(255));\n };\n}\n\nexport function encodeSignature(\n stub: Uint8Array,\n counter: number,\n flag: boolean,\n payloadRandom: number,\n key: number,\n): string {\n const stubDigest = digest(stub);\n\n const payload = Uint8Array.of(\n counter & 0x3f,\n 0,\n 1,\n 14,\n emptyDigest[14],\n emptyDigest[15],\n stubDigest[14],\n stubDigest[15],\n payloadRandom,\n 0,\n );\n\n payload[9] = payload.reduce((checksum, byte) => checksum ^ byte, 0);\n\n const bytes = Buffer.from([flag ? 0x50 : 0x40, key, ...legacyStreamCipher(payload, key)]);\n\n return bytes.toString('base64').replaceAll(/[A-Za-z0-9+/]/g, char => {\n return webcastAlphabet[base64Alphabet.indexOf(char)];\n });\n}\n\nfunction legacyStreamCipher(input: Uint8Array, key: number): Uint8Array {\n const state = Uint8Array.from({ length: 256 }, (_, index) => index);\n let position = 0;\n\n for (let index = 0; index < state.length; index++) {\n position = (position + state[index] + key) & 0xff;\n [state[index], state[position]] = [state[position], state[index]];\n }\n\n let index = 0;\n position = 0;\n\n return input.map(byte => {\n index = (index + 1) & 0xff;\n position = (position + state[index]) & 0xff;\n [state[index], state[position]] = [state[position], state[index]];\n\n return byte ^ state[(state[index] + state[position]) & 0xff];\n });\n}\n","import { WebSocket } from 'ws';\nimport type { RawData } from 'ws';\n\nimport { resolveConnection } from './api';\nimport type { CookieSource, Fetcher } from './api';\nimport { LiveClient, timerDuration } from './client';\nimport type { ClientLifecycleOptions, Session } from './client';\nimport { decodeFrame } from './protocol';\nimport { createWebcastSigner } from './signature';\n\ntype UrlSource = string | ((signal: AbortSignal) => string | Promise<string>);\n\ninterface WebSocketSettings {\n headers: Record<string, string>;\n}\n\ninterface TransportOptions extends Omit<ClientLifecycleOptions, 'roomId'> {\n cookie?: CookieSource;\n fetch?: Fetcher;\n createWebSocket?: (url: string, options: WebSocketSettings) => WebSocket;\n connectTimeout?: number;\n heartbeatInterval?: number;\n}\n\nexport type ClientOptions = TransportOptions &\n ({ roomId: string | number; url?: UrlSource } | { roomId?: never; url: UrlSource });\n\nexport function createClient(options: ClientOptions): LiveClient {\n const roomId = normalizeRoomId(options.roomId);\n const { url } = options;\n const connectTimeout = timerDuration(options.connectTimeout ?? 15_000, 'connectTimeout');\n const heartbeatInterval = timerDuration(options.heartbeatInterval ?? 5000, 'heartbeatInterval');\n const sign = createWebcastSigner();\n const fetcher = options.fetch ?? fetch;\n\n if (roomId === undefined && url === undefined) {\n throw new TypeError('Provide a Douyin live room ID or WebSocket URL');\n }\n\n return new LiveClient({ ...options, roomId }, async session => {\n const preparation = AbortSignal.any([session.signal, AbortSignal.timeout(connectTimeout)]);\n const cookie = await readCookie(options.cookie, preparation);\n\n const connection =\n url === undefined && roomId !== undefined\n ? await abortable(\n resolveConnection({\n webRoomId: roomId,\n cookie,\n fetch: fetcher,\n signal: preparation,\n sign,\n }),\n preparation,\n )\n : await resolveUrl(url, cookie, preparation);\n\n preparation.throwIfAborted();\n session.onRoom(connection.roomId);\n let socket: WebSocket;\n\n try {\n socket = options.createWebSocket\n ? options.createWebSocket(connection.url, { headers: connection.headers })\n : new WebSocket(connection.url, {\n headers: connection.headers,\n handshakeTimeout: connectTimeout,\n maxPayload: 16 * 1024 * 1024,\n });\n } catch {\n throw new Error('Could not create the Douyin WebSocket');\n }\n\n await openSocket(socket, session, connectTimeout, heartbeatInterval);\n });\n}\n\nfunction normalizeRoomId(value: string | number | undefined): string | undefined {\n if (value === undefined) {\n return undefined;\n }\n\n if (typeof value === 'number' && !Number.isSafeInteger(value)) {\n throw new TypeError('roomId must use a string for integers outside the safe range');\n }\n\n const text = String(value);\n\n if (!/^[1-9]\\d{0,19}$/.test(text)) {\n throw new TypeError('roomId must be a positive decimal ID');\n }\n\n return text;\n}\n\nasync function readCookie(source: CookieSource | undefined, signal: AbortSignal): Promise<string> {\n try {\n signal.throwIfAborted();\n const value = typeof source === 'function' ? source(signal) : source;\n const cookie = (await abortable(Promise.resolve(value), signal)) ?? '';\n\n if (typeof cookie !== 'string' || /[\\r\\n\\0]/.test(cookie)) {\n throw new Error('Invalid Cookie');\n }\n\n return cookie;\n } catch {\n throw new Error('Douyin Cookie provider failed or was cancelled');\n }\n}\n\nasync function resolveUrl(\n source: UrlSource | undefined,\n cookie: string,\n signal: AbortSignal,\n): Promise<{\n url: string;\n headers: Record<string, string>;\n roomId?: string;\n}> {\n try {\n signal.throwIfAborted();\n const input = typeof source === 'function' ? source(signal) : source;\n const value = await abortable(Promise.resolve(input), signal);\n const url = value && URL.parse(value);\n\n if (!url || (url.protocol !== 'ws:' && url.protocol !== 'wss:')) {\n throw new Error('Invalid WebSocket URL');\n }\n\n const headers: Record<string, string> = {};\n\n if (cookie && url.protocol === 'wss:' && url.hostname.endsWith('.douyin.com')) {\n headers.cookie = cookie;\n }\n\n return { url: url.href, headers };\n } catch {\n // 地址提供方抛出的错误可能带有签名或登录凭据。\n throw new Error('Could not resolve the Douyin WebSocket URL');\n }\n}\n\nasync function abortable<T>(promise: Promise<T>, signal: AbortSignal): Promise<T> {\n const abort = Promise.withResolvers<never>();\n const cancel = () => abort.reject(signal.reason);\n const result = Promise.race([promise, abort.promise]);\n\n signal.addEventListener('abort', cancel, { once: true });\n\n if (signal.aborted) {\n cancel();\n }\n\n try {\n return await result;\n } finally {\n signal.removeEventListener('abort', cancel);\n }\n}\n\nasync function openSocket(\n socket: WebSocket,\n session: Session,\n timeout: number,\n heartbeatInterval: number,\n): Promise<void> {\n const done = Promise.withResolvers<void>();\n\n const deadline = setTimeout(\n () => done.reject(new Error('WebSocket connection timed out')),\n timeout,\n );\n\n let heartbeat: ReturnType<typeof setInterval> | undefined;\n let awaitingPong = false;\n\n function onOpen(): void {\n clearTimeout(deadline);\n session.onConnected();\n session.onReady();\n\n if (session.signal.aborted) {\n return;\n }\n\n heartbeat = setInterval(() => {\n if (awaitingPong) {\n done.reject(new Error('Douyin heartbeat timed out'));\n\n return;\n }\n\n awaitingPong = true;\n socket.ping(Buffer.from([0x3a, 0x02, 0x68, 0x62]), true, error => {\n if (error) {\n done.reject(new Error('Could not send the Douyin heartbeat'));\n }\n });\n }, heartbeatInterval);\n }\n\n function onMessage(data: RawData, isBinary: boolean): void {\n if (!isBinary || session.signal.aborted) {\n return;\n }\n\n try {\n const bytes = Array.isArray(data) ? Buffer.concat(data) : new Uint8Array(data);\n const { messages, ack } = decodeFrame(bytes);\n\n if (ack) {\n socket.send(encodeAck(ack.logId, ack.payload));\n }\n\n session.onMessages(messages);\n } catch {\n session.onError(new Error('Could not process the Douyin WebSocket message'));\n }\n }\n\n const onPong = () => {\n awaitingPong = false;\n };\n\n const onClose = (code: number) => done.reject(new Error(`WebSocket closed (code ${code})`));\n const onError = () => done.reject(new Error('Douyin WebSocket transport failed'));\n const stop = () => done.resolve();\n socket.on('open', onOpen);\n socket.on('message', onMessage);\n socket.on('pong', onPong);\n socket.on('close', onClose);\n socket.on('error', onError);\n session.signal.addEventListener('abort', stop, { once: true });\n\n if (session.signal.aborted) {\n stop();\n }\n\n try {\n await done.promise;\n } finally {\n clearTimeout(deadline);\n clearInterval(heartbeat);\n session.signal.removeEventListener('abort', stop);\n socket.off('open', onOpen);\n socket.off('message', onMessage);\n socket.off('pong', onPong);\n socket.off('close', onClose);\n socket.off('error', onError);\n socket.on('error', () => undefined);\n socket.terminate();\n }\n}\n\nfunction encodeAck(logId: bigint, payload: Uint8Array): Buffer {\n const header = Buffer.from([\n 0x10,\n ...varint(logId),\n 0x3a,\n 0x03,\n 0x61,\n 0x63,\n 0x6b,\n 0x42,\n ...varint(BigInt(payload.length)),\n ]);\n\n return Buffer.concat([header, payload]);\n}\n\nfunction varint(input: bigint): number[] {\n let value = input;\n const bytes: number[] = [];\n\n while (value > 0x7fn) {\n bytes.push(Number(value & 0x7fn) | 0x80);\n value >>= 7n;\n }\n\n bytes.push(Number(value));\n\n return bytes;\n}\n"],"mappings":";;;;;;AAoBA,MAAM,aAAa;AACnB,MAAM,kBAAkB;AAExB,MAAM,iBACJ;AAEF,MAAM,aAAa;AAEnB,MAAM,iBAAiB;CACrB,cAAc,WAAW;CACzB,SAAS,GAAG,WAAW;AACzB;AAEA,eAAsB,kBAAkB,SAAkD;CACxF,MAAM,UAAU,IAAI,IAAI,IAAI,QAAQ,aAAa,UAAU;CAE3D,MAAM,UAAU,QAAQ,SAAS;EAAE,GAAG;EAAgB,QAAQ,QAAQ;CAAO,IAAI;CAEjF,IAAI;CAEJ,IAAI;EACF,WAAW,MAAM,QAAQ,MAAM,SAAS;GACtC;GACA,QAAQ,QAAQ;GAChB,UAAU;EACZ,CAAC;CACH,QAAQ;EACN,MAAM,IAAI,MAAM,6CAA6C;CAC/D;CAEA,IAAI,CAAC,SAAS,IACZ,MAAM,IAAI,MAAM,uCAAuC,SAAS,QAAQ;CAG1E,MAAM,OAAO,aAAa,MAAM,SAAS,KAAK,GAAG,QAAQ,SAAS;CAClE,M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O,oBAAoB,SAAS,IAAI;EAChD,OAAO,IAAI,QAAQ,MAAM;EACzB,OAAO,IAAI,WAAW,SAAS;EAC/B,OAAO,IAAI,QAAQ,MAAM;EACzB,OAAO,IAAI,SAAS,OAAO;EAC3B,OAAO,IAAI,SAAS,OAAO;EAC3B,OAAO,GAAG,eAAe,KAAA,CAAS;EAClC,OAAO,UAAU;CACnB;AACF;AAEA,SAAS,UAAU,OAAe,SAA6B;CAC7D,MAAM,SAAS,OAAO,KAAK;EACzB;EACA,GAAG,OAAO,KAAK;EACf;EACA;EACA;EACA;EACA;EACA;EACA,GAAG,OAAO,OAAO,QAAQ,MAAM,CAAC;CAClC,CAAC;CAED,OAAO,OAAO,OAAO,CAAC,QAAQ,OAAO,CAAC;AACxC;AAEA,SAAS,OAAO,OAAyB;CACvC,IAAI,QAAQ;CACZ,MAAM,QAAkB,CAAC;CAEzB,OAAO,QAAQ,MAAO;EACpB,MAAM,KAAK,OAAO,QAAQ,IAAK,IAAI,GAAI;EACvC,UAAU;CACZ;CAEA,MAAM,KAAK,OAAO,KAAK,CAAC;CAExB,OAAO;AACT"}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { t as RawMessage } from "./protocol-B2FdR4E9.mjs";
|
|
2
|
+
interface ChatEvent {
|
|
3
|
+
type: 'message';
|
|
4
|
+
content: string;
|
|
5
|
+
user: {
|
|
6
|
+
name: string;
|
|
7
|
+
id?: string;
|
|
8
|
+
};
|
|
9
|
+
id?: string;
|
|
10
|
+
roomId?: string;
|
|
11
|
+
platformTime?: string;
|
|
12
|
+
}
|
|
13
|
+
interface ParseContext {
|
|
14
|
+
roomId?: string;
|
|
15
|
+
}
|
|
16
|
+
type ParseResult = {
|
|
17
|
+
status: 'parsed';
|
|
18
|
+
event: ChatEvent;
|
|
19
|
+
raw: RawMessage;
|
|
20
|
+
} | {
|
|
21
|
+
status: 'unknown';
|
|
22
|
+
raw: RawMessage;
|
|
23
|
+
} | {
|
|
24
|
+
status: 'mismatch';
|
|
25
|
+
raw: RawMessage;
|
|
26
|
+
issue: string;
|
|
27
|
+
};
|
|
28
|
+
declare function parseEvent(raw: RawMessage, context?: ParseContext): ParseResult;
|
|
29
|
+
export { parseEvent as i, ParseContext as n, ParseResult as r, ChatEvent as t };
|
|
30
|
+
//# sourceMappingURL=parser-B2hsJb39.d.mts.map
|
package/dist/parser.mjs
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { t as ProtoMessage } from "./protobuf-Dwp5TIr1.mjs";
|
|
2
|
+
// src/parser.ts
|
|
3
|
+
function parseEvent(raw, context = {}) {
|
|
4
|
+
if (raw.method !== "WebcastChatMessage") return {
|
|
5
|
+
status: "unknown",
|
|
6
|
+
raw
|
|
7
|
+
};
|
|
8
|
+
try {
|
|
9
|
+
return {
|
|
10
|
+
status: "parsed",
|
|
11
|
+
raw,
|
|
12
|
+
event: parseChat(raw, context)
|
|
13
|
+
};
|
|
14
|
+
} catch (error) {
|
|
15
|
+
return {
|
|
16
|
+
status: "mismatch",
|
|
17
|
+
raw,
|
|
18
|
+
issue: error instanceof Error ? error.message : String(error)
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function parseChat(raw, context) {
|
|
23
|
+
const chat = new ProtoMessage(raw.payload, [
|
|
24
|
+
1,
|
|
25
|
+
2,
|
|
26
|
+
3
|
|
27
|
+
]);
|
|
28
|
+
const content = chat.string(3);
|
|
29
|
+
if (content === void 0) throw new Error("Missing chat text in protobuf field 3");
|
|
30
|
+
const userBytes = chat.dataField(2);
|
|
31
|
+
const user = new ProtoMessage(userBytes ?? /* @__PURE__ */ new Uint8Array(), [
|
|
32
|
+
1,
|
|
33
|
+
3,
|
|
34
|
+
1028
|
|
35
|
+
]);
|
|
36
|
+
const commonBytes = chat.dataField(1);
|
|
37
|
+
const common = commonBytes && new ProtoMessage(commonBytes, [
|
|
38
|
+
2,
|
|
39
|
+
3,
|
|
40
|
+
4
|
|
41
|
+
]);
|
|
42
|
+
return {
|
|
43
|
+
type: "message",
|
|
44
|
+
content,
|
|
45
|
+
user: {
|
|
46
|
+
name: user.string(3) ?? "",
|
|
47
|
+
id: nonzero(user.string(1028)) ?? nonzero(user.uint64(1))
|
|
48
|
+
},
|
|
49
|
+
id: nonzero(raw.id) ?? nonzero(common?.uint64(2)),
|
|
50
|
+
roomId: nonzero(common?.uint64(3)) ?? context.roomId,
|
|
51
|
+
platformTime: nonzero(common?.uint64(4))
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
function nonzero(value) {
|
|
55
|
+
return value && value !== "0" ? value : void 0;
|
|
56
|
+
}
|
|
57
|
+
export { parseEvent };
|
|
58
|
+
|
|
59
|
+
//# sourceMappingURL=parser.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"parser.mjs","names":[],"sources":["../src/parser.ts"],"sourcesContent":["import { ProtoMessage } from './protobuf';\nimport type { RawMessage } from './protocol';\n\nexport interface ChatEvent {\n type: 'message';\n content: string;\n user: {\n name: string;\n id?: string;\n };\n id?: string;\n roomId?: string;\n platformTime?: string;\n}\n\nexport interface ParseContext {\n roomId?: string;\n}\n\nexport type ParseResult =\n | { status: 'parsed'; event: ChatEvent; raw: RawMessage }\n | { status: 'unknown'; raw: RawMessage }\n | { status: 'mismatch'; raw: RawMessage; issue: string };\n\nexport function parseEvent(raw: RawMessage, context: ParseContext = {}): ParseResult {\n if (raw.method !== 'WebcastChatMessage') {\n return { status: 'unknown', raw };\n }\n\n try {\n return { status: 'parsed', raw, event: parseChat(raw, context) };\n } catch (error) {\n return {\n status: 'mismatch',\n raw,\n issue: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nfunction parseChat(raw: RawMessage, context: ParseContext): ChatEvent {\n const chat = new ProtoMessage(raw.payload, [1, 2, 3]);\n const content = chat.string(3);\n\n if (content === undefined) {\n throw new Error('Missing chat text in protobuf field 3');\n }\n\n const userBytes = chat.dataField(2);\n const user = new ProtoMessage(userBytes ?? new Uint8Array(), [1, 3, 1028]);\n const commonBytes = chat.dataField(1);\n const common = commonBytes && new ProtoMessage(commonBytes, [2, 3, 4]);\n\n return {\n type: 'message',\n content,\n user: {\n name: user.string(3) ?? '',\n id: nonzero(user.string(1028)) ?? nonzero(user.uint64(1)),\n },\n id: nonzero(raw.id) ?? nonzero(common?.uint64(2)),\n roomId: nonzero(common?.uint64(3)) ?? context.roomId,\n platformTime: nonzero(common?.uint64(4)),\n };\n}\n\nfunction nonzero(value: string | undefined): string | undefined {\n return value && value !== '0' ? value : undefined;\n}\n"],"mappings":";;AAwBA,SAAgB,WAAW,KAAiB,UAAwB,CAAC,GAAgB;CACnF,IAAI,IAAI,WAAW,sBACjB,OAAO;EAAE,QAAQ;EAAW;CAAI;CAGlC,IAAI;EACF,OAAO;GAAE,QAAQ;GAAU;GAAK,OAAO,UAAU,KAAK,OAAO;EAAE;CACjE,SAAS,OAAO;EACd,OAAO;GACL,QAAQ;GACR;GACA,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAC9D;CACF;AACF;AAEA,SAAS,UAAU,KAAiB,SAAkC;CACpE,MAAM,OAAO,IAAI,aAAa,IAAI,SAAS;EAAC;EAAG;EAAG;CAAC,CAAC;CACpD,MAAM,UAAU,KAAK,OAAO,CAAC;CAE7B,IAAI,YAAY,KAAA,GACd,MAAM,IAAI,MAAM,uCAAuC;CAGzD,MAAM,YAAY,KAAK,UAAU,CAAC;CAClC,MAAM,OAAO,IAAI,aAAa,6BAAa,IAAI,WAAW,GAAG;EAAC;EAAG;EAAG;CAAI,CAAC;CACzE,MAAM,cAAc,KAAK,UAAU,CAAC;CACpC,MAAM,SAAS,eAAe,IAAI,aAAa,aAAa;EAAC;EAAG;EAAG;CAAC,CAAC;CAErE,OAAO;EACL,MAAM;EACN;EACA,MAAM;GACJ,MAAM,KAAK,OAAO,CAAC,KAAK;GACxB,IAAI,QAAQ,KAAK,OAAO,IAAI,CAAC,KAAK,QAAQ,KAAK,OAAO,CAAC,CAAC;EAC1D;EACA,IAAI,QAAQ,IAAI,EAAE,KAAK,QAAQ,QAAQ,OAAO,CAAC,CAAC;EAChD,QAAQ,QAAQ,QAAQ,OAAO,CAAC,CAAC,KAAK,QAAQ;EAC9C,cAAc,QAAQ,QAAQ,OAAO,CAAC,CAAC;CACzC;AACF;AAEA,SAAS,QAAQ,OAA+C;CAC9D,OAAO,SAAS,UAAU,MAAM,QAAQ,KAAA;AAC1C"}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// src/protobuf.ts
|
|
2
|
+
const textDecoder = new TextDecoder("utf-8", { fatal: true });
|
|
3
|
+
var ProtoMessage = class {
|
|
4
|
+
data;
|
|
5
|
+
offset = 0;
|
|
6
|
+
fields = /* @__PURE__ */ new Map();
|
|
7
|
+
constructor(data, wanted) {
|
|
8
|
+
this.data = data;
|
|
9
|
+
while (this.offset < data.length) {
|
|
10
|
+
const tag = this.varint();
|
|
11
|
+
const field = Number(tag >> 3n);
|
|
12
|
+
const wireType = Number(tag & 7n);
|
|
13
|
+
if (field < 1 || field > 536870911) throw new Error("Invalid protobuf field number");
|
|
14
|
+
const value = wireType === 0 ? this.varint() : this.bytes(wireType);
|
|
15
|
+
if (!wanted.includes(field)) continue;
|
|
16
|
+
const values = this.fields.get(field);
|
|
17
|
+
if (values) values.push({
|
|
18
|
+
wireType,
|
|
19
|
+
value
|
|
20
|
+
});
|
|
21
|
+
else this.fields.set(field, [{
|
|
22
|
+
wireType,
|
|
23
|
+
value
|
|
24
|
+
}]);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
uint64(field) {
|
|
28
|
+
const value = this.fields.get(field)?.at(-1);
|
|
29
|
+
if (!value) return;
|
|
30
|
+
if (value.wireType !== 0) throw new Error(`Expected a protobuf varint in field ${field}`);
|
|
31
|
+
return value.value.toString();
|
|
32
|
+
}
|
|
33
|
+
string(field) {
|
|
34
|
+
const value = this.dataField(field);
|
|
35
|
+
return value && textDecoder.decode(value);
|
|
36
|
+
}
|
|
37
|
+
dataField(field) {
|
|
38
|
+
const value = this.fields.get(field)?.at(-1);
|
|
39
|
+
return value && this.expectBytes(value, field);
|
|
40
|
+
}
|
|
41
|
+
repeatedBytes(field) {
|
|
42
|
+
return (this.fields.get(field) ?? []).map((value) => this.expectBytes(value, field));
|
|
43
|
+
}
|
|
44
|
+
expectBytes(field, number) {
|
|
45
|
+
if (field.wireType !== 2 || typeof field.value === "bigint") throw new Error(`Expected protobuf bytes in field ${number}`);
|
|
46
|
+
return field.value;
|
|
47
|
+
}
|
|
48
|
+
varint() {
|
|
49
|
+
let result = 0n;
|
|
50
|
+
for (let index = 0; index < 10; index++) {
|
|
51
|
+
const byte = this.data[this.offset++];
|
|
52
|
+
if (byte === void 0 || index === 9 && byte > 1) throw new Error("Invalid protobuf uint64 varint");
|
|
53
|
+
result |= BigInt(byte & 127) << BigInt(index * 7);
|
|
54
|
+
if (byte < 128) return result;
|
|
55
|
+
}
|
|
56
|
+
throw new Error("Invalid protobuf uint64 varint");
|
|
57
|
+
}
|
|
58
|
+
bytes(wireType) {
|
|
59
|
+
let length;
|
|
60
|
+
switch (wireType) {
|
|
61
|
+
case 1:
|
|
62
|
+
length = 8;
|
|
63
|
+
break;
|
|
64
|
+
case 2:
|
|
65
|
+
length = Number(this.varint());
|
|
66
|
+
break;
|
|
67
|
+
case 5:
|
|
68
|
+
length = 4;
|
|
69
|
+
break;
|
|
70
|
+
default: throw new Error(`Unsupported protobuf wire type ${wireType}`);
|
|
71
|
+
}
|
|
72
|
+
if (length > this.data.length - this.offset) throw new Error("Truncated protobuf field");
|
|
73
|
+
const value = this.data.subarray(this.offset, this.offset + length);
|
|
74
|
+
this.offset += length;
|
|
75
|
+
return value;
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
export { ProtoMessage as t };
|
|
79
|
+
|
|
80
|
+
//# sourceMappingURL=protobuf-Dwp5TIr1.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"protobuf-Dwp5TIr1.mjs","names":[],"sources":["../src/protobuf.ts"],"sourcesContent":["interface Field {\n wireType: number;\n value: bigint | Uint8Array;\n}\n\nconst textDecoder = new TextDecoder('utf-8', { fatal: true });\n\nexport class ProtoMessage {\n private offset = 0;\n private readonly fields = new Map<number, Field[]>();\n\n constructor(\n private readonly data: Uint8Array,\n wanted: readonly number[],\n ) {\n while (this.offset < data.length) {\n const tag = this.varint();\n const field = Number(tag >> 3n);\n const wireType = Number(tag & 7n);\n\n if (field < 1 || field > 0x1fff_ffff) {\n throw new Error('Invalid protobuf field number');\n }\n\n const value = wireType === 0 ? this.varint() : this.bytes(wireType);\n\n if (!wanted.includes(field)) {\n continue;\n }\n\n const values = this.fields.get(field);\n\n if (values) {\n values.push({ wireType, value });\n } else {\n this.fields.set(field, [{ wireType, value }]);\n }\n }\n }\n\n uint64(field: number): string | undefined {\n const value = this.fields.get(field)?.at(-1);\n\n if (!value) {\n return undefined;\n }\n\n if (value.wireType !== 0) {\n throw new Error(`Expected a protobuf varint in field ${field}`);\n }\n\n return value.value.toString();\n }\n\n string(field: number): string | undefined {\n const value = this.dataField(field);\n\n return value && textDecoder.decode(value);\n }\n\n dataField(field: number): Uint8Array | undefined {\n const value = this.fields.get(field)?.at(-1);\n\n return value && this.expectBytes(value, field);\n }\n\n repeatedBytes(field: number): Uint8Array[] {\n return (this.fields.get(field) ?? []).map(value => this.expectBytes(value, field));\n }\n\n private expectBytes(field: Field, number: number): Uint8Array {\n if (field.wireType !== 2 || typeof field.value === 'bigint') {\n throw new Error(`Expected protobuf bytes in field ${number}`);\n }\n\n return field.value;\n }\n\n private varint(): bigint {\n let result = 0n;\n\n for (let index = 0; index < 10; index++) {\n const byte = this.data[this.offset++];\n\n if (byte === undefined || (index === 9 && byte > 1)) {\n throw new Error('Invalid protobuf uint64 varint');\n }\n\n result |= BigInt(byte & 0x7f) << BigInt(index * 7);\n\n if (byte < 0x80) {\n return result;\n }\n }\n\n throw new Error('Invalid protobuf uint64 varint');\n }\n\n private bytes(wireType: number): Uint8Array {\n let length: number;\n\n switch (wireType) {\n case 1: {\n length = 8;\n break;\n }\n\n case 2: {\n length = Number(this.varint());\n break;\n }\n\n case 5: {\n length = 4;\n break;\n }\n\n default: {\n throw new Error(`Unsupported protobuf wire type ${wireType}`);\n }\n }\n\n if (length > this.data.length - this.offset) {\n throw new Error('Truncated protobuf field');\n }\n\n const value = this.data.subarray(this.offset, this.offset + length);\n this.offset += length;\n\n return value;\n }\n}\n"],"mappings":";AAKA,MAAM,cAAc,IAAI,YAAY,SAAS,EAAE,OAAO,KAAK,CAAC;AAE5D,IAAa,eAAb,MAA0B;CAKL;CAJnB,SAAiB;CACjB,yBAA0B,IAAI,IAAqB;CAEnD,YACE,MACA,QACA;EAFiB,KAAA,OAAA;EAGjB,OAAO,KAAK,SAAS,KAAK,QAAQ;GAChC,MAAM,MAAM,KAAK,OAAO;GACxB,MAAM,QAAQ,OAAO,OAAO,EAAE;GAC9B,MAAM,WAAW,OAAO,MAAM,EAAE;GAEhC,IAAI,QAAQ,KAAK,QAAQ,WACvB,MAAM,IAAI,MAAM,+BAA+B;GAGjD,MAAM,QAAQ,aAAa,IAAI,KAAK,OAAO,IAAI,KAAK,MAAM,QAAQ;GAElE,IAAI,CAAC,OAAO,SAAS,KAAK,GACxB;GAGF,MAAM,SAAS,KAAK,OAAO,IAAI,KAAK;GAEpC,IAAI,QACF,OAAO,KAAK;IAAE;IAAU;GAAM,CAAC;QAE/B,KAAK,OAAO,IAAI,OAAO,CAAC;IAAE;IAAU;GAAM,CAAC,CAAC;EAEhD;CACF;CAEA,OAAO,OAAmC;EACxC,MAAM,QAAQ,KAAK,OAAO,IAAI,KAAK,CAAC,EAAE,GAAG,EAAE;EAE3C,IAAI,CAAC,OACH;EAGF,IAAI,MAAM,aAAa,GACrB,MAAM,IAAI,MAAM,uCAAuC,OAAO;EAGhE,OAAO,MAAM,MAAM,SAAS;CAC9B;CAEA,OAAO,OAAmC;EACxC,MAAM,QAAQ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1
|
+
interface RawMessage {
|
|
2
|
+
method: string;
|
|
3
|
+
payload: Uint8Array;
|
|
4
|
+
id?: string;
|
|
5
|
+
}
|
|
6
|
+
declare function decodeMessages(frame: Uint8Array): RawMessage[];
|
|
7
|
+
declare function decodeFrame(frame: Uint8Array): {
|
|
8
|
+
messages: RawMessage[];
|
|
9
|
+
ack?: {
|
|
10
|
+
logId: bigint;
|
|
11
|
+
payload: Uint8Array;
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
declare function decodeCdpPayload(payloadData: string): RawMessage[];
|
|
15
|
+
export { decodeMessages as i, decodeCdpPayload as n, decodeFrame as r, RawMessage as t };
|
|
16
|
+
//# sourceMappingURL=protocol-B2FdR4E9.d.mts.map
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { t as ProtoMessage } from "./protobuf-Dwp5TIr1.mjs";
|
|
2
|
+
import { gunzipSync } from "node:zlib";
|
|
3
|
+
// src/protocol.ts
|
|
4
|
+
const maxFrameBytes = 16777216;
|
|
5
|
+
const controlTypes = /* @__PURE__ */ new Set([
|
|
6
|
+
"hb",
|
|
7
|
+
"ack",
|
|
8
|
+
"pong"
|
|
9
|
+
]);
|
|
10
|
+
function decodeMessages(frame) {
|
|
11
|
+
return decodeFrame(frame).messages;
|
|
12
|
+
}
|
|
13
|
+
function decodeFrame(frame) {
|
|
14
|
+
if (frame.length > maxFrameBytes) throw new Error("WebSocket message exceeds the size limit");
|
|
15
|
+
const push = new ProtoMessage(frame, [
|
|
16
|
+
2,
|
|
17
|
+
6,
|
|
18
|
+
7,
|
|
19
|
+
8
|
|
20
|
+
]);
|
|
21
|
+
const type = push.string(7) ?? "";
|
|
22
|
+
const payload = push.dataField(8);
|
|
23
|
+
if (!payload?.length || controlTypes.has(type)) return { messages: [] };
|
|
24
|
+
const body = expandPayload(payload, push.string(6));
|
|
25
|
+
const response = new ProtoMessage(body, [
|
|
26
|
+
1,
|
|
27
|
+
5,
|
|
28
|
+
9
|
|
29
|
+
]);
|
|
30
|
+
const messages = response.repeatedBytes(1).map((bytes) => {
|
|
31
|
+
const message = new ProtoMessage(bytes, [
|
|
32
|
+
1,
|
|
33
|
+
2,
|
|
34
|
+
3
|
|
35
|
+
]);
|
|
36
|
+
return {
|
|
37
|
+
method: message.string(1) ?? "",
|
|
38
|
+
payload: message.dataField(2) ?? /* @__PURE__ */ new Uint8Array(),
|
|
39
|
+
id: message.uint64(3)
|
|
40
|
+
};
|
|
41
|
+
});
|
|
42
|
+
if (response.uint64(9) === "1") return {
|
|
43
|
+
messages,
|
|
44
|
+
ack: {
|
|
45
|
+
logId: BigInt(push.uint64(2) ?? "0"),
|
|
46
|
+
payload: response.dataField(5) ?? /* @__PURE__ */ new Uint8Array()
|
|
47
|
+
}
|
|
48
|
+
};
|
|
49
|
+
return { messages };
|
|
50
|
+
}
|
|
51
|
+
function decodeCdpPayload(payloadData) {
|
|
52
|
+
if (payloadData.length > Math.ceil(maxFrameBytes / 3) * 4) throw new Error("CDP payload exceeds the size limit");
|
|
53
|
+
const bytes = Buffer.from(payloadData, "base64");
|
|
54
|
+
if (bytes.toString("base64") !== payloadData) throw new Error("Invalid CDP Base64 payload");
|
|
55
|
+
return decodeMessages(bytes);
|
|
56
|
+
}
|
|
57
|
+
function expandPayload(payload, encoding = "") {
|
|
58
|
+
if (encoding === "gzip" || payload[0] === 31 && payload[1] === 139) return gunzipSync(payload, { maxOutputLength: maxFrameBytes });
|
|
59
|
+
if (encoding && encoding !== "identity") throw new Error(`Unsupported payload encoding: ${encoding}`);
|
|
60
|
+
return payload;
|
|
61
|
+
}
|
|
62
|
+
export { decodeCdpPayload, decodeFrame, decodeMessages };
|
|
63
|
+
|
|
64
|
+
//# sourceMappingURL=protocol.mjs.map
|