dsh-netchat 0.0.0-stage → 0.3.19
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/README.md +147 -2
- package/client/client.js +696 -0
- package/cordis.patch.yml +4 -0
- package/lib/host.mjs +234 -0
- package/lib/index.js +243 -0
- package/lib/runtime.mjs +9 -0
- package/lib/shared.mjs +28 -0
- package/package.json +34 -4
- package/shared/core/client.mjs +301 -0
- package/shared/core/consts.mjs +71 -0
- package/shared/core/datadir.mjs +92 -0
- package/shared/core/feishu-frame.mjs +190 -0
- package/shared/core/feishu.mjs +878 -0
- package/shared/core/hostbridge.mjs +115 -0
- package/shared/core/netchat.mjs +2542 -0
- package/shared/core/ops.mjs +803 -0
- package/shared/core/protocol.mjs +132 -0
- package/shared/core/util.mjs +184 -0
- package/shared/core/wsstream.mjs +204 -0
- package/shared/mcp/server.mjs +212 -0
- package/shared/skills/net-chat/SKILL.md +110 -0
- package/shared/ui/panel.html +2652 -0
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import { createHmac, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import * as C from "./consts.mjs";
|
|
3
|
+
import { canonicalJson, newId, nowIso } from "./util.mjs";
|
|
4
|
+
|
|
5
|
+
const ID_PATTERN = /^[A-Za-z0-9_.:-]{8,80}$/;
|
|
6
|
+
const HEX_64 = /^[a-f0-9]{64}$/;
|
|
7
|
+
|
|
8
|
+
/** Short public fingerprint of the team key, so peers can label each other without leaking the key. */
|
|
9
|
+
export function teamTag(teamKey) {
|
|
10
|
+
if (!teamKey) return null;
|
|
11
|
+
return createHmac("sha256", teamKey).update("netchat/tag/v1", "utf8").digest("hex").slice(0, 8);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function signingText(envelope) {
|
|
15
|
+
return [
|
|
16
|
+
envelope.msgId,
|
|
17
|
+
envelope.ts,
|
|
18
|
+
envelope.kind,
|
|
19
|
+
envelope.from.id,
|
|
20
|
+
envelope.from.name,
|
|
21
|
+
envelope.to,
|
|
22
|
+
envelope.threadId ?? "",
|
|
23
|
+
canonicalJson(envelope.payload),
|
|
24
|
+
].join("\n");
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function signEnvelope(teamKey, envelope) {
|
|
28
|
+
if (!teamKey) return undefined;
|
|
29
|
+
return createHmac("sha256", teamKey).update(signingText(envelope), "utf8").digest("hex");
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function verifySignature(teamKey, envelope) {
|
|
33
|
+
if (!teamKey || typeof envelope.sig !== "string" || !HEX_64.test(envelope.sig)) return false;
|
|
34
|
+
const expected = signEnvelope(teamKey, envelope);
|
|
35
|
+
return timingSafeEqual(Buffer.from(expected, "utf8"), Buffer.from(envelope.sig, "utf8"));
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function buildEnvelope({ kind, from, to, payload, threadId = null, teamKey = "" }) {
|
|
39
|
+
const envelope = {
|
|
40
|
+
v: C.PROTOCOL,
|
|
41
|
+
kind,
|
|
42
|
+
msgId: newId("msg"),
|
|
43
|
+
ts: nowIso(),
|
|
44
|
+
from: { id: from.id, name: from.name, role: from.role ?? "" },
|
|
45
|
+
to,
|
|
46
|
+
...(threadId ? { threadId } : {}),
|
|
47
|
+
payload: JSON.parse(JSON.stringify(payload)),
|
|
48
|
+
};
|
|
49
|
+
const sig = signEnvelope(teamKey, envelope);
|
|
50
|
+
return sig ? { ...envelope, sig } : envelope;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const text = (value, max, { allowEmpty = false } = {}) =>
|
|
54
|
+
typeof value === "string" && value.length <= max && (allowEmpty || value.trim().length > 0);
|
|
55
|
+
|
|
56
|
+
function validTranscript(value) {
|
|
57
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return false;
|
|
58
|
+
if (typeof value.title !== "string" || value.title.length > C.MAX_SESSION_TITLE_CHARS * 4) return false;
|
|
59
|
+
if (!Array.isArray(value.messages) || value.messages.length > C.MAX_TRANSCRIPT_MESSAGES) return false;
|
|
60
|
+
let chars = 0;
|
|
61
|
+
for (const entry of value.messages) {
|
|
62
|
+
if (!entry || (entry.role !== "user" && entry.role !== "assistant")) return false;
|
|
63
|
+
if (typeof entry.text !== "string") return false;
|
|
64
|
+
chars += entry.text.length;
|
|
65
|
+
if (entry.text.length > C.MAX_TRANSCRIPT_TEXT_CHARS || chars > C.MAX_TRANSCRIPT_CHARS) return false;
|
|
66
|
+
}
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Choices offered with a question: a short list of short, distinct, non-blank labels. */
|
|
71
|
+
function validOptions(value) {
|
|
72
|
+
if (!Array.isArray(value) || value.length === 0 || value.length > C.MAX_OPTION_COUNT) return false;
|
|
73
|
+
const seen = new Set();
|
|
74
|
+
for (const option of value) {
|
|
75
|
+
if (!text(option, C.MAX_OPTION_CHARS) || option.trim() !== option || seen.has(option)) return false;
|
|
76
|
+
seen.add(option);
|
|
77
|
+
}
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** Strict shape check of an inbound envelope. Returns the reason when rejected. */
|
|
82
|
+
export function validateEnvelope(input) {
|
|
83
|
+
if (!input || typeof input !== "object" || Array.isArray(input)) return "envelope must be an object";
|
|
84
|
+
if (input.v !== C.PROTOCOL) return `unsupported protocol version: ${String(input.v)}`;
|
|
85
|
+
if (!C.KINDS.includes(input.kind)) return `unknown kind: ${String(input.kind)}`;
|
|
86
|
+
if (typeof input.msgId !== "string" || !ID_PATTERN.test(input.msgId)) return "invalid msgId";
|
|
87
|
+
if (typeof input.ts !== "string" || input.ts.length > 40 || Number.isNaN(Date.parse(input.ts))) return "invalid ts";
|
|
88
|
+
if (typeof input.to !== "string" || !ID_PATTERN.test(input.to)) return "invalid to";
|
|
89
|
+
if (input.threadId !== undefined && (typeof input.threadId !== "string" || !ID_PATTERN.test(input.threadId))) {
|
|
90
|
+
return "invalid threadId";
|
|
91
|
+
}
|
|
92
|
+
// Feedback on a task only exists inside that task's thread.
|
|
93
|
+
if (input.kind !== "task" && input.threadId === undefined) return "threadId is required";
|
|
94
|
+
if (input.sig !== undefined && (typeof input.sig !== "string" || !HEX_64.test(input.sig))) return "invalid sig";
|
|
95
|
+
const from = input.from;
|
|
96
|
+
if (!from || typeof from !== "object") return "invalid from";
|
|
97
|
+
if (typeof from.id !== "string" || !ID_PATTERN.test(from.id)) return "invalid from.id";
|
|
98
|
+
if (!text(from.name, C.MAX_NAME_CHARS)) return "invalid from.name";
|
|
99
|
+
if (from.role !== undefined && !text(from.role, C.MAX_ROLE_CHARS, { allowEmpty: true })) return "invalid from.role";
|
|
100
|
+
if (from.id === input.to) return "self addressed envelope";
|
|
101
|
+
|
|
102
|
+
const payload = input.payload;
|
|
103
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return "invalid payload";
|
|
104
|
+
if (input.kind === "task") {
|
|
105
|
+
if (!text(payload.title, C.MAX_TITLE_CHARS)) return "invalid task.title";
|
|
106
|
+
if (!text(payload.body, C.MAX_BODY_CHARS)) return "invalid task.body";
|
|
107
|
+
if (payload.workspaceHint !== undefined && !text(payload.workspaceHint, C.MAX_HINT_CHARS)) return "invalid task.workspaceHint";
|
|
108
|
+
if (payload.priority !== undefined && !C.PRIORITIES.includes(payload.priority)) return "invalid task.priority";
|
|
109
|
+
if (payload.session != null && !validTranscript(payload.session)) return "invalid task.session";
|
|
110
|
+
if (payload.projectName !== undefined && !text(payload.projectName, C.MAX_PROJECT_NAME_CHARS)) return "invalid task.projectName";
|
|
111
|
+
} else if (input.kind === "reply") {
|
|
112
|
+
if (!text(payload.text, C.MAX_REPLY_CHARS)) return "invalid reply.text";
|
|
113
|
+
// A question may offer choices; an answer names the question it answers.
|
|
114
|
+
if (payload.options !== undefined && !validOptions(payload.options)) return "invalid reply.options";
|
|
115
|
+
if (payload.answerOf !== undefined && !text(payload.answerOf, 80)) return "invalid reply.answerOf";
|
|
116
|
+
} else if (input.kind === "receipt") {
|
|
117
|
+
if (!C.RECEIPT_STATUSES.includes(payload.status)) return "invalid receipt.status";
|
|
118
|
+
if (payload.sessionId !== undefined && !text(payload.sessionId, 200)) return "invalid receipt.sessionId";
|
|
119
|
+
if (payload.sessionTitle !== undefined && !text(payload.sessionTitle, 400, { allowEmpty: true })) return "invalid receipt.sessionTitle";
|
|
120
|
+
if (payload.detail !== undefined && !text(payload.detail, C.MAX_NOTE_CHARS, { allowEmpty: true })) return "invalid receipt.detail";
|
|
121
|
+
// The name of the project a task was done in, as its executor confirmed it (see execute).
|
|
122
|
+
if (payload.projectName !== undefined && !text(payload.projectName, C.MAX_PROJECT_NAME_CHARS)) return "invalid receipt.projectName";
|
|
123
|
+
}
|
|
124
|
+
for (const key of Object.keys(payload)) {
|
|
125
|
+
if (JSON.stringify(payload[key]) === undefined) return `payload.${key} is not JSON serializable`;
|
|
126
|
+
}
|
|
127
|
+
return null;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function envelopeBytes(envelope) {
|
|
131
|
+
return Buffer.byteLength(JSON.stringify(envelope), "utf8");
|
|
132
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { appendFileSync, mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { basename, dirname } from "node:path";
|
|
4
|
+
|
|
5
|
+
export class NetChatError extends Error {
|
|
6
|
+
constructor(code, message, extra = {}) {
|
|
7
|
+
super(message);
|
|
8
|
+
this.name = "NetChatError";
|
|
9
|
+
this.code = code;
|
|
10
|
+
Object.assign(this, extra);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export const nowIso = () => new Date().toISOString();
|
|
15
|
+
|
|
16
|
+
export function newId(prefix) {
|
|
17
|
+
return `${prefix}_${randomUUID().replace(/-/g, "")}`;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function hmacHex(key, data) {
|
|
21
|
+
return createHmac("sha256", key).update(data, "utf8").digest("hex");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isPlainObject(value) {
|
|
25
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** JSON with sorted object keys, so both sides sign byte-identical text. */
|
|
29
|
+
export function canonicalJson(value) {
|
|
30
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
31
|
+
if (isPlainObject(value)) {
|
|
32
|
+
const body = Object.keys(value)
|
|
33
|
+
.sort()
|
|
34
|
+
.map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`)
|
|
35
|
+
.join(",");
|
|
36
|
+
return `{${body}}`;
|
|
37
|
+
}
|
|
38
|
+
return JSON.stringify(value) ?? "null";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function readJson(file, fallback) {
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(readFileSync(file, "utf8"));
|
|
44
|
+
} catch {
|
|
45
|
+
return fallback;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const writeChains = new Map();
|
|
50
|
+
|
|
51
|
+
/** Serialized per file, tmp + rename, with a short retry for Windows file locks. */
|
|
52
|
+
export function writeJsonAtomic(file, data) {
|
|
53
|
+
const previous = writeChains.get(file) ?? Promise.resolve();
|
|
54
|
+
const next = previous.catch(() => {}).then(async () => {
|
|
55
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
56
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
57
|
+
writeFileSync(tmp, JSON.stringify(data, null, 2));
|
|
58
|
+
for (let attempt = 0; ; attempt++) {
|
|
59
|
+
try {
|
|
60
|
+
renameSync(tmp, file);
|
|
61
|
+
return;
|
|
62
|
+
} catch (error) {
|
|
63
|
+
if (attempt >= 20) throw error;
|
|
64
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
});
|
|
68
|
+
writeChains.set(file, next);
|
|
69
|
+
next.finally(() => {
|
|
70
|
+
if (writeChains.get(file) === next) writeChains.delete(file);
|
|
71
|
+
}, () => {});
|
|
72
|
+
return next;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export function clip(text, max) {
|
|
76
|
+
const value = String(text ?? "");
|
|
77
|
+
return value.length > max ? value.slice(0, max) : value;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function baseName(path) {
|
|
81
|
+
const normalized = String(path ?? "").replace(/[\\/]+$/, "");
|
|
82
|
+
return basename(normalized.replace(/\\/g, "/"));
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function normalizePath(path) {
|
|
86
|
+
return String(path ?? "").replace(/\\/g, "/").replace(/\/+$/, "").toLowerCase();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function timingSafeHexEqual(a, b) {
|
|
90
|
+
if (typeof a !== "string" || typeof b !== "string" || a.length !== b.length) return false;
|
|
91
|
+
return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export function newToken() {
|
|
95
|
+
return randomBytes(32).toString("hex");
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* JSON request with a timeout, retried once when the connection itself fails. A keep-alive
|
|
100
|
+
* connection that the server already closed fails instantly and is only worth another try;
|
|
101
|
+
* a timeout means the other side is slow or gone and is reported as `timeout`.
|
|
102
|
+
* Only use `retries` for requests the receiver treats idempotently.
|
|
103
|
+
*/
|
|
104
|
+
export async function fetchJson(url, { method = "GET", headers = {}, body, timeoutMs = 8000, retries = 0 } = {}) {
|
|
105
|
+
for (let attempt = 0; ; attempt++) {
|
|
106
|
+
const controller = new AbortController();
|
|
107
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs);
|
|
108
|
+
try {
|
|
109
|
+
const response = await fetch(url, {
|
|
110
|
+
method,
|
|
111
|
+
headers: { "content-type": "application/json", ...headers },
|
|
112
|
+
...(body === undefined ? {} : { body }),
|
|
113
|
+
signal: controller.signal,
|
|
114
|
+
});
|
|
115
|
+
const data = await response.json().catch(() => null);
|
|
116
|
+
return { status: response.status, ok: response.ok, data };
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (controller.signal.aborted) throw new NetChatError("timeout", `No answer within ${timeoutMs / 1000}s`);
|
|
119
|
+
if (attempt >= retries) throw error;
|
|
120
|
+
} finally {
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function sleep(ms, signal) {
|
|
127
|
+
return new Promise((resolve, reject) => {
|
|
128
|
+
if (signal?.aborted) return reject(abortError(signal));
|
|
129
|
+
const timer = setTimeout(() => {
|
|
130
|
+
signal?.removeEventListener("abort", onAbort);
|
|
131
|
+
resolve();
|
|
132
|
+
}, ms);
|
|
133
|
+
const onAbort = () => {
|
|
134
|
+
clearTimeout(timer);
|
|
135
|
+
reject(abortError(signal));
|
|
136
|
+
};
|
|
137
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function abortError(signal) {
|
|
142
|
+
return signal?.reason instanceof Error ? signal.reason : new DOMException("The operation was aborted", "AbortError");
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
export function describeError(error) {
|
|
146
|
+
return error instanceof Error ? error.message : String(error);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Append-only log in the plugin data directory, rotated once when it grows. */
|
|
150
|
+
export class FileLogger {
|
|
151
|
+
constructor(file, maxBytes = 256 * 1024) {
|
|
152
|
+
this.file = file;
|
|
153
|
+
this.maxBytes = maxBytes;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
log(level, message) {
|
|
157
|
+
const line = `${new Date().toISOString()} [${level}] ${message}\n`;
|
|
158
|
+
try {
|
|
159
|
+
mkdirSync(dirname(this.file), { recursive: true });
|
|
160
|
+
if (statSync(this.file).size > this.maxBytes) {
|
|
161
|
+
try {
|
|
162
|
+
renameSync(this.file, `${this.file}.1`);
|
|
163
|
+
} catch {
|
|
164
|
+
// A failed rotation only means the log keeps growing.
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
appendFileSync(this.file, line, "utf8");
|
|
168
|
+
} catch {
|
|
169
|
+
// Logging must never break the plugin.
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
info(message) {
|
|
174
|
+
this.log("info", message);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
warn(message) {
|
|
178
|
+
this.log("warn", message);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
error(message) {
|
|
182
|
+
this.log("error", message);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
// A small WebSocket client (RFC 6455) on node:http(s): the one piece Feishu's long connection
|
|
2
|
+
// needs that Node 18 has no built-in for. Written for that server and nothing else — outbound
|
|
3
|
+
// frames are always whole and masked, inbound frames of any length are reassembled across
|
|
4
|
+
// continuation frames, ping is answered with pong, and close is a handshake. No extensions.
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import http from "node:http";
|
|
7
|
+
import https from "node:https";
|
|
8
|
+
|
|
9
|
+
const GUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
|
10
|
+
const MAX_FRAME_BYTES = 64 * 1024 * 1024;
|
|
11
|
+
|
|
12
|
+
export class WsConnection {
|
|
13
|
+
constructor(url, { headers = {}, handshakeTimeoutMs = 15_000 } = {}) {
|
|
14
|
+
this.url = new URL(url);
|
|
15
|
+
this.headers = headers;
|
|
16
|
+
this.handshakeTimeoutMs = handshakeTimeoutMs;
|
|
17
|
+
this.socket = null;
|
|
18
|
+
this.buffer = Buffer.alloc(0);
|
|
19
|
+
this.fragments = [];
|
|
20
|
+
this.fragmentOpcode = 0;
|
|
21
|
+
this.closed = false;
|
|
22
|
+
this.handlers = { open: [], text: [], binary: [], close: [], error: [] };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
on(event, handler) {
|
|
26
|
+
(this.handlers[event] ??= []).push(handler);
|
|
27
|
+
return this;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
emit(event, ...args) {
|
|
31
|
+
for (const handler of this.handlers[event] ?? []) {
|
|
32
|
+
try {
|
|
33
|
+
handler(...args);
|
|
34
|
+
} catch {
|
|
35
|
+
// A handler's failure is not the connection's.
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
connect() {
|
|
41
|
+
return new Promise((resolve, reject) => {
|
|
42
|
+
const secure = this.url.protocol === "wss:";
|
|
43
|
+
const key = randomBytes(16).toString("base64");
|
|
44
|
+
const request = (secure ? https : http).request({
|
|
45
|
+
hostname: this.url.hostname,
|
|
46
|
+
port: this.url.port || (secure ? 443 : 80),
|
|
47
|
+
path: `${this.url.pathname}${this.url.search}`,
|
|
48
|
+
method: "GET",
|
|
49
|
+
headers: {
|
|
50
|
+
...this.headers,
|
|
51
|
+
Host: this.url.host,
|
|
52
|
+
Upgrade: "websocket",
|
|
53
|
+
Connection: "Upgrade",
|
|
54
|
+
"Sec-WebSocket-Key": key,
|
|
55
|
+
"Sec-WebSocket-Version": "13",
|
|
56
|
+
},
|
|
57
|
+
});
|
|
58
|
+
const timer = setTimeout(() => {
|
|
59
|
+
request.destroy();
|
|
60
|
+
reject(new Error("websocket handshake timed out"));
|
|
61
|
+
}, this.handshakeTimeoutMs);
|
|
62
|
+
request.on("upgrade", (response, socket, head) => {
|
|
63
|
+
clearTimeout(timer);
|
|
64
|
+
const expected = createHash("sha1").update(`${key}${GUID}`, "utf8").digest("base64");
|
|
65
|
+
if (response.headers["sec-websocket-accept"] !== expected) {
|
|
66
|
+
socket.destroy();
|
|
67
|
+
reject(new Error("websocket handshake: bad Sec-WebSocket-Accept"));
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
this.socket = socket;
|
|
71
|
+
socket.setNoDelay(true);
|
|
72
|
+
socket.on("data", (chunk) => this.onData(chunk));
|
|
73
|
+
socket.on("error", (error) => this.emit("error", error));
|
|
74
|
+
socket.on("close", () => this.finish(1006, "socket closed"));
|
|
75
|
+
socket.on("end", () => this.finish(1006, "socket ended"));
|
|
76
|
+
if (head?.length) this.onData(head);
|
|
77
|
+
this.emit("open");
|
|
78
|
+
resolve();
|
|
79
|
+
});
|
|
80
|
+
request.on("response", (response) => {
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
reject(new Error(`websocket handshake: server answered ${response.statusCode}`));
|
|
83
|
+
});
|
|
84
|
+
request.on("error", (error) => {
|
|
85
|
+
clearTimeout(timer);
|
|
86
|
+
reject(error);
|
|
87
|
+
});
|
|
88
|
+
request.end();
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** Sends one whole frame. `opcode` defaults to binary (2); text is 1, control frames pass theirs. */
|
|
93
|
+
send(data, { opcode = 0x2 } = {}) {
|
|
94
|
+
if (!this.socket || this.socket.destroyed || this.closed) return false;
|
|
95
|
+
const payload = Buffer.isBuffer(data) ? data : Buffer.from(String(data), "utf8");
|
|
96
|
+
let header;
|
|
97
|
+
if (payload.length < 126) {
|
|
98
|
+
header = Buffer.from([0x80 | opcode, 0x80 | payload.length]);
|
|
99
|
+
} else if (payload.length < 65_536) {
|
|
100
|
+
header = Buffer.alloc(4);
|
|
101
|
+
header[0] = 0x80 | opcode;
|
|
102
|
+
header[1] = 0x80 | 126;
|
|
103
|
+
header.writeUInt16BE(payload.length, 2);
|
|
104
|
+
} else {
|
|
105
|
+
header = Buffer.alloc(10);
|
|
106
|
+
header[0] = 0x80 | opcode;
|
|
107
|
+
header[1] = 0x80 | 127;
|
|
108
|
+
header.writeBigUInt64BE(BigInt(payload.length), 2);
|
|
109
|
+
}
|
|
110
|
+
const mask = randomBytes(4);
|
|
111
|
+
const masked = Buffer.alloc(payload.length);
|
|
112
|
+
for (let i = 0; i < payload.length; i++) masked[i] = payload[i] ^ mask[i & 3];
|
|
113
|
+
this.socket.write(Buffer.concat([header, mask, masked]));
|
|
114
|
+
return true;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
close(code = 1000, reason = "") {
|
|
118
|
+
if (this.closed || !this.socket) return;
|
|
119
|
+
const reasonBuf = Buffer.from(reason, "utf8").subarray(0, 120);
|
|
120
|
+
const body = Buffer.concat([Buffer.from([code >> 8, code & 255]), reasonBuf]);
|
|
121
|
+
const mask = randomBytes(4);
|
|
122
|
+
const frame = Buffer.alloc(2 + 4 + body.length);
|
|
123
|
+
frame[0] = 0x88;
|
|
124
|
+
frame[1] = 0x80 | body.length;
|
|
125
|
+
mask.copy(frame, 2);
|
|
126
|
+
for (let i = 0; i < body.length; i++) frame[6 + i] = body[i] ^ mask[i & 3];
|
|
127
|
+
try {
|
|
128
|
+
this.socket.write(frame);
|
|
129
|
+
} catch {
|
|
130
|
+
// Already gone.
|
|
131
|
+
}
|
|
132
|
+
// Give the peer a moment to echo the close frame, then drop the socket.
|
|
133
|
+
const socket = this.socket;
|
|
134
|
+
setTimeout(() => socket.destroy(), 1500).unref?.();
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
onData(chunk) {
|
|
138
|
+
this.buffer = this.buffer.length ? Buffer.concat([this.buffer, chunk]) : chunk;
|
|
139
|
+
for (;;) {
|
|
140
|
+
const frame = this.readFrame();
|
|
141
|
+
if (!frame) return;
|
|
142
|
+
this.handle(frame);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
/** One complete frame off the buffer, or null until the rest of it has arrived. */
|
|
147
|
+
readFrame() {
|
|
148
|
+
const buf = this.buffer;
|
|
149
|
+
if (buf.length < 2) return null;
|
|
150
|
+
const fin = (buf[0] & 0x80) !== 0;
|
|
151
|
+
const opcode = buf[0] & 0x0f;
|
|
152
|
+
const masked = (buf[1] & 0x80) !== 0;
|
|
153
|
+
let length = buf[1] & 0x7f;
|
|
154
|
+
let offset = 2;
|
|
155
|
+
if (length === 126) {
|
|
156
|
+
if (buf.length < 4) return null;
|
|
157
|
+
length = buf.readUInt16BE(2);
|
|
158
|
+
offset = 4;
|
|
159
|
+
} else if (length === 127) {
|
|
160
|
+
if (buf.length < 10) return null;
|
|
161
|
+
const big = buf.readBigUInt64BE(2);
|
|
162
|
+
if (big > BigInt(MAX_FRAME_BYTES)) throw new Error("websocket frame too large");
|
|
163
|
+
length = Number(big);
|
|
164
|
+
offset = 10;
|
|
165
|
+
}
|
|
166
|
+
const maskKey = masked ? buf.subarray(offset, offset + 4) : null;
|
|
167
|
+
if (masked) offset += 4;
|
|
168
|
+
if (buf.length < offset + length) return null;
|
|
169
|
+
const payload = Buffer.from(buf.subarray(offset, offset + length));
|
|
170
|
+
if (maskKey) for (let i = 0; i < payload.length; i++) payload[i] ^= maskKey[i & 3];
|
|
171
|
+
this.buffer = buf.subarray(offset + length);
|
|
172
|
+
return { fin, opcode, payload };
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
handle({ fin, opcode, payload }) {
|
|
176
|
+
if (opcode === 0x8) {
|
|
177
|
+
const code = payload.length >= 2 ? payload.readUInt16BE(0) : 1005;
|
|
178
|
+
if (!this.closed) this.close(code);
|
|
179
|
+
this.socket?.destroy();
|
|
180
|
+
this.finish(code, payload.subarray(2).toString("utf8"));
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
if (opcode === 0x9) {
|
|
184
|
+
this.send(payload, { opcode: 0xa });
|
|
185
|
+
return;
|
|
186
|
+
}
|
|
187
|
+
if (opcode === 0xa) return;
|
|
188
|
+
if (opcode !== 0x0) this.fragmentOpcode = opcode;
|
|
189
|
+
this.fragments.push(payload);
|
|
190
|
+
if (!fin) return;
|
|
191
|
+
const whole = Buffer.concat(this.fragments);
|
|
192
|
+
const kind = this.fragmentOpcode;
|
|
193
|
+
this.fragments = [];
|
|
194
|
+
this.fragmentOpcode = 0;
|
|
195
|
+
if (kind === 0x1) this.emit("text", whole.toString("utf8"));
|
|
196
|
+
else this.emit("binary", whole);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
finish(code, reason) {
|
|
200
|
+
if (this.closed) return;
|
|
201
|
+
this.closed = true;
|
|
202
|
+
this.emit("close", code, reason);
|
|
203
|
+
}
|
|
204
|
+
}
|