koishi-plugin-jscn-aaaquery 1.0.22 → 1.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/lib/index.d.ts CHANGED
@@ -5,6 +5,7 @@ export interface Config {
5
5
  password: string;
6
6
  baseUrl: string;
7
7
  radiusApiUrl?: string;
8
+ captchaMode?: 'interactive';
8
9
  }
9
10
  export declare const Config: Schema<Config>;
10
11
  export declare function apply(ctx: Context, config: Config): void;
package/lib/index.js CHANGED
@@ -32,7 +32,9 @@ var Config = import_koishi.Schema.object({
32
32
  password: import_koishi.Schema.string().required().description("运维系统登录密码").default("admin"),
33
33
  baseUrl: import_koishi.Schema.string().default("http://172.16.251.75:8090/nms/api").description("运维系统API地址"),
34
34
  // 添加RADIUS API的配置项
35
- radiusApiUrl: import_koishi.Schema.string().description("RADIUS API基础URL").default("http://111.208.114.248:28210/api/radius")
35
+ radiusApiUrl: import_koishi.Schema.string().description("RADIUS API基础URL").default("http://111.208.114.248:28210/api/radius"),
36
+ // 验证码模式
37
+ captchaMode: import_koishi.Schema.const("interactive").description("登录验证码获取方式(发送图片到对话,用户输入)").default("interactive")
36
38
  });
