larkmate 0.1.8 → 0.1.10

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
@@ -66,4 +66,4 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
66
66
 
67
67
  具体用法和能力边界见 [LarkMate Skill](skills/larkmate/SKILL.md)。
68
68
 
69
- 如需将部分能力交给其他 Agent,可使用 [Agent 权限委托](docs/agent-broker.md)。
69
+ 如需将部分能力交给其他 Agent,可使用 [系统用户权限委托](docs/os-delegation.md)或 [本地代理](docs/agent-broker.md)。
package/bin/larkmate.js CHANGED
@@ -9,12 +9,15 @@ import { writeFile } from 'node:fs/promises';
9
9
  import { FeishuError } from '../src/errors.js';
10
10
  import { exportMessages } from '../src/export-messages.js';
11
11
  import { brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
12
+ import { callOsDelegate, osDelegateProxy } from '../src/os-delegate-client.js';
12
13
 
13
14
  const program = new Command();
14
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.8');
15
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.10');
15
16
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
16
17
  program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
17
18
  program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
19
+ program.option('--delegate-owner <user>', 'execute through a protected OS-user delegate (or LARKMATE_DELEGATE_OWNER)');
20
+ program.option('--delegate-launcher <path>', 'protected delegate launcher (or LARKMATE_DELEGATE_LAUNCHER)');
18
21
  program.exitOverride();
19
22
  let activeCommand;
20
23
  program.hook('preAction', (_program, command) => { activeCommand = command.name(); });
@@ -24,7 +27,16 @@ const output = value => process.stdout.write(`${JSON.stringify({ ok: true, ...va
24
27
 
25
28
  function configuredBroker() { return program.opts().broker || process.env.LARKMATE_BROKER || null; }
26
29
  function configuredBrokerToken() { return program.opts().brokerTokenFile || process.env.LARKMATE_BROKER_TOKEN_FILE || null; }
30
+ function configuredDelegate() {
31
+ const owner = program.opts().delegateOwner || process.env.LARKMATE_DELEGATE_OWNER;
32
+ const launcher = program.opts().delegateLauncher || process.env.LARKMATE_DELEGATE_LAUNCHER;
33
+ if (!!owner !== !!launcher) throw new FeishuError('DELEGATE_CONFIG_INVALID', 'Both delegate owner and launcher are required.');
34
+ if (owner && (configuredBroker() || configuredBrokerToken() || program.opts().credentialsFile)) throw new FeishuError('DELEGATE_CONFIG_INVALID', 'Do not combine OS delegation with broker or credentials options.');
35
+ return owner ? { owner, launcher } : null;
36
+ }
27
37
  function proxy(service) {
38
+ const delegate = configuredDelegate();
39
+ if (delegate) return osDelegateProxy(delegate.owner, delegate.launcher, service, () => activeCommand);
28
40
  const path = configuredBroker();
29
41
  if (!path && configuredBrokerToken()) throw new FeishuError('BROKER_CONFIGURATION_INVALID', 'A broker token file was configured without a broker socket.');
30
42
  if (path && program.opts().credentialsFile) throw new FeishuError('INVALID_ARGUMENT', 'A broker client cannot select a credentials file.');
@@ -53,6 +65,16 @@ async function minutes() {
53
65
  program.command('broker-commands').description('List operations supported by the agent broker and their scopes.')
54
66
  .action(() => output({ items: brokerCommands() }));
55
67
 
68
+ program.command('delegate-commands').description('List operations supported by OS-user delegation and their scopes.')
69
+ .action(() => output({ items: brokerCommands() }));
70
+
71
+ program.command('delegate-info').description('Show the current OS-user delegation permissions.')
72
+ .action(async () => {
73
+ const delegate = configuredDelegate();
74
+ if (!delegate) throw new FeishuError('DELEGATE_CONFIG_INVALID', 'Configure the delegate owner and launcher.');
75
+ output(await callOsDelegate({ ...delegate, request: { command: 'delegate-info' } }));
76
+ });
77
+
56
78
  program.command('broker-token-create').description('Create a private token for one agent broker.')
57
79
  .requiredOption('--output <path>', 'absolute path for a new token file')
58
80
  .action(async o => { await createBrokerToken(o.output); output({ status: 'created', output: o.output }); });
@@ -62,7 +84,7 @@ program.command('broker-serve').description('Start a restricted local agent brok
62
84
  .requiredOption('--policy <path>', 'absolute JSON policy path')
63
85
  .requiredOption('--token-file <path>', 'absolute owner-controlled agent token file')
64
86
  .action(async o => {
65
- if (configuredBroker()) throw new FeishuError('INVALID_ARGUMENT', 'Start the broker directly, without --broker or LARKMATE_BROKER.');
87
+ if (configuredBroker() || configuredDelegate()) throw new FeishuError('INVALID_ARGUMENT', 'Start the broker directly, without a broker or OS delegate.');
66
88
  const policy = await loadPolicy(o.policy);
67
89
  const token = await loadBrokerToken(o.tokenFile, { owner: true });
68
90
  let promise;
@@ -256,8 +278,9 @@ program.command('download-file').description('Download a message file or image t
256
278
  .requiredOption('--chat <id>', 'numeric chat ID')
257
279
  .requiredOption('--message <id>', 'numeric message ID')
258
280
  .requiredOption('--key <key>', 'file or image key from history')
281
+ .option('--position <number>', 'message position from history (required by a broker or OS delegate)')
259
282
  .requiredOption('--output <path>', 'new local output file')
260
- .action(async o => output(await (await client()).downloadFile({ chatId: o.chat, messageId: o.message, key: o.key, output: o.output })));
283
+ .action(async o => output(await (await client()).downloadFile({ chatId: o.chat, messageId: o.message, key: o.key, output: o.output, ...(o.position != null ? { position: Number(o.position) } : {}) })));
261
284
  program.command('message-link').description('Get the native link to a message.')
262
285
  .requiredOption('--chat <id>', 'numeric chat ID')
263
286
  .requiredOption('--message <id>', 'numeric message ID')
@@ -0,0 +1,28 @@
1
+ // This helper is launched once by a protected, environment-clearing sudo wrapper.
2
+ // The policy location is fixed relative to this protected installation, never to caller input.
3
+ import { fileURLToPath } from 'node:url';
4
+ import { loadDelegateConfig, serveOne } from '../src/os-delegate.js';
5
+ import { loadCookie } from '../src/credentials.js';
6
+ import { Gateway } from '../src/gateway.js';
7
+ import { LarkMateClient } from '../src/client.js';
8
+ import { SessionControls } from '../src/session-controls.js';
9
+ import { Minutes } from '../src/minutes.js';
10
+ import { FeishuError } from '../src/errors.js';
11
+
12
+ try {
13
+ const caller = process.env.SUDO_UID, owner = process.getuid?.();
14
+ if (!Number.isInteger(owner) || typeof caller !== 'string' || !/^[1-9]\d*$/.test(caller) || !Number.isSafeInteger(Number(caller)) || Number(caller) === owner) throw new FeishuError('POLICY_DENIED', 'The operating-system caller identity is unavailable.');
15
+ const config = await loadDelegateConfig(fileURLToPath(new URL('../delegate-policy.json', import.meta.url)), owner);
16
+ const profile = config.users[caller];
17
+ if (!profile) throw new FeishuError('POLICY_DENIED', 'This operating-system user has no delegation profile.');
18
+ let services;
19
+ const getServices = () => services ||= (async () => {
20
+ const gateway = new Gateway({ cookie: await loadCookie({ file: config.credentialsFile }) });
21
+ return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway) };
22
+ })();
23
+ await serveOne({ input: process.stdin, output: process.stdout, uid: caller, profile, getServices });
24
+ } catch (error) {
25
+ const detail = error instanceof FeishuError ? { code: error.code, message: error.message } : { code: 'DELEGATE_ERROR', message: 'Cannot start the delegated operation.' };
26
+ process.stdout.write(JSON.stringify({ ok: false, error: detail }) + '\n');
27
+ process.exitCode = 1;
28
+ }
@@ -41,6 +41,7 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
41
41
  | `allowAllChats` | 设为 `true` 时允许访问任意会话,默认为 `false`。 |
42
42
  | `allowAllMinutes` | 设为 `true` 时允许访问任意妙记,默认为 `false`。 |
43
43
  | `allowGlobal` | 设为 `true` 时允许在 `allow` 中额外授权账号级操作,默认为 `false`。 |
44
+ | `maxFileBytes` | 单个文件传输的字节上限,范围为 1 至 104857600,默认 104857600(100 MiB)。图片仍以 10 MiB 为上限。 |
44
45
 
45
46
  未知字段、未知命令、重复授权、错误类型以及 `*` 都会导致代理拒绝启动。`allowAllChats`、`allowAllMinutes` 和 `allowGlobal` 不会自行开放命令;对应命令仍须出现在 `allow` 中。
46
47
 
@@ -52,7 +53,11 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
52
53
 
53
54
  `status` 以及用于搜索用户、机器人、群聊的 `search` 需要开启 `allowGlobal`。跨会话搜索、会话及收藏列表、标签管理,以及仅凭消息 ID 操作的链接、编辑、撤回、转发、收藏和表情命令,除须在 `allow` 中各自授权外,还必须同时开启 `allowGlobal` 和 `allowAllChats`——这是因为代理无法仅凭消息 ID 判断其是否属于受限会话。群创建、邀请成员和机器人保护设置同样需要同时开启这两个开关。开启这些权限会扩大 Agent 可访问的信息范围或可执行的操作范围,请按需选择。
54
55
 
55
- 代理不提供 `send-file`、`send-image` 和 `download-file`,以免调用方驱使持有 Cookie 的进程读写任意本地路径。`messages-export` 和 `minutes-export` 的输出文件则由 Agent 自己的进程创建,受 Agent 自身的文件权限约束。
56
+ `send-file`、`send-image` 与 `download-file` 均可单独加入 `allow` 列表,并受 `chatIds` 约束。发送时,由 Agent 进程读取本地文件并传输内容;下载时,由 Agent 进程创建输出文件。代理不接受 Agent 指定的代理端本地路径,而是在私有临时目录中处理中转文件,并在正常结束或失败时将其删除。若进程异常终止,可能会遗留临时文件,因此部署方应保护并按需清理代理账户的临时目录。
57
+
58
+ 如需限制 Agent 可访问的本地目录,部署方应通过配置 Agent 的系统账户或容器权限来实现。策略文件中的会话与大小限制不会约束 Agent 自身的文件系统,也无法阻止其向代理发送已读取的数据。请仅向 Agent 挂载或开放其业务所需的目录,禁止其读取 Cookie 及其他敏感文件。
59
+
60
+ 在受限代理模式下执行下载时,须提供 `history` 返回的消息 `position`、消息 ID 与资源键。代理会重新读取该会话的对应位置,仅在三者完全匹配时才执行下载;若无法核对,则会拒绝请求。普通直连模式不要求提供 `--position`。
56
61
 
57
62
  授权导出即意味着授权读取对应内容,调用方仍可通过其他方式保存这些数据。对于仅需查看内容的 Agent,建议优先授予目标会话的只读命令;仅在确需执行修改、发送消息或邀请成员等操作时,再开放相应命令。
58
63
 
@@ -65,6 +70,9 @@ export LARKMATE_BROKER=/absolute/path/run/agent.sock
65
70
  export LARKMATE_BROKER_TOKEN_FILE=/absolute/path/agent.token
66
71
  larkmate broker-info
67
72
  larkmate history --chat "$CHAT_ID" --limit 20
73
+ larkmate send-file --chat "$CHAT_ID" --file /agent/files/report.pdf
74
+ larkmate send-image --chat "$CHAT_ID" --file /agent/files/image.png
75
+ larkmate download-file --chat "$CHAT_ID" --message "$MESSAGE_ID" --key "$RESOURCE_KEY" --position "$POSITION" --output /agent/files/attachment
68
76
  ```
69
77
 
70
78
  也可以通过全局选项 `--broker` 和 `--broker-token-file` 指定路径。`broker-info` 会返回当前连接的权限配置,不会返回 Cookie 或令牌。当 Agent 收到 `POLICY_DENIED`,或导出错误的 `cause` 为 `POLICY_DENIED` 时,应停止该操作并说明权限不足,由所有者决定是否调整策略;不能改用直连模式尝试绕过。
@@ -5,5 +5,6 @@
5
5
  "minuteTokens": [],
6
6
  "allowAllChats": false,
7
7
  "allowAllMinutes": false,
8
- "allowGlobal": false
8
+ "allowGlobal": false,
9
+ "maxFileBytes": 104857600
9
10
  }
@@ -22,9 +22,11 @@
22
22
 
23
23
  ## 登录与使用
24
24
 
25
+ 若环境中已配置 `LARKMATE_DELEGATE_OWNER` 和 `LARKMATE_DELEGATE_LAUNCHER`,请先运行 `larkmate delegate-info`,通过系统用户委托使用 LarkMate,无需读取或配置 Cookie。遇到权限不足时遵循审批结果,不尝试绕过;具体部署见 [系统用户权限委托](https://github.com/NWYLZW/larkmate/blob/main/docs/os-delegation.md)。
26
+
25
27
  若运行环境中已配置 `LARKMATE_BROKER` 和 `LARKMATE_BROKER_TOKEN_FILE`,请先运行 `larkmate broker-info`,通过受限代理使用 LarkMate,无需读取或配置 Cookie。当代理权限不足时,应说明具体情况,由所有者决定是否调整权限;具体部署见 [Agent 权限委托指南](https://github.com/NWYLZW/larkmate/blob/main/docs/agent-broker.md)。
26
28
 
27
- 未使用受限代理时,LarkMate 默认从 `~/.larkmate/credentials.json` 读取 Cookie,也支持 `LARKMATE_HOME`、`LARKMATE_COOKIE` 和 `--credentials-file`。先保留并检查已有登录态,可用 `larkmate status` 验证;不要读取或打印 Cookie 的值到对话、日志或命令参数中。
29
+ 未使用系统用户委托或受限代理时,LarkMate 默认从 `~/.larkmate/credentials.json` 读取 Cookie,也支持 `LARKMATE_HOME`、`LARKMATE_COOKIE` 和 `--credentials-file`。先保留并检查已有登录态,可用 `larkmate status` 验证;不要读取或打印 Cookie 的值到对话、日志或命令参数中。
28
30
 
29
31
  如果没有可用登录态,引导用户在本机安全配置,不要要求用户把 Cookie、密码或验证码发到对话中。配置格式和手动步骤见 [快速安装](https://github.com/NWYLZW/larkmate/blob/main/INSTALL.md)。不能自动完成登录时,如实说明,不声称已经登录。
30
32
 
@@ -0,0 +1,21 @@
1
+ {
2
+ "version": 1,
3
+ "ownerUid": 1000,
4
+ "credentialsFile": "/absolute/owner-only/credentials.json",
5
+ "users": {
6
+ "1001": {
7
+ "policy": {
8
+ "version": 1,
9
+ "allow": ["chat-info", "history"],
10
+ "chatIds": [],
11
+ "minuteTokens": [],
12
+ "allowAllChats": false,
13
+ "allowAllMinutes": false,
14
+ "allowGlobal": false,
15
+ "maxFileBytes": 104857600
16
+ },
17
+ "approvalScript": "/absolute/owner-controlled/approve",
18
+ "approvalTimeoutSeconds": 300
19
+ }
20
+ }
21
+ }
@@ -0,0 +1,65 @@
1
+ # 按系统用户委托 LarkMate
2
+
3
+ 系统用户委托无需常驻服务:Agent 每次通过 `sudo` 启动受保护的执行器,执行器依据调用者的系统 UID 读取对应授权。策略允许的操作直接执行;其余受支持的操作交由该用户配置的审批脚本处理。只有审批脚本明确批准当前请求后,执行器才会执行飞书操作;调用完成后进程退出。原有的[本地代理模式](agent-broker.md)仍可使用。
4
+
5
+ ## 安全边界
6
+
7
+ 部署方须将 Agent 与 Cookie 所有者配置为不同的系统用户,确保 Agent 无法读取 Cookie,也无法修改受保护安装、Node.js 可执行文件及其依赖、启动器、策略文件、审批脚本或这些文件的上级目录,同时禁止 Agent 通过其他 `sudo` 规则以所有者身份运行任意程序。Agent 对其他文件的访问范围由系统账户或容器权限限制;策略文件无法限制 Agent 已有的系统权限。
8
+
9
+ 以下为部署示例,请由系统管理员按实际路径和账户配置;LarkMate 不自动修改系统账户、文件权限或 `sudoers`。若没有满足这些条件,不能仅靠策略文件防止绕过或 Cookie 泄露。
10
+
11
+ ## 策略文件
12
+
13
+ 将 [示例配置](os-delegation.example.json) 复制到受保护安装包根目录的 `delegate-policy.json`。这个位置相对于安装包固定,不接受调用方指定。文件必须是所有者或 root 拥有的普通文件,不得允许组用户或其他用户写入;还应保护上级目录和 ACL。`ownerUid` 填写执行器所有者的 UID,`credentialsFile` 指向仅所有者可读的 Cookie 配置文件;`users` 的键是 Agent 的数字 UID。调用者 UID 未配置时直接拒绝,不进入审批。不能把所有者自身配置为 Agent。
14
+
15
+ 每个用户的 `policy` 与[代理策略](agent-broker.md#配置授权)使用相同字段;只允许 `allow` 和资源范围共同匹配的操作。可通过 `larkmate delegate-commands` 查看可委托的命令及范围。可选的 `approvalScript` 必须是绝对路径、由所有者或 root 拥有的可执行普通文件,且不得允许组用户或其他用户写入;不配置时未授权操作直接拒绝。`approvalTimeoutSeconds` 默认 300 秒,可设为 1 至 600 秒。
16
+
17
+ 文件、图片发送及附件下载可分别授权;上传文件由 Agent 进程读取,下载文件由 Agent 进程写入。执行器不接受 Agent 提供的所有者本地路径。下载时须提供 `history` 返回的 `--position`,执行器会核验会话、消息和资源键。单个文件受 `maxFileBytes` 限制;执行器在所有者私有临时目录中处理中转数据,正常结束或失败时删除,异常退出可能留下临时文件。部署方应保护、按需清理临时目录,并根据实际需要配置系统资源限制。
18
+
19
+ ## 启动器与 sudoers 示例
20
+
21
+ 将 LarkMate 包及依赖安装在 Agent 无法修改的受保护位置,将以下启动器放在同样受保护的位置。示例路径均须替换为实际绝对路径;Node.js 可执行文件和其依赖也不能由 Agent 修改。固定工作目录并清空环境,避免调用者通过环境变量或当前目录影响执行器。
22
+
23
+ ```sh
24
+ #!/bin/sh
25
+ case "${SUDO_UID-}" in ''|*[!0-9]*) exit 1 ;; esac
26
+ cd /opt/larkmate/node_modules/larkmate || exit 1
27
+ umask 077
28
+ exec /usr/bin/env -i \
29
+ SUDO_UID="$SUDO_UID" HOME=/absolute/owner/home PATH=/usr/bin:/bin \
30
+ /absolute/protected/node \
31
+ /opt/larkmate/node_modules/larkmate/bin/os-delegate-helper.js
32
+ ```
33
+
34
+ 例如,以下 sudoers 片段只允许 `agent` 以 `owner` 身份、不带额外参数运行这个启动器。必须先用 `visudo` 验证并由管理员安装,实际规则不能向 Agent 提供任意命令、`SETENV`、保留调用者环境或其他提权通道:
35
+
36
+ ```sudoers
37
+ Cmnd_Alias LARKMATE_DELEGATE = /opt/larkmate/launch ""
38
+ Defaults!LARKMATE_DELEGATE env_reset
39
+ agent ALL=(owner) NOPASSWD: NOSETENV: LARKMATE_DELEGATE
40
+ ```
41
+
42
+ 执行器依赖 `sudo` 设置的 `SUDO_UID` 确定调用者;不要从 Agent 的环境、参数或文件中自行接收该 UID。启动器、策略、Node.js、依赖、审批脚本及上级目录的保护是部署前提,应检查 ACL 和已有的其他 sudo 规则。不要让 Agent 直接使用所有者账号。
43
+
44
+ 在 Agent 环境中设置所有者名称和受保护启动器路径:
45
+
46
+ ```sh
47
+ export LARKMATE_DELEGATE_OWNER=owner
48
+ export LARKMATE_DELEGATE_LAUNCHER=/opt/larkmate/launch
49
+ larkmate delegate-info
50
+ larkmate history --chat "$CHAT_ID" --limit 20
51
+ ```
52
+
53
+ 也可使用 `--delegate-owner` 和 `--delegate-launcher`。不可同时配置本地代理或指定 Cookie 文件。没有预设权限且配置了审批脚本时,调用会等待脚本结果。分页导出可能产生多次独立调用;若这些调用不在预设权限内,每次都会分别请求审批。
54
+
55
+ ## 审批脚本协议
56
+
57
+ 执行器不经 shell 直接启动脚本,通过标准输入发送一行 JSON;脚本通过标准输出返回一行 JSON,其他日志应写入标准错误。输入包含 `version`、随机 `requestId`、`callerUid` 和完整 `request`。发送文件或图片时还包含 `file.name`、`file.size` 和 `file.sha256`;摘要对应已收到的文件内容。脚本运行在所有者身份下,环境仅提供固定的 `PATH`、所有者 `HOME` 和 `LANG`。
58
+
59
+ 脚本应把操作、目标及必要的内容呈现给所有者,可以自行发送卡片并等待确认。只有获得针对该 `requestId` 和对应请求的有效确认后,才以退出码 0 输出:
60
+
61
+ ```json
62
+ {"decision":"allow","requestId":"输入中的 requestId"}
63
+ ```
64
+
65
+ 脚本必须自行验证卡片确认人的身份,确保确认绑定当前请求且不可重放。拒绝、超时、异常、非零退出码、输出过大、格式错误或 `requestId` 不匹配均视为拒绝。一次批准只用于当前调用,不更改策略文件,也不会绕过文件大小上限、请求格式检查或附件归属校验。审批内容可能包含消息正文和文件名,请按数据敏感程度保护脚本、审批渠道和日志。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.8",
3
+ "version": "0.1.10",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
@@ -9,6 +9,8 @@ description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、
9
9
 
10
10
  若运行环境提供 `LARKMATE_BROKER` 和 `LARKMATE_BROKER_TOKEN_FILE`,使用受限代理并先执行 `larkmate broker-info`。错误码或导出错误的 `cause` 为 `POLICY_DENIED` 时,不尝试绕过或读取 Cookie;由代理所有者调整授权。账号隔离、策略和可用命令见 [Agent 权限委托指南](https://github.com/NWYLZW/larkmate/blob/main/docs/agent-broker.md)。
11
11
 
12
+ 若环境提供 `LARKMATE_DELEGATE_OWNER` 和 `LARKMATE_DELEGATE_LAUNCHER`,使用系统用户委托并先执行 `larkmate delegate-info`。权限未预先开放时调用可能等待所有者审批;拒绝或失败时不尝试绕过。不要同时配置委托和本地代理,部署见 [系统用户权限委托](https://github.com/NWYLZW/larkmate/blob/main/docs/os-delegation.md)。
13
+
12
14
  根据任务读取所需参考:
13
15
 
14
16
  - 查找会话、搜索与导出消息、获取链接、下载资源,以及管理会话状态和标签: [会话与消息](references/chats.md)。
@@ -20,6 +20,8 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
20
20
 
21
21
  `search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
22
22
 
23
+ 使用受限代理或系统用户委托下载时,还须传入目标消息的 `--position`,取值为 `history` 返回的 `position`;执行器会核验消息和资源是否属于授权会话。文件大小受策略的 `maxFileBytes` 限制。
24
+
23
25
  `messages-export` 会自动向前分页至会话最早位置,并按从新到旧的顺序输出 Markdown 或 JSON Lines。该命令支持 `--sender`、`--query`,以及以 Unix 秒为单位的 `--after` 和 `--before`;筛选范围仅限指定会话。可通过 `--max-pages` 限制页数,导出结束时需检查 `reachedBeginning`、`nextStart`、`nextLimit`、`omittedPositions` 和 `missingTimestamps`。
24
26
 
25
27
  输出文件不会覆盖已有文件;若导出中断,文件中不会包含完成统计,须视为不完整。继续导出时,请使用新的输出文件,并将 `nextStart` 和 `nextLimit` 分别传给 `--start` 和 `--limit`,以避免分页重叠。
@@ -19,6 +19,8 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
19
19
 
20
20
  文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
21
21
 
22
+ 使用受限代理或系统用户委托发送文件或图片时,需要相应命令和目标会话的授权;文件由 Agent 自身读取,且还受策略 `maxFileBytes` 限制。
23
+
22
24
  图片支持 PNG、JPEG、GIF 和 WebP 格式,大小不超过 10 MiB。`message-edit` 会以纯文本替换原消息内容,无法保留原有的富文本格式或提及。`--emoji` 需传入飞书表情名称,默认值为 `DarkThumbsup`。`favorite-add` 成功确认时会返回收藏 ID,供 `favorite-remove` 使用;该收藏 ID 也可从 `favorites` 首页获取。发送、编辑、撤回、转发、表情及收藏操作均须遵循用户的明确意图。
23
25
 
24
26
  回复已有回复时,需同时传入 `--reply-root`,其值取目标消息的 `rootId`;若目标消息是回复链的第一条,则只需传入 `--reply-to`。`history` 会返回每条消息的 `rootId` 和 `parentId`。
@@ -5,6 +5,7 @@ import { chmod, lstat, open, realpath, unlink, writeFile } from 'node:fs/promise
5
5
  import { dirname, isAbsolute, join } from 'node:path';
6
6
  import { FeishuError } from './errors.js';
7
7
  import { minuteToken } from './minutes.js';
8
+ import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.js';
8
9
 
9
10
  // The socket policy is enforced in this process, never by the calling agent.
10
11
  // An explicit mapping prevents callers from reaching arbitrary object methods.
@@ -37,11 +38,13 @@ const routes = {
37
38
  read: ['controls', 'setRead', 'chatArg'], unread: ['controls', 'setUnread', 'chatArg'],
38
39
  'minutes-list': ['minutes', 'list', 'allMinutes'], 'minutes-export': ['minutes', 'transcript', 'minute'],
39
40
  'minutes-access-info': ['minutes', 'accessInfo', 'minute'], 'minutes-request-access': ['minutes', 'requestAccess', 'minute'],
41
+ 'send-file': ['files', 'upload', 'file'], 'send-image': ['files', 'upload', 'file'],
42
+ 'download-file': ['files', 'download', 'file'],
40
43
  };
41
44
  const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
42
45
  'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
43
46
  'group-update', 'group-dissolve', 'group-bot-protection', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
44
- 'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access']);
47
+ 'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image']);
45
48
 
46
49
  export function brokerCommands() {
47
50
  return Object.entries(routes).map(([command, [, , scope]]) => ({ command,
@@ -57,16 +60,18 @@ const invalidPolicy = () => { throw new FeishuError('POLICY_INVALID', 'The broke
57
60
  const numeric = value => typeof value === 'string' && /^[1-9]\d{0,18}$/.test(value) && BigInt(value) <= 9223372036854775807n;
58
61
 
59
62
  export function parsePolicy(raw) {
60
- if (!only(raw, ['version', 'allow', 'chatIds', 'minuteTokens', 'allowAllChats', 'allowAllMinutes', 'allowGlobal']) || raw.version !== 1 || !Array.isArray(raw.allow)) invalidPolicy();
63
+ if (!only(raw, ['version', 'allow', 'chatIds', 'minuteTokens', 'allowAllChats', 'allowAllMinutes', 'allowGlobal', 'maxFileBytes']) || raw.version !== 1 || !Array.isArray(raw.allow)) invalidPolicy();
61
64
  if (raw.allow.some(x => typeof x !== 'string' || !Object.hasOwn(routes, x)) || new Set(raw.allow).size !== raw.allow.length) invalidPolicy();
62
65
  const chatIds = Object.hasOwn(raw, 'chatIds') ? raw.chatIds : [];
63
66
  const minuteTokens = Object.hasOwn(raw, 'minuteTokens') ? raw.minuteTokens : [];
64
67
  if (!Array.isArray(chatIds) || chatIds.some(x => !numeric(x)) || new Set(chatIds).size !== chatIds.length) invalidPolicy();
65
68
  if (!Array.isArray(minuteTokens) || minuteTokens.some(x => typeof x !== 'string' || !/^[A-Za-z0-9_-]{10,128}$/.test(x)) || new Set(minuteTokens).size !== minuteTokens.length) invalidPolicy();
66
69
  for (const key of ['allowAllChats', 'allowAllMinutes', 'allowGlobal']) if (Object.hasOwn(raw, key) && typeof raw[key] !== 'boolean') invalidPolicy();
70
+ const maxFileBytes = Object.hasOwn(raw, 'maxFileBytes') ? raw.maxFileBytes : 100 * 1024 * 1024;
71
+ if (!Number.isSafeInteger(maxFileBytes) || maxFileBytes < 1 || maxFileBytes > 100 * 1024 * 1024) invalidPolicy();
67
72
  return Object.freeze({ version: 1, allow: Object.freeze([...raw.allow]), chatIds: Object.freeze([...chatIds]),
68
73
  minuteTokens: Object.freeze([...minuteTokens]), allowAllChats: raw.allowAllChats === true,
69
- allowAllMinutes: raw.allowAllMinutes === true, allowGlobal: raw.allowGlobal === true });
74
+ allowAllMinutes: raw.allowAllMinutes === true, allowGlobal: raw.allowGlobal === true, maxFileBytes });
70
75
  }
71
76
 
72
77
  export async function loadPolicy(path) {
@@ -113,6 +118,7 @@ export function authorize(policy, request) {
113
118
  if (scope === 'global' && !policy.allowGlobal) denied();
114
119
  if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
115
120
  if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
121
+ if (scope === 'file' && (args.length !== 1 || !only(args[0], method === 'download' ? ['chatId', 'messageId', 'key', 'position'] : ['chatId']) || !chatAllowed(args[0].chatId))) denied();
116
122
  if (['labelTrue', 'labelFalse'].includes(scope) && (args.length !== 3 || args[2] !== (scope === 'labelTrue'))) denied();
117
123
  if (['reactionAdd', 'reactionRemove'].includes(scope) && (args.length !== 1 || !only(args[0], ['messageId', 'emoji', 'remove']) || args[0].remove !== (scope === 'reactionRemove'))) denied();
118
124
  if (['chatArg', 'chatTrue', 'chatFalse'].includes(scope)) {
@@ -147,13 +153,22 @@ function safeError(error) {
147
153
  }
148
154
 
149
155
  export function createBrokerHandler({ policy, token, getServices }) {
156
+ let transfers = 0;
150
157
  return async (req, res) => {
151
158
  const answer = (status, body) => { if (!res.headersSent) res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', 'connection': 'close' }); res.end(JSON.stringify(body)); };
152
- if (req.method !== 'POST' || req.url !== '/v1/call' || !/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] || '')) return answer(400, { ok: false, error: { code: 'INVALID_REQUEST', message: 'Invalid broker request.' } });
159
+ if (req.method !== 'POST' || !['/v1/call', '/v1/file'].includes(req.url)) return answer(400, { ok: false, error: { code: 'INVALID_REQUEST', message: 'Invalid broker request.' } });
153
160
  const authorization = req.headers.authorization || '';
154
161
  const provided = Buffer.from(authorization.startsWith('Bearer ') ? authorization.slice(7) : '');
155
162
  const expected = Buffer.from(token);
156
163
  if (provided.length !== expected.length || !timingSafeEqual(provided, expected)) return answer(401, { ok: false, error: { code: 'BROKER_AUTH_FAILED', message: 'Invalid broker token.' } });
164
+ if (req.url === '/v1/file') {
165
+ if (transfers >= 2) return answer(429, { ok: false, error: { code: 'BROKER_BUSY', message: 'Too many file transfers.' } });
166
+ transfers++;
167
+ try { await handleFileRequest({ req, res, policy, getServices, authorize, answer }); }
168
+ finally { transfers--; }
169
+ return;
170
+ }
171
+ if (!/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] || '')) return answer(400, { ok: false, error: { code: 'INVALID_REQUEST', message: 'Invalid broker request.' } });
157
172
  let chunks = [], size = 0, command, dispatched = false;
158
173
  try {
159
174
  for await (const chunk of req) { size += chunk.length; if (size > 65536) throw new FeishuError('INVALID_REQUEST', 'Broker request is too large.'); chunks.push(chunk); }
@@ -161,6 +176,7 @@ export function createBrokerHandler({ policy, token, getServices }) {
161
176
  command = request?.command;
162
177
  if (only(request, ['command']) && request.command === 'broker-info') return answer(200, { ok: true, policy });
163
178
  const { service, method, args } = authorize(policy, request);
179
+ if (service === 'files') denied(); // File bytes use a separate endpoint, never owner-local paths.
164
180
  const services = await getServices();
165
181
  dispatched = true;
166
182
  const data = await services[service][method](...args);
@@ -233,6 +249,8 @@ export async function brokerCall(socketPath, request, tokenFile) {
233
249
  export function brokerProxy(socketPath, service, getCommand, tokenFile) {
234
250
  return new Proxy({}, { get(_target, method) {
235
251
  if (method === 'then' || typeof method !== 'string') return undefined;
252
+ if (service === 'client' && ['sendFile', 'sendImage'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
253
+ if (service === 'client' && method === 'downloadFile') return options => brokerDownload(socketPath, tokenFile, options);
236
254
  return (...args) => brokerCall(socketPath, { command: getCommand(), service, method, args }, tokenFile);
237
255
  } });
238
256
  }
@@ -0,0 +1,144 @@
1
+ import http from 'node:http';
2
+ import { createReadStream } from 'node:fs';
3
+ import { mkdtemp, open, rm, stat } from 'node:fs/promises';
4
+ import { basename, join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { pipeline } from 'node:stream/promises';
7
+ import { FeishuError, requireInt64Id } from './errors.js';
8
+ import { loadBrokerToken } from './agent-broker.js';
9
+
10
+ const MAX = 100 * 1024 * 1024;
11
+ const object = x => x !== null && typeof x === 'object' && !Array.isArray(x);
12
+ const only = (x, keys) => object(x) && Object.keys(x).every(key => keys.includes(key));
13
+ const bad = () => { throw new FeishuError('INVALID_REQUEST', 'Invalid file transfer request.'); };
14
+ const denied = () => { throw new FeishuError('POLICY_DENIED', 'This action or resource is not permitted by the broker policy.'); };
15
+ const safeName = name => typeof name === 'string' && name.length > 0 && Buffer.byteLength(name) <= 200
16
+ && name !== '.' && name !== '..' && !/[\/\\\x00-\x1f\x7f]/.test(name);
17
+
18
+ // The privileged process never receives a client-provided path. Each transfer gets
19
+ // a private, disposable directory and only validated, single-component names.
20
+ export async function handleFileRequest({ req, res, policy, getServices, authorize, answer }) {
21
+ let dir, dispatched = false, command;
22
+ try {
23
+ if (req.headers['content-type'] !== 'application/octet-stream' || typeof req.headers['x-larkmate-file'] !== 'string' || req.headers['x-larkmate-file'].length > 4096) bad();
24
+ let meta;
25
+ try { meta = JSON.parse(Buffer.from(req.headers['x-larkmate-file'], 'base64url').toString('utf8')); } catch { bad(); }
26
+ command = meta?.command;
27
+ const upload = command === 'send-file' || command === 'send-image';
28
+ if (!only(meta, upload ? ['command', 'chatId', 'name', 'size'] : ['command', 'chatId', 'messageId', 'key', 'position']) || (!upload && command !== 'download-file')) bad();
29
+ authorize(policy, { command, service: 'files', method: upload ? 'upload' : 'download', args: [{ chatId: meta.chatId }] });
30
+ requireInt64Id(meta.chatId, 'chat ID');
31
+ if (upload) {
32
+ if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (command === 'send-image' && meta.size > 10 * 1024 * 1024)) bad();
33
+ dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
34
+ const path = join(dir, meta.name);
35
+ const file = await open(path, 'wx', 0o600);
36
+ let bytes = 0;
37
+ try {
38
+ for await (const chunk of req) {
39
+ bytes += chunk.length;
40
+ if (bytes > meta.size || bytes > policy.maxFileBytes) bad();
41
+ await file.writeFile(chunk);
42
+ }
43
+ } finally { await file.close(); }
44
+ if (bytes !== meta.size || !req.complete || res.destroyed) bad();
45
+ const { client } = await getServices();
46
+ if (res.destroyed) return;
47
+ dispatched = true;
48
+ const data = await client[command === 'send-file' ? 'sendFile' : 'sendImage']({ chatId: meta.chatId, path });
49
+ answer(200, { ok: true, data });
50
+ } else {
51
+ requireInt64Id(meta.messageId, 'message ID');
52
+ if (typeof meta.key !== 'string' || !/^[\w.-]{1,200}$/.test(meta.key) || !Number.isInteger(meta.position) || meta.position < 1 || meta.position > 2147483647) bad();
53
+ const { client } = await getServices();
54
+ const page = await client.history({ chatId: meta.chatId, start: meta.position, limit: 1 });
55
+ const item = page.items?.[0];
56
+ if (!item || item.position !== meta.position || item.id !== meta.messageId || item.resource?.key !== meta.key) denied();
57
+ dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
58
+ const path = join(dir, 'download');
59
+ const result = await client.downloadFile({ chatId: meta.chatId, messageId: meta.messageId, key: meta.key, output: path, maxBytes: policy.maxFileBytes });
60
+ const size = (await stat(path)).size;
61
+ if (size > policy.maxFileBytes || size !== result.bytes) throw new FeishuError('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
62
+ if (res.destroyed) return;
63
+ res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': String(size), 'cache-control': 'no-store', 'connection': 'close' });
64
+ await pipeline(createReadStream(path), res);
65
+ }
66
+ } catch (error) {
67
+ if (res.headersSent) { res.destroy(); return; }
68
+ const failure = dispatched && !(error instanceof FeishuError)
69
+ ? new FeishuError('EFFECT_UNKNOWN', 'The broker could not confirm the result; inspect before retrying.') : error;
70
+ answer(400, { ok: false, error: failure instanceof FeishuError ? { code: failure.code, message: failure.message } : { code: 'BROKER_ERROR', message: 'The file transfer failed.' } });
71
+ } finally {
72
+ if (dir) await rm(dir, { recursive: true, force: true });
73
+ }
74
+ }
75
+
76
+ function fileRequest(socketPath, token, meta) {
77
+ return http.request({ socketPath, method: 'POST', path: '/v1/file', timeout: 120000, headers: {
78
+ 'content-type': 'application/octet-stream', authorization: `Bearer ${token}`,
79
+ 'x-larkmate-file': Buffer.from(JSON.stringify(meta)).toString('base64url'),
80
+ ...(meta.size != null ? { 'content-length': String(meta.size) } : { 'content-length': '0' }),
81
+ } });
82
+ }
83
+ async function errorResponse(res) {
84
+ let data = '';
85
+ for await (const chunk of res) { data += chunk; if (data.length > 65536) break; }
86
+ try { const error = JSON.parse(data).error; return new FeishuError(error.code, error.message); }
87
+ catch { return new FeishuError('BROKER_INVALID_RESPONSE', 'The broker returned an invalid response.'); }
88
+ }
89
+ export async function brokerUpload(socketPath, tokenFile, command, { chatId, path }) {
90
+ const token = await loadBrokerToken(tokenFile);
91
+ if (typeof path !== 'string' || !path) throw new FeishuError('FILE_UNAVAILABLE', 'Cannot open the file.');
92
+ let handle;
93
+ try { handle = await open(path, 'r'); } catch { throw new FeishuError('FILE_UNAVAILABLE', 'Cannot open the file.'); }
94
+ try {
95
+ const info = await handle.stat(), name = basename(path);
96
+ if (!info.isFile() || info.size < 1 || info.size > MAX || !safeName(name)) throw new FeishuError('FILE_INVALID', 'Use a regular, non-empty file up to 100 MiB with a valid name.');
97
+ const req = fileRequest(socketPath, token, { command, chatId, name, size: info.size });
98
+ return await new Promise((resolve, reject) => {
99
+ const source = handle.createReadStream({ autoClose: false });
100
+ let done = false;
101
+ const finish = (error, data) => { if (done) return; done = true; source.destroy(); error ? reject(error) : resolve(data); };
102
+ req.on('response', async res => {
103
+ try {
104
+ if (res.statusCode !== 200) return finish(await errorResponse(res));
105
+ let body = ''; for await (const chunk of res) { body += chunk; if (body.length > 65536) throw new Error(); }
106
+ const parsed = JSON.parse(body);
107
+ if (!parsed.ok) throw new Error();
108
+ finish(null, parsed.data);
109
+ } catch { finish(new FeishuError('EFFECT_UNKNOWN', 'The broker could not confirm the result; inspect before retrying.')); }
110
+ });
111
+ req.on('timeout', () => req.destroy());
112
+ req.on('error', () => finish(new FeishuError('EFFECT_UNKNOWN', 'The broker connection failed; inspect the result before retrying.')));
113
+ source.on('error', () => req.destroy());
114
+ source.pipe(req);
115
+ });
116
+ } finally { await handle.close(); }
117
+ }
118
+ export async function brokerDownload(socketPath, tokenFile, { chatId, messageId, key, position, output }) {
119
+ if (!Number.isInteger(position) || position < 1 || position > 2147483647) throw new FeishuError('INVALID_ARGUMENT', 'A message --position from history is required by the broker.');
120
+ if (typeof output !== 'string' || !output.trim()) throw new FeishuError('INVALID_ARGUMENT', 'An output path is required.');
121
+ const token = await loadBrokerToken(tokenFile);
122
+ const req = fileRequest(socketPath, token, { command: 'download-file', chatId, messageId, key, position });
123
+ return await new Promise((resolve, reject) => {
124
+ let done = false;
125
+ const finish = (error, data) => { if (done) return; done = true; error ? reject(error) : resolve(data); };
126
+ req.on('response', async res => {
127
+ if (res.statusCode !== 200) { try { return finish(await errorResponse(res)); } catch { return finish(new FeishuError('BROKER_INVALID_RESPONSE', 'Invalid broker response.')); } }
128
+ let file, bytes = 0;
129
+ try {
130
+ const length = Number(res.headers['content-length']);
131
+ if (!Number.isSafeInteger(length) || length < 0 || length > MAX) throw new Error('invalid length');
132
+ try { file = await open(output, 'wx', 0o600); }
133
+ catch (error) { res.destroy(); return finish(new FeishuError('DOWNLOAD_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.')); }
134
+ for await (const chunk of res) { bytes += chunk.length; if (bytes > length) throw new Error('too large'); await file.writeFile(chunk); }
135
+ if (bytes !== length) throw new Error('incomplete');
136
+ finish(null, { output, bytes, messageId });
137
+ } catch { finish(new FeishuError('DOWNLOAD_INCOMPLETE', 'The download stopped; the output file is incomplete.', { output, bytes })); }
138
+ finally { await file?.close(); }
139
+ });
140
+ req.on('timeout', () => req.destroy());
141
+ req.on('error', () => finish(new FeishuError('BROKER_UNAVAILABLE', 'Cannot connect to the broker.')));
142
+ req.end();
143
+ });
144
+ }
package/src/download.js CHANGED
@@ -2,7 +2,7 @@ import { open } from 'node:fs/promises';
2
2
  import { FeishuError, requireInt64Id, requireText } from './errors.js';
3
3
 
4
4
  // Uses the same message-scoped access check as the web client; never follows redirects with the Cookie.
5
- export async function downloadFile(gateway, { chatId, messageId, key, output }) {
5
+ export async function downloadFile(gateway, { chatId, messageId, key, output, maxBytes = Infinity }) {
6
6
  requireInt64Id(chatId, 'chat ID');
7
7
  requireInt64Id(messageId, 'message ID');
8
8
  requireText(output, 'output path');
@@ -26,12 +26,16 @@ export async function downloadFile(gateway, { chatId, messageId, key, output })
26
26
  let bytes = 0;
27
27
  try {
28
28
  if (!response.body) throw new Error('empty response');
29
- for await (const chunk of response.body) { await handle.writeFile(chunk); bytes += chunk.length; }
29
+ for await (const chunk of response.body) {
30
+ if (bytes + chunk.length > maxBytes) throw new FeishuError('FILE_TOO_LARGE', 'The download exceeds the configured file limit.');
31
+ await handle.writeFile(chunk); bytes += chunk.length;
32
+ }
30
33
  const length = response.headers.get('content-length');
31
34
  const encoding = response.headers.get('content-encoding');
32
35
  if (length && (!encoding || encoding === 'identity') && /^\d+$/.test(length) && BigInt(bytes) !== BigInt(length)) throw new Error('incomplete response');
33
36
  return { output, bytes, messageId };
34
- } catch {
37
+ } catch (error) {
38
+ if (error instanceof FeishuError && error.code === 'FILE_TOO_LARGE') throw error;
35
39
  throw new FeishuError('DOWNLOAD_INCOMPLETE', 'The download stopped; the output file is incomplete.', { output, bytes });
36
40
  } finally { await handle.close(); }
37
41
  }
@@ -0,0 +1,94 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { open } from 'node:fs/promises';
3
+ import { basename, isAbsolute } from 'node:path';
4
+ import { once } from 'node:events';
5
+ import { FeishuError } from './errors.js';
6
+ import { brokerCommands } from './agent-broker.js';
7
+
8
+ const MAX_FILE = 100 * 1024 * 1024, MAX_JSON = 32 * 1024 * 1024;
9
+ const fail = (code, message) => { throw new FeishuError(code, message); };
10
+
11
+ export async function callOsDelegate({ owner, launcher, request, inputPath, outputPath, spawnImpl = spawn }) {
12
+ if (typeof owner !== 'string' || !/^[A-Za-z_][A-Za-z0-9_.-]*$/.test(owner) || typeof launcher !== 'string' || !isAbsolute(launcher)) fail('DELEGATE_CONFIG_INVALID', 'A valid owner and absolute protected launcher are required.');
13
+ let source;
14
+ if (inputPath != null) {
15
+ try { source = await open(inputPath, 'r'); } catch { fail('FILE_UNAVAILABLE', 'Cannot open the file.'); }
16
+ }
17
+ try {
18
+ let meta = request;
19
+ if (source) {
20
+ const s = await source.stat();
21
+ if (!s.isFile() || s.size < 1 || s.size > MAX_FILE) fail('FILE_INVALID', 'Use a regular, non-empty file up to 100 MiB.');
22
+ meta = { ...request, fileName: basename(inputPath), size: s.size };
23
+ }
24
+ const child = spawnImpl('/usr/bin/sudo', ['-n', '-u', owner, '--', launcher], { stdio: ['pipe', 'pipe', 'ignore'] });
25
+ const mutating = brokerCommands().find(x => x.command === request.command)?.mutating === true;
26
+ const unavailable = () => new FeishuError(mutating ? 'EFFECT_UNKNOWN' : 'DELEGATE_UNAVAILABLE', mutating ? 'The delegated operation could not be confirmed; inspect before retrying.' : 'Cannot run the OS delegate.');
27
+ let spawnError;
28
+ child.on('error', error => { spawnError = error; });
29
+ child.stdin.on('error', () => {});
30
+ const writing = (async () => {
31
+ try {
32
+ child.stdin.write(JSON.stringify(meta) + '\n');
33
+ if (source) {
34
+ for await (const chunk of source.createReadStream({ autoClose: false })) if (!child.stdin.write(chunk)) await once(child.stdin, 'drain');
35
+ }
36
+ child.stdin.end();
37
+ } catch { child.stdin.destroy(); }
38
+ })();
39
+ let header = Buffer.alloc(0), parsed, bytes = 0, output;
40
+ try {
41
+ for await (const chunk of child.stdout) {
42
+ let data = chunk;
43
+ if (!parsed) {
44
+ header = Buffer.concat([header, data]);
45
+ const end = header.indexOf(10);
46
+ if (end < 0) { if (header.length > MAX_JSON) throw unavailable(); continue; }
47
+ try { parsed = JSON.parse(header.subarray(0, end).toString('utf8')); } catch { throw unavailable(); }
48
+ data = header.subarray(end + 1); header = null;
49
+ if (!parsed.ok) { const error = parsed.error || {}; throw new FeishuError(error.code || 'DELEGATE_ERROR', error.message || 'Delegated operation failed.'); }
50
+ if (outputPath != null) {
51
+ if (!Number.isSafeInteger(parsed.size) || parsed.size < 0 || parsed.size > MAX_FILE) throw unavailable();
52
+ try { output = await open(outputPath, 'wx', 0o600); }
53
+ catch (error) { throw new FeishuError('DOWNLOAD_WRITE_FAILED', error.code === 'EEXIST' ? 'Output file already exists; choose a new path.' : 'Could not create the output file.'); }
54
+ }
55
+ }
56
+ if (outputPath != null) {
57
+ bytes += data.length;
58
+ if (bytes > parsed.size) throw new Error('too large');
59
+ if (data.length) await output.writeFile(data);
60
+ } else if (data.length) throw unavailable();
61
+ }
62
+ await writing;
63
+ if (spawnError || !parsed) throw unavailable();
64
+ if (outputPath != null) {
65
+ if (bytes !== parsed.size) fail('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
66
+ return { output: outputPath, bytes, messageId: request.args[0].messageId };
67
+ }
68
+ return parsed.data;
69
+ } catch (error) {
70
+ child.kill('SIGTERM');
71
+ if (output && !(error instanceof FeishuError)) throw new FeishuError('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.', { output: outputPath, bytes });
72
+ throw error instanceof FeishuError ? error : unavailable();
73
+ } finally { await output?.close(); }
74
+ } finally { await source?.close(); }
75
+ }
76
+
77
+ export function osDelegateProxy(owner, launcher, service, getCommand) {
78
+ return new Proxy({}, { get(_target, method) {
79
+ if (method === 'then' || typeof method !== 'string') return undefined;
80
+ return (...args) => {
81
+ const command = getCommand();
82
+ if (service === 'client' && ['sendFile', 'sendImage'].includes(method)) {
83
+ const { chatId, path } = args[0];
84
+ return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [{ chatId }] }, inputPath: path });
85
+ }
86
+ if (service === 'client' && method === 'downloadFile') {
87
+ const { chatId, messageId, key, position, output } = args[0];
88
+ if (!Number.isInteger(position) || position < 1) fail('INVALID_ARGUMENT', 'A message --position from history is required by the delegate.');
89
+ return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'download', args: [{ chatId, messageId, key, position }] }, outputPath: output });
90
+ }
91
+ return callOsDelegate({ owner, launcher, request: { command, service, method, args } });
92
+ };
93
+ } });
94
+ }
@@ -0,0 +1,172 @@
1
+ import { constants } from 'node:fs';
2
+ import { open, stat, lstat, mkdtemp, rm } from 'node:fs/promises';
3
+ import { createReadStream } from 'node:fs';
4
+ import { isAbsolute, join } from 'node:path';
5
+ import { tmpdir } from 'node:os';
6
+ import { createHash, randomUUID } from 'node:crypto';
7
+ import { spawn } from 'node:child_process';
8
+ import { FeishuError } from './errors.js';
9
+ import { authorize, brokerCommands, parsePolicy } from './agent-broker.js';
10
+
11
+ const MAX_HEADER = 65536, MAX_FILE = 100 * 1024 * 1024;
12
+ const obj = x => x !== null && typeof x === 'object' && !Array.isArray(x);
13
+ const only = (x, keys) => obj(x) && Object.keys(x).every(k => keys.includes(k));
14
+ const fail = (code, message) => { throw new FeishuError(code, message); };
15
+ const invalid = () => fail('DELEGATE_CONFIG_INVALID', 'Invalid OS delegation configuration.');
16
+ const noAccess = () => fail('POLICY_DENIED', 'This operation is not permitted.');
17
+ const nameOk = name => typeof name === 'string' && name.length > 0 && Buffer.byteLength(name) <= 200 && name !== '.' && name !== '..' && !/[\/\\\x00-\x1f\x7f]/.test(name);
18
+ const uint = x => typeof x === 'string' && /^(0|[1-9]\d*)$/.test(x) && Number.isSafeInteger(Number(x));
19
+
20
+ export async function loadDelegateConfig(path, ownerUid) {
21
+ if (!isAbsolute(path)) invalid();
22
+ let h, raw;
23
+ try {
24
+ h = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
25
+ const info = await h.stat();
26
+ if (!info.isFile() || info.size > 262144 || ![0, ownerUid].includes(info.uid) || (info.mode & 0o022)) throw new Error();
27
+ raw = JSON.parse(await h.readFile('utf8'));
28
+ } catch { return invalid(); } finally { await h?.close(); }
29
+ if (!only(raw, ['version', 'ownerUid', 'credentialsFile', 'users']) || raw.version !== 1 || raw.ownerUid !== ownerUid || !isAbsolute(raw.credentialsFile || '') || !obj(raw.users)) invalid();
30
+ const users = {};
31
+ for (const [uid, v] of Object.entries(raw.users)) {
32
+ if (!uint(uid) || Number(uid) === ownerUid || !only(v, ['policy', 'approvalScript', 'approvalTimeoutSeconds'])) invalid();
33
+ const policy = parsePolicy(v.policy);
34
+ const approvalScript = v.approvalScript;
35
+ if (approvalScript !== undefined && (typeof approvalScript !== 'string' || !isAbsolute(approvalScript))) invalid();
36
+ const timeout = v.approvalTimeoutSeconds ?? 300;
37
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 600) invalid();
38
+ users[uid] = { policy, approvalScript, approvalTimeoutSeconds: timeout };
39
+ }
40
+ return { credentialsFile: raw.credentialsFile, users };
41
+ }
42
+
43
+ function broadPolicy(request, maxFileBytes) {
44
+ return parsePolicy({ version: 1, allow: [request.command], allowGlobal: true, allowAllChats: true, allowAllMinutes: true, maxFileBytes });
45
+ }
46
+
47
+ async function approve(script, uid, request, payload, timeout) {
48
+ let info;
49
+ try { info = await lstat(script); } catch { noAccess(); }
50
+ if (!info.isFile() || ![0, process.getuid()].includes(info.uid) || (info.mode & 0o022) || !(info.mode & 0o111)) noAccess();
51
+ const requestId = randomUUID();
52
+ const data = JSON.stringify({ version: 1, requestId, callerUid: Number(uid), request, ...(payload ? { file: payload } : {}) });
53
+ return await new Promise(resolve => {
54
+ const child = spawn(script, [], { stdio: ['pipe', 'pipe', 'ignore'], env: { PATH: '/usr/bin:/bin', HOME: process.env.HOME || '/', LANG: 'C.UTF-8' } });
55
+ let text = '', finished = false;
56
+ const done = yes => { if (finished) return; finished = true; clearTimeout(timer); resolve(yes); };
57
+ const timer = setTimeout(() => { child.kill('SIGKILL'); done(false); }, timeout * 1000);
58
+ child.on('error', () => done(false));
59
+ child.stdin.on('error', () => done(false));
60
+ child.stdout.on('data', chunk => { text += chunk; if (Buffer.byteLength(text) > 8192) { child.kill('SIGKILL'); done(false); } });
61
+ child.on('close', code => {
62
+ try { const result = JSON.parse(text); done(code === 0 && only(result, ['decision', 'requestId']) && result.decision === 'allow' && result.requestId === requestId); }
63
+ catch { done(false); }
64
+ });
65
+ child.stdin.end(data + '\n');
66
+ });
67
+ }
68
+
69
+ export async function checkDelegation({ profile, uid, request, file }) {
70
+ if (!profile || !obj(request)) noAccess();
71
+ // Validate the operation and its argument shape even when a hook may approve it.
72
+ const wide = broadPolicy(request, profile.policy.maxFileBytes);
73
+ authorize(wide, request);
74
+ try { authorize(profile.policy, request); return; }
75
+ catch (error) { if (!(error instanceof FeishuError) || error.code !== 'POLICY_DENIED') throw error; }
76
+ if (!profile.approvalScript || !await approve(profile.approvalScript, uid, request, file, profile.approvalTimeoutSeconds)) noAccess();
77
+ }
78
+
79
+ export async function invokeDelegated({ profile, uid, request, getServices, filePath }) {
80
+ const fileOp = ['send-file', 'send-image', 'download-file'].includes(request?.command);
81
+ if (fileOp && request.service !== 'files') noAccess();
82
+ if (!fileOp && request.service === 'files') noAccess();
83
+ let file;
84
+ if (request.command === 'send-file' || request.command === 'send-image') {
85
+ if (!filePath || !nameOk(request.fileName)) fail('INVALID_REQUEST', 'Invalid file transfer.');
86
+ const info = await stat(filePath);
87
+ if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (request.command === 'send-image' && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
88
+ const hash = createHash('sha256'); for await (const chunk of createReadStream(filePath)) hash.update(chunk);
89
+ file = { name: request.fileName, size: info.size, sha256: hash.digest('hex') };
90
+ }
91
+ // fileName is transfer metadata, not a service argument.
92
+ const { fileName, ...rpc } = request;
93
+ if (rpc.command === 'download-file') {
94
+ const o = rpc.args?.[0];
95
+ if (!only(o, ['chatId', 'messageId', 'key', 'position']) || !Number.isInteger(o.position) || o.position < 1 || o.position > 2147483647 || typeof o.messageId !== 'string' || typeof o.key !== 'string') fail('INVALID_REQUEST', 'A valid message position and resource are required.');
96
+ }
97
+ await checkDelegation({ profile, uid, request: rpc, file });
98
+ const { service, method, args } = authorize(broadPolicy(rpc, profile.policy.maxFileBytes), rpc);
99
+ const services = await getServices();
100
+ if (service !== 'files') {
101
+ try { return { data: await services[service][method](...args) }; }
102
+ catch (error) {
103
+ if (!(error instanceof FeishuError) && brokerCommands().find(x => x.command === rpc.command)?.mutating) fail('EFFECT_UNKNOWN', 'The delegated write could not be confirmed; inspect before retrying.');
104
+ throw error;
105
+ }
106
+ }
107
+ const client = services.client, o = args[0];
108
+ if (method === 'upload') {
109
+ try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : 'sendImage']({ chatId: o.chatId, path: filePath }) }; }
110
+ catch (error) { if (!(error instanceof FeishuError)) fail('EFFECT_UNKNOWN', 'The delegated write could not be confirmed; inspect before retrying.'); throw error; }
111
+ }
112
+ return { download: true, client, options: o };
113
+ }
114
+
115
+ // The privileged helper parses one framed request and terminates; it never opens a listening socket.
116
+ export async function serveOne({ input, output, uid, profile, getServices }) {
117
+ let temp, header = Buffer.alloc(0), received = 0, path, file, request, expected = 0, outcome, started = false;
118
+ try {
119
+ for await (const chunk of input) {
120
+ let data = chunk;
121
+ if (!request) {
122
+ header = Buffer.concat([header, data]);
123
+ const end = header.indexOf(10);
124
+ if (end < 0) { if (header.length > MAX_HEADER) fail('INVALID_REQUEST', 'Request is too large.'); continue; }
125
+ if (end > MAX_HEADER) fail('INVALID_REQUEST', 'Request is too large.');
126
+ try { request = JSON.parse(header.subarray(0, end).toString('utf8')); } catch { fail('INVALID_REQUEST', 'Invalid request.'); }
127
+ data = header.subarray(end + 1); header = null;
128
+ if (!only(request, ['command', 'service', 'method', 'args', 'fileName', 'size'])) fail('INVALID_REQUEST', 'Invalid request.');
129
+ const upload = request.command === 'send-file' || request.command === 'send-image';
130
+ if (upload) {
131
+ if (!nameOk(request.fileName) || !Number.isSafeInteger(request.size) || request.size < 1 || request.size > profile.policy.maxFileBytes || request.size > MAX_FILE) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
132
+ const { size, fileName, ...rpc } = request;
133
+ authorize(broadPolicy(rpc, profile.policy.maxFileBytes), rpc);
134
+ if (!profile.approvalScript) authorize(profile.policy, rpc);
135
+ expected = request.size;
136
+ temp = await mkdtemp(join(tmpdir(), 'larkmate-os-transfer-'));
137
+ path = join(temp, request.fileName); file = await open(path, 'wx', 0o600);
138
+ } else if (Object.hasOwn(request, 'size') || Object.hasOwn(request, 'fileName')) fail('INVALID_REQUEST', 'Invalid request.');
139
+ }
140
+ received += data.length;
141
+ if (received > expected) fail('INVALID_REQUEST', 'Invalid request body.');
142
+ if (data.length) await file.writeFile(data);
143
+ }
144
+ if (!request || received !== expected) fail('INVALID_REQUEST', 'Incomplete request.');
145
+ await file?.close(); file = null;
146
+ if (only(request, ['command']) && request.command === 'delegate-info') {
147
+ output.write(JSON.stringify({ ok: true, data: { policy: profile.policy, approvalConfigured: !!profile.approvalScript } }) + '\n');
148
+ return;
149
+ }
150
+ const { size, ...rpc } = request;
151
+ outcome = await invokeDelegated({ profile, uid, request: rpc, getServices, filePath: path });
152
+ if (!outcome.download) { output.write(JSON.stringify({ ok: true, data: outcome.data }) + '\n'); return; }
153
+ const o = outcome.options;
154
+ if (!only(o, ['chatId', 'messageId', 'key', 'position']) || !Number.isInteger(o.position) || o.position < 1 || o.position > 2147483647 || typeof o.messageId !== 'string' || typeof o.key !== 'string') fail('INVALID_REQUEST', 'A valid message position and resource are required.');
155
+ const page = await outcome.client.history({ chatId: o.chatId, start: o.position, limit: 1 });
156
+ const item = page.items?.[0];
157
+ if (!item || item.position !== o.position || item.id !== o.messageId || item.resource?.key !== o.key) noAccess();
158
+ temp = await mkdtemp(join(tmpdir(), 'larkmate-os-transfer-')); path = join(temp, 'download');
159
+ const result = await outcome.client.downloadFile({ chatId: o.chatId, messageId: o.messageId, key: o.key, output: path, maxBytes: profile.policy.maxFileBytes });
160
+ const info = await stat(path);
161
+ if (info.size !== result.bytes || info.size > profile.policy.maxFileBytes) fail('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
162
+ output.write(JSON.stringify({ ok: true, size: info.size }) + '\n');
163
+ started = true;
164
+ for await (const chunk of createReadStream(path)) if (!output.write(chunk)) await new Promise(resolve => output.once('drain', resolve));
165
+ } catch (error) {
166
+ if (started) { output.destroy(); return; }
167
+ const result = error instanceof FeishuError ? { code: error.code, message: error.message } : { code: 'DELEGATE_ERROR', message: 'The delegated operation failed.' };
168
+ output.write(JSON.stringify({ ok: false, error: result }) + '\n');
169
+ } finally { await file?.close(); if (temp) await rm(temp, { recursive: true, force: true }); }
170
+ }
171
+
172
+ export function osDelegateInfo() { return brokerCommands(); }