larkmate 0.1.17 → 0.1.18

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
@@ -20,7 +20,7 @@ import { createRuleOutput, loadListenRules, startListenService } from '../src/li
20
20
 
21
21
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
22
22
  const program = new Command();
23
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.17');
23
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.18');
24
24
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
25
25
  program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
26
26
  program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
@@ -154,9 +154,10 @@ program.command('listen-service').description('Serve messages on a private Unix
154
154
  .action(async o => {
155
155
  if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
156
156
  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();
157
+ const gateway=new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}), self=await gateway.authenticate();
158
+ const service = await startListenService(o.socket,{selfId:self.id}), controller = new AbortController(), stop = () => controller.abort();
158
159
  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 }); }
160
+ try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway,chatIds:o.chat,output:service.output,signal:controller.signal }); }
160
161
  finally { await service.close(); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
161
162
  });
162
163
  program.command('listen-run').description('Run configured scripts for matching new messages.')
@@ -16,7 +16,29 @@ 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
+ | `sender` | 发送人 ID,可重复传入 |
25
+ | `type` | 消息类型数字,可重复传入;`4` 表示文本 |
26
+ | `contains` | 正文包含指定文本 |
27
+ | `excludeContains` | 正文不包含指定文本 |
28
+ | `excludeSelf` | 设为 `true` 时排除当前账号发出的消息 |
29
+
30
+ 同一参数多次出现时,满足其一即可;不同参数之间须同时满足。文本匹配区分大小写。示例:
31
+
32
+ ```sh
33
+ curl -N -G --unix-socket "$HOME/.larkmate/events/messages.sock" \
34
+ --data-urlencode "chat=$CHAT_ID" --data-urlencode 'type=4' \
35
+ --data-urlencode 'contains=需要处理' --data-urlencode 'excludeSelf=true' \
36
+ http://localhost/events
37
+ ```
38
+
39
+ 条件格式错误或包含未知参数时,服务返回 HTTP 400。与订阅相关或范围未知的 `gap` 事件仍会发送;启动服务时通过 `--chat` 指定的范围始终生效,订阅过滤无法扩大该范围。自定义过滤脚本用于下述规则模式,订阅连接不执行脚本。
40
+
41
+ socket 为 `0600`,父目录必须归当前用户所有且不能被其他用户写入。订阅过滤仅用于筛选事件,并非权限控制:能访问 socket 的连接者可以自行设置过滤条件,或订阅服务配置范围内的全部消息。订阅者不在线时不保存事件。也可用 `larkmate listen` 直接向标准输出流式输出,不启动服务;该命令同样支持 `--chat` 限定会话。
20
42
 
21
43
  ## 规则与脚本
