larkmate 0.1.17 → 0.1.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 CHANGED
@@ -57,7 +57,7 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
57
57
  - [x] 发送图片消息、下载图片或附件
58
58
  - [x] 给消息添加和取消表情回应
59
59
  - [x] 获取消息链接
60
- - [x] 全局或按会话监听新消息,支持本地服务和规则触发脚本
60
+ - [x] 全局或按会话监听新消息,支持名称、正则、组合过滤和规则触发脚本
61
61
  - 群聊
62
62
  - [x] 查询群信息、成员、管理员和入退群记录
63
63
  - [x] 修改群名称、描述、头像和本人群昵称
package/bin/larkmate.js CHANGED
@@ -17,10 +17,11 @@ import { Calendar } from '../src/calendar.js';
17
17
  import { GroupManagement, groupSettingsSchema } from '../src/group-management.js';
18
18
  import { listen } from '../src/listen.js';
19
19
  import { createRuleOutput, loadListenRules, startListenService } from '../src/listen-modes.js';
20
+ import { createNameResolver } from '../src/listen-names.js';
20
21
 
21
22
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
22
23
  const program = new Command();
23
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.17');
24
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.19');
24
25
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
25
26
  program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
26
27
  program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
@@ -154,9 +155,10 @@ program.command('listen-service').description('Serve messages on a private Unix
154
155
  .action(async o => {
155
156
  if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
156
157
  if (o.all && o.chat.length) throw new FeishuError('INVALID_ARGUMENT', 'Use --all or --chat, not both.');
157
- const service = await startListenService(o.socket), controller = new AbortController(), stop = () => controller.abort();
158
+ const gateway=new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}), self=await gateway.authenticate();
159
+ const service = await startListenService(o.socket,{selfId:self.id,resolveNames:createNameResolver(gateway,self.id)}), controller = new AbortController(), stop = () => controller.abort();
158
160
  process.once('SIGINT', stop); process.once('SIGTERM', stop);
159
- try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway:new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}),chatIds:o.chat,output:service.output,signal:controller.signal }); }
161
+ try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway,chatIds:o.chat,output:service.output,signal:controller.signal }); }
160
162
  finally { await service.close(); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
161
163
  });
162
164
  program.command('listen-run').description('Run configured scripts for matching new messages.')
