larkmate 0.1.19 → 0.1.20
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 +2 -1
- package/bin/larkmate.js +26 -3
- package/docs/api-service.md +109 -0
- package/package.json +1 -1
- package/skills/larkmate/SKILL.md +1 -0
- package/skills/larkmate/references/listen.md +3 -1
- package/src/access-policy.js +62 -0
- package/src/agent-broker.js +3 -0
- package/src/api-service.js +45 -0
- package/src/listen-modes.js +27 -8
package/README.md
CHANGED
|
@@ -58,6 +58,7 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
58
58
|
- [x] 给消息添加和取消表情回应
|
|
59
59
|
- [x] 获取消息链接
|
|
60
60
|
- [x] 全局或按会话监听新消息,支持名称、正则、组合过滤和规则触发脚本
|
|
61
|
+
- [x] 按 API key 限定消息服务的订阅范围
|
|
61
62
|
- 群聊
|
|
62
63
|
- [x] 查询群信息、成员、管理员和入退群记录
|
|
63
64
|
- [x] 修改群名称、描述、头像和本人群昵称
|
|
@@ -89,4 +90,4 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
89
90
|
|
|
90
91
|
具体用法和能力边界见 [LarkMate Skill](skills/larkmate/SKILL.md)。
|
|
91
92
|
|
|
92
|
-
如需将部分能力交给其他 Agent,可使用 [系统用户权限委托](docs/os-delegation.md)或 [本地代理](docs/agent-broker.md)。
|
|
93
|
+
如需将部分能力交给其他 Agent,可使用 [API 服务与 API key 授权](docs/api-service.md)、[系统用户权限委托](docs/os-delegation.md)或 [本地代理](docs/agent-broker.md)。
|
package/bin/larkmate.js
CHANGED
|
@@ -8,7 +8,7 @@ import { Minutes, formatTranscript } from '../src/minutes.js';
|
|
|
8
8
|
import { writeFile, readFile } from 'node:fs/promises';
|
|
9
9
|
import { FeishuError } from '../src/errors.js';
|
|
10
10
|
import { exportMessages } from '../src/export-messages.js';
|
|
11
|
-
import { brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
|
|
11
|
+
import { apiCommands, brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
|
|
12
12
|
import { callOsDelegate, osDelegateProxy } from '../src/os-delegate-client.js';
|
|
13
13
|
import { SidebarFilters } from '../src/sidebar-filters.js';
|
|
14
14
|
import { FeedGroups } from '../src/feed-groups.js';
|
|
@@ -18,10 +18,12 @@ 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
20
|
import { createNameResolver } from '../src/listen-names.js';
|
|
21
|
+
import { createApiKey } from '../src/access-policy.js';
|
|
22
|
+
import { startApiService } from '../src/api-service.js';
|
|
21
23
|
|
|
22
24
|
const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
|
|
23
25
|
const program = new Command();
|
|
24
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
26
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.20');
|
|
25
27
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
26
28
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
27
29
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -81,6 +83,10 @@ async function groups() { const remote = proxy('groups'); return remote || new G
|
|
|
81
83
|
async function calendar() { const remote = proxy('calendar'); return remote || new Calendar(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
82
84
|
async function feeds() { const remote = proxy('feeds'); return remote || new FeedGroups(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
83
85
|
async function tasks() { const remote = proxy('tasks'); return remote || new Tasks(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
|
|
86
|
+
function servicesFactory() {
|
|
87
|
+
let promise;
|
|
88
|
+
return () => promise ||= (async()=>{const gateway=new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})});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)};})().catch(error=>{promise=undefined;throw error;});
|
|
89
|
+
}
|
|
84
90
|
async function readJson(path, fallback) {
|
|
85
91
|
if (!path) return fallback;
|
|
86
92
|
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');
|
|
@@ -90,6 +96,21 @@ async function readJson(path, fallback) {
|
|
|
90
96
|
|
|
91
97
|
program.command('broker-commands').description('List operations supported by the agent broker and their scopes.')
|
|
92
98
|
.action(() => output({ items: brokerCommands() }));
|
|
99
|
+
program.command('api-commands').description('List API commands, services, methods and scopes.')
|
|
100
|
+
.action(() => output({ items: apiCommands() }));
|
|
101
|
+
program.command('api-key-create').description('Create a private API key and print its SHA-256 policy value.')
|
|
102
|
+
.requiredOption('--output <path>', 'absolute path for a new private key file')
|
|
103
|
+
.action(async o=>output({status:'created',...await createApiKey(o.output)}));
|
|
104
|
+
program.command('api-service').description('Start the API service with API-key permissions.')
|
|
105
|
+
.requiredOption('--policy <path>','absolute protected API key policy path').option('--host <address>','IP address or localhost','127.0.0.1').option('--port <number>','port (0 chooses a free port)','0')
|
|
106
|
+
.option('--tls-cert <path>','TLS certificate path').option('--tls-key <path>','protected TLS private key path')
|
|
107
|
+
.action(async o=>{
|
|
108
|
+
if(configuredBroker()||configuredBrokerToken()||configuredDelegate())throw new FeishuError('INVALID_ARGUMENT','Start the API service directly.');
|
|
109
|
+
if(!/^\d+$/.test(o.port))throw new FeishuError('INVALID_ARGUMENT','Port must be a number.');
|
|
110
|
+
const service=await startApiService({host:o.host,port:Number(o.port),policyPath:o.policy,getServices:servicesFactory(),tlsCert:o.tlsCert,tlsKey:o.tlsKey});
|
|
111
|
+
output({status:'listening',host:service.host,port:service.port,tls:service.tls});
|
|
112
|
+
let closing=false;const stop=async()=>{if(closing)return;closing=true;try{await service.close()}finally{process.exit(0)}};process.once('SIGINT',stop);process.once('SIGTERM',stop);
|
|
113
|
+
});
|
|
93
114
|
|
|
94
115
|
program.command('delegate-commands').description('List operations supported by OS-user delegation and their scopes.')
|
|
95
116
|
.action(() => output({ items: brokerCommands() }));
|
|
@@ -152,11 +173,13 @@ program.command('listen').description('Stream new messages as JSON lines; defaul
|
|
|
152
173
|
});
|
|
153
174
|
program.command('listen-service').description('Serve messages on a private Unix socket; defaults to all chats.')
|
|
154
175
|
.option('--chat <id>', 'restrict to a numeric chat ID; repeatable', collect, []).option('--all', 'listen to all chats').requiredOption('--socket <path>', 'absolute Unix socket path')
|
|
176
|
+
.option('--policy <path>','absolute protected API key policy path').option('--socket-mode <mode>','0600 or 0660 (0660 requires a key policy)','0600')
|
|
155
177
|
.action(async o => {
|
|
156
178
|
if (configuredBroker() || configuredBrokerToken() || configuredDelegate()) throw new FeishuError('UNSUPPORTED_MODE', 'Message listening is not available through broker or OS delegation.');
|
|
157
179
|
if (o.all && o.chat.length) throw new FeishuError('INVALID_ARGUMENT', 'Use --all or --chat, not both.');
|
|
158
180
|
const gateway=new Gateway({cookie:await loadCookie({file:program.opts().credentialsFile})}), self=await gateway.authenticate();
|
|
159
|
-
|
|
181
|
+
if(!['0600','0660'].includes(o.socketMode))throw new FeishuError('INVALID_ARGUMENT','Socket mode must be 0600 or 0660.');
|
|
182
|
+
const service = await startListenService(o.socket,{selfId:self.id,resolveNames:createNameResolver(gateway,self.id),policyPath:o.policy,socketMode:parseInt(o.socketMode,8)}), controller = new AbortController(), stop = () => controller.abort();
|
|
160
183
|
process.once('SIGINT', stop); process.once('SIGTERM', stop);
|
|
161
184
|
try { process.stderr.write(`LarkMate: event socket ${service.path}\n`); await listen({ gateway,chatIds:o.chat,output:service.output,signal:controller.signal }); }
|
|
162
185
|
finally { await service.close(); process.removeListener('SIGINT',stop);process.removeListener('SIGTERM',stop); }
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# API 服务与 API key 授权
|
|
2
|
+
|
|
3
|
+
LarkMate 提供通用的 HTTP API 服务与 Unix socket 消息服务,两者可共用同一份策略文件。每个 API key 均可独立配置允许调用的操作及可接收的消息范围。服务使用启动者配置的飞书 Cookie 访问飞书,因此仍受该账号权限的限制。
|
|
4
|
+
|
|
5
|
+
## 创建 key 和策略
|
|
6
|
+
|
|
7
|
+
先在服务运行用户的私有目录创建 key:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
mkdir -p "$HOME/.larkmate/keys"
|
|
11
|
+
chmod 700 "$HOME/.larkmate/keys"
|
|
12
|
+
larkmate api-key-create --output "$HOME/.larkmate/keys/agent-a.key"
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
命令只输出 key 文件路径和 SHA-256 摘要;将摘要填入策略,key 文件交给需要访问服务的调用方。不要把 key、Cookie 或包含 key 的请求头放进代码仓库或日志。为每个调用方创建不同的 key,便于单独调整权限或撤销。
|
|
16
|
+
|
|
17
|
+
例如,将以下内容保存为 `~/.larkmate/api-policy.json`,替换摘要和数字 ID:
|
|
18
|
+
|
|
19
|
+
```json
|
|
20
|
+
{
|
|
21
|
+
"version": 1,
|
|
22
|
+
"keys": [
|
|
23
|
+
{
|
|
24
|
+
"name": "agent-a",
|
|
25
|
+
"sha256": "替换为 api-key-create 输出的 64 位摘要",
|
|
26
|
+
"api": {
|
|
27
|
+
"version": 1,
|
|
28
|
+
"allow": ["chat-info", "history"],
|
|
29
|
+
"chatIds": ["123"]
|
|
30
|
+
},
|
|
31
|
+
"events": [
|
|
32
|
+
{ "chatIds": ["123"], "senderIds": ["456"], "types": [4] }
|
|
33
|
+
]
|
|
34
|
+
}
|
|
35
|
+
]
|
|
36
|
+
}
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
策略文件须使用绝对路径,归服务用户或 root 所有,且不能允许组用户或其他用户写入;建议设置为 `chmod 600 ~/.larkmate/api-policy.json`。策略不能是符号链接。`api` 和 `events` 可分别省略:省略后该 key 就不能使用对应的服务。增加 `keys` 条目可为不同调用方设置不同权限。
|
|
40
|
+
|
|
41
|
+
`api.allow` 指定允许调用的命令;`chatIds` 限定会话。运行 `larkmate api-commands` 查看可用命令、调用方法和权限范围。某些全局操作、妙记以及附件操作还需要对应的策略字段,完整含义见 [Agent 权限委托指南](agent-broker.md)中的策略说明。请按需授权,避免使用全局授权来代替具体范围。
|
|
42
|
+
|
|
43
|
+
`events` 是授权规则数组,任一规则匹配即可接收;单条规则中的 `chatIds`、`senderIds` 和 `types` 同时生效,每个数组可包含多个值。`senderIds` 和 `types` 可以省略;每条规则必须指定 `chatIds`,或明确设置 `"allChats": true` 允许所有会话。授权使用稳定的数字 ID;调用方还可以在订阅时用名称、正则和组合条件进一步过滤,但不能扩大 key 的授权范围。
|
|
44
|
+
|
|
45
|
+
修改策略后,新 API 请求和后续消息事件会读取新策略。已开始执行的 API 请求可能完成;已撤销的消息连接会在处理下一条事件时断开。建议通过创建新的受保护文件并原子替换策略文件来更新,避免读取到不完整的内容。
|
|
46
|
+
|
|
47
|
+
## 启动通用 API 服务
|
|
48
|
+
|
|
49
|
+
```sh
|
|
50
|
+
larkmate api-service --policy "$HOME/.larkmate/api-policy.json" --port 18765
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
默认只监听 `127.0.0.1`,每个请求都必须在 `X-API-Key` 或 `Authorization: Bearer` 请求头中提供 key。`GET /v1/commands` 返回当前 key 可使用的命令;`POST /v1/call` 执行操作。例子从文件读取 key,不把 key 写在命令参数里:
|
|
54
|
+
|
|
55
|
+
```sh
|
|
56
|
+
export LARKMATE_API_KEY_FILE="$HOME/.larkmate/keys/agent-a.key"
|
|
57
|
+
node --input-type=module <<'JS'
|
|
58
|
+
import { readFile } from 'node:fs/promises';
|
|
59
|
+
const key = (await readFile(process.env.LARKMATE_API_KEY_FILE, 'utf8')).trim();
|
|
60
|
+
const response = await fetch('http://127.0.0.1:18765/v1/call', {
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: { 'content-type': 'application/json', 'x-api-key': key },
|
|
63
|
+
body: JSON.stringify({ command: 'chat-info', service: 'client', method: 'chatInfo', args: ['123'] }),
|
|
64
|
+
});
|
|
65
|
+
console.log(await response.text());
|
|
66
|
+
JS
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
`POST /v1/file` 传输文件和图片。请求使用 `Content-Type: application/octet-stream`,`X-Larkmate-File` 为 UTF-8 JSON 元数据的 base64url 编码:
|
|
70
|
+
|
|
71
|
+
- 上传时元数据为 `{"command":"send-file","chatId":"123","name":"a.txt","size":5}`,请求体为文件字节;发送图片使用 `send-image`,设置群头像使用 `group-avatar-set`。
|
|
72
|
+
- 下载时元数据为 `{"command":"download-file","chatId":"123","messageId":"456","key":"attachment-key","position":1}`,请求体为空,成功响应体为文件字节。消息 ID、附件 key 和 position 来自对应会话的历史消息;服务会核对它们确实属于该消息。
|
|
73
|
+
|
|
74
|
+
文件内容通过请求或响应传输,服务端不会按调用方提供的本地路径读取文件。文件操作必须分别在 `api.allow` 中授权,并受会话及大小限制。
|
|
75
|
+
|
|
76
|
+
如需绑定非回环地址,必须配置 TLS:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
larkmate api-service --policy "$HOME/.larkmate/api-policy.json" \
|
|
80
|
+
--host 0.0.0.0 --port 18765 --tls-cert /absolute/path/cert.pem --tls-key /absolute/path/key.pem
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
证书与私钥路径必须为绝对路径,私钥须归服务用户或 root 所有且仅允许所有者访问。调用方应验证服务端证书并通过 HTTPS 传输 key。
|
|
84
|
+
|
|
85
|
+
## 为消息服务授权
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
larkmate listen-service --socket "$HOME/.larkmate/events.sock" \
|
|
89
|
+
--policy "$HOME/.larkmate/api-policy.json"
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
通过 Unix socket 连接 `/events`,同样在请求头提供 key。以下示例读取服务授权范围内的事件:
|
|
93
|
+
|
|
94
|
+
```sh
|
|
95
|
+
export LARKMATE_API_KEY_FILE="$HOME/.larkmate/keys/agent-a.key"
|
|
96
|
+
node --input-type=module <<'JS'
|
|
97
|
+
import http from 'node:http';
|
|
98
|
+
import { readFile } from 'node:fs/promises';
|
|
99
|
+
const key = (await readFile(process.env.LARKMATE_API_KEY_FILE, 'utf8')).trim();
|
|
100
|
+
const request = http.get({
|
|
101
|
+
socketPath: `${process.env.HOME}/.larkmate/events.sock`,
|
|
102
|
+
path: '/events',
|
|
103
|
+
headers: { 'x-api-key': key },
|
|
104
|
+
}, response => response.pipe(process.stdout));
|
|
105
|
+
request.on('error', console.error);
|
|
106
|
+
JS
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
订阅时还可传过滤条件,详见[消息监听指南](message-listening.md)。默认 socket 权限为 `0600`;需要由其他系统用户连接时,可在已配置 key 策略的前提下设置 `--socket-mode 0660`,由部署方安排目录、socket 所属组及 key 文件的访问权限。未指定 `--policy` 时,消息服务只依靠 socket 文件权限控制访问。
|
package/package.json
CHANGED
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -15,6 +15,7 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
|
|
|
15
15
|
|
|
16
16
|
- 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
|
|
17
17
|
- 全局或按会话监听、本地事件服务及脚本触发规则: [消息监听](references/listen.md)。
|
|
18
|
+
- 配置 API 服务、API key 及受限订阅权限: [API 服务与授权](https://github.com/NWYLZW/larkmate/blob/main/docs/api-service.md)。
|
|
18
19
|
- 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
|
|
19
20
|
- 查询和管理飞书任务、任务视图及成员: [飞书任务](references/tasks.md)。
|
|
20
21
|
- 查询和管理日历、日程及邀请: [日历与日程](references/calendar.md)。
|
|
@@ -2,7 +2,9 @@
|
|
|
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
|
|
5
|
+
服务订阅支持会话及发送人的 ID、名称和正则,以及消息类型、正文包含/排除、正文正则和排除本人。相同维度的 ID、名称和正则是“或”,不同维度是“且”。大量条件或 `anyOf`、`allOf`、`not` 组合通过 `POST /events` JSON 传入;规则模式支持同样的条件。正则使用 RE2 语法,不支持部分 JavaScript 正则特性。名称解析失败且结果无法确定时会发出 `name_unavailable` 缺口,不猜测匹配;同名对象都会匹配,需要精确区分时使用 ID。
|
|
6
|
+
|
|
7
|
+
通过 `listen-service --policy <绝对路径>` 为每个 API key 限定会话、发送人和类型;订阅过滤条件只能缩小授权范围。未配置策略时依靠 socket 文件权限控制访问。授权配置及订阅示例见 [API 服务与授权](https://github.com/NWYLZW/larkmate/blob/main/docs/api-service.md)。限制范围内的 `gap` 会传递;无法定位会话的全局缺口只包含通用原因。
|
|
6
8
|
|
|
7
9
|
`listen-run` 的规则可省略 `chatIds` 以匹配全部会话,也可按会话、发送人、类型、文本和自定义过滤脚本筛选。过滤脚本和目标脚本通过标准输入接收消息 JSON,不通过 shell 传递消息。`excludeSelf: true` 可防止处理账号自身发出的消息。只有用户明确要求配置触发行为时才创建规则或启动脚本,不根据收到的消息自行扩大脚本权限。
|
|
8
10
|
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { open, writeFile } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute } from 'node:path';
|
|
5
|
+
import { FeishuError, requireInt64Id } from './errors.js';
|
|
6
|
+
import { parsePolicy } from './agent-broker.js';
|
|
7
|
+
|
|
8
|
+
const object=x=>x!==null&&typeof x==='object'&&!Array.isArray(x);
|
|
9
|
+
const only=(x,keys)=>object(x)&&Object.keys(x).every(k=>keys.includes(k));
|
|
10
|
+
const invalid=()=>{throw new FeishuError('ACCESS_POLICY_INVALID','Invalid API key access policy.');};
|
|
11
|
+
const ids=(value)=>{if(!Array.isArray(value)||!value.length)invalid();for(const id of value)try{requireInt64Id(id,'ID')}catch{invalid()}return [...new Set(value)];};
|
|
12
|
+
function eventGrant(raw) {
|
|
13
|
+
if(!only(raw,['allChats','chatIds','senderIds','types']))invalid();
|
|
14
|
+
if(raw.allChats!==undefined&&typeof raw.allChats!=='boolean')invalid();
|
|
15
|
+
if(raw.allChats===true&&raw.chatIds!==undefined)invalid();
|
|
16
|
+
if(raw.allChats!==true&&raw.chatIds===undefined)invalid();
|
|
17
|
+
const chatIds=raw.allChats===true?null:ids(raw.chatIds),senderIds=raw.senderIds===undefined?null:ids(raw.senderIds);
|
|
18
|
+
let types=null;if(raw.types!==undefined){if(!Array.isArray(raw.types)||!raw.types.length||raw.types.some(x=>!Number.isInteger(x)||x<0||x>2147483647))invalid();types=[...new Set(raw.types)];}
|
|
19
|
+
return Object.freeze({chatIds:chatIds&&new Set(chatIds),senderIds:senderIds&&new Set(senderIds),types:types&&new Set(types)});
|
|
20
|
+
}
|
|
21
|
+
export function parseAccessPolicy(raw) {
|
|
22
|
+
if(!only(raw,['version','keys'])||raw.version!==1||!Array.isArray(raw.keys))invalid();
|
|
23
|
+
const idsSeen=new Set(),hashes=new Set(),keys=[];
|
|
24
|
+
for(const entry of raw.keys){
|
|
25
|
+
if(!only(entry,['name','sha256','api','events'])||typeof entry.name!=='string'||!entry.name.trim()||entry.name.length>100||idsSeen.has(entry.name)||typeof entry.sha256!=='string'||!/^[a-f0-9]{64}$/.test(entry.sha256)||hashes.has(entry.sha256))invalid();
|
|
26
|
+
if(entry.api===undefined&&entry.events===undefined)invalid();
|
|
27
|
+
let api=null;if(entry.api!==undefined){try{api=parsePolicy(entry.api)}catch{invalid()}}
|
|
28
|
+
let events=null;if(entry.events!==undefined){if(!Array.isArray(entry.events)||!entry.events.length)invalid();events=entry.events.map(eventGrant)}
|
|
29
|
+
idsSeen.add(entry.name);hashes.add(entry.sha256);keys.push(Object.freeze({name:entry.name,sha256:entry.sha256,api,events}));
|
|
30
|
+
}
|
|
31
|
+
return Object.freeze({keys:Object.freeze(keys)});
|
|
32
|
+
}
|
|
33
|
+
export async function loadAccessPolicy(path) {
|
|
34
|
+
if(typeof path!=='string'||!isAbsolute(path))invalid();let file;
|
|
35
|
+
try{file=await open(path,constants.O_RDONLY|constants.O_NOFOLLOW);const st=await file.stat();if(!st.isFile()||![0,process.getuid?.()].includes(st.uid)||(st.mode&0o022))throw new Error();return parseAccessPolicy(JSON.parse(await file.readFile('utf8')))}
|
|
36
|
+
catch(error){if(error instanceof FeishuError)throw error;throw new FeishuError('ACCESS_POLICY_UNAVAILABLE','Cannot read the protected API key access policy.');}finally{await file?.close()}
|
|
37
|
+
}
|
|
38
|
+
export async function createApiKey(path) {
|
|
39
|
+
if(typeof path!=='string'||!isAbsolute(path))throw new FeishuError('INVALID_ARGUMENT','The API key output path must be absolute.');
|
|
40
|
+
const key=randomBytes(32).toString('base64url');
|
|
41
|
+
try{await writeFile(path,`${key}\n`,{mode:0o600,flag:'wx'})}catch(error){throw new FeishuError('API_KEY_WRITE_FAILED',error.code==='EEXIST'?'Key file already exists.':'Cannot create the key file.')}
|
|
42
|
+
return {output:path,sha256:createHash('sha256').update(key).digest('hex')};
|
|
43
|
+
}
|
|
44
|
+
export function requestKey(req) {
|
|
45
|
+
const auth=[],api=[];for(let i=0;i<req.rawHeaders.length;i+=2){const name=req.rawHeaders[i].toLowerCase();if(name==='authorization')auth.push(req.rawHeaders[i+1]);if(name==='x-api-key')api.push(req.rawHeaders[i+1]);}
|
|
46
|
+
if(auth.length+api.length!==1)throw new FeishuError('API_KEY_INVALID','A valid API key is required.');
|
|
47
|
+
const token=api.length?api[0]:/^Bearer ([\x21-\x7e]+)$/i.exec(auth[0]||'')?.[1];
|
|
48
|
+
if(typeof token!=='string'||token.length<16||token.length>512||!/^[\x21-\x7e]+$/.test(token))throw new FeishuError('API_KEY_INVALID','A valid API key is required.');
|
|
49
|
+
return token;
|
|
50
|
+
}
|
|
51
|
+
export function lookupAccessKey(policy, tokenOrHash, {hashed=false}={}) {
|
|
52
|
+
const digest=hashed?tokenOrHash:createHash('sha256').update(tokenOrHash).digest('hex');
|
|
53
|
+
if(typeof digest!=='string'||!/^[a-f0-9]{64}$/.test(digest))return null;
|
|
54
|
+
const input=Buffer.from(digest,'hex');let match=null;
|
|
55
|
+
for(const key of policy.keys)if(timingSafeEqual(input,Buffer.from(key.sha256,'hex')))match=key;
|
|
56
|
+
return match;
|
|
57
|
+
}
|
|
58
|
+
export function eventAllowed(grants,event) {
|
|
59
|
+
if(!grants||event?.kind!=='message'||typeof event.chatId!=='string')return false;
|
|
60
|
+
return grants.some(g=>(!g.chatIds||g.chatIds.has(event.chatId))&&(!g.senderIds||g.senderIds.has(event.senderId))&&(!g.types||g.types.has(event.type)));
|
|
61
|
+
}
|
|
62
|
+
export function chatAllowed(grants,chatId) {return !!grants?.some(g=>!g.chatIds||g.chatIds.has(chatId));}
|
package/src/agent-broker.js
CHANGED
|
@@ -75,6 +75,9 @@ export function brokerCommands() {
|
|
|
75
75
|
: ['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) ? 'global-and-all-chats'
|
|
76
76
|
: scope === 'minute' ? 'minute' : 'chat', mutating: writes.has(command) }));
|
|
77
77
|
}
|
|
78
|
+
export function apiCommands() {
|
|
79
|
+
return brokerCommands().map(item=>({ ...item, service:routes[item.command][0], method:routes[item.command][1] }));
|
|
80
|
+
}
|
|
78
81
|
|
|
79
82
|
const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
80
83
|
const only = (value, keys) => object(value) && Object.keys(value).every(k => keys.includes(k));
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import http from 'node:http';
|
|
2
|
+
import https from 'node:https';
|
|
3
|
+
import { isIP } from 'node:net';
|
|
4
|
+
import { constants } from 'node:fs';
|
|
5
|
+
import { open, readFile } from 'node:fs/promises';
|
|
6
|
+
import { isAbsolute } from 'node:path';
|
|
7
|
+
import { apiCommands, createBrokerHandler } from './agent-broker.js';
|
|
8
|
+
import { loadAccessPolicy, lookupAccessKey, requestKey } from './access-policy.js';
|
|
9
|
+
import { FeishuError } from './errors.js';
|
|
10
|
+
|
|
11
|
+
async function tlsOptions(certPath,keyPath) {
|
|
12
|
+
if(!isAbsolute(certPath||'')||!isAbsolute(keyPath||''))throw new FeishuError('TLS_CONFIG_INVALID','Use absolute paths for both TLS certificate and key.');
|
|
13
|
+
let keyFile;
|
|
14
|
+
try{keyFile=await open(keyPath,constants.O_RDONLY|constants.O_NOFOLLOW);const st=await keyFile.stat();if(!st.isFile()||![0,process.getuid?.()].includes(st.uid)||(st.mode&0o077))throw new Error();
|
|
15
|
+
const [key,cert]=await Promise.all([keyFile.readFile(),readFile(certPath)]);return {key,cert};
|
|
16
|
+
}catch{throw new FeishuError('TLS_CONFIG_INVALID','Cannot read the protected TLS key and certificate.');}finally{await keyFile?.close()}
|
|
17
|
+
}
|
|
18
|
+
export async function startApiService({host='127.0.0.1',port=0,policyPath,getServices,tlsCert,tlsKey}={}) {
|
|
19
|
+
if((host!=='localhost'&&!isIP(host))||!Number.isInteger(port)||port<0||port>65535||typeof getServices!=='function')throw new FeishuError('INVALID_ARGUMENT','Invalid API service address.');
|
|
20
|
+
if(!!tlsCert!==!!tlsKey)throw new FeishuError('TLS_CONFIG_INVALID','Specify both TLS certificate and key.');
|
|
21
|
+
const loopback=host==='localhost'||host==='127.0.0.1'||host==='::1';
|
|
22
|
+
if(!loopback&&!tlsCert)throw new FeishuError('TLS_REQUIRED','TLS is required for non-loopback API addresses.');
|
|
23
|
+
await loadAccessPolicy(policyPath);
|
|
24
|
+
const tls=tlsCert?await tlsOptions(tlsCert,tlsKey):null;let transfers=0;
|
|
25
|
+
const handler=async(req,res)=>{
|
|
26
|
+
const answer=(status,code,message)=>{if(!res.headersSent)res.writeHead(status,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify({ok:false,error:{code,message}}));};
|
|
27
|
+
let key,token;
|
|
28
|
+
try{token=requestKey(req);key=lookupAccessKey(await loadAccessPolicy(policyPath),token);if(!key)throw new FeishuError('API_KEY_INVALID','A valid API key is required.');}
|
|
29
|
+
catch(error){if(error.code==='API_KEY_INVALID')return answer(401,'API_KEY_INVALID','A valid API key is required.');return answer(503,'ACCESS_POLICY_UNAVAILABLE','The API key access policy is unavailable.');}
|
|
30
|
+
if(!key.api)return answer(403,'POLICY_DENIED','This API key cannot call API operations.');
|
|
31
|
+
if(req.method==='GET'&&req.url==='/v1/commands'){
|
|
32
|
+
res.writeHead(200,{'content-type':'application/json','cache-control':'no-store'});
|
|
33
|
+
res.end(JSON.stringify({ok:true,items:apiCommands().filter(item=>key.api.allow.includes(item.command))}));return;
|
|
34
|
+
}
|
|
35
|
+
if(req.url==='/v1/file'&&transfers>=2)return answer(429,'API_BUSY','Too many file transfers.');
|
|
36
|
+
const file=req.url==='/v1/file';if(file)transfers++;
|
|
37
|
+
try{req.headers.authorization=`Bearer ${token}`;await createBrokerHandler({policy:key.api,token,getServices})(req,res);}
|
|
38
|
+
catch{if(!res.headersSent)answer(500,'API_ERROR','The API request failed.');else res.destroy();}
|
|
39
|
+
finally{if(file)transfers--;}
|
|
40
|
+
};
|
|
41
|
+
const server=tls?https.createServer(tls,handler):http.createServer(handler);
|
|
42
|
+
try{await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(port,host,resolve)})}catch{throw new FeishuError('API_LISTEN_FAILED','Cannot start the API service.');}
|
|
43
|
+
const address=server.address();
|
|
44
|
+
return {host,port:address.port,tls:!!tls,async close(){server.closeAllConnections?.();await new Promise(resolve=>server.close(resolve));}};
|
|
45
|
+
}
|
package/src/listen-modes.js
CHANGED
|
@@ -6,6 +6,7 @@ import { open, lstat, realpath, chmod, unlink } from 'node:fs/promises';
|
|
|
6
6
|
import { dirname, isAbsolute, join } from 'node:path';
|
|
7
7
|
import { FeishuError } from './errors.js';
|
|
8
8
|
import { compileFilter, filterMatches, filterNeeds, queryFilter } from './listen-filter.js';
|
|
9
|
+
import { loadAccessPolicy, lookupAccessKey, requestKey, eventAllowed, chatAllowed } from './access-policy.js';
|
|
9
10
|
|
|
10
11
|
const obj = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
|
11
12
|
const only = (x, fields) => obj(x) && Object.keys(x).every(k => fields.includes(k));
|
|
@@ -88,8 +89,10 @@ export function createRuleOutput({rules,selfId,resolveNames,log=process.stderr})
|
|
|
88
89
|
}
|
|
89
90
|
|
|
90
91
|
// Exposes the configured event stream, protected by the socket and parent directory permissions.
|
|
91
|
-
export async function startListenService(socketPath, {selfId,resolveNames}={}) {
|
|
92
|
+
export async function startListenService(socketPath, {selfId,resolveNames,policyPath,socketMode=0o600}={}) {
|
|
92
93
|
if(typeof socketPath!=='string'||!isAbsolute(socketPath)||socketPath.endsWith('/'))throw new FeishuError('INVALID_ARGUMENT','Use an absolute socket path.');
|
|
94
|
+
if(![0o600,0o660].includes(socketMode)||(socketMode!==0o600&&!policyPath))throw new FeishuError('INVALID_ARGUMENT','A shared socket requires an API key policy.');
|
|
95
|
+
if(policyPath)await loadAccessPolicy(policyPath);
|
|
93
96
|
let parent;try{parent=await realpath(dirname(socketPath));}catch{throw new FeishuError('LISTEN_SOCKET_INVALID','The socket directory must exist.');}
|
|
94
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.');
|
|
95
98
|
const path=join(parent,socketPath.slice(socketPath.lastIndexOf('/')+1));
|
|
@@ -97,6 +100,11 @@ export async function startListenService(socketPath, {selfId,resolveNames}={}) {
|
|
|
97
100
|
const clients=new Map();
|
|
98
101
|
const server=http.createServer(async(req,res)=>{
|
|
99
102
|
if(!['GET','POST'].includes(req.method)){res.writeHead(404);res.end();return;}
|
|
103
|
+
let keyHash=null;
|
|
104
|
+
if(policyPath){
|
|
105
|
+
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){res.writeHead(403);res.end();return;}keyHash=key.sha256;}
|
|
106
|
+
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
|
+
}
|
|
100
108
|
let filter;
|
|
101
109
|
try {
|
|
102
110
|
if(req.method==='GET') filter=parseSubscriptionFilter(req.url,selfId);
|
|
@@ -112,30 +120,41 @@ export async function startListenService(socketPath, {selfId,resolveNames}={}) {
|
|
|
112
120
|
if((needs.chat||needs.sender)&&typeof resolveNames!=='function')throw new FeishuError('INVALID_FILTER','Name lookup is unavailable.');
|
|
113
121
|
}
|
|
114
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||'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));
|
|
123
|
+
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),keyHash});res.on('close',()=>clients.delete(res));
|
|
116
124
|
});
|
|
117
125
|
const oldMask=process.umask(0o077);
|
|
118
126
|
try { await new Promise((resolve,reject)=>{server.once('error',reject);server.listen(path,resolve)}); } finally { process.umask(oldMask); }
|
|
119
|
-
await chmod(path,
|
|
127
|
+
await chmod(path,socketMode);const inode=(await lstat(path)).ino;
|
|
120
128
|
const output=new Writable({write(chunk,_encoding,callback){(async()=>{
|
|
121
129
|
let event;try{event=JSON.parse(chunk.toString())}catch{throw new FeishuError('INVALID_RESPONSE','Invalid listener event.')}
|
|
122
|
-
const
|
|
130
|
+
let policy=null;if(policyPath){try{policy=await loadAccessPolicy(policyPath)}catch{for(const client of clients.keys())client.destroy();return;}}
|
|
131
|
+
const snapshot=[];
|
|
132
|
+
for(const [client,entry] of clients){
|
|
133
|
+
if(policyPath){const key=lookupAccessKey(policy,entry.keyHash,{hashed:true});if(!key?.events){client.destroy();continue;}
|
|
134
|
+
if(event.kind==='message'&&!eventAllowed(key.events,event))continue;
|
|
135
|
+
if(event.kind==='gap'&&event.chatId&&!chatAllowed(key.events,event.chatId))continue;
|
|
136
|
+
if(!['message','gap'].includes(event.kind))continue;
|
|
137
|
+
}
|
|
138
|
+
snapshot.push([client,entry]);
|
|
139
|
+
}
|
|
123
140
|
const deliver=(client,filter,value)=>{
|
|
124
141
|
if(!clients.has(client))return;
|
|
125
142
|
if(client.writableLength>1024*1024){client.destroy();return;}
|
|
126
143
|
const matched=subscriptionMatches(filter,value,selfId);
|
|
127
144
|
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`);
|
|
145
|
+
else if(matched)client.write(`${JSON.stringify(policyPath&&value.kind==='gap'?{kind:'gap',reason:value.reason}:value)}\n`);
|
|
129
146
|
};
|
|
130
147
|
// Resolve names only when an existing subscriber cannot decide from IDs and other fields.
|
|
131
148
|
const deferred=[];
|
|
132
|
-
for(const [client,
|
|
133
|
-
|
|
149
|
+
for(const [client,entry] of snapshot){
|
|
150
|
+
const {filter,needs:n}=entry;
|
|
151
|
+
if(event.kind==='message'&&(n.chat||n.sender)&&subscriptionMatches(filter,event,selfId)===null)deferred.push([client,entry]);
|
|
134
152
|
else deliver(client,filter,event);
|
|
135
153
|
}
|
|
136
154
|
const needs={chat:false,sender:false};for(const [, {needs:n}] of deferred){needs.chat ||= n.chat;needs.sender ||= n.sender;}
|
|
137
155
|
if(needs.chat||needs.sender){let names={};try{names=await resolveNames?.(event,needs)||{}}catch{}event={...event,...names};}
|
|
138
|
-
for(const [client
|
|
156
|
+
if(policyPath&&deferred.length){try{policy=await loadAccessPolicy(policyPath)}catch{for(const [client] of deferred)client.destroy();return;}}
|
|
157
|
+
for(const [client,{filter,keyHash}] of deferred){if(policyPath){const key=lookupAccessKey(policy,keyHash,{hashed:true});if(!key?.events){client.destroy();continue;}if(!eventAllowed(key.events,event))continue;}deliver(client,filter,event);}
|
|
139
158
|
})().then(()=>callback(),callback)}});
|
|
140
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;}}};
|
|
141
160
|
}
|