22
44
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.17",
3
+ "version": "0.1.18",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -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
+ 服务订阅 URL 支持 `chat`、`sender`、`type`、`contains`、`excludeContains` 和 `excludeSelf` 查询参数;前三项可重复指定。不同条件同时生效,无效或未知参数返回 HTTP 400。相关或范围未知的 `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、规则文件和脚本的访问由部署方负责。
@@ -50,6 +50,41 @@ function matches(rule,event,selfId) {
50
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
51
  &&(!rule.excludeSelf||(selfId&&event.senderId!==selfId))&&(rule.contains===undefined||(event.text||'').includes(rule.contains))&&(rule.excludeContains===undefined||!(event.text||'').includes(rule.excludeContains));
52
52
  }
53
+
54
+ export function parseSubscriptionFilter(requestUrl, selfId) {
55
+ if (typeof requestUrl !== 'string' || requestUrl.length > 8192) throw new FeishuError('INVALID_FILTER', 'Invalid subscription URL.');
56
+ let url;
57
+ try { url = new URL(requestUrl, 'http://localhost'); } catch { throw new FeishuError('INVALID_FILTER', 'Invalid subscription URL.'); }
58
+ if (url.pathname !== '/events') throw new FeishuError('NOT_FOUND', 'Unknown endpoint.');
59
+ const params=url.searchParams, allowed=new Set(['chat','sender','type','contains','excludeContains','excludeSelf']);
60
+ for(const key of params.keys()) if(!allowed.has(key)) throw new FeishuError('INVALID_FILTER', 'Unknown subscription filter.');
61
+ const many = (name, validate) => {
62
+ const values=params.getAll(name);
63
+ if(values.length>100 || values.some(value=>!validate(value))) throw new FeishuError('INVALID_FILTER', `Invalid ${name} filter.`);
64
+ return [...new Set(values)];
65
+ };
66
+ const validId=value=>{try{requireInt64Id(value,'ID');return true}catch{return false}};
67
+ const chatIds=many('chat',validId), senderIds=many('sender',validId);
68
+ const types=many('type',value=>/^(0|[1-9]\d{0,9})$/.test(value)&&Number(value)<=2147483647).map(Number);
69
+ const scalar=name=>{const values=params.getAll(name);if(values.length>1)throw new FeishuError('INVALID_FILTER', `Duplicate ${name} filter.`);return values[0];};
70
+ const contains=scalar('contains'), excludeContains=scalar('excludeContains'), excludeSelf=scalar('excludeSelf');
71
+ for(const value of [contains,excludeContains])if(value!==undefined&&(!value||Buffer.byteLength(value)>4096))throw new FeishuError('INVALID_FILTER','Invalid text filter.');
72
+ if(excludeSelf!==undefined&&!['true','false'].includes(excludeSelf))throw new FeishuError('INVALID_FILTER','excludeSelf must be true or false.');
73
+ if(excludeSelf==='true'&&!validId(selfId))throw new FeishuError('INVALID_FILTER','The current user is unavailable.');
74
+ return {chatIds,senderIds,types,contains,excludeContains,excludeSelf:excludeSelf==='true'};
75
+ }
76
+
77
+ function subscriptionMatches(filter,event,selfId) {
78
+ if(!event || typeof event!=='object') return false;
79
+ // Gap/control events remain visible when their scope may affect the subscriber.
80
+ if(event.kind!=='message') return !event.chatId || !filter.chatIds.length || filter.chatIds.includes(event.chatId);
81
+ return (!filter.chatIds.length||filter.chatIds.includes(event.chatId))
82
+ && (!filter.senderIds.length||filter.senderIds.includes(event.senderId))
83
+ && (!filter.types.length||filter.types.includes(event.type))
84
+ && (!filter.excludeSelf||(typeof event.senderId==='string'&&event.senderId!==selfId))
85
+ && (filter.contains===undefined||(event.text||'').includes(filter.contains))
86
+ && (filter.excludeContains===undefined||!(event.text||'').includes(filter.excludeContains));
87
+ }
53
88
  function runScript(config,event) {
54
89
  return new Promise(resolve=>{
55
90
  let child, settled=false, timer;
@@ -74,21 +109,24 @@ export function createRuleOutput({rules,selfId,log=process.stderr}) {
74
109
  }
75
110
 
76
111
  // Exposes the configured event stream, protected by the socket and parent directory permissions.
77
- export async function startListenService(socketPath) {
112
+ export async function startListenService(socketPath, {selfId}={}) {
78
113
  if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
79
114
  let parent;try{parent=await realpath(dirname(socketPath));}catch{throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must exist.');}
80
115
  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
116
  const path=join(parent,socketPath.slice(socketPath.lastIndexOf('/')+1));
82
117
  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();
118
+ const clients=new Map();
84
119
  const server=http.createServer((req,res)=>{
85
- if(req.method!=='GET'||req.url!=='/events'){res.writeHead(404);res.end();return;}
120
+ if(req.method!=='GET'){res.writeHead(404);res.end();return;}
121
+ let filter;
122
+ try { filter=parseSubscriptionFilter(req.url,selfId); }
123
+ 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; }
86
124
  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));
125
+ res.writeHead(200,{'content-type':'application/x-ndjson','cache-control':'no-store','x-content-type-options':'nosniff'});res.flushHeaders();clients.set(res,filter);res.on('close',()=>clients.delete(res));
88
126
  });
89
127
  const oldMask=process.umask(0o077);
90
128
  try { await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve)}); } finally { process.umask(oldMask); }
91
129
  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;}}};
130
+ const output=new Writable({write(chunk,_encoding,callback){let event;try{event=JSON.parse(chunk.toString())}catch{callback(new FeishuError('INVALID_RESPONSE','Invalid listener event.'));return;}for(const [client,filter] of clients){if(!subscriptionMatches(filter,event,selfId))continue;if(client.writableLength>1024*1024){client.destroy();continue;}client.write(chunk);}callback();}});
131
+ 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
132
  }