@zhin.js/adapter-weixin-ilink 1.0.1 → 1.1.2
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/CHANGELOG.md +512 -0
- package/README.md +24 -42
- package/adapters/weixin-ilink/index.js +32 -0
- package/adapters/weixin-ilink/index.ts +43 -0
- package/commands/weixin-ilink/endpoint/add/[id]/index.js +3 -0
- package/commands/weixin-ilink/endpoint/add/[id]/index.ts +3 -0
- package/commands/weixin-ilink/endpoint/definition.js +17 -0
- package/commands/weixin-ilink/endpoint/definition.ts +17 -0
- package/commands/weixin-ilink/endpoint/list/index.js +3 -0
- package/commands/weixin-ilink/endpoint/list/index.ts +3 -0
- package/commands/weixin-ilink/endpoint/remove/[id]/index.js +3 -0
- package/commands/weixin-ilink/endpoint/remove/[id]/index.ts +3 -0
- package/lib/aes-ecb.d.ts +0 -1
- package/lib/aes-ecb.js +0 -1
- package/lib/cdn-upload.d.ts +0 -1
- package/lib/cdn-upload.js +0 -1
- package/lib/cdn-url.d.ts +0 -1
- package/lib/cdn-url.js +0 -1
- package/lib/client.d.ts +35 -0
- package/lib/client.js +89 -0
- package/lib/context-store.d.ts +15 -2
- package/lib/context-store.js +93 -2
- package/lib/credentials.d.ts +15 -8
- package/lib/credentials.js +59 -43
- package/lib/endpoint.d.ts +40 -35
- package/lib/endpoint.js +311 -262
- package/lib/ilink-api.d.ts +7 -6
- package/lib/ilink-api.js +26 -16
- package/lib/ilink-config-cache.d.ts +3 -8
- package/lib/ilink-config-cache.js +13 -15
- package/lib/ilink-logger.d.ts +0 -2
- package/lib/ilink-logger.js +11 -26
- package/lib/ilink-meta.d.ts +13 -8
- package/lib/ilink-meta.js +24 -21
- package/lib/ilink-random.d.ts +0 -1
- package/lib/ilink-random.js +0 -1
- package/lib/ilink-redact.d.ts +0 -1
- package/lib/ilink-redact.js +0 -1
- package/lib/ilink-session-guard.d.ts +13 -15
- package/lib/ilink-session-guard.js +29 -43
- package/lib/ilink-types.d.ts +0 -1
- package/lib/ilink-types.js +0 -1
- package/lib/index.d.ts +8 -20
- package/lib/index.js +7 -38
- package/lib/login.d.ts +5 -6
- package/lib/login.js +85 -77
- package/lib/media-download.d.ts +1 -2
- package/lib/media-download.js +1 -2
- package/lib/mime.d.ts +0 -1
- package/lib/mime.js +0 -1
- package/lib/outbound-media.d.ts +4 -5
- package/lib/outbound-media.js +85 -86
- package/lib/pic-decrypt.d.ts +0 -1
- package/lib/pic-decrypt.js +0 -1
- package/lib/protocol.d.ts +60 -0
- package/lib/protocol.js +127 -0
- package/lib/silk-transcode.d.ts +0 -1
- package/lib/silk-transcode.js +0 -1
- package/lib/types.d.ts +2 -26
- package/lib/types.js +0 -1
- package/lib/upload.d.ts +1 -2
- package/lib/upload.js +1 -2
- package/lib/weixin-ilink-runtime-state.d.ts +1 -0
- package/lib/weixin-ilink-runtime-state.js +6 -0
- package/lib/weixin-inbound.d.ts +4 -43
- package/lib/weixin-inbound.js +22 -162
- package/lib/weixin-send-media.d.ts +0 -1
- package/lib/weixin-send-media.js +5 -2
- package/lib/weixin-send.d.ts +1 -2
- package/lib/weixin-send.js +4 -3
- package/package.json +48 -39
- package/plugin.js +14 -0
- package/schema.json +116 -0
- package/src/client.ts +117 -0
- package/src/context-store.ts +101 -8
- package/src/credentials.ts +68 -45
- package/src/endpoint.ts +384 -315
- package/src/ilink-api.ts +31 -21
- package/src/ilink-config-cache.ts +17 -13
- package/src/ilink-logger.ts +11 -26
- package/src/ilink-meta.ts +31 -21
- package/src/ilink-session-guard.ts +29 -46
- package/src/index.ts +41 -56
- package/src/login.ts +112 -85
- package/src/media-download.ts +1 -2
- package/src/outbound-media.ts +97 -97
- package/src/protocol.ts +180 -0
- package/src/silk-wasm.d.ts +6 -2
- package/src/types.ts +5 -25
- package/src/upload.test.ts +11 -8
- package/src/upload.ts +2 -2
- package/src/weixin-ilink-runtime-state.ts +7 -0
- package/src/weixin-inbound.ts +25 -187
- package/src/weixin-send-media.ts +5 -1
- package/src/weixin-send.ts +6 -4
- package/client/LoginAssistPanel.tsx +0 -200
- package/client/WeixinIlinkManagement.tsx +0 -139
- package/client/index.tsx +0 -11
- package/client/tsconfig.json +0 -13
- package/client/utils/api.ts +0 -30
- package/dist/index.js +0 -29
- package/lib/adapter.d.ts +0 -12
- package/lib/adapter.d.ts.map +0 -1
- package/lib/adapter.js +0 -15
- package/lib/adapter.js.map +0 -1
- package/lib/aes-ecb.d.ts.map +0 -1
- package/lib/aes-ecb.js.map +0 -1
- package/lib/cdn-upload.d.ts.map +0 -1
- package/lib/cdn-upload.js.map +0 -1
- package/lib/cdn-upload.test.d.ts +0 -2
- package/lib/cdn-upload.test.d.ts.map +0 -1
- package/lib/cdn-upload.test.js +0 -150
- package/lib/cdn-upload.test.js.map +0 -1
- package/lib/cdn-url.d.ts.map +0 -1
- package/lib/cdn-url.js.map +0 -1
- package/lib/context-store.d.ts.map +0 -1
- package/lib/context-store.js.map +0 -1
- package/lib/credentials.d.ts.map +0 -1
- package/lib/credentials.js.map +0 -1
- package/lib/endpoint.d.ts.map +0 -1
- package/lib/endpoint.js.map +0 -1
- package/lib/ilink-api.d.ts.map +0 -1
- package/lib/ilink-api.js.map +0 -1
- package/lib/ilink-config-cache.d.ts.map +0 -1
- package/lib/ilink-config-cache.js.map +0 -1
- package/lib/ilink-logger.d.ts.map +0 -1
- package/lib/ilink-logger.js.map +0 -1
- package/lib/ilink-meta.d.ts.map +0 -1
- package/lib/ilink-meta.js.map +0 -1
- package/lib/ilink-random.d.ts.map +0 -1
- package/lib/ilink-random.js.map +0 -1
- package/lib/ilink-redact.d.ts.map +0 -1
- package/lib/ilink-redact.js.map +0 -1
- package/lib/ilink-session-guard.d.ts.map +0 -1
- package/lib/ilink-session-guard.js.map +0 -1
- package/lib/ilink-types.d.ts.map +0 -1
- package/lib/ilink-types.js.map +0 -1
- package/lib/index.d.ts.map +0 -1
- package/lib/index.js.map +0 -1
- package/lib/login-assist-routes.d.ts +0 -7
- package/lib/login-assist-routes.d.ts.map +0 -1
- package/lib/login-assist-routes.js +0 -29
- package/lib/login-assist-routes.js.map +0 -1
- package/lib/login.d.ts.map +0 -1
- package/lib/login.js.map +0 -1
- package/lib/media-download.d.ts.map +0 -1
- package/lib/media-download.js.map +0 -1
- package/lib/mime.d.ts.map +0 -1
- package/lib/mime.js.map +0 -1
- package/lib/mime.test.d.ts +0 -2
- package/lib/mime.test.d.ts.map +0 -1
- package/lib/mime.test.js +0 -62
- package/lib/mime.test.js.map +0 -1
- package/lib/outbound-media.d.ts.map +0 -1
- package/lib/outbound-media.js.map +0 -1
- package/lib/pic-decrypt.d.ts.map +0 -1
- package/lib/pic-decrypt.js.map +0 -1
- package/lib/routes.d.ts +0 -8
- package/lib/routes.d.ts.map +0 -1
- package/lib/routes.js +0 -29
- package/lib/routes.js.map +0 -1
- package/lib/silk-transcode.d.ts.map +0 -1
- package/lib/silk-transcode.js.map +0 -1
- package/lib/silk-transcode.test.d.ts +0 -2
- package/lib/silk-transcode.test.d.ts.map +0 -1
- package/lib/silk-transcode.test.js +0 -53
- package/lib/silk-transcode.test.js.map +0 -1
- package/lib/types.d.ts.map +0 -1
- package/lib/types.js.map +0 -1
- package/lib/typing-indicator.d.ts +0 -32
- package/lib/typing-indicator.d.ts.map +0 -1
- package/lib/typing-indicator.js +0 -95
- package/lib/typing-indicator.js.map +0 -1
- package/lib/upload.d.ts.map +0 -1
- package/lib/upload.js.map +0 -1
- package/lib/upload.test.d.ts +0 -2
- package/lib/upload.test.d.ts.map +0 -1
- package/lib/upload.test.js +0 -250
- package/lib/upload.test.js.map +0 -1
- package/lib/weixin-inbound.d.ts.map +0 -1
- package/lib/weixin-inbound.js.map +0 -1
- package/lib/weixin-send-media.d.ts.map +0 -1
- package/lib/weixin-send-media.js.map +0 -1
- package/lib/weixin-send.d.ts.map +0 -1
- package/lib/weixin-send.js.map +0 -1
- package/src/adapter.ts +0 -18
- package/src/login-assist-routes.ts +0 -36
- package/src/routes.ts +0 -39
- package/src/typing-indicator.ts +0 -139
package/src/ilink-api.ts
CHANGED
|
@@ -2,8 +2,7 @@ import crypto from "node:crypto";
|
|
|
2
2
|
|
|
3
3
|
import { logger } from "./ilink-logger.js";
|
|
4
4
|
import {
|
|
5
|
-
|
|
6
|
-
ILINK_APP_CLIENT_VERSION,
|
|
5
|
+
type IlinkClientMetadata,
|
|
7
6
|
ILINK_APP_ID,
|
|
8
7
|
} from "./ilink-meta.js";
|
|
9
8
|
import { redactBody, redactUrl } from "./ilink-redact.js";
|
|
@@ -20,10 +19,11 @@ import type {
|
|
|
20
19
|
GetConfigResp,
|
|
21
20
|
} from "./ilink-types.js";
|
|
22
21
|
|
|
23
|
-
export {
|
|
22
|
+
export { IlinkClientMetadata, sanitizeBotAgent } from "./ilink-meta.js";
|
|
24
23
|
|
|
25
24
|
export type WeixinApiOptions = {
|
|
26
25
|
baseUrl: string;
|
|
26
|
+
metadata: IlinkClientMetadata;
|
|
27
27
|
token?: string;
|
|
28
28
|
timeoutMs?: number;
|
|
29
29
|
/** Long-poll timeout for getUpdates (server may hold the request up to this). */
|
|
@@ -48,20 +48,20 @@ function randomWechatUin(): string {
|
|
|
48
48
|
}
|
|
49
49
|
|
|
50
50
|
/** Build headers shared by both GET and POST requests. */
|
|
51
|
-
function buildCommonHeaders(): Record<string, string> {
|
|
51
|
+
function buildCommonHeaders(metadata: IlinkClientMetadata): Record<string, string> {
|
|
52
52
|
const headers: Record<string, string> = {
|
|
53
53
|
"iLink-App-Id": ILINK_APP_ID,
|
|
54
|
-
"iLink-App-ClientVersion": String(
|
|
54
|
+
"iLink-App-ClientVersion": String(metadata.appClientVersion),
|
|
55
55
|
};
|
|
56
56
|
return headers;
|
|
57
57
|
}
|
|
58
58
|
|
|
59
|
-
function buildHeaders(opts: { token?: string }): Record<string, string> {
|
|
59
|
+
function buildHeaders(opts: { metadata: IlinkClientMetadata; token?: string }): Record<string, string> {
|
|
60
60
|
const headers: Record<string, string> = {
|
|
61
61
|
"Content-Type": "application/json",
|
|
62
62
|
AuthorizationType: "ilink_bot_token",
|
|
63
63
|
"X-WECHAT-UIN": randomWechatUin(),
|
|
64
|
-
...buildCommonHeaders(),
|
|
64
|
+
...buildCommonHeaders(opts.metadata),
|
|
65
65
|
};
|
|
66
66
|
if (opts.token?.trim()) {
|
|
67
67
|
headers.Authorization = `Bearer ${opts.token.trim()}`;
|
|
@@ -80,13 +80,15 @@ function buildHeaders(opts: { token?: string }): Record<string, string> {
|
|
|
80
80
|
*/
|
|
81
81
|
export async function apiGetFetch(params: {
|
|
82
82
|
baseUrl: string;
|
|
83
|
+
metadata: IlinkClientMetadata;
|
|
83
84
|
endpoint: string;
|
|
84
85
|
timeoutMs?: number;
|
|
85
86
|
label: string;
|
|
87
|
+
abortSignal?: AbortSignal;
|
|
86
88
|
}): Promise<string> {
|
|
87
89
|
const base = ensureTrailingSlash(params.baseUrl);
|
|
88
90
|
const url = new URL(params.endpoint, base);
|
|
89
|
-
const hdrs = buildCommonHeaders();
|
|
91
|
+
const hdrs = buildCommonHeaders(params.metadata);
|
|
90
92
|
logger.debug(`GET ${redactUrl(url.toString())}`);
|
|
91
93
|
|
|
92
94
|
const timeoutMs = params.timeoutMs;
|
|
@@ -96,11 +98,12 @@ export async function apiGetFetch(params: {
|
|
|
96
98
|
controller != null && timeoutMs != null
|
|
97
99
|
? setTimeout(() => controller.abort(), timeoutMs)
|
|
98
100
|
: undefined;
|
|
101
|
+
const { signal, cleanup } = combineAbortSignals(controller, params.abortSignal);
|
|
99
102
|
try {
|
|
100
103
|
const res = await fetch(url.toString(), {
|
|
101
104
|
method: "GET",
|
|
102
105
|
headers: hdrs,
|
|
103
|
-
...(
|
|
106
|
+
...(signal ? { signal } : {}),
|
|
104
107
|
});
|
|
105
108
|
if (t !== undefined) clearTimeout(t);
|
|
106
109
|
const rawText = await res.text();
|
|
@@ -112,6 +115,8 @@ export async function apiGetFetch(params: {
|
|
|
112
115
|
} catch (err) {
|
|
113
116
|
if (t !== undefined) clearTimeout(t);
|
|
114
117
|
throw err;
|
|
118
|
+
} finally {
|
|
119
|
+
cleanup();
|
|
115
120
|
}
|
|
116
121
|
}
|
|
117
122
|
|
|
@@ -145,6 +150,7 @@ function combineAbortSignals(
|
|
|
145
150
|
*/
|
|
146
151
|
export async function apiPostFetch(params: {
|
|
147
152
|
baseUrl: string;
|
|
153
|
+
metadata: IlinkClientMetadata;
|
|
148
154
|
endpoint: string;
|
|
149
155
|
body: string;
|
|
150
156
|
token?: string;
|
|
@@ -154,7 +160,7 @@ export async function apiPostFetch(params: {
|
|
|
154
160
|
}): Promise<string> {
|
|
155
161
|
const base = ensureTrailingSlash(params.baseUrl);
|
|
156
162
|
const url = new URL(params.endpoint, base);
|
|
157
|
-
const hdrs = buildHeaders({ token: params.token });
|
|
163
|
+
const hdrs = buildHeaders({ metadata: params.metadata, token: params.token });
|
|
158
164
|
logger.debug(`POST ${redactUrl(url.toString())} body=${redactBody(params.body)}`);
|
|
159
165
|
|
|
160
166
|
const controller =
|
|
@@ -192,10 +198,7 @@ export async function apiPostFetch(params: {
|
|
|
192
198
|
* with ret=0 so the caller can simply retry. This is normal for long-poll.
|
|
193
199
|
*/
|
|
194
200
|
export async function getUpdates(
|
|
195
|
-
params: GetUpdatesReq & {
|
|
196
|
-
baseUrl: string;
|
|
197
|
-
token?: string;
|
|
198
|
-
timeoutMs?: number;
|
|
201
|
+
params: GetUpdatesReq & WeixinApiOptions & {
|
|
199
202
|
/**
|
|
200
203
|
* Optional external abort signal (e.g. from the gateway when stopping the
|
|
201
204
|
* channel). When this aborts, the in-flight long-poll is terminated
|
|
@@ -209,10 +212,11 @@ export async function getUpdates(
|
|
|
209
212
|
try {
|
|
210
213
|
const rawText = await apiPostFetch({
|
|
211
214
|
baseUrl: params.baseUrl,
|
|
215
|
+
metadata: params.metadata,
|
|
212
216
|
endpoint: "ilink/bot/getupdates",
|
|
213
217
|
body: JSON.stringify({
|
|
214
218
|
get_updates_buf: params.get_updates_buf ?? "",
|
|
215
|
-
base_info: buildBaseInfo(),
|
|
219
|
+
base_info: params.metadata.buildBaseInfo(),
|
|
216
220
|
}),
|
|
217
221
|
token: params.token,
|
|
218
222
|
timeoutMs: timeout,
|
|
@@ -245,6 +249,7 @@ export async function getUploadUrl(
|
|
|
245
249
|
): Promise<GetUploadUrlResp> {
|
|
246
250
|
const rawText = await apiPostFetch({
|
|
247
251
|
baseUrl: params.baseUrl,
|
|
252
|
+
metadata: params.metadata,
|
|
248
253
|
endpoint: "ilink/bot/getuploadurl",
|
|
249
254
|
body: JSON.stringify({
|
|
250
255
|
filekey: params.filekey,
|
|
@@ -258,7 +263,7 @@ export async function getUploadUrl(
|
|
|
258
263
|
thumb_filesize: params.thumb_filesize,
|
|
259
264
|
no_need_thumb: params.no_need_thumb,
|
|
260
265
|
aeskey: params.aeskey,
|
|
261
|
-
base_info: buildBaseInfo(),
|
|
266
|
+
base_info: params.metadata.buildBaseInfo(),
|
|
262
267
|
}),
|
|
263
268
|
token: params.token,
|
|
264
269
|
timeoutMs: params.timeoutMs ?? DEFAULT_API_TIMEOUT_MS,
|
|
@@ -274,8 +279,9 @@ export async function sendMessage(
|
|
|
274
279
|
): Promise<void> {
|
|
275
280
|
await apiPostFetch({
|
|
276
281
|
baseUrl: params.baseUrl,
|
|
282
|
+
metadata: params.metadata,
|
|
277
283
|
endpoint: "ilink/bot/sendmessage",
|
|
278
|
-
body: JSON.stringify({ ...params.body, base_info: buildBaseInfo() }),
|
|
284
|
+
body: JSON.stringify({ ...params.body, base_info: params.metadata.buildBaseInfo() }),
|
|
279
285
|
token: params.token,
|
|
280
286
|
timeoutMs: params.timeoutMs ?? DEFAULT_API_TIMEOUT_MS,
|
|
281
287
|
label: "sendMessage",
|
|
@@ -288,11 +294,12 @@ export async function getConfig(
|
|
|
288
294
|
): Promise<GetConfigResp> {
|
|
289
295
|
const rawText = await apiPostFetch({
|
|
290
296
|
baseUrl: params.baseUrl,
|
|
297
|
+
metadata: params.metadata,
|
|
291
298
|
endpoint: "ilink/bot/getconfig",
|
|
292
299
|
body: JSON.stringify({
|
|
293
300
|
ilink_user_id: params.ilinkUserId,
|
|
294
301
|
context_token: params.contextToken,
|
|
295
|
-
base_info: buildBaseInfo(),
|
|
302
|
+
base_info: params.metadata.buildBaseInfo(),
|
|
296
303
|
}),
|
|
297
304
|
token: params.token,
|
|
298
305
|
timeoutMs: params.timeoutMs ?? DEFAULT_CONFIG_TIMEOUT_MS,
|
|
@@ -308,8 +315,9 @@ export async function sendTyping(
|
|
|
308
315
|
): Promise<void> {
|
|
309
316
|
await apiPostFetch({
|
|
310
317
|
baseUrl: params.baseUrl,
|
|
318
|
+
metadata: params.metadata,
|
|
311
319
|
endpoint: "ilink/bot/sendtyping",
|
|
312
|
-
body: JSON.stringify({ ...params.body, base_info: buildBaseInfo() }),
|
|
320
|
+
body: JSON.stringify({ ...params.body, base_info: params.metadata.buildBaseInfo() }),
|
|
313
321
|
token: params.token,
|
|
314
322
|
timeoutMs: params.timeoutMs ?? DEFAULT_CONFIG_TIMEOUT_MS,
|
|
315
323
|
label: "sendTyping",
|
|
@@ -324,8 +332,9 @@ export async function sendTyping(
|
|
|
324
332
|
export async function notifyStop(params: WeixinApiOptions): Promise<NotifyStopResp> {
|
|
325
333
|
const rawText = await apiPostFetch({
|
|
326
334
|
baseUrl: params.baseUrl,
|
|
335
|
+
metadata: params.metadata,
|
|
327
336
|
endpoint: "ilink/bot/msg/notifystop",
|
|
328
|
-
body: JSON.stringify({ base_info: buildBaseInfo() }),
|
|
337
|
+
body: JSON.stringify({ base_info: params.metadata.buildBaseInfo() }),
|
|
329
338
|
token: params.token,
|
|
330
339
|
timeoutMs: params.timeoutMs ?? DEFAULT_CONFIG_TIMEOUT_MS,
|
|
331
340
|
label: "notifyStop",
|
|
@@ -339,8 +348,9 @@ export async function notifyStop(params: WeixinApiOptions): Promise<NotifyStopRe
|
|
|
339
348
|
export async function notifyStart(params: WeixinApiOptions): Promise<NotifyStartResp> {
|
|
340
349
|
const rawText = await apiPostFetch({
|
|
341
350
|
baseUrl: params.baseUrl,
|
|
351
|
+
metadata: params.metadata,
|
|
342
352
|
endpoint: "ilink/bot/msg/notifystart",
|
|
343
|
-
body: JSON.stringify({ base_info: buildBaseInfo() }),
|
|
353
|
+
body: JSON.stringify({ base_info: params.metadata.buildBaseInfo() }),
|
|
344
354
|
token: params.token,
|
|
345
355
|
timeoutMs: params.timeoutMs ?? DEFAULT_CONFIG_TIMEOUT_MS,
|
|
346
356
|
label: "notifyStart",
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { getConfig } from "./ilink-api.js";
|
|
1
|
+
import { getConfig, type WeixinApiOptions } from "./ilink-api.js";
|
|
2
2
|
|
|
3
3
|
/** Subset of getConfig fields that we actually need; add new fields here as needed. */
|
|
4
4
|
export interface CachedConfig {
|
|
@@ -21,41 +21,45 @@ interface ConfigCacheEntry {
|
|
|
21
21
|
* exponential-backoff retry (up to 1h) on failure.
|
|
22
22
|
*/
|
|
23
23
|
export class WeixinConfigManager {
|
|
24
|
-
|
|
24
|
+
readonly #cache = new Map<string, ConfigCacheEntry>();
|
|
25
|
+
readonly #apiOptions: WeixinApiOptions;
|
|
26
|
+
readonly #log: (msg: string) => void;
|
|
25
27
|
|
|
26
28
|
constructor(
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
) {
|
|
29
|
+
apiOptions: WeixinApiOptions,
|
|
30
|
+
log: (msg: string) => void,
|
|
31
|
+
) {
|
|
32
|
+
this.#apiOptions = apiOptions;
|
|
33
|
+
this.#log = log;
|
|
34
|
+
}
|
|
30
35
|
|
|
31
36
|
async getForUser(userId: string, contextToken?: string): Promise<CachedConfig> {
|
|
32
37
|
const now = Date.now();
|
|
33
|
-
const entry = this
|
|
38
|
+
const entry = this.#cache.get(userId);
|
|
34
39
|
const shouldFetch = !entry || now >= entry.nextFetchAt;
|
|
35
40
|
|
|
36
41
|
if (shouldFetch) {
|
|
37
42
|
let fetchOk = false;
|
|
38
43
|
try {
|
|
39
44
|
const resp = await getConfig({
|
|
40
|
-
|
|
41
|
-
token: this.apiOpts.token,
|
|
45
|
+
...this.#apiOptions,
|
|
42
46
|
ilinkUserId: userId,
|
|
43
47
|
contextToken,
|
|
44
48
|
});
|
|
45
49
|
if (resp.ret === 0) {
|
|
46
|
-
this
|
|
50
|
+
this.#cache.set(userId, {
|
|
47
51
|
config: { typingTicket: resp.typing_ticket ?? "" },
|
|
48
52
|
everSucceeded: true,
|
|
49
53
|
nextFetchAt: now + Math.random() * CONFIG_CACHE_TTL_MS,
|
|
50
54
|
retryDelayMs: CONFIG_CACHE_INITIAL_RETRY_MS,
|
|
51
55
|
});
|
|
52
|
-
this
|
|
56
|
+
this.#log(
|
|
53
57
|
`[weixin] config ${entry?.everSucceeded ? "refreshed" : "cached"} for ${userId}`,
|
|
54
58
|
);
|
|
55
59
|
fetchOk = true;
|
|
56
60
|
}
|
|
57
61
|
} catch (err) {
|
|
58
|
-
this
|
|
62
|
+
this.#log(`[weixin] getConfig failed for ${userId} (ignored): ${String(err)}`);
|
|
59
63
|
}
|
|
60
64
|
if (!fetchOk) {
|
|
61
65
|
const prevDelay = entry?.retryDelayMs ?? CONFIG_CACHE_INITIAL_RETRY_MS;
|
|
@@ -64,7 +68,7 @@ export class WeixinConfigManager {
|
|
|
64
68
|
entry.nextFetchAt = now + nextDelay;
|
|
65
69
|
entry.retryDelayMs = nextDelay;
|
|
66
70
|
} else {
|
|
67
|
-
this
|
|
71
|
+
this.#cache.set(userId, {
|
|
68
72
|
config: { typingTicket: "" },
|
|
69
73
|
everSucceeded: false,
|
|
70
74
|
nextFetchAt: now + CONFIG_CACHE_INITIAL_RETRY_MS,
|
|
@@ -74,6 +78,6 @@ export class WeixinConfigManager {
|
|
|
74
78
|
}
|
|
75
79
|
}
|
|
76
80
|
|
|
77
|
-
return this
|
|
81
|
+
return this.#cache.get(userId)?.config ?? { typingTicket: "" };
|
|
78
82
|
}
|
|
79
83
|
}
|
package/src/ilink-logger.ts
CHANGED
|
@@ -6,31 +6,16 @@ export type IlinkLogger = {
|
|
|
6
6
|
withAccount: (accountId: string) => IlinkLogger;
|
|
7
7
|
};
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
warn: (msg) => sink.warn(`${prefix} ${msg}`),
|
|
20
|
-
error: (msg) => sink.error(`${prefix} ${msg}`),
|
|
21
|
-
withAccount: () => this,
|
|
22
|
-
};
|
|
23
|
-
},
|
|
24
|
-
};
|
|
25
|
-
|
|
26
|
-
export function setIlinkLogger(next: IlinkLogger): void {
|
|
27
|
-
sink = next;
|
|
9
|
+
function createIlinkLogger(prefix = '[weixin-ilink]'): IlinkLogger {
|
|
10
|
+
return Object.freeze({
|
|
11
|
+
debug: () => {},
|
|
12
|
+
info: () => {},
|
|
13
|
+
warn: (msg) => console.warn(`${prefix} ${msg}`),
|
|
14
|
+
error: (msg) => console.error(`${prefix} ${msg}`),
|
|
15
|
+
withAccount(accountId) {
|
|
16
|
+
return createIlinkLogger(`[weixin-ilink:${accountId}]`);
|
|
17
|
+
},
|
|
18
|
+
});
|
|
28
19
|
}
|
|
29
20
|
|
|
30
|
-
export const logger: IlinkLogger =
|
|
31
|
-
debug: (msg) => sink.debug(msg),
|
|
32
|
-
info: (msg) => sink.info(msg),
|
|
33
|
-
warn: (msg) => sink.warn(msg),
|
|
34
|
-
error: (msg) => sink.error(msg),
|
|
35
|
-
withAccount: (accountId) => sink.withAccount(accountId),
|
|
36
|
-
};
|
|
21
|
+
export const logger: IlinkLogger = createIlinkLogger();
|
package/src/ilink-meta.ts
CHANGED
|
@@ -10,9 +10,6 @@ export const DEFAULT_API_BASE_URL = "https://ilinkai.weixin.qq.com";
|
|
|
10
10
|
const DEFAULT_BOT_AGENT = "Zhin.js";
|
|
11
11
|
const BOT_AGENT_MAX_LEN = 256;
|
|
12
12
|
|
|
13
|
-
let channelVersion = "0.0.0";
|
|
14
|
-
let configuredBotAgent: string | undefined;
|
|
15
|
-
|
|
16
13
|
function readPackageVersion(): string {
|
|
17
14
|
try {
|
|
18
15
|
const pkgPath = path.join(path.dirname(fileURLToPath(import.meta.url)), "../package.json");
|
|
@@ -23,12 +20,7 @@ function readPackageVersion(): string {
|
|
|
23
20
|
}
|
|
24
21
|
}
|
|
25
22
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
export function configureIlinkMeta(opts: { botAgent?: string; version?: string }): void {
|
|
29
|
-
if (opts.botAgent) configuredBotAgent = opts.botAgent;
|
|
30
|
-
if (opts.version) channelVersion = opts.version;
|
|
31
|
-
}
|
|
23
|
+
const PACKAGE_VERSION = readPackageVersion();
|
|
32
24
|
|
|
33
25
|
export function buildClientVersion(version: string): number {
|
|
34
26
|
const parts = version.split(".").map((p) => parseInt(p, 10));
|
|
@@ -38,23 +30,41 @@ export function buildClientVersion(version: string): number {
|
|
|
38
30
|
return ((major & 0xff) << 16) | ((minor & 0xff) << 8) | (patch & 0xff);
|
|
39
31
|
}
|
|
40
32
|
|
|
41
|
-
export
|
|
42
|
-
|
|
43
|
-
export function sanitizeBotAgent(raw: string | undefined): string {
|
|
44
|
-
if (!raw || typeof raw !== "string") return configuredBotAgent ?? DEFAULT_BOT_AGENT;
|
|
33
|
+
export function sanitizeBotAgent(raw: string | undefined, fallback = DEFAULT_BOT_AGENT): string {
|
|
34
|
+
if (!raw || typeof raw !== "string") return fallback;
|
|
45
35
|
const trimmed = raw.trim();
|
|
46
|
-
if (!trimmed) return
|
|
36
|
+
if (!trimmed) return fallback;
|
|
47
37
|
const productRe = /^[A-Za-z0-9_.\-]{1,32}\/[A-Za-z0-9_.+\-]{1,32}$/;
|
|
48
38
|
const tokens = trimmed.split(/\s+/).filter((tok) => productRe.test(tok));
|
|
49
|
-
if (tokens.length === 0) return
|
|
39
|
+
if (tokens.length === 0) return fallback;
|
|
50
40
|
const joined = tokens.join(" ");
|
|
51
41
|
if (Buffer.byteLength(joined, "utf-8") <= BOT_AGENT_MAX_LEN) return joined;
|
|
52
|
-
return
|
|
42
|
+
return fallback;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface IlinkClientMetadataOptions {
|
|
46
|
+
readonly botAgent?: string;
|
|
47
|
+
readonly version?: string;
|
|
53
48
|
}
|
|
54
49
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
50
|
+
/** Immutable request identity owned by one endpoint. */
|
|
51
|
+
export class IlinkClientMetadata {
|
|
52
|
+
readonly channelVersion: string;
|
|
53
|
+
readonly botAgent: string;
|
|
54
|
+
readonly appClientVersion: number;
|
|
55
|
+
|
|
56
|
+
constructor(options: IlinkClientMetadataOptions = {}) {
|
|
57
|
+
this.channelVersion = options.version ?? PACKAGE_VERSION;
|
|
58
|
+
const defaultBotAgent = `Zhin.js/${this.channelVersion}`;
|
|
59
|
+
this.botAgent = sanitizeBotAgent(options.botAgent, defaultBotAgent);
|
|
60
|
+
this.appClientVersion = buildClientVersion(this.channelVersion);
|
|
61
|
+
Object.freeze(this);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
buildBaseInfo(): BaseInfo {
|
|
65
|
+
return {
|
|
66
|
+
channel_version: this.channelVersion,
|
|
67
|
+
bot_agent: this.botAgent,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
60
70
|
}
|
|
@@ -1,58 +1,41 @@
|
|
|
1
|
-
import { logger } from
|
|
1
|
+
import { logger } from './ilink-logger.js';
|
|
2
2
|
|
|
3
|
-
const SESSION_PAUSE_DURATION_MS = 60 * 60 * 1000;
|
|
4
|
-
|
|
5
|
-
/** Error code returned by the server when the bot session has expired. */
|
|
6
3
|
export const SESSION_EXPIRED_ERRCODE = -14;
|
|
4
|
+
export const SESSION_PAUSE_DURATION_MS = 60 * 60 * 1000;
|
|
5
|
+
|
|
6
|
+
/** Endpoint-owned cooldown state for an authenticated iLink session. */
|
|
7
|
+
export class IlinkSessionGuard {
|
|
8
|
+
#pauseUntil = 0;
|
|
9
|
+
|
|
10
|
+
constructor(
|
|
11
|
+
readonly accountId: string,
|
|
12
|
+
private readonly now: () => number = Date.now,
|
|
13
|
+
private readonly pauseDurationMs = SESSION_PAUSE_DURATION_MS,
|
|
14
|
+
) {}
|
|
15
|
+
|
|
16
|
+
pause(): void {
|
|
17
|
+
this.#pauseUntil = this.now() + this.pauseDurationMs;
|
|
18
|
+
logger.info(
|
|
19
|
+
`session-guard: paused accountId=${this.accountId} until=${new Date(this.#pauseUntil).toISOString()} (${this.pauseDurationMs / 1000}s)`,
|
|
20
|
+
);
|
|
21
|
+
}
|
|
7
22
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
/** Pause all inbound/outbound API calls for `accountId` for one hour. */
|
|
11
|
-
export function pauseSession(accountId: string): void {
|
|
12
|
-
const until = Date.now() + SESSION_PAUSE_DURATION_MS;
|
|
13
|
-
pauseUntilMap.set(accountId, until);
|
|
14
|
-
logger.info(
|
|
15
|
-
`session-guard: paused accountId=${accountId} until=${new Date(until).toISOString()} (${SESSION_PAUSE_DURATION_MS / 1000}s)`,
|
|
16
|
-
);
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
/** Returns `true` when the bot is still within its one-hour cooldown window. */
|
|
20
|
-
export function isSessionPaused(accountId: string): boolean {
|
|
21
|
-
const until = pauseUntilMap.get(accountId);
|
|
22
|
-
if (until === undefined) return false;
|
|
23
|
-
if (Date.now() >= until) {
|
|
24
|
-
pauseUntilMap.delete(accountId);
|
|
25
|
-
return false;
|
|
23
|
+
get paused(): boolean {
|
|
24
|
+
return this.remainingMs > 0;
|
|
26
25
|
}
|
|
27
|
-
return true;
|
|
28
|
-
}
|
|
29
26
|
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
const remaining = until - Date.now();
|
|
35
|
-
if (remaining <= 0) {
|
|
36
|
-
pauseUntilMap.delete(accountId);
|
|
27
|
+
get remainingMs(): number {
|
|
28
|
+
const remaining = this.#pauseUntil - this.now();
|
|
29
|
+
if (remaining > 0) return remaining;
|
|
30
|
+
this.#pauseUntil = 0;
|
|
37
31
|
return 0;
|
|
38
32
|
}
|
|
39
|
-
return remaining;
|
|
40
|
-
}
|
|
41
33
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const remainingMin = Math.ceil(getRemainingPauseMs(accountId) / 60_000);
|
|
34
|
+
assertActive(): void {
|
|
35
|
+
const remaining = this.remainingMs;
|
|
36
|
+
if (remaining === 0) return;
|
|
46
37
|
throw new Error(
|
|
47
|
-
`session paused for accountId=${accountId}, ${
|
|
38
|
+
`session paused for accountId=${this.accountId}, ${Math.ceil(remaining / 60_000)} min remaining (errcode ${SESSION_EXPIRED_ERRCODE})`,
|
|
48
39
|
);
|
|
49
40
|
}
|
|
50
41
|
}
|
|
51
|
-
|
|
52
|
-
/**
|
|
53
|
-
* Reset internal state — only for tests.
|
|
54
|
-
* @internal
|
|
55
|
-
*/
|
|
56
|
-
export function _resetForTest(): void {
|
|
57
|
-
pauseUntilMap.clear();
|
|
58
|
-
}
|
package/src/index.ts
CHANGED
|
@@ -1,60 +1,45 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 微信 iLink(ClawBot)适配器入口
|
|
3
|
-
*/
|
|
4
|
-
import path from "node:path";
|
|
5
|
-
import { usePlugin, type Plugin } from "zhin.js";
|
|
6
|
-
import type { Router } from "@zhin.js/host-router";
|
|
7
|
-
import { PageManager } from "@zhin.js/host-api";
|
|
8
|
-
import { WeixinIlinkAdapter } from "./adapter.js";
|
|
9
|
-
import { registerRoutes } from "./routes.js";
|
|
10
|
-
|
|
11
|
-
declare module "zhin.js" {
|
|
12
|
-
namespace Plugin {
|
|
13
|
-
interface Contexts {
|
|
14
|
-
web: PageManager;
|
|
15
|
-
router: Router;
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
interface Adapters {
|
|
19
|
-
"weixin-ilink": WeixinIlinkAdapter;
|
|
20
|
-
}
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export * from "./types.js";
|
|
24
|
-
export { WeixinIlinkEndpoint } from "./endpoint.js";
|
|
25
|
-
export { WeixinIlinkAdapter } from "./adapter.js";
|
|
26
1
|
export {
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
2
|
+
formatInboundContent,
|
|
3
|
+
formatOutboundSegments,
|
|
4
|
+
inboundMessageId,
|
|
5
|
+
resolveWeixinIlinkConfig,
|
|
6
|
+
segmentLocalPath,
|
|
7
|
+
sleep,
|
|
8
|
+
type ResolvedWeixinIlinkConfig,
|
|
9
|
+
type WeixinIlinkEndpointConfig,
|
|
10
|
+
type WeixinInboundMediaPaths,
|
|
11
|
+
type WeixinMessageWithMedia,
|
|
12
|
+
type WeixinWireSegment,
|
|
13
|
+
} from './protocol.js';
|
|
32
14
|
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
15
|
+
export type { WeixinMessage, MessageItem } from './ilink-types.js';
|
|
16
|
+
export {
|
|
17
|
+
WeixinIlinkStateStore,
|
|
18
|
+
type WeixinIlinkCredentials,
|
|
19
|
+
} from './credentials.js';
|
|
20
|
+
export {
|
|
21
|
+
IlinkClientMetadata,
|
|
22
|
+
sanitizeBotAgent,
|
|
23
|
+
type IlinkClientMetadataOptions,
|
|
24
|
+
} from './ilink-meta.js';
|
|
25
|
+
export { WeixinContextTokenStore } from './context-store.js';
|
|
26
|
+
export {
|
|
27
|
+
IlinkSessionGuard,
|
|
28
|
+
SESSION_EXPIRED_ERRCODE,
|
|
29
|
+
SESSION_PAUSE_DURATION_MS,
|
|
30
|
+
} from './ilink-session-guard.js';
|
|
48
31
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
meta: { name: "微信 iLink" },
|
|
55
|
-
});
|
|
56
|
-
});
|
|
32
|
+
export {
|
|
33
|
+
WeixinIlinkClient,
|
|
34
|
+
weixinIlinkClient,
|
|
35
|
+
type WeixinIlinkClientEventMap,
|
|
36
|
+
} from './client.js';
|
|
57
37
|
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
38
|
+
export {
|
|
39
|
+
WeixinIlinkEndpoint,
|
|
40
|
+
type WeixinIlinkEndpointOptions,
|
|
41
|
+
type WeixinIlinkGetUpdates,
|
|
42
|
+
type WeixinIlinkNotifyStart,
|
|
43
|
+
type WeixinIlinkNotifyStop,
|
|
44
|
+
type WeixinIlinkSendText,
|
|
45
|
+
} from './endpoint.js';
|