cortico-world-telegram 0.45.0 → 0.46.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/src/approval.ts CHANGED
@@ -12,6 +12,8 @@
12
12
  * - 码不能当短期通用授权。
13
13
  */
14
14
 
15
+ import { randomInt } from 'node:crypto';
16
+
15
17
  export type RiskKind = 'delete' | 'forward' | 'send_outside' | 'contact_write' | 'sticker_set' | 'send_file';
16
18
 
17
19
  export type GuardPolicy = 'auto' | 'ask' | 'deny';
@@ -32,14 +34,19 @@ export interface ApprovalRequest {
32
34
  /** 去掉容易看错的 0/O/1/I。 */
33
35
  const ALPHABET = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
34
36
 
35
- export function makeApprovalCode(random: () => number = Math.random): string {
37
+ export function makeApprovalCode(random?: () => number): string {
36
38
  let out = '';
37
39
  for (let i = 0; i < 4; i += 1) {
38
- out += ALPHABET[Math.floor(random() * ALPHABET.length)] ?? 'A';
40
+ const idx = random
41
+ ? Math.min(ALPHABET.length - 1, Math.max(0, Math.floor(random() * ALPHABET.length)))
42
+ : randomInt(ALPHABET.length);
43
+ out += ALPHABET[idx] ?? 'A';
39
44
  }
40
45
  return out;
41
46
  }
42
47
 
48
+ const MAX_PENDING_APPROVALS = 50;
49
+
43
50
  export interface ApprovalsOptions {
44
51
  ttlMs?: number;
45
52
  now?: () => number;
@@ -50,12 +57,12 @@ export class Approvals {
50
57
  private readonly items = new Map<string, ApprovalRequest>();
51
58
  private ttlMs: number;
52
59
  private readonly now: () => number;
53
- private readonly random: () => number;
60
+ private readonly random?: () => number;
54
61
 
55
62
  constructor(opts: ApprovalsOptions = {}) {
56
63
  this.ttlMs = opts.ttlMs ?? 5 * 60_000;
57
64
  this.now = opts.now ?? (() => Date.now());
58
- this.random = opts.random ?? Math.random;
65
+ this.random = opts.random;
59
66
  }
60
67
 
61
68
  /** 热更新审批有效期(新发起的审批生效)。 */
@@ -63,11 +70,22 @@ export class Approvals {
63
70
  if (Number.isFinite(ttlMs) && ttlMs > 0) this.ttlMs = ttlMs;
64
71
  }
65
72
 
73
+ /** 清空所有待批准项(停机或登出时调用)。 */
74
+ clear(): void {
75
+ this.items.clear();
76
+ }
77
+
66
78
  /** 登记一次待批准操作,返回带码的请求。 */
67
79
  request(kind: RiskKind, summary: string, target: string, run: () => Promise<string>): ApprovalRequest {
68
80
  this.purge();
81
+ // 防止待审队列无限增长:超出上限时淘汰最旧条目
82
+ while (this.items.size >= MAX_PENDING_APPROVALS) {
83
+ const oldest = this.items.keys().next().value;
84
+ if (oldest === undefined) break;
85
+ this.items.delete(oldest);
86
+ }
69
87
  let code = makeApprovalCode(this.random);
70
- for (let attempt = 0; attempt < 8 && this.items.has(code); attempt += 1) {
88
+ for (let attempt = 0; attempt < 32 && this.items.has(code); attempt += 1) {
71
89
  code = makeApprovalCode(this.random);
72
90
  }
73
91
  const at = this.now();
@@ -136,8 +154,7 @@ export class Approvals {
136
154
  /** 解析 `!ok A7F3` / `!no a7f3` / `!ok`(不带码时列清单)。 */
137
155
  export function parseApprovalCommand(text: string): { decision: 'ok' | 'no' | 'list'; code?: string } | null {
138
156
  const value = text.trim();
139
- if (!/^!(ok|no|list)\b/i.test(value)) return null;
140
- const match = /^!(ok|no|list)\s*([A-Za-z0-9]{0,8})?/i.exec(value);
157
+ const match = /^!(ok|no|list)(?:\s+([A-Za-z0-9]{1,8}))?$/i.exec(value);
141
158
  if (!match) return null;
142
159
  const decision = match[1]?.toLowerCase() as 'ok' | 'no' | 'list';
143
160
  const code = match[2]?.trim();
@@ -175,11 +192,11 @@ const ALLOW_EXACT = new Set(['好', '行', '嗯', '发']);
175
192
  const ALLOW_ENGLISH = ['ok', 'okay', 'yes', 'sure', 'fine'];
176
193
 
177
194
  const DENY_PHRASES = [
178
- '不行', '不可以', '不好', '不能', '不能发', '不发', '不要', '不用', '不必',
179
- '别发', '别给', '别删', '别做', '别弄', '别了', '别吧', '算了', '不给', '不许', '不准', '拒绝', '收回',
195
+ '不行', '不可以', '不好', '不能', '不能发', '不发', '不要', '不用', '不必', '不太', '不了', '先别', '暂不',
196
+ '别发', '别给', '别删', '别做', '别弄', '别了', '别吧', '算了', '不给', '不许', '不准', '拒绝', '收回', '个屁', '才不', '先等等', '等等再',
180
197
  ];
181
198
  const DENY_EXACT = new Set(['别', '不']);
182
- const DENY_ENGLISH = ['no', 'nope', 'stop', 'cancel'];
199
+ const DENY_ENGLISH = ['no', 'nope', 'nah', 'not', 'dont', "don't", 'never', 'stop', 'cancel', 'wait', 'hold', 'deny', 'reject', 'refuse'];
183
200
 
184
201
  const DELEGATE_WORDS = [
185
202
  '随便你', '随你', '你看着办', '你定', '你决定', '你说了算', '看你', '你拿主意', '你自己决定', '随意',
@@ -187,7 +204,10 @@ const DELEGATE_WORDS = [
187
204
  ];
188
205
 
189
206
  function hasEnglishWord(raw: string, words: readonly string[]): boolean {
190
- return words.some((word) => new RegExp(`(?:^|[^a-z])${word}(?:$|[^a-z])`, 'i').test(raw));
207
+ return words.some((word) => {
208
+ const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
209
+ return new RegExp(`(?:^|[^a-z'])${escaped}(?:$|[^a-z'])`, 'i').test(raw);
210
+ });
191
211
  }
192
212
 
193
213
  export function classifyOwnerReply(text: string): OwnerReply | null {
@@ -198,8 +218,9 @@ export function classifyOwnerReply(text: string): OwnerReply | null {
198
218
  if (!flat) return null;
199
219
  // 太长的当普通聊天,不碰审批(避免"我觉得可以但……"误判成同意)
200
220
  if (flat.length > 24) return null;
201
- // 问句一律不当成决定:「你觉得可以吗」「能发吗」
202
- if (/[吗么呢]$/.test(flat) || /[??]$/.test(raw)) return null;
221
+ // 问句一律不当成决定:「你觉得可以吗」「能发吗」「可以不」(明确拒绝词如「暂不」「才不」除外)
222
+ if (/[吗么呢不]$/.test(flat) && flat !== '不' && !DENY_PHRASES.includes(flat)) return null;
223
+ if (/[??]$/.test(raw)) return null;
203
224
 
204
225
  if (DELEGATE_WORDS.some((word) => flat.includes(word.replace(/\s+/g, '')))) return 'delegate';
205
226
 
package/src/audit.ts CHANGED
@@ -20,7 +20,7 @@ export interface AuditEntry {
20
20
  /** done / denied / pending / failed。 */
21
21
  result: string;
22
22
  /** 目标会话 id(有就记)。 */
23
- chatId?: number;
23
+ chatId?: number | string;
24
24
  /** 参数摘要(已脱敏、已截断)。 */
25
25
  args?: string;
26
26
  /** 回执摘要(已脱敏、已截断)。 */
@@ -35,13 +35,16 @@ export interface AuditOptions {
35
35
  }
36
36
 
37
37
  const SECRET_PATTERNS: Array<[RegExp, string]> = [
38
+ // Telegram Bot Token(如 123456789:AAH...)
39
+ [/\b\d{6,15}:[A-Za-z0-9_-]{30,}\b/g, '[redacted-token]'],
38
40
  // 形似 session 串(很长、base64 风格)与 api_hash(32 位十六进制)
39
41
  [/\b[A-Za-z0-9+/=_-]{40,}\b/g, '[redacted-session]'],
40
42
  [/\b[a-f0-9]{32}\b/gi, '[redacted-hash]'],
41
- // 手机号(+86 138… / 独立 11 位数字;加前边界避免误伤 -100… 超级群 ID 和 13 位时间戳)
42
- [/(?<![\d-])(?:\+\d{1,3}[\s-]?)?\d{11}\b/g, '[redacted-phone]'],
43
- // 明确的键值对
44
- [/(api_hash|apiHash|session|password)\s*[=:]\s*\S+/gi, '$1=[redacted]'],
43
+ // 手机号:国际区号(+86 138-0013-8000 / +1 5551234567)或独立 11 位数字;加前边界避免误伤 -100… 超级群 ID 和 13 位时间戳
44
+ [/(?<![\d-])\+\d{1,3}[\s-]?\d{2,4}(?:[\s-]?\d{3,4}){2,3}\b/g, '[redacted-phone]'],
45
+ [/(?<![\d-])\d{11}\b/g, '[redacted-phone]'],
46
+ // 明确的键值对(兼容纯文本 k=v 与 JSON 序列化 "password":"...")
47
+ [/("?(?:api_hash|apiHash|api_key|apiKey|session|password|secret|token|phone|authorization)"?\s*[=:]\s*)(?:"[^"]*"|'[^']*'|[^\s,}]+)/gi, '$1[redacted]'],
45
48
  ];
46
49
 
47
50
  /** 脱敏:把看起来像密钥/手机号的东西换掉。 */
package/src/config.ts CHANGED
@@ -106,6 +106,12 @@ export interface TelegramConfigSection {
106
106
  rateLimit: { perChatMs: number; globalPerMinute: number };
107
107
  /** 会话页双击展开时的默认历史条数(10–900)。 */
108
108
  panelHistoryLimit: number;
109
+ /** 入站唤醒事件末尾附带就地路由提示(提醒模型用 telegram_send_message 回复而非写到控制台,默认开)。 */
110
+ inboundRouteHint: boolean;
111
+ /** 代码级硬兜底:纯 TG 唤醒回合里模型忘调任何工具而直接输出纯文本时,自动补发回该 TG 会话(默认开,热生效)。 */
112
+ autoRescueReply: boolean;
113
+ /** 精简工具模式:只向模型暴露核心 10 个日常工具,降低反代/中转站/弱模型工具退化率(需重启 World 生效)。 */
114
+ compactTools: boolean;
109
115
  transport: { useWSS: boolean; proxy: string };
110
116
  }
111
117
 
@@ -158,6 +164,9 @@ export function telegramDefaults(): TelegramConfigSection {
158
164
  mediaKeepHours: 72,
159
165
  rateLimit: { perChatMs: 1000, globalPerMinute: 20 },
160
166
  panelHistoryLimit: 100,
167
+ inboundRouteHint: true,
168
+ autoRescueReply: true,
169
+ compactTools: false,
161
170
  transport: { useWSS: true, proxy: '' },
162
171
  };
163
172
  }
@@ -174,7 +183,7 @@ export function enabledIds(entries: TelegramRosterEntry[] | undefined): Set<numb
174
183
  /**
175
184
  * 「配置」页签里的可调项。
176
185
  *
177
- * 只放**热更新**字段(读的是 `ctx.cfg` 活引用);凭据、传输要重启,放在登录面板里。
186
+ * 只放最基础的**热更新**字段(读的是 `ctx.cfg` 活引用);凭据与行为/反代兼容开关统一归在对应面板,避免重复。
178
187
  */
179
188
  export function telegramConfigGroup(language: Language): ConfigGroup {
180
189
  const zh = language === 'zh' || language === 'zh-Hant';
@@ -185,8 +194,8 @@ export function telegramConfigGroup(language: Language): ConfigGroup {
185
194
  type: 'object',
186
195
  title: zh ? 'Telegram' : 'Telegram',
187
196
  description: zh
188
- ? '监听范围与合并窗口。改动立即生效;凭据与代理需要重启 World。'
189
- : 'Watch scope and merge window. Takes effect immediately; credentials and proxy need a restart.',
197
+ ? '监听范围、合并窗口与媒体缓存,改动立即生效;更多选项见「行为」页。'
198
+ : 'Watch scope, batching and media retention. Changes take effect immediately; see the Behavior panel for more.',
190
199
  properties: {
191
200
  'worlds.telegram.watchPrivate': {
192
201
  type: 'boolean',
package/src/definition.ts CHANGED
@@ -137,12 +137,12 @@ export const TELEGRAM: WorldDefinition<TelegramConfigSection> = {
137
137
  en: 'Edits a message this account sent (within ~48h).',
138
138
  },
139
139
  telegram_delete_message: {
140
- zh: '删除消息;默认需要真人回「!ok 码」批准。',
141
- en: 'Deletes messages; needs user approval (!ok CODE) by default.',
140
+ zh: '删除消息(受「删除消息」策略控制:允许 / 先问我 / 不允许)。',
141
+ en: 'Deletes messages (controlled by guard.deleteRevoke: auto / ask / deny).',
142
142
  },
143
143
  telegram_forward_messages: {
144
- zh: '把消息转发到别的会话;转出白名单需要审批。',
145
- en: 'Forwards messages; forwarding outside the allow list needs approval.',
144
+ zh: '在白名单会话之间转发消息(来源与目标都必须在监听名单里)。',
145
+ en: 'Forwards messages between allowlisted chats (both source and target must be allowlisted).',
146
146
  },
147
147
  telegram_send_reaction: {
148
148
  zh: '给某条消息加一个 emoji 反应。',
package/src/deps.ts CHANGED
@@ -11,8 +11,8 @@
11
11
  */
12
12
 
13
13
  import { spawn } from 'node:child_process';
14
- import { existsSync, readFileSync } from 'node:fs';
15
- import { dirname, join } from 'node:path';
14
+ import { existsSync, readFileSync, statSync } from 'node:fs';
15
+ import { dirname, isAbsolute, join } from 'node:path';
16
16
  import { fileURLToPath } from 'node:url';
17
17
 
18
18
  export interface DepsStatus {
@@ -202,19 +202,7 @@ export class DepsInstaller {
202
202
  private async run(): Promise<void> {
203
203
  const distReady = existsSync(join(this.packageDir, 'dist', 'webui.js'));
204
204
  try {
205
- try {
206
- await this.exec(this.installArgs(distReady), 'install', this.packageDir);
207
- } catch (error) {
208
- const reason = error instanceof Error ? error.message : String(error);
209
- // 市场装的包可能落在包管理器的只读目录里:改在上层 node_modules 装(Node 会向上找)
210
- if (/EACCES|EPERM|permission|denied|EROFS/i.test(reason)) {
211
- const parent = dirname(this.packageDir);
212
- this.push(`本包目录不可写,改在 ${parent} 安装(Node 会向上查找依赖)`);
213
- await this.exec(this.installArgs(distReady), 'install', parent);
214
- } else {
215
- throw error;
216
- }
217
- }
205
+ await this.exec(this.installArgs(distReady), 'install', this.packageDir);
218
206
 
219
207
  this.progress.phase = 'build';
220
208
  if (existsSync(join(this.packageDir, 'dist', 'webui.js'))) {
@@ -287,7 +275,7 @@ export class DepsInstaller {
287
275
  shell: useShell,
288
276
  windowsHide: true,
289
277
  env: {
290
- ...process.env,
278
+ ...sanitizedInstallEnv(process.env),
291
279
  ...manager.env,
292
280
  npm_config_loglevel: 'warn',
293
281
  // 只在"确实只要运行依赖"时才压 NODE_ENV;
@@ -300,14 +288,34 @@ export class DepsInstaller {
300
288
  return;
301
289
  }
302
290
  this.child = child;
291
+ let settled = false;
292
+ const timeout = setTimeout(() => {
293
+ if (settled) return;
294
+ settled = true;
295
+ try {
296
+ child.kill();
297
+ } catch {
298
+ // 忽略
299
+ }
300
+ reject(new Error(`${manager.label} ${args.join(' ')} 执行超时(>5 分钟)`));
301
+ }, 5 * 60_000);
302
+ timeout.unref?.();
303
303
  child.stdout?.on('data', (chunk: Buffer) => this.push(chunk.toString()));
304
304
  child.stderr?.on('data', (chunk: Buffer) => {
305
305
  const text = chunk.toString();
306
306
  this.push(text);
307
307
  if (errLines.length < 12) errLines.push(text.trim());
308
308
  });
309
- child.on('error', (error) => reject(new Error(`依赖安装启动失败:${error.message}`)));
309
+ child.on('error', (error) => {
310
+ if (settled) return;
311
+ settled = true;
312
+ clearTimeout(timeout);
313
+ reject(new Error(`依赖安装启动失败:${error.message}`));
314
+ });
310
315
  child.on('close', (code) => {
316
+ if (settled) return;
317
+ settled = true;
318
+ clearTimeout(timeout);
311
319
  if (code === 0) resolve();
312
320
  else {
313
321
  const tail = errLines.filter(Boolean).slice(-2).join(' | ').slice(0, 200);
@@ -349,14 +357,29 @@ export function bundledPnpmCandidates(execPath = process.execPath): string[] {
349
357
  return roots.map((root) => join(root, 'node_modules', 'pnpm', 'bin', 'pnpm.cjs'));
350
358
  }
351
359
 
352
- /** 找系统 PATH 里的某个可执行文件(不做 shell 调用,纯文件判断 + PATH 扫描)。 */
360
+ /** 过滤宿主环境变量中的敏感凭据(TG_API_*、*_KEY、*_SECRET、*_TOKEN、*_PASSWORD),避免泄露给第三方安装脚本。 */
361
+ function sanitizedInstallEnv(env: NodeJS.ProcessEnv): Record<string, string | undefined> {
362
+ const out: Record<string, string | undefined> = {};
363
+ for (const [k, v] of Object.entries(env)) {
364
+ if (/^(TG_API_|.*(?:API_KEY|SECRET|TOKEN|PASSWORD|PASSWD|PRIVATE_KEY|AUTH_KEY))/i.test(k)) continue;
365
+ out[k] = v;
366
+ }
367
+ return out;
368
+ }
369
+
370
+ /** 找系统 PATH 里的某个可执行文件(不做 shell 调用,纯绝对路径 + 文件判断)。 */
353
371
  function findOnPath(name: string): string | null {
354
372
  const exts = process.platform === 'win32' ? ['.cmd', '.exe', ''] : [''];
355
373
  const dirs = (process.env.PATH ?? '').split(process.platform === 'win32' ? ';' : ':').filter(Boolean);
356
374
  for (const dir of dirs) {
375
+ if (!isAbsolute(dir)) continue;
357
376
  for (const ext of exts) {
358
377
  const full = join(dir, `${name}${ext}`);
359
- if (existsSync(full)) return full;
378
+ try {
379
+ if (existsSync(full) && statSync(full).isFile()) return full;
380
+ } catch {
381
+ // 忽略无权限条目
382
+ }
360
383
  }
361
384
  }
362
385
  return null;
@@ -10,12 +10,18 @@
10
10
 
11
11
  export const QUOTE_MAX_CHARS = 120;
12
12
 
13
- /** 把被引用消息的正文压成一行,超长截断。 */
13
+ /** 把被引用消息的正文压成一行,超长截断(不劈开 UTF-16 emoji 代理对)。 */
14
14
  export function compactQuote(text: string, max = QUOTE_MAX_CHARS): string {
15
15
  const flat = (text ?? '').replace(/\s+/g, ' ').trim();
16
16
  if (!flat) return '';
17
17
  if (flat.length <= max) return flat;
18
- return `${flat.slice(0, max - 1)}…`;
18
+ let cut = Math.max(1, max - 1);
19
+ const prev = flat.charCodeAt(cut - 1);
20
+ const next = flat.charCodeAt(cut);
21
+ if (prev >= 0xd800 && prev <= 0xdbff && next >= 0xdc00 && next <= 0xdfff) {
22
+ cut = Math.max(1, cut - 1);
23
+ }
24
+ return `${flat.slice(0, cut)}…`;
19
25
  }
20
26
 
21
27
  /** 生成引用标记;没有正文时退回老格式(只有编号)。 */