larkmate 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/larkmate.js +3 -2
- package/docs/agent-broker.md +9 -1
- package/docs/agent-policy.example.json +2 -1
- package/package.json +1 -1
- package/skills/larkmate/references/chats.md +2 -0
- package/skills/larkmate/references/writes.md +2 -0
- package/src/agent-broker.js +22 -4
- package/src/agent-files.js +144 -0
- package/src/download.js +7 -3
package/bin/larkmate.js
CHANGED
|
@@ -11,7 +11,7 @@ import { exportMessages } from '../src/export-messages.js';
|
|
|
11
11
|
import { brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
|
|
12
12
|
|
|
13
13
|
const program = new Command();
|
|
14
|
-
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.
|
|
14
|
+
program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.9');
|
|
15
15
|
program.option('--credentials-file <path>', 'read LarkMate credentials.json');
|
|
16
16
|
program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
|
|
17
17
|
program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
|
|
@@ -256,8 +256,9 @@ program.command('download-file').description('Download a message file or image t
|
|
|
256
256
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
257
257
|
.requiredOption('--message <id>', 'numeric message ID')
|
|
258
258
|
.requiredOption('--key <key>', 'file or image key from history')
|
|
259
|
+
.option('--position <number>', 'message position from history (required by a restricted broker)')
|
|
259
260
|
.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 })));
|
|
261
|
+
.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
262
|
program.command('message-link').description('Get the native link to a message.')
|
|
262
263
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
263
264
|
.requiredOption('--message <id>', 'numeric message ID')
|
package/docs/agent-broker.md
CHANGED
|
@@ -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
|
-
|
|
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` 时,应停止该操作并说明权限不足,由所有者决定是否调整策略;不能改用直连模式尝试绕过。
|
package/package.json
CHANGED
|
@@ -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`。
|
package/src/agent-broker.js
CHANGED
|
@@ -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], ['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' ||
|
|
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) {
|
|
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
|
}
|