larkmate 0.1.9 → 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.9');
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,7 +278,7 @@ 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')
259
- .option('--position <number>', 'message position from history (required by a restricted broker)')
281
+ .option('--position <number>', 'message position from history (required by a broker or OS delegate)')
260
282
  .requiredOption('--output <path>', 'new local output file')
261
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) } : {}) })));
262
284
  program.command('message-link').description('Get the native link to a message.')
@@ -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
+ }
@@ -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.9",
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,7 +20,7 @@ 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` 限制。
23
+ 使用受限代理或系统用户委托下载时,还须传入目标消息的 `--position`,取值为 `history` 返回的 `position`;执行器会核验消息和资源是否属于授权会话。文件大小受策略的 `maxFileBytes` 限制。
24
24
 
25
25
  `messages-export` 会自动向前分页至会话最早位置,并按从新到旧的顺序输出 Markdown 或 JSON Lines。该命令支持 `--sender`、`--query`,以及以 Unix 秒为单位的 `--after` 和 `--before`;筛选范围仅限指定会话。可通过 `--max-pages` 限制页数,导出结束时需检查 `reachedBeginning`、`nextStart`、`nextLimit`、`omittedPositions` 和 `missingTimestamps`。
26
26
 
@@ -19,7 +19,7 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
19
19
 
20
20
  文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
21
21
 
22
- 使用受限代理发送文件或图片时,需要相应命令和目标会话的授权;文件由 Agent 自身读取,且还受代理策略 `maxFileBytes` 限制。
22
+ 使用受限代理或系统用户委托发送文件或图片时,需要相应命令和目标会话的授权;文件由 Agent 自身读取,且还受策略 `maxFileBytes` 限制。
23
23
 
24
24
  图片支持 PNG、JPEG、GIF 和 WebP 格式,大小不超过 10 MiB。`message-edit` 会以纯文本替换原消息内容,无法保留原有的富文本格式或提及。`--emoji` 需传入飞书表情名称,默认值为 `DarkThumbsup`。`favorite-add` 成功确认时会返回收藏 ID,供 `favorite-remove` 使用;该收藏 ID 也可从 `favorites` 首页获取。发送、编辑、撤回、转发、表情及收藏操作均须遵循用户的明确意图。
25
25
 
@@ -118,7 +118,7 @@ export function authorize(policy, request) {
118
118
  if (scope === 'global' && !policy.allowGlobal) denied();
119
119
  if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
120
120
  if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
121
- if (scope === 'file' && (args.length !== 1 || !only(args[0], ['chatId']) || !chatAllowed(args[0].chatId))) denied();
121
+ if (scope === 'file' && (args.length !== 1 || !only(args[0], method === 'download' ? ['chatId', 'messageId', 'key', 'position'] : ['chatId']) || !chatAllowed(args[0].chatId))) denied();
122
122
  if (['labelTrue', 'labelFalse'].includes(scope) && (args.length !== 3 || args[2] !== (scope === 'labelTrue'))) denied();
123
123
  if (['reactionAdd', 'reactionRemove'].includes(scope) && (args.length !== 1 || !only(args[0], ['messageId', 'emoji', 'remove']) || args[0].remove !== (scope === 'reactionRemove'))) denied();
124
124
  if (['chatArg', 'chatTrue', 'chatFalse'].includes(scope)) {
@@ -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(); }