37
39
  function evaluateOpticalPower(power) {
38
40
  if (power === "设备不在线" || power === void 0 || power === null) {
@@ -83,6 +85,7 @@ function apply(ctx, config) {
83
85
  const requestWaitQueue = [];
84
86
  const messageQueue = [];
85
87
  let isProcessingMessage = false;
88
+ let currentSession = null;
86
89
  const MESSAGE_TIMEOUT2 = 1 * 60 * 1e3;
87
90
  const MESSAGE_CLEAN_INTERVAL2 = 60 * 1e3;
88
91
  const MAX_QUEUE_LENGTH = 50;
@@ -260,7 +263,7 @@ function apply(ctx, config) {
260
263
  refreshTokenInBackground();
261
264
  return currentToken;
262
265
  }
263
- return refreshToken();
266
+ return refreshToken(currentSession);
264
267
  }
265
268
  __name(getToken, "getToken");
266
269
  async function refreshTokenInBackground() {
@@ -274,28 +277,107 @@ function apply(ctx, config) {
274
277
  }
275
278
  }
276
279
  __name(refreshTokenInBackground, "refreshTokenInBackground");
277
- async function refreshToken() {
280
+ const captchaPendingMap = /* @__PURE__ */ new Map();
281
+ const CAPTCHA_TIMEOUT = 5 * 60 * 1e3;
282
+ setInterval(() => {
283
+ const now = Date.now();
284
+ for (const [key, task] of captchaPendingMap) {
285
+ if (now - task.timestamp > CAPTCHA_TIMEOUT) {
286
+ task.reject(new Error("验证码输入超时(5分钟),登录已取消"));
287
+ captchaPendingMap.delete(key);
288
+ console.log(`清理超时的验证码等待任务: ${key}`);
289
+ }
290
+ }
291
+ }, 30 * 1e3);
292
+ function extractBase64(dataUri) {
293
+ const commaIdx = dataUri.indexOf(",");
294
+ if (commaIdx >= 0) return dataUri.substring(commaIdx + 1);
295
+ return dataUri;
296
+ }
297
+ __name(extractBase64, "extractBase64");
298
+ async function fetchCaptcha() {
299
+ const response = await ctx.http.get(`${config.baseUrl}/admin/captcha`, {
300
+ headers: {
301
+ "Accept": "application/json"
302
+ },
303
+ timeout: 1e4
304
+ });
305
+ if (response.status === 200 && response.data && response.data.captchaKey && response.data.captchaImage) {
306
+ return {
307
+ captchaKey: response.data.captchaKey,
308
+ captchaImage: response.data.captchaImage
309
+ };
310
+ }
311
+ throw new Error(`获取验证码失败:${response.message || "未知错误"}`);
312
+ }
313
+ __name(fetchCaptcha, "fetchCaptcha");
314
+ async function refreshToken(session) {
278
315
  try {
279
316
  console.log("开始登录请求刷新token...");
280
317
  await waitForRequestSlot();
281
- const response = await ctx.http.post(
282
- `${config.baseUrl}/admin/login`,
283
- `loginName=${encodeURIComponent(config.loginName)}&pwd=${encodeURIComponent(config.password)}`,
284
- {
285
- headers: {
286
- "Content-Type": "application/x-www-form-urlencoded",
287
- "Accept": "application/json"
318
+ let captchaKey = "";
319
+ let captchaCode = "";
320
+ if (config.captchaMode === "interactive") {
321
+ if (!session) {
322
+ throw new Error("交互式验证码需要 session,但未检测到用户会话,请稍后重试");
323
+ }
324
+ const MAX_CAPTCHA_ATTEMPTS = 5;
325
+ const sessionKey = `${session.userId || "anon"}:${session.channelId || "dm"}`;
326
+ for (let attempt = 1; attempt <= MAX_CAPTCHA_ATTEMPTS; attempt++) {
327
+ captchaPendingMap.delete(sessionKey);
328
+ const { captchaKey: key, captchaImage } = await fetchCaptcha();
329
+ captchaKey = key;
330
+ try {
331
+ const base64Data = extractBase64(captchaImage);
332
+ const promptText = attempt > 1 ? `🔐 验证码错误,请重新输入新图中的验证码(第${attempt}/${MAX_CAPTCHA_ATTEMPTS}次)` : "🔐 请输入图中验证码(5分钟内有效,超时需重新发起查询)";
333
+ await session.send([
334
+ import_koishi.h.image(Buffer.from(base64Data, "base64"), "image/png"),
335
+ promptText
336
+ ]);
337
+ } catch (sendError) {
338
+ console.error("发送验证码图片失败:", sendError);
339
+ throw new Error("发送验证码图片失败,请检查图片发送权限");
340
+ }
341
+ captchaCode = await new Promise((resolve, reject) => {
342
+ captchaPendingMap.set(sessionKey, {
343
+ session,
344
+ captchaKey,
345
+ captchaImage,
346
+ resolve,
347
+ reject,
348
+ timestamp: Date.now()
349
+ });
350
+ console.log(`验证码等待任务已注册: ${sessionKey}, captchaKey: ${captchaKey}, 第${attempt}轮`);
351
+ });
352
+ const response = await ctx.http.post(
353
+ `${config.baseUrl}/admin/login`,
354
+ `loginName=${encodeURIComponent(config.loginName)}&pwd=${encodeURIComponent(config.password)}&captchaKey=${encodeURIComponent(captchaKey)}&captchaCode=${encodeURIComponent(captchaCode)}`,
355
+ {
356
+ headers: {
357
+ "Content-Type": "application/x-www-form-urlencoded",
358
+ "Accept": "application/json"
359
+ }
360
+ }
361
+ );
362
+ console.log("登录响应:", JSON.stringify(response, null, 2));
363
+ if (response.status === 200 && response.data && response.data.token) {
364
+ currentToken = response.data.token;
365
+ tokenExpireTime = response.data.timeStamp * 1e3;
366
+ console.log("获取新token成功,过期时间:", new Date(tokenExpireTime).toLocaleString());
367
+ return currentToken;
288
368
  }
369
+ const message = response.data?.message || response.message || "";
370
+ if (message.includes("验证码") || message.includes("captcha")) {
371
+ console.log(`验证码错误,第${attempt}轮失败,准备进入第${attempt + 1}轮`);
372
+ captchaPendingMap.delete(sessionKey);
373
+ if (attempt === MAX_CAPTCHA_ATTEMPTS) {
374
+ throw new Error("验证码错误次数过多,请稍后重新发起查询");
375
+ }
376
+ continue;
377
+ }
378
+ throw new Error(`登录失败:${message || "未知错误"}`);
289
379
  }
290
- );
291
- console.log("登录响应:", JSON.stringify(response, null, 2));
292
- if (response.status === 200 && response.data && response.data.token) {
293
- currentToken = response.data.token;
294
- tokenExpireTime = response.data.timeStamp * 1e3;
295
- console.log("获取新token成功,过期时间:", new Date(tokenExpireTime).toLocaleString());
296
- return currentToken;
297
380
  }
298
- throw new Error(`登录失败:${response.message || "未知错误"}`);
299
381
  } catch (error) {
300
382
  console.error("登录错误详情:", error);
301
383
  if (error.response) {
@@ -893,6 +975,7 @@ function apply(ctx, config) {
893
975
  return;
894
976
  }
895
977
  console.log("开始处理消息队列中的任务");
978
+ currentSession = task.session || null;
896
979
  const result = await task.handler();
897
980
  if (result && task.session?.send) {
898
981
  const formattedResult = formatOutputMessage(result);
@@ -1069,6 +1152,26 @@ function apply(ctx, config) {
1069
1152
  }
1070
1153
  }
1071
1154
  __name(smartQueryMacAddress, "smartQueryMacAddress");
1155
+ ctx.middleware(async (session, next) => {
1156
+ const input = (session.stripped?.content || session.content || "").trim();
1157
+ if (!input) return next();
1158
+ const sessionKey = `${session.userId || "anon"}:${session.channelId || "dm"}`;
1159
+ const pendingTask = captchaPendingMap.get(sessionKey);
1160
+ if (!pendingTask) {
1161
+ return next();
1162
+ }
1163
+ console.log(`捕获到验证码输入: "${input}",对应 captchaKey: ${pendingTask.captchaKey}`);
1164
+ if (!/^[a-z0-9]{2,8}$/i.test(input)) {
1165
+ return next();
1166
+ }
1167
+ captchaPendingMap.delete(sessionKey);
1168
+ pendingTask.resolve(input.replace(/\s+/g, "").toLowerCase());
1169
+ try {
1170
+ await session.send("✅ 验证码已接收,正在登录...");
1171
+ } catch (_) {
1172
+ }
1173
+ return;
1174
+ });
1072
1175
  ctx.middleware(async (session, next) => {
1073
1176
  console.log("原始消息:", session.content);
1074
1177
  const originalInput = session.stripped.content.trim();
@@ -1620,6 +1723,12 @@ function apply(ctx, config) {
1620
1723
  const result = clearCache();
1621
1724
  return formatOutputMessage(`✅ ${result}`);
1622
1725
  });
1726
+ ctx.command("强制刷新token", "强制清除缓存的token,重新获取登录验证码").action(async ({ session }) => {
1727
+ currentToken = null;
1728
+ tokenExpireTime = 0;
1729
+ const token = await refreshToken(session);
1730
+ return formatOutputMessage(`✅ Token已刷新,过期时间: ${new Date(tokenExpireTime).toLocaleString()}`);
1731
+ });
1623
1732
  async function diagnoseNetwork() {
1624
1733
  const results = [];
1625
1734
  results.push("🌐 网络连接诊断");
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "koishi-plugin-jscn-aaaquery",
3
3
  "description": "江苏有线无锡分公司宽带信息查询插件",
4
- "version": "1.0.22",
4
+ "version": "1.1.0",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",
7
7
  "files": [