larkmate 0.1.21 → 0.1.22
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/bin/larkmate.js +26 -12
- package/bin/os-delegate-helper.js +2 -2
- package/docs/agent-broker.md +1 -1
- package/docs/api-service.md +6 -2
- package/docs/message-listening.md +2 -0
- package/docs/os-delegation.md +2 -0
- package/package.json +1 -1
- package/skills/larkmate/references/listen.md +2 -0
- package/src/listen-modes.js +25 -6
- package/src/listen.js +2 -0
package/bin/larkmate.js
CHANGED
|
@@ -25,7 +25,7 @@ import { startApiService } from '../src/api-service.js';
|
|
|
25
25
|
|
|
26
26
|
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
27
27
|
const program = new Command();
|
|
28
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
28
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.22');
|
|
29
29
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
30
30
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
31
31
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -86,10 +86,11 @@ async function calendar() { const remote = proxy('calendar'); return remote || n
|
|
|
86
86
|
async function feeds() { const remote = proxy('feeds'); return remote || new FeedGroups(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
87
87
|
async function tasks() { const remote = proxy('tasks'); return remote || new Tasks(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
88
88
|
function servicesFactory() {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return file=>file?make(file):(promise ||= make(null).catch(error=>{promise=undefined;throw error;}));
|
|
89
|
+
const make=async file=>{const gateway=new Gateway({cookie:await loadProtectedCookie(file||serviceAccountFile())});return {client:new LarkMateClient(gateway),controls:new SessionControls(gateway),minutes:new Minutes(gateway),sidebar:new SidebarFilters(gateway),feeds:new FeedGroups(gateway),tasks:new Tasks(gateway),calendar:new Calendar(gateway),groups:new GroupManagement(gateway)};};
|
|
90
|
+
return file=>make(file);
|
|
92
91
|
}
|
|
92
|
+
function serviceAccountFile(){return resolve(program.opts().credentialsFile||join(process.env.LARKMATE_HOME||join(homedir(),'.larkmate'),'credentials.json'));}
|
|
93
|
+
function requireFileCredentials(){if(process.env.LARKMATE_COOKIE)throw new FeishuError('INVALID_ARGUMENT','Services require a protected credentials file; remove LARKMATE_COOKIE from the service environment.');}
|
|
93
94
|
async function readJson(path, fallback) {
|
|
94
95
|
if (!path) return fallback;
|
|
95
96
|
let data; try { data = path === '-' ? await new Promise((resolve, reject) => { let text = ''; process.stdin.setEncoding('utf8'); process.stdin.on('data', x => { text += x; if (text.length > 1048576) reject(new Error()); }); process.stdin.on('end', () => resolve(text)); process.stdin.on('error', reject); }) : await readFile(path, 'utf8');
|
|
@@ -109,6 +110,7 @@ program.command('api-service').description('Start the API service with API-key p
|
|
|
109
110
|
.option('--tls-cert <path>','TLS certificate path').option('--tls-key <path>','protected TLS private key path')
|
|
110
111
|
.action(async o=>{
|
|
111
112
|
if(configuredBroker()||configuredBrokerToken()||configuredDelegate())throw new FeishuError('INVALID_ARGUMENT','Start the API service directly.');
|
|
113
|
+
requireFileCredentials();
|
|
112
114
|
if(!/^\d+$/.test(o.port))throw new FeishuError('INVALID_ARGUMENT','Port must be a number.');
|
|
113
115
|
const service=await startApiService({host:o.host,port:Number(o.port),policyPath:o.policy,getServices:servicesFactory(),tlsCert:o.tlsCert,tlsKey:o.tlsKey});
|
|
114
116
|
output({status:'listening',host:service.host,port:service.port,tls:service.tls});
|
|
@@ -135,13 +137,13 @@ program.command('broker-serve').description('Start a restricted local agent brok
|
|
|
135
137
|
.requiredOption('--token-file <path>', 'absolute owner-controlled agent token file')
|
|
136
138
|
.action(async o => {
|
|
137
139
|
if (configuredBroker() || configuredDelegate()) throw new FeishuError('INVALID_ARGUMENT', 'Start the broker directly, without a broker or OS delegate.');
|
|
140
|
+
requireFileCredentials();
|
|
138
141
|
const policy = await loadPolicy(o.policy);
|
|
139
142
|
const token = await loadBrokerToken(o.tokenFile, { owner: true });
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
const gateway = new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) });
|
|
143
|
+
const getServices = async () => {
|
|
144
|
+
const gateway = new Gateway({ cookie: await loadProtectedCookie(serviceAccountFile()) });
|
|
143
145
|
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
|
|
144
|
-
}
|
|
146
|
+
};
|
|
145
147
|
const broker = await startBroker({ socketPath: o.socket, policy, token, getServices });
|
|
146
148
|
output({ status: 'listening', socket: broker.socketPath });
|
|
147
149
|
let closing = false;
|
|
@@ -180,14 +182,26 @@ program.command('listen-service').description('Serve messages on a private Unix
|
|
|
180
182
|
.action(async o => {
|
|
181
183
|
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
182
184
|
if (o.all && o.chat.length) throw new FeishuError('INVALID_ARGUMENT', 'Use --all or --chat, not both.');
|
|
185
|
+
requireFileCredentials();
|
|
183
186
|
const selected=program.opts().credentialsFile;
|
|
184
|
-
const defaultAccountFile=
|
|
187
|
+
const defaultAccountFile=resolve(join(process.env.LARKMATE_HOME||join(homedir(),'.larkmate'),'credentials.json'));
|
|
185
188
|
const accountFile=selected?resolve(selected):defaultAccountFile;
|
|
186
|
-
const gateway=new Gateway({cookie:accountFile&&o.policy?await loadProtectedCookie(accountFile):await loadCookie({file:selected})}), self=await gateway.authenticate();
|
|
187
189
|
if(!['0600','0660'].includes(o.socketMode))throw new FeishuError('INVALID_ARGUMENT','Socket mode must be 0600 or 0660.');
|
|
188
|
-
|
|
190
|
+
let service,active;
|
|
191
|
+
const onStart=async()=>{
|
|
192
|
+
const controller=new AbortController();active=controller;
|
|
193
|
+
try{
|
|
194
|
+
const gateway=new Gateway({cookie:await loadProtectedCookie(accountFile)}),self=await gateway.authenticate();
|
|
195
|
+
if(controller.signal.aborted)throw new FeishuError('LISTEN_STOPPED','Listener stopped.');
|
|
196
|
+
listen({gateway,chatIds:o.chat,output:service.output,signal:controller.signal}).catch(error=>{if(!controller.signal.aborted)service.output.write(JSON.stringify({kind:'gap',reason:'listener_failed',code:error.code||'LISTEN_FAILED'})+'\n');});
|
|
197
|
+
return {selfId:self.id,resolveNames:createNameResolver(gateway,self.id)};
|
|
198
|
+
}catch(error){controller.abort();if(active===controller)active=null;throw error;}
|
|
199
|
+
};
|
|
200
|
+
const onIdle=()=>{active?.abort();active=null;};
|
|
201
|
+
service = await startListenService(o.socket,{policyPath:o.policy,socketMode:parseInt(o.socketMode,8),credentialsFile:accountFile,defaultCredentialsFile:defaultAccountFile,onStart,onIdle});
|
|
202
|
+
let finish;const stopped=new Promise(resolve=>{finish=resolve});const stop=()=>finish();
|
|
189
203
|
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
190
|
-
try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await
|
|
204
|
+
try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await stopped; }
|
|
191
205
|
finally { await service.close(); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
|
|
192
206
|
});
|
|
193
207
|
program.command('listen-run').description('Run configured scripts for matching new messages.')
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
// The policy location is fixed relative to this protected installation, never to caller input.
|
|
3
3
|
import { fileURLToPath } from 'node:url';
|
|
4
4
|
import { loadDelegateConfig, serveOne } from '../src/os-delegate.js';
|
|
5
|
-
import {
|
|
5
|
+
import { loadProtectedCookie } from '../src/credentials.js';
|
|
6
6
|
import { Gateway } from '../src/gateway.js';
|
|
7
7
|
import { LarkMateClient } from '../src/client.js';
|
|
8
8
|
import { SessionControls } from '../src/session-controls.js';
|
|
@@ -22,7 +22,7 @@ try {
|
|
|
22
22
|
if (!profile) throw new FeishuError('POLICY_DENIED', 'This operating-system user has no delegation profile.');
|
|
23
23
|
let services;
|
|
24
24
|
const getServices = () => services ||= (async () => {
|
|
25
|
-
const gateway = new Gateway({ cookie:
|
|
25
|
+
const gateway = new Gateway({ cookie: await loadProtectedCookie(profile.credentialsFile || config.credentialsFile) });
|
|
26
26
|
return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
|
|
27
27
|
})();
|
|
28
28
|
await serveOne({ input: process.stdin, output: process.stdout, uid: caller, profile, getServices });
|
package/docs/agent-broker.md
CHANGED
|
@@ -26,7 +26,7 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
|
|
|
26
26
|
策略文件和令牌文件须归代理账户或 `root` 所有,且不能允许组用户或其他用户写入;两者须为普通文件,不能是符号链接。启动时检查文件类型、属主和 Unix 模式;ACL 和上级目录的保护由部署方验证。socket 的父目录须归代理账户所有,且同样不能允许组用户或其他用户写入。socket 初始权限为 `0600`,代理仅监听这个 Unix socket。
|
|
27
27
|
4. 由部署方配置系统账户、目录遍历权限以及 ACL 或组权限,使 Agent 能够连接 socket 并读取自己的令牌文件,但不能写入令牌、策略、代理程序或其所在目录,也不能读取 Cookie。不要将 socket 文件权限作为唯一的身份验证手段:连接时还必须提供令牌。
|
|
28
28
|
|
|
29
|
-
|
|
29
|
+
策略和令牌在代理启动时读取,修改后需要重启代理。Cookie 在每次调用通过授权后从受保护文件读取,更新文件后用于后续调用;服务环境不能包含 `LARKMATE_COOKIE`。令牌属于持有者凭证(Bearer Token),Agent 可能会保留已读取的令牌;如需撤销访问权限,应先停止代理并更换令牌,再按需重新启动。不同 Agent 应使用各自的策略、令牌和 socket。代理停止后会清理自己创建的 socket;若因异常退出遗留了 socket,须在确认代理已停止后由所有者处理。
|
|
30
30
|
|
|
31
31
|
## 配置授权
|
|
32
32
|
|
package/docs/api-service.md
CHANGED
|
@@ -39,13 +39,17 @@ larkmate api-key-create --output "$HOME/.larkmate/keys/agent-a.key"
|
|
|
39
39
|
|
|
40
40
|
策略文件须使用绝对路径,归服务用户或 root 所有,且不能允许组用户或其他用户写入;建议设置为 `chmod 600 ~/.larkmate/api-policy.json`。策略不能是符号链接。`api` 和 `events` 可分别省略:省略后该 key 就不能使用对应的服务。增加 `keys` 条目可为不同调用方设置不同权限。
|
|
41
41
|
|
|
42
|
+
服务模式仅使用受保护的凭据文件;若环境中存在 `LARKMATE_COOKIE`,启动会拒绝并提示移除该变量。API 调用先校验 key、命令及资源范围,再读取对应 Cookie;服务不提供读取 Cookie 的接口。消息服务在订阅通过授权后才读取 Cookie 和连接飞书,最后一个订阅断开后停止监听。Cookie 仅供服务处理使用,内存回收由运行时管理,无法保证即时擦除。
|
|
43
|
+
|
|
44
|
+
这里的授权是服务程序的访问控制,不是对服务器管理员或进程内存的加密隔离。为隔离不同账号,应使用独立系统用户或容器、受保护的文件和服务进程;能够读取进程内存、凭据文件或控制服务进程的用户仍可能获取 Cookie。
|
|
45
|
+
|
|
42
46
|
`credentialsFile` 将 key 绑定到服务端的飞书账号,使用与现有 `credentials.json` 相同的 `{"cookie":"..."}` 格式。凭据文件须是服务用户或 root 拥有、仅所有者可访问的普通文件,不能是符号链接;保护好上级目录和 ACL。多个 API key 既可绑定至同一账号,也可分别绑定至不同账号。调用方仅持有 API key,无法在请求中指定其他凭据文件。若未配置账号绑定,API 服务沿用启动时指定的账号。账号绑定的文件会在每次 API 操作时读取,更新后用于后续调用;进行中的调用可能仍使用原凭据。
|
|
43
47
|
|
|
44
48
|
`api.allow` 指定允许调用的命令;`chatIds` 限定会话。运行 `larkmate api-commands` 查看可用命令、调用方法和权限范围。某些全局操作、妙记以及附件操作还需要对应的策略字段,完整含义见 [Agent 权限委托指南](agent-broker.md)中的策略说明。请按需授权,避免使用全局授权来代替具体范围。
|
|
45
49
|
|
|
46
50
|
`events` 是授权规则数组,任一规则匹配即可接收;单条规则中的 `chatIds`、`senderIds` 和 `types` 同时生效,每个数组可包含多个值。`senderIds` 和 `types` 可以省略;每条规则必须指定 `chatIds`,或明确设置 `"allChats": true` 允许所有会话。授权使用稳定的数字 ID;调用方还可以在订阅时用名称、正则和组合条件进一步过滤,但不能扩大 key 的授权范围。
|
|
47
51
|
|
|
48
|
-
修改策略后,新 API 请求和后续消息事件会读取新策略。已开始执行的 API
|
|
52
|
+
修改策略后,新 API 请求和后续消息事件会读取新策略。已开始执行的 API 请求可能完成;消息服务还会定期检查有效订阅并断开已撤销的连接。建议通过创建新的受保护文件并原子替换策略文件来更新,避免读取到不完整的内容。
|
|
49
53
|
|
|
50
54
|
## 启动通用 API 服务
|
|
51
55
|
|
|
@@ -92,7 +96,7 @@ larkmate listen-service --socket "$HOME/.larkmate/events.sock" \
|
|
|
92
96
|
--policy "$HOME/.larkmate/api-policy.json"
|
|
93
97
|
```
|
|
94
98
|
|
|
95
|
-
每个消息服务进程监听一个账号。监听指定账号时,在命令名前使用 `--credentials-file /绝对路径/account-a.json`,并为不同账号启动不同的 socket。绑定了账号的 key 只能连接匹配该凭据文件的消息服务;未绑定账号的 key
|
|
99
|
+
每个消息服务进程监听一个账号。监听指定账号时,在命令名前使用 `--credentials-file /绝对路径/account-a.json`,并为不同账号启动不同的 socket。绑定了账号的 key 只能连接匹配该凭据文件的消息服务;未绑定账号的 key 只能连接使用默认凭据的消息服务。活跃订阅使用启动监听时读取的 Cookie;所有订阅断开后,下次订阅会重新读取凭据。如果现有监听服务使用了 `--credentials-file` 指定非默认文件,请为其 key 添加相同的 `credentialsFile`,以继续订阅。
|
|
96
100
|
|
|
97
101
|
通过 Unix socket 连接 `/events`,同样在请求头提供 key。以下示例读取服务授权范围内的事件:
|
|
98
102
|
|
|
@@ -12,6 +12,8 @@ larkmate listen-service --socket "$HOME/.larkmate/events/messages.sock"
|
|
|
12
12
|
|
|
13
13
|
默认监听全部会话;传入 `--chat "$CHAT_ID"` 可限制范围,并可重复指定。也可用 `--all` 显式表示全局监听。其他本机程序通过 Unix socket 订阅 JSON Lines:
|
|
14
14
|
|
|
15
|
+
消息服务在订阅通过授权后读取 Cookie 并连接飞书,并在最后一个订阅断开时停止监听。无订阅期间的消息不会被收取,后续重新订阅也无法保证补回该时段内的消息。
|
|
16
|
+
|
|
15
17
|
```sh
|
|
16
18
|
curl -N --unix-socket "$HOME/.larkmate/events/messages.sock" http://localhost/events
|
|
17
19
|
```
|
package/docs/os-delegation.md
CHANGED
|
@@ -14,6 +14,8 @@
|
|
|
14
14
|
|
|
15
15
|
每个用户的 `policy` 与[代理策略](agent-broker.md#配置授权)使用相同字段;只允许 `allow` 和资源范围共同匹配的操作。可通过 `larkmate delegate-commands` 查看可委托的命令及范围。可选的 `approvalScript` 必须是绝对路径、由所有者或 root 拥有的可执行普通文件,且不得允许组用户或其他用户写入;不配置时未授权操作直接拒绝。`approvalTimeoutSeconds` 默认 300 秒,可设为 1 至 600 秒。
|
|
16
16
|
|
|
17
|
+
授权检查或审批通过后,执行器才读取对应 Cookie,并用于当前进程中的飞书调用;凭据不会返回给调用方。顶层及用户级的凭据文件均须是所有者或 root 拥有、仅所有者可访问的普通文件,不能是符号链接。
|
|
18
|
+
|
|
17
19
|
可在每个 `users` 条目内设置 `credentialsFile` 绝对路径,为该系统用户指定飞书账号。不同用户可以指向不同文件;未设置时继承顶层的 `credentialsFile`。顶层文件可省略,但每个用户都必须有自己的文件。用户条目中的凭据文件须归所有者或 root 所有,仅所有者可访问,且必须是普通文件而非符号链接;格式与现有登录凭据相同。Agent 不能自行指定或更换账号,每个账号仍受对应用户的命令和资源策略限制。
|
|
18
20
|
|
|
19
21
|
文件、图片发送及附件下载可分别授权;上传文件由 Agent 进程读取,下载文件由 Agent 进程写入。执行器不接受 Agent 提供的所有者本地路径。下载时须提供 `history` 返回的 `--position`,执行器会核验会话、消息和资源键。单个文件受 `maxFileBytes` 限制;执行器在所有者私有临时目录中处理中转数据,正常结束或失败时删除,异常退出可能留下临时文件。部署方应保护、按需清理临时目录,并根据实际需要配置系统资源限制。
|
package/package.json
CHANGED
|
@@ -9,3 +9,5 @@
|
|
|
9
9
|
`listen-run` 的规则可省略 `chatIds` 以匹配全部会话,也可按会话、发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
|
|
10
10
|
|
|
11
11
|
自动重连时会尽力按会话位置补拉,补拉事件带 `backfill: true`;全局模式只能补拉本次进程已见过的会话,并在中断时发出 `global_coverage_unknown` 缺口事件。处理 `gap` 事件并按需查询历史。去重和补拉位置仅保存在当前进程内,重启后不恢复,不能保证不漏或恰好执行一次。服务订阅者不在线时不会缓存事件。监听目前不能通过 broker 或系统用户委托使用;保护 socket、Cookie、规则文件和脚本的访问由部署方负责。
|
|
12
|
+
|
|
13
|
+
消息服务仅在订阅通过系统 socket 权限或 API key 授权后读取 Cookie 和连接飞书,最后一个订阅断开后停止监听;无订阅期间的消息不会收取,重新订阅不能保证补回。
|
package/src/listen-modes.js
CHANGED
|
@@ -89,7 +89,7 @@ export function createRuleOutput({rules,selfId,resolveNames,log=process.stderr})
|
|
|
89
89
|
}
|
|
90
90
|
|
|
91
91
|
// Exposes the configured event stream, protected by the socket and parent directory permissions.
|
|
92
|
-
export async function startListenService(socketPath, {selfId,resolveNames,policyPath,socketMode=0o600,credentialsFile=null,defaultCredentialsFile=null}={}) {
|
|
92
|
+
export async function startListenService(socketPath, {selfId,resolveNames,policyPath,socketMode=0o600,credentialsFile=null,defaultCredentialsFile=null,onStart,onIdle}={}) {
|
|
93
93
|
if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
|
|
94
94
|
if(![0o600,0o660].includes(socketMode)||(socketMode!==0o600&&!policyPath))throw new FeishuError('INVALID_ARGUMENT','A shared socket requires an API key policy.');
|
|
95
95
|
if(policyPath)await loadAccessPolicy(policyPath);
|
|
@@ -97,16 +97,26 @@ export async function startListenService(socketPath, {selfId,resolveNames,policy
|
|
|
97
97
|
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.');
|
|
98
98
|
const path=join(parent,socketPath.slice(socketPath.lastIndexOf('/')+1));
|
|
99
99
|
try{await lstat(path);throw new FeishuError('LISTEN_SOCKET_EXISTS','The socket path already exists.');}catch(e){if(e.code!=='ENOENT')throw e;}
|
|
100
|
-
const clients=new Map();
|
|
100
|
+
const clients=new Map();let starting=null,pending=0,closing=false;
|
|
101
|
+
const idle=()=>{if(!closing&&onStart&&starting&&pending===0&&clients.size===0){starting=null;selfId=undefined;resolveNames=undefined;onIdle?.();}};
|
|
102
|
+
const activate=async()=>{
|
|
103
|
+
if(!onStart)return;
|
|
104
|
+
starting ||= Promise.resolve().then(onStart).then(runtime=>{selfId=runtime.selfId;resolveNames=runtime.resolveNames;});
|
|
105
|
+
try{await starting}catch(error){starting=null;throw error;}
|
|
106
|
+
};
|
|
101
107
|
const server=http.createServer(async(req,res)=>{
|
|
102
108
|
if(!['GET','POST'].includes(req.method)){res.writeHead(404);res.end();return;}
|
|
109
|
+
if((req.method==='GET'&&!/^\/events(?:\?|$)/.test(req.url))||(req.method==='POST'&&req.url!=='/events')){res.writeHead(404);res.end();return;}
|
|
103
110
|
let keyHash=null;
|
|
104
111
|
if(policyPath){
|
|
105
112
|
try{const key=lookupAccessKey(await loadAccessPolicy(policyPath),requestKey(req));if(!key)throw new FeishuError('API_KEY_INVALID','A valid API key is required.');if(!key.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile){res.writeHead(403);res.end();return;}keyHash=key.sha256;}
|
|
106
113
|
catch(error){const status=error.code==='API_KEY_INVALID'?401:503;res.writeHead(status,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify({ok:false,error:{code:status===401?'API_KEY_INVALID':'ACCESS_POLICY_UNAVAILABLE',message:status===401?'A valid API key is required.':'The API key access policy is unavailable.'}}));return;}
|
|
107
114
|
}
|
|
108
|
-
let filter;
|
|
115
|
+
let filter;pending++;
|
|
109
116
|
try {
|
|
117
|
+
await activate();
|
|
118
|
+
if(closing||req.destroyed||res.destroyed) return;
|
|
119
|
+
if(policyPath){const key=lookupAccessKey(await loadAccessPolicy(policyPath),keyHash,{hashed:true});if(!key?.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile)throw new FeishuError('POLICY_DENIED','Subscription permission has been revoked.');}
|
|
110
120
|
if(req.method==='GET') filter=parseSubscriptionFilter(req.url,selfId);
|
|
111
121
|
else {
|
|
112
122
|
if(req.url!=='/events')throw new FeishuError('NOT_FOUND','Unknown endpoint.');
|
|
@@ -118,13 +128,22 @@ export async function startListenService(socketPath, {selfId,resolveNames,policy
|
|
|
118
128
|
}
|
|
119
129
|
const needs=filterNeeds(filter);
|
|
120
130
|
if((needs.chat||needs.sender)&&typeof resolveNames!=='function')throw new FeishuError('INVALID_FILTER','Name lookup is unavailable.');
|
|
131
|
+
res.writeHead(200,{'content-type':'application/x-ndjson','cache-control':'no-store','x-content-type-options':'nosniff'});clients.set(res,{filter,needs:filterNeeds(filter),keyHash});res.on('close',()=>{clients.delete(res);idle();});res.flushHeaders();
|
|
121
132
|
}
|
|
122
|
-
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||'
|
|
123
|
-
|
|
133
|
+
catch(error) { if(!res.destroyed){const status=error.code==='NOT_FOUND'?404:error.code==='POLICY_DENIED'?403:error.code==='INVALID_FILTER'?400:503;res.writeHead(status,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify({ok:false,error:{code:error.code||'LISTEN_UNAVAILABLE',message:error instanceof FeishuError?error.message:'Cannot start the listener.'}}));} }
|
|
134
|
+
finally {pending--;idle();}
|
|
124
135
|
});
|
|
125
136
|
const oldMask=process.umask(0o077);
|
|
126
137
|
try { await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve)}); } finally { process.umask(oldMask); }
|
|
127
138
|
await chmod(path,socketMode);const inode=(await lstat(path)).ino;
|
|
139
|
+
let checking=false;
|
|
140
|
+
const timer=policyPath&&onStart?setInterval(async()=>{
|
|
141
|
+
if(checking||!clients.size)return;checking=true;
|
|
142
|
+
try{const policy=await loadAccessPolicy(policyPath);for(const [client,entry] of clients){const key=lookupAccessKey(policy,entry.keyHash,{hashed:true});if(!key?.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile)client.destroy();}}
|
|
143
|
+
catch{for(const client of clients.keys())client.destroy();}
|
|
144
|
+
finally{checking=false;}
|
|
145
|
+
},1000):null;
|
|
146
|
+
timer?.unref();
|
|
128
147
|
const output=new Writable({write(chunk,_encoding,callback){(async()=>{
|
|
129
148
|
let event;try{event=JSON.parse(chunk.toString())}catch{throw new FeishuError('INVALID_RESPONSE','Invalid listener event.')}
|
|
130
149
|
let policy=null;if(policyPath){try{policy=await loadAccessPolicy(policyPath)}catch{for(const client of clients.keys())client.destroy();return;}}
|
|
@@ -156,5 +175,5 @@ export async function startListenService(socketPath, {selfId,resolveNames,policy
|
|
|
156
175
|
if(policyPath&&deferred.length){try{policy=await loadAccessPolicy(policyPath)}catch{for(const [client] of deferred)client.destroy();return;}}
|
|
157
176
|
for(const [client,{filter,keyHash}] of deferred){if(policyPath){const key=lookupAccessKey(policy,keyHash,{hashed:true});if(!key?.events||(key.credentialsFile??defaultCredentialsFile)!==credentialsFile){client.destroy();continue;}if(!eventAllowed(key.events,event))continue;}deliver(client,filter,event);}
|
|
158
177
|
})().then(()=>callback(),callback)}});
|
|
159
|
-
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;}}};
|
|
178
|
+
return {path,output,async close(){closing=true;clearInterval(timer);for(const c of clients.keys())c.destroy();if(starting)onIdle?.();starting=null;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;}}};
|
|
160
179
|
}
|
package/src/listen.js
CHANGED
|
@@ -118,6 +118,7 @@ export async function listen({ gateway, chatIds = [], output = process.stdout, l
|
|
|
118
118
|
let socket, heartbeat, pending = Promise.resolve(), connected = false, failure = null, reported = false;
|
|
119
119
|
try {
|
|
120
120
|
const url = await connectionUrl(gateway);
|
|
121
|
+
if (signal?.aborted) break;
|
|
121
122
|
socket = new WebSocketImpl(url); socket.binaryType = 'arraybuffer';
|
|
122
123
|
await new Promise((resolve,reject) => {
|
|
123
124
|
const cleanup = () => { clearTimeout(timeout); signal?.removeEventListener('abort',abort); };
|
|
@@ -128,6 +129,7 @@ export async function listen({ gateway, chatIds = [], output = process.stdout, l
|
|
|
128
129
|
socket.addEventListener('close',()=>{cleanup();reject(new FeishuError('LISTEN_CONNECT_FAILED','Feishu closed the message connection.'));},{once:true});
|
|
129
130
|
signal?.addEventListener('abort',abort,{once:true});
|
|
130
131
|
});
|
|
132
|
+
if (signal?.aborted) { socket.close(); break; }
|
|
131
133
|
connected = true; attempt = 0;
|
|
132
134
|
const closed = new Promise(resolve => socket.addEventListener('close',resolve,{once:true}));
|
|
133
135
|
const stop = () => socket.close(); signal?.addEventListener('abort',stop,{once:true});
|