@@ -164,7 +166,7 @@ program.command('listen-run').description('Run configured scripts for matching n
164
166
  .action(async o => {
165
167
  if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
166
168
  const config=await loadListenRules(o.rules), gateway=new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}), self=await gateway.authenticate();
167
- const sink=createRuleOutput({...config,selfId:self.id}), controller=new AbortController(), stop=()=>controller.abort();
169
+ const sink=createRuleOutput({...config,selfId:self.id,resolveNames:createNameResolver(gateway,self.id)}), controller=new AbortController(), stop=()=>controller.abort();
168
170
  process.once('SIGINT',stop);process.once('SIGTERM',stop);
169
171
  try { await listen({ gateway,chatIds:config.chatIds,output:sink,signal:controller.signal }); }
170
172
  finally { await new Promise(resolve=>sink.end(resolve)); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
@@ -16,7 +16,55 @@ larkmate listen-service --socket "$HOME/.larkmate/events/messages.sock"
16
16
  curl -N --unix-socket "$HOME/.larkmate/events/messages.sock" http://localhost/events
17
17
  ```
18
18
 
19
- socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户写入。所有连接者接收服务配置范围内的消息;订阅者不在线时不保存事件。也可用 `larkmate listen` 直接向标准输出流式输出,不启动服务;该命令同样支持 `--chat` 限定会话。
19
+ 订阅时可以通过查询参数为每个连接独立设置过滤条件:
20
+
21
+ | 参数 | 作用 |
22
+ | --- | --- |
23
+ | `chat` | 会话 ID,可重复传入 |
24
+ | `chatName` / `chatRegex` | 会话名称精确匹配 / 正则匹配,可重复传入 |
25
+ | `sender` | 发送人 ID,可重复传入 |
26
+ | `senderName` / `senderRegex` | 发送人名称精确匹配 / 正则匹配,可重复传入 |
27
+ | `type` | 消息类型数字,可重复传入;`4` 表示文本 |
28
+ | `contains` / `textRegex` | 正文包含指定文本 / 符合正则,可重复传入 |
29
+ | `excludeContains` / `excludeTextRegex` | 排除正文包含指定文本 / 符合正则的消息,可重复传入 |
30
+ | `excludeSelf` | 设为 `true` 时排除当前账号发出的消息 |
31
+
32
+ 同一维度的多个正向条件满足其一即可:例如 `sender`、`senderName` 和 `senderRegex` 之间为“或”。会话、发送人、类型、正向文本等不同维度之间为“且”;命中任意排除文本条件时,该消息会被排除。文本和名称默认区分大小写。示例:
33
+
34
+ ```sh
35
+ curl -N -G --unix-socket "$HOME/.larkmate/events/messages.sock" \
36
+ --data-urlencode "chat=$CHAT_ID" --data-urlencode 'type=4' \
37
+ --data-urlencode 'senderName=张三' --data-urlencode 'senderName=李四' \
38
+ --data-urlencode 'textRegex=^(需要处理|紧急)' --data-urlencode 'excludeSelf=true' \
39
+ http://localhost/events
40
+ ```
41
+
42
+ 对于大量条件或复杂组合,请使用 `POST /events` 配合 JSON 请求体建立订阅,响应仍为持续输出的 JSON Lines。文件中可包含任意数量的 ID、名称和条件:
43
+
44
+ ```json
45
+ {
46
+ "anyOf": [
47
+ { "chatNames": ["需求群"], "senderNames": ["张三", "李四"], "textRegex": ["^紧急", "待处理"] },
48
+ { "chatIds": ["123456789"], "senderIds": ["111111111", "222222222"], "contains": ["上线", "发布"] }
49
+ ]
50
+ }
51
+ ```
52
+
53
+ ```sh
54
+ curl -N --unix-socket "$HOME/.larkmate/events/messages.sock" \
55
+ -H 'Content-Type: application/json' --data-binary @filters.json \
56
+ http://localhost/events
57
+ ```
58
+
59
+ JSON 支持 `chatIds`、`chatNames`、`chatRegex`、`senderIds`、`senderNames`、`senderRegex`、`types`、`contains`、`excludeContains`、`textRegex`、`excludeTextRegex` 和 `excludeSelf`。除 `excludeSelf` 使用布尔值外,各项可使用单值或数组;`anyOf`、`allOf` 和 `not` 可嵌套组合条件。同层普通条件与组合条件同时生效。GET URL 受 HTTP 请求行长度限制,条件较多时应使用 POST。
60
+
61
+ 名称从飞书查询并短暂缓存;相同名称的多个会话或用户都会匹配,精确区分时请使用 ID。名称暂时无法获取且无法仅凭其他条件确定匹配结果时,不会转发该消息,会发出 `name_unavailable` 缺口事件。正文未能完整解析且无法确定文本条件时,会发出 `filter_input_unavailable`。私聊名称取飞书返回的会话名称,缺失时使用对方名称;不保证包含个人备注或群昵称。
62
+
63
+ 正则使用 RE2 语法,支持例如 `^`、`$`、`|` 和 `(?i)`;不支持反向引用或前瞻等部分 JavaScript 正则特性。非法或不支持的表达式会拒绝订阅。
64
+
65
+ 条件格式错误或包含未知参数时,服务返回 HTTP 400。与订阅相关或范围未知的 `gap` 事件仍会发送;启动服务时通过 `--chat` 指定的范围始终生效,订阅过滤无法扩大该范围。自定义过滤脚本用于下述规则模式,订阅连接不执行脚本。
66
+
67
+ socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户写入。订阅过滤仅用于筛选事件,并非权限控制:能访问 socket 的连接者可以自行设置过滤条件,或订阅服务配置范围内的全部消息。订阅者不在线时不保存事件。也可用 `larkmate listen` 直接向标准输出流式输出,不启动服务;该命令同样支持 `--chat` 限定会话。
20
68
 
21
69
  ## 规则与脚本
22
70
 
@@ -47,7 +95,7 @@ socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户
47
95
  larkmate listen-run --rules ./rules.json
48
96
  ```
49
97
 
50
- `run` 必填;省略 `chatIds` 或传入空数组时匹配全部会话,填写会话 ID 时只匹配指定会话。其他筛选项可省略,填写的条件同时生效。`types` 使用消息类型数字,`4` 表示文本;`contains` 和 `excludeContains` 区分大小写。`excludeSelf` 为 `true` 时跳过当前账号发送的消息。
98
+ `run` 必填;省略会话条件或传入空数组时匹配全部会话。规则支持与 POST 订阅相同的名称、正则及组合条件,例如 `"senderNames": ["张三", "李四"]`。同一维度的 ID、名称和正则是“或”,不同维度是“且”。`types` 使用消息类型数字,`4` 表示文本;`excludeSelf` 为 `true` 时跳过当前账号发送的消息。
51
99
 
52
100
  过滤器和目标脚本均为固定的绝对可执行文件路径,`args` 为固定参数;消息不会经由 shell 解析。每次调用时,通过标准输入传入一行消息 JSON。过滤器退出码 `0` 表示匹配,`1` 表示不匹配,其余退出码或超时均视为错误;仅在匹配成功时执行 `run`。过滤器和脚本的标准输出与标准错误不会被转发,失败信息写入监听进程的标准错误。脚本默认超时时间为 30 秒,可配置为 1–600 秒。规则按顺序执行,脚本执行失败不会自动重试。
53
101
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.17",
3
+ "version": "0.1.19",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -35,6 +35,7 @@
35
35
  "dependencies": {
36
36
  "commander": "^13.1.0",
37
37
  "protobufjs": "^8.6.0",
38
+ "re2js": "^2.10.0",
38
39
  "rrule": "^2.8.1"
39
40
  }
40
41
  }
@@ -2,6 +2,8 @@
2
2
 
3
3
  用 `larkmate listen` 输出全部会话的实时 JSON Lines;传入 `--chat "$CHAT_ID"` 可限定会话,且支持重复传入。`listen-service --socket <绝对路径>` 在私有 Unix socket 的 `/events` 提供事件流,`listen-run --rules <文件>` 按规则筛选消息并运行脚本。完整规则格式和示例见[消息监听指南](https://github.com/NWYLZW/larkmate/blob/main/docs/message-listening.md)。
4
4
 
5
+ 服务订阅支持会话及发送人的 ID、名称和正则,以及消息类型、正文包含/排除、正文正则和排除本人。相同维度的 ID、名称和正则是“或”,不同维度是“且”。大量条件或 `anyOf`、`allOf`、`not` 组合通过 `POST /events` JSON 传入;规则模式支持同样的条件。正则使用 RE2 语法,不支持部分 JavaScript 正则特性。名称解析失败且结果无法确定时会发出 `name_unavailable` 缺口,不猜测匹配;同名对象都会匹配,需要精确区分时使用 ID。相关或范围未知的 `gap` 事件仍会传递。连接条件只是数据筛选,能访问 socket 的调用者仍可自行订阅服务允许范围内的所有消息。
6
+
5
7
  `listen-run` 的规则可省略 `chatIds` 以匹配全部会话,也可按会话、发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
6
8
 
7
9
  自动重连时会尽力按会话位置补拉,补拉事件带 `backfill: true`;全局模式只能补拉本次进程已见过的会话,并在中断时发出 `global_coverage_unknown` 缺口事件。处理 `gap` 事件并按需查询历史。去重和补拉位置仅保存在当前进程内,重启后不恢复,不能保证不漏或恰好执行一次。服务订阅者不在线时不会缓存事件。监听目前不能通过 broker 或系统用户委托使用;保护 socket、Cookie、规则文件和脚本的访问由部署方负责。
@@ -0,0 +1,74 @@
1
+ import { RE2JS } from 're2js';
2
+ import { FeishuError, requireInt64Id } from './errors.js';
3
+
4
+ const fields = new Set(['chatIds','chatNames','chatRegex','senderIds','senderNames','senderRegex','types','contains','excludeContains','textRegex','excludeTextRegex','excludeSelf','anyOf','allOf','not']);
5
+ const arrays = ['chatIds','chatNames','chatRegex','senderIds','senderNames','senderRegex','types','contains','excludeContains','textRegex','excludeTextRegex'];
6
+ const regexFields = new Set(['chatRegex','senderRegex','textRegex','excludeTextRegex']);
7
+ const aliases = {chat:'chatIds',chatName:'chatNames',sender:'senderIds',senderName:'senderNames',type:'types'};
8
+ const fail = message => { throw new FeishuError('INVALID_FILTER',message); };
9
+ const plain = value => value!==null && typeof value==='object' && !Array.isArray(value);
10
+
11
+ export function compileFilter(raw, selfId, depth=0) {
12
+ if(!plain(raw)||depth>32)fail('Invalid filter structure.');
13
+ const mapped=Object.create(null);
14
+ for(const [input,value] of Object.entries(raw)) {
15
+ const key=aliases[input]||input;
16
+ if(!fields.has(key)||Object.hasOwn(mapped,key))fail('Unknown or duplicate filter field.');
17
+ mapped[key]=value;
18
+ }
19
+ const out={};
20
+ for(const name of arrays) {
21
+ const value=mapped[name]; if(value===undefined){out[name]=[];continue;}
22
+ const values=Array.isArray(value)?value:[value];
23
+ if(values.some(x => name==='types' ? !(Number.isInteger(x)&&x>=0&&x<=2147483647) : typeof x!=='string'||!x||Buffer.byteLength(x)>4096))fail(`Invalid ${name}.`);
24
+ if(['chatIds','senderIds'].includes(name))for(const id of values){try{requireInt64Id(id,'ID')}catch{fail(`Invalid ${name}.`)}}
25
+ if(regexFields.has(name)) { try{out[name]=values.map(x=>RE2JS.compile(x));}catch{fail(`Invalid or unsupported ${name} regular expression.`)} }
26
+ else out[name]=[...new Set(values)];
27
+ }
28
+ if(mapped.excludeSelf!==undefined&&typeof mapped.excludeSelf!=='boolean')fail('excludeSelf must be boolean.');
29
+ out.excludeSelf=mapped.excludeSelf===true;
30
+ for(const key of ['anyOf','allOf']) {
31
+ if(mapped[key]===undefined){out[key]=[];continue;}
32
+ if(!Array.isArray(mapped[key])||mapped[key].length===0)fail(`${key} must be a nonempty array.`);
33
+ out[key]=mapped[key].map(x=>compileFilter(x,selfId,depth+1));
34
+ }
35
+ out.not=mapped.not===undefined?null:compileFilter(mapped.not,selfId,depth+1);
36
+ return out;
37
+ }
38
+ export function filterNeeds(filter) {
39
+ const out={chat:!!(filter.chatNames.length||filter.chatRegex.length),sender:!!(filter.senderNames.length||filter.senderRegex.length),text:!!(filter.contains.length||filter.textRegex.length||filter.excludeContains.length||filter.excludeTextRegex.length),self:filter.excludeSelf};
40
+ for(const child of [...filter.anyOf,...filter.allOf,...(filter.not?[filter.not]:[])]) { const needs=filterNeeds(child);out.chat ||= needs.chat;out.sender ||= needs.sender;out.text ||= needs.text;out.self ||= needs.self; }
41
+ return out;
42
+ }
43
+ export function filterMatches(f,event,selfId) {
44
+ const chatSpecified=f.chatIds.length||f.chatNames.length||f.chatRegex.length;
45
+ const senderSpecified=f.senderIds.length||f.senderNames.length||f.senderRegex.length;
46
+ const textSpecified=f.contains.length||f.textRegex.length;
47
+ const chatMatch=f.chatIds.includes(event.chatId) ? true : (f.chatNames.length||f.chatRegex.length) && !event.chatName ? null
48
+ : f.chatNames.includes(event.chatName)||f.chatRegex.some(r=>typeof event.chatName==='string'&&r.test(event.chatName));
49
+ const senderMatch=f.senderIds.includes(event.senderId) ? true : (f.senderNames.length||f.senderRegex.length) && !event.senderName ? null
50
+ : f.senderNames.includes(event.senderName)||f.senderRegex.some(r=>typeof event.senderName==='string'&&r.test(event.senderName));
51
+ const text=typeof event.text==='string'?event.text:'';
52
+ const and=values=>values.includes(false)?false:values.includes(null)?null:true;
53
+ const or=values=>values.includes(true)?true:values.includes(null)?null:false;
54
+ const not=value=>value===null?null:!value;
55
+ const incomplete=event.textIncomplete===true;
56
+ return and([!chatSpecified?true:chatMatch,!senderSpecified?true:senderMatch,!f.types.length||f.types.includes(event.type),
57
+ !f.excludeSelf||!!(selfId&&typeof event.senderId==='string'&&event.senderId!==selfId),
58
+ !textSpecified?true:incomplete?null:f.contains.some(x=>text.includes(x))||f.textRegex.some(r=>r.test(text)),
59
+ !f.excludeContains.length?true:incomplete?null:!f.excludeContains.some(x=>text.includes(x)),
60
+ !f.excludeTextRegex.length?true:incomplete?null:!f.excludeTextRegex.some(r=>r.test(text)),
61
+ !f.anyOf.length?true:or(f.anyOf.map(x=>filterMatches(x,event,selfId))),
62
+ and(f.allOf.map(x=>filterMatches(x,event,selfId))),f.not?not(filterMatches(f.not,event,selfId)):true]);
63
+ }
64
+ export function queryFilter(params) {
65
+ const obj=Object.create(null);
66
+ for(const key of params.keys()) {
67
+ if(Object.hasOwn(obj,key))continue;
68
+ const values=params.getAll(key);
69
+ if(key==='excludeSelf') {if(values.length!==1||!['true','false'].includes(values[0]))fail('Invalid excludeSelf.');obj[key]=values[0]==='true';}
70
+ else if(key==='type'||key==='types') {if(values.some(v=>!/^(0|[1-9]\d{0,9})$/.test(v)))fail('Invalid type.');obj[key]=values.map(Number);}
71
+ else obj[key]=values;
72
+ }
73
+ return obj;
74
+ }
@@ -4,51 +4,60 @@ import { spawn } from 'node:child_process';
4
4
  import { constants } from 'node:fs';
5
5
  import { open, lstat, realpath, chmod, unlink } from 'node:fs/promises';
6
6
  import { dirname, isAbsolute, join } from 'node:path';
7
- import { FeishuError, requireInt64Id } from './errors.js';
7
+ import { FeishuError } from './errors.js';
8
+ import { compileFilter, filterMatches, filterNeeds, queryFilter } from './listen-filter.js';
8
9
 
9
10
  const obj = x => x !== null && typeof x === 'object' && !Array.isArray(x);
10
11
  const only = (x, fields) => obj(x) && Object.keys(x).every(k => fields.includes(k));
11
12
  const invalid = message => { throw new FeishuError('LISTEN_CONFIG_INVALID', message); };
12
- function stringArray(value, label, max = 100) {
13
+ function stringArray(value, label, max = Infinity) {
13
14
  if (!Array.isArray(value) || value.length > max || value.some(x => typeof x !== 'string' || Buffer.byteLength(x)>4096)) invalid(`Invalid ${label}.`);
14
15
  return value;
15
16
  }
16
17
  function script(value, label) {
17
18
  if (!only(value,['path','args','timeoutSeconds']) || typeof value.path !== 'string' || !isAbsolute(value.path) || value.path.includes('\0')) invalid(`Invalid ${label}.`);
18
- const args = value.args === undefined ? [] : stringArray(value.args, `${label} arguments`, 32);
19
+ const args = value.args === undefined ? [] : stringArray(value.args, `${label} arguments`);
19
20
  const timeoutSeconds = value.timeoutSeconds ?? 30;
20
21
  if (!Number.isInteger(timeoutSeconds) || timeoutSeconds < 1 || timeoutSeconds > 600) invalid(`Invalid ${label} timeout.`);
21
22
  return {path:value.path,args,timeoutSeconds};
22
23
  }
23
24
  export function parseListenRules(raw) {
24
- if (!only(raw,['version','rules']) || raw.version!==1 || !Array.isArray(raw.rules) || !raw.rules.length || raw.rules.length>100) invalid('Use version 1 and 1 to 100 rules.');
25
+ if (!only(raw,['version','rules']) || raw.version!==1 || !Array.isArray(raw.rules) || !raw.rules.length) invalid('Use version 1 and at least one rule.');
25
26
  const names=new Set(), chats=new Set(); let allChats=false;
26
27
  const rules=raw.rules.map(r=>{
27
- if (!only(r,['name','chatIds','senderIds','types','contains','excludeContains','excludeSelf','filter','run']) || typeof r.name!=='string' || !r.name.trim() || r.name.length>100 || names.has(r.name)) invalid('Invalid or duplicate rule name.');
28
+ if (!obj(r) || typeof r.name!=='string' || !r.name.trim() || r.name.length>100 || names.has(r.name)) invalid('Invalid or duplicate rule name.');
28
29
  names.add(r.name);
29
- const chatIds=r.chatIds===undefined ? [] : stringArray(r.chatIds,'chat IDs',Infinity);
30
- if (!chatIds.length) allChats=true;
31
- for(const id of chatIds){requireInt64Id(id,'chat ID');chats.add(id);}
32
- const senderIds=r.senderIds===undefined?null:stringArray(r.senderIds,'sender IDs'); if(senderIds)for(const id of senderIds)requireInt64Id(id,'sender ID');
33
- const types=r.types===undefined?null:r.types;
34
- if(types!==null&&(!Array.isArray(types)||types.length>100||types.some(x=>!Number.isInteger(x)||x<0)))invalid('Invalid message types.');
35
- for(const k of ['contains','excludeContains'])if(r[k]!==undefined&&(typeof r[k]!=='string'||!r[k]||Buffer.byteLength(r[k])>4096))invalid(`Invalid ${k}.`);
36
- if(r.excludeSelf!==undefined&&typeof r.excludeSelf!=='boolean')invalid('Invalid excludeSelf.');
37
- return {name:r.name,chatIds,senderIds,types,contains:r.contains,excludeContains:r.excludeContains,excludeSelf:r.excludeSelf===true,filter:r.filter===undefined?null:script(r.filter,'filter'),run:script(r.run,'run')};
30
+ const {name,filter,run,...rawFilter}=r;
31
+ let predicate;try{predicate=compileFilter(rawFilter)}catch(e){invalid(e.message)}
32
+ if (!predicate.chatIds.length || predicate.chatNames.length || predicate.chatRegex.length) allChats=true;
33
+ for(const id of predicate.chatIds)chats.add(id);
34
+ return {name,predicate,needs:filterNeeds(predicate),filter:filter===undefined?null:script(filter,'filter'),run:script(run,'run')};
38
35
  });
39
36
  return {rules,chatIds:allChats?[]:[...chats],allChats};
40
37
  }
41
38
  export async function loadListenRules(path) {
42
39
  let f;
43
40
  try { f=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW); const st=await f.stat();
44
- if(!st.isFile()||st.size>65536||![0,process.getuid?.()].includes(st.uid)||(st.mode&0o022)) throw new Error();
41
+ if(!st.isFile()||![0,process.getuid?.()].includes(st.uid)||(st.mode&0o022)) throw new Error();
45
42
  const input=await f.readFile('utf8');return parseListenRules(JSON.parse(input));
46
43
  } catch(e) { if(e instanceof FeishuError)throw e;throw new FeishuError('LISTEN_CONFIG_INVALID','Cannot read a protected rules file.'); }
47
44
  finally { await f?.close(); }
48
45
  }
49
- function matches(rule,event,selfId) {
50
- return event.kind==='message'&&(!rule.chatIds.length||rule.chatIds.includes(event.chatId))&&(!rule.senderIds||rule.senderIds.includes(event.senderId))&&(!rule.types||rule.types.includes(event.type))
51
- &&(!rule.excludeSelf||(selfId&&event.senderId!==selfId))&&(rule.contains===undefined||(event.text||'').includes(rule.contains))&&(rule.excludeContains===undefined||!(event.text||'').includes(rule.excludeContains));
46
+ export function parseSubscriptionFilter(requestUrl, selfId) {
47
+ if (typeof requestUrl !== 'string') throw new FeishuError('INVALID_FILTER', 'Invalid subscription URL.');
48
+ let url;
49
+ try { url = new URL(requestUrl, 'http://localhost'); } catch { throw new FeishuError('INVALID_FILTER', 'Invalid subscription URL.'); }
50
+ if (url.pathname !== '/events') throw new FeishuError('NOT_FOUND', 'Unknown endpoint.');
51
+ const filter=compileFilter(queryFilter(url.searchParams),selfId);
52
+ if(filterNeeds(filter).self&&!selfId)throw new FeishuError('INVALID_FILTER','The current user is unavailable.');
53
+ return filter;
54
+ }
55
+
56
+ function subscriptionMatches(filter,event,selfId) {
57
+ if(!event || typeof event!=='object') return false;
58
+ // Gap/control events remain visible when their scope may affect the subscriber.
59
+ if(event.kind!=='message') return !event.chatId || !filter.chatIds.length || filter.chatNames.length || filter.chatRegex.length || filter.anyOf.length || filter.allOf.length || filter.not || filter.chatIds.includes(event.chatId);
60
+ return filterMatches(filter,event,selfId);
52
61
  }
53
62
  function runScript(config,event) {
54
63
  return new Promise(resolve=>{
@@ -62,11 +71,16 @@ function runScript(config,event) {
62
71
  child.stdin.on('error',()=>{});child.stdin.end(`${JSON.stringify(event)}\n`);
63
72
  });
64
73
  }
65
- export function createRuleOutput({rules,selfId,log=process.stderr}) {
74
+ export function createRuleOutput({rules,selfId,resolveNames,log=process.stderr}) {
66
75
  return new Writable({write(chunk,_encoding,callback){(async()=>{
67
- const event=JSON.parse(chunk.toString());
76
+ let event=JSON.parse(chunk.toString());
68
77
  if(event.kind!=='message'){log.write(`${JSON.stringify(event)}\n`);return;}
69
- for(const rule of rules){if(!matches(rule,event,selfId))continue;
78
+ const needs={chat:rules.some(r=>r.needs.chat),sender:rules.some(r=>r.needs.sender)};
79
+ if(needs.chat||needs.sender) { let names={};try{names=await resolveNames?.(event,needs)||{}}catch{}event={...event,...names}; }
80
+ for(const rule of rules){
81
+ const matched=filterMatches(rule.predicate,event,selfId);
82
+ if(matched===null){log.write(`${JSON.stringify({kind:'gap',chatId:event.chatId,reason:rule.needs.text&&event.textIncomplete?'filter_input_unavailable':'name_unavailable',rule:rule.name})}\n`);continue;}
83
+ if(!matched)continue;
70
84
  if(rule.filter){const result=await runScript(rule.filter,event);if(!result.ok){if(result.code!==1)log.write(`${JSON.stringify({kind:'filter_error',rule:rule.name,reason:result.reason||'exit',code:result.code})}\n`);continue;}}
71
85
  const result=await runScript(rule.run,event);if(!result.ok)log.write(`${JSON.stringify({kind:'script_error',rule:rule.name,reason:result.reason||'exit',code:result.code})}\n`);
72
86
  }
@@ -74,21 +88,54 @@ export function createRuleOutput({rules,selfId,log=process.stderr}) {
74
88
  }
75
89
 
76
90
  // Exposes the configured event stream, protected by the socket and parent directory permissions.
77
- export async function startListenService(socketPath) {
91
+ export async function startListenService(socketPath, {selfId,resolveNames}={}) {
78
92
  if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
79
93
  let parent;try{parent=await realpath(dirname(socketPath));}catch{throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must exist.');}
80
94
  const st=await lstat(parent);if(!st.isDirectory()||st.uid!==process.getuid?.()||(st.mode&0o022))throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must be owned by the user and not writable by others.');
81
95
  const path=join(parent,socketPath.slice(socketPath.lastIndexOf('/')+1));
82
96
  try{await lstat(path);throw new FeishuError('LISTEN_SOCKET_EXISTS','The socket path already exists.');}catch(e){if(e.code!=='ENOENT')throw e;}
83
- const clients=new Set();
84
- const server=http.createServer((req,res)=>{
85
- if(req.method!=='GET'||req.url!=='/events'){res.writeHead(404);res.end();return;}
86
- if(clients.size>=20){res.writeHead(503);res.end();return;}
87
- res.writeHead(200,{'content-type':'application/x-ndjson','cache-control':'no-store','x-content-type-options':'nosniff'});res.flushHeaders();clients.add(res);res.on('close',()=>clients.delete(res));
97
+ const clients=new Map();
98
+ const server=http.createServer(async(req,res)=>{
99
+ if(!['GET','POST'].includes(req.method)){res.writeHead(404);res.end();return;}
100
+ let filter;
101
+ try {
102
+ if(req.method==='GET') filter=parseSubscriptionFilter(req.url,selfId);
103
+ else {
104
+ if(req.url!=='/events')throw new FeishuError('NOT_FOUND','Unknown endpoint.');
105
+ if(!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type']||''))throw new FeishuError('INVALID_FILTER','Use application/json.');
106
+ req.setEncoding('utf8');let data='';for await(const chunk of req)data+=chunk;
107
+ let body;try{body=JSON.parse(data)}catch{throw new FeishuError('INVALID_FILTER','Invalid JSON filter.')}
108
+ filter=compileFilter(body,selfId);
109
+ if(filterNeeds(filter).self&&!selfId)throw new FeishuError('INVALID_FILTER','The current user is unavailable.');
110
+ }
111
+ const needs=filterNeeds(filter);
112
+ if((needs.chat||needs.sender)&&typeof resolveNames!=='function')throw new FeishuError('INVALID_FILTER','Name lookup is unavailable.');
113
+ }
114
+ catch(error) { const status=error.code==='NOT_FOUND'?404:400;res.writeHead(status,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify({ok:false,error:{code:error.code||'INVALID_FILTER',message:error.message}}));return; }
115
+ res.writeHead(200,{'content-type':'application/x-ndjson','cache-control':'no-store','x-content-type-options':'nosniff'});res.flushHeaders();clients.set(res,{filter,needs:filterNeeds(filter)});res.on('close',()=>clients.delete(res));
88
116
  });
89
117
  const oldMask=process.umask(0o077);
90
118
  try { await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve)}); } finally { process.umask(oldMask); }
91
119
  await chmod(path,0o600);const inode=(await lstat(path)).ino;
92
- const output=new Writable({write(chunk,_encoding,callback){for(const client of clients){if(client.writableLength>1024*1024){client.destroy();continue;}client.write(chunk);}callback();}});
93
- return {path,output,async close(){for(const c of clients)c.destroy();await new Promise(resolve=>server.close(resolve));try{const now=await lstat(path);if(now.ino===inode&&now.isSocket())await unlink(path);}catch(e){if(e.code!=='ENOENT')throw e;}}};
120
+ const output=new Writable({write(chunk,_encoding,callback){(async()=>{
121
+ let event;try{event=JSON.parse(chunk.toString())}catch{throw new FeishuError('INVALID_RESPONSE','Invalid listener event.')}
122
+ const snapshot=[...clients];
123
+ const deliver=(client,filter,value)=>{
124
+ if(!clients.has(client))return;
125
+ if(client.writableLength>1024*1024){client.destroy();return;}
126
+ const matched=subscriptionMatches(filter,value,selfId);
127
+ if(matched===null)client.write(`${JSON.stringify({kind:'gap',chatId:value.chatId,reason:filterNeeds(filter).text&&value.textIncomplete?'filter_input_unavailable':'name_unavailable'})}\n`);
128
+ else if(matched)client.write(`${JSON.stringify(value)}\n`);
129
+ };
130
+ // Resolve names only when an existing subscriber cannot decide from IDs and other fields.
131
+ const deferred=[];
132
+ for(const [client,{filter,needs:n}] of snapshot){
133
+ if(event.kind==='message'&&(n.chat||n.sender)&&subscriptionMatches(filter,event,selfId)===null)deferred.push([client,{filter,needs:n}]);
134
+ else deliver(client,filter,event);
135
+ }
136
+ const needs={chat:false,sender:false};for(const [, {needs:n}] of deferred){needs.chat ||= n.chat;needs.sender ||= n.sender;}
137
+ if(needs.chat||needs.sender){let names={};try{names=await resolveNames?.(event,needs)||{}}catch{}event={...event,...names};}
138
+ for(const [client,{filter}] of deferred)deliver(client,filter,event);
139
+ })().then(()=>callback(),callback)}});
140
+ return {path,output,async close(){for(const c of clients.keys())c.destroy();await new Promise(resolve=>server.close(resolve));try{const now=await lstat(path);if(now.ino===inode&&now.isSocket())await unlink(path);}catch(e){if(e.code!=='ENOENT')throw e;}}};
94
141
  }
@@ -0,0 +1,27 @@
1
+ import { LarkMateClient } from './client.js';
2
+
3
+ // Names are resolved only for filters that need them. Failed lookups are not cached.
4
+ export function createNameResolver(gateway, selfId, {ttlMs=60000}={}) {
5
+ const client=new LarkMateClient(gateway), chats=new Map(), senders=new Map(), inFlight=new Map();
6
+ async function cached(kind,id,load) {
7
+ if(!id)return null;const cache=kind==='chat'?chats:senders,old=cache.get(id);
8
+ if(old&&old.expiry>Date.now())return old.value;
9
+ const key=kind+':'+id;if(inFlight.has(key))return inFlight.get(key);
10
+ const promise=(async()=>{try{const value=await load();if(typeof value==='string'&&value){cache.delete(id);if(cache.size>=10000)cache.delete(cache.keys().next().value);cache.set(id,{value,expiry:Date.now()+ttlMs});return value}return null}catch{return null}finally{inFlight.delete(key)}})();
11
+ inFlight.set(key,promise);return promise;
12
+ }
13
+ async function sender(id) {return cached('sender',id,async()=>{
14
+ const r=await gateway.call(46,'PullChattersByIdsRequest',{chatterIds:[id],needBotInfo:true,notSubscribeChatters:true},{operation:'listen-resolve-sender'});
15
+ const chatter=gateway.decode('PullChattersByIdsResponse',r.packet.payload).chatters?.[id];
16
+ return String(chatter?.id||'')===id?chatter.name:null;
17
+ });}
18
+ async function chat(id) {return cached('chat',id,async()=>{
19
+ const info=await client.chatInfo(id);if(info.name)return info.name;
20
+ if(info.type==='p2p') {const members=(await client.members({chatId:id,limit:20})).items;const person=members.find(x=>x.id!==selfId)||members.find(x=>x.id===selfId);return person?.name||null;}
21
+ return null;
22
+ });}
23
+ return async (event,needs)=>{
24
+ const [chatName,senderName]=await Promise.all([needs.chat?chat(event.chatId):null,needs.sender?sender(event.senderId):null]);
25
+ return {...(needs.chat?{chatName}:{}),...(needs.sender?{senderName}:{})};
26
+ };
27
+ }