larkmate 0.1.26 → 0.1.28
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 +3 -0
- package/bin/larkmate.js +35 -3
- package/docs/agent-broker.md +2 -0
- package/docs/os-delegation.md +2 -0
- package/package.json +1 -1
- package/proto/lark.proto +33 -1
- package/skills/larkmate/references/chats.md +2 -0
- package/skills/larkmate/references/writes.md +15 -0
- package/src/agent-broker.js +14 -4
- package/src/agent-files.js +51 -6
- package/src/client.js +16 -0
- package/src/export-stickers.js +30 -0
- package/src/os-delegate-client.js +11 -2
- package/src/os-delegate.js +16 -12
- package/src/stickers.js +101 -0
package/README.md
CHANGED
|
@@ -68,6 +68,9 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
|
|
|
68
68
|
- [x] 转发或收藏消息
|
|
69
69
|
- [x] 发送图片消息、下载图片或附件
|
|
70
70
|
- [x] 给消息添加和取消表情回应
|
|
71
|
+
- [x] 查询、发送、添加和移除收藏的单个表情
|
|
72
|
+
- [x] 下载单个表情或批量导出原文件
|
|
73
|
+
- [x] 调整收藏表情的顺序
|
|
71
74
|
- [x] 获取消息链接
|
|
72
75
|
- [x] 全局或按会话监听新消息,支持名称、正则、组合过滤和规则触发脚本
|
|
73
76
|
- [x] 按 API key 限定消息服务的订阅范围
|
package/bin/larkmate.js
CHANGED
|
@@ -10,6 +10,7 @@ import { resolve, join } from 'node:path';
|
|
|
10
10
|
import { homedir } from 'node:os';
|
|
11
11
|
import { FeishuError } from '../src/errors.js';
|
|
12
12
|
import { exportMessages } from '../src/export-messages.js';
|
|
13
|
+
import { exportStickers } from '../src/export-stickers.js';
|
|
13
14
|
import { apiCommands, brokerCall, brokerCommands, brokerProxy, createBrokerToken, loadBrokerToken, loadPolicy, startBroker } from '../src/agent-broker.js';
|
|
14
15
|
import { callOsDelegate, osDelegateProxy } from '../src/os-delegate-client.js';
|
|
15
16
|
import { SidebarFilters } from '../src/sidebar-filters.js';
|
|
@@ -48,13 +49,20 @@ function configuredDelegate() {
|
|
|
48
49
|
if (owner && (configuredBroker() || configuredBrokerToken() || program.opts().credentialsFile)) throw new FeishuError('DELEGATE_CONFIG_INVALID', 'Do not combine OS delegation with broker or credentials options.');
|
|
49
50
|
return owner ? { owner, launcher } : null;
|
|
50
51
|
}
|
|
51
|
-
function proxy(service) {
|
|
52
|
+
function proxy(service, command) {
|
|
52
53
|
const delegate = configuredDelegate();
|
|
53
|
-
if (delegate) return osDelegateProxy(delegate.owner, delegate.launcher, service, () => activeCommand);
|
|
54
|
+
if (delegate) return osDelegateProxy(delegate.owner, delegate.launcher, service, () => command || activeCommand);
|
|
54
55
|
const path = configuredBroker();
|
|
55
56
|
if (!path && configuredBrokerToken()) throw new FeishuError('BROKER_CONFIGURATION_INVALID', 'A broker token file was configured without a broker socket.');
|
|
56
57
|
if (path && program.opts().credentialsFile) throw new FeishuError('INVALID_ARGUMENT', 'A broker client cannot select a credentials file.');
|
|
57
|
-
return path ? brokerProxy(path, service, () => activeCommand, configuredBrokerToken()) : null;
|
|
58
|
+
return path ? brokerProxy(path, service, () => command || activeCommand, configuredBrokerToken()) : null;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function stickerExportClient() {
|
|
62
|
+
const list = proxy('client', 'stickers-list');
|
|
63
|
+
if (!list) return client();
|
|
64
|
+
const downloads = proxy('client', 'sticker-download');
|
|
65
|
+
return { stickerList: () => list.stickerList(), downloadSticker: options => downloads.downloadSticker(options) };
|
|
58
66
|
}
|
|
59
67
|
|
|
60
68
|
async function controls() {
|
|
@@ -472,6 +480,30 @@ program.command('emoji-list').description('List available Feishu emoji names and
|
|
|
472
480
|
.option('--query <text>', 'filter by emoji name or key')
|
|
473
481
|
.action(async options => output(await (await client()).emojiList({ query: options.query })));
|
|
474
482
|
|
|
483
|
+
program.command('stickers-list').description('List the current account’s saved individual stickers.')
|
|
484
|
+
.action(async () => output(await (await client()).stickerList()));
|
|
485
|
+
program.command('sticker-send').description('Send a saved sticker to a chat.')
|
|
486
|
+
.requiredOption('--chat <id>', 'numeric chat ID').requiredOption('--id <id>', 'saved sticker ID or key')
|
|
487
|
+
.action(async options => output(await (await client()).sendSticker({ chatId: options.chat, stickerId: options.id })));
|
|
488
|
+
program.command('sticker-add').description('Save an existing sticker key to the account collection.')
|
|
489
|
+
.requiredOption('--key <key>', 'sticker resource key')
|
|
490
|
+
.action(async options => output(await (await client()).addSticker({ key: options.key })));
|
|
491
|
+
program.command('sticker-add-file').description('Upload an image as a saved individual sticker.')
|
|
492
|
+
.requiredOption('--file <path>', 'local PNG, JPEG, GIF or WebP file')
|
|
493
|
+
.action(async options => output(await (await client()).addStickerFile({ path: options.file })));
|
|
494
|
+
program.command('sticker-remove').description('Remove a saved individual sticker.')
|
|
495
|
+
.requiredOption('--id <id>', 'saved sticker ID or key')
|
|
496
|
+
.action(async options => output(await (await client()).removeSticker({ stickerId: options.id })));
|
|
497
|
+
program.command('sticker-move').description('Move a saved sticker to a position in the collection.')
|
|
498
|
+
.requiredOption('--id <id>', 'saved sticker ID or key').requiredOption('--position <number>', '1-based position')
|
|
499
|
+
.action(async options => output(await (await client()).moveSticker({ stickerId: options.id, position: Number(options.position) })));
|
|
500
|
+
program.command('sticker-download').description('Download a saved sticker in its original format.')
|
|
501
|
+
.requiredOption('--id <id>', 'saved sticker ID or key').requiredOption('--output <path>', 'new output file')
|
|
502
|
+
.action(async options => output(await (await client()).downloadSticker({ stickerId: options.id, output: options.output })));
|
|
503
|
+
program.command('stickers-export').description('Download saved stickers and a manifest to a new directory.')
|
|
504
|
+
.requiredOption('--output <dir>', 'new output directory').option('--limit <number>', 'maximum number to export')
|
|
505
|
+
.action(async options => output(await exportStickers(await stickerExportClient(), { output: options.output, ...(options.limit != null ? { limit: Number(options.limit) } : {}) })));
|
|
506
|
+
|
|
475
507
|
program.command('send-rich').description('Send structured text, links, mentions and emoji from JSON.')
|
|
476
508
|
.requiredOption('--chat <id>', 'numeric chat ID')
|
|
477
509
|
.requiredOption('--json <path>', 'JSON file or - for standard input')
|
package/docs/agent-broker.md
CHANGED
|
@@ -55,6 +55,8 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
|
|
|
55
55
|
|
|
56
56
|
`send-file`、`send-image` 与 `download-file` 均可单独加入 `allow` 列表,并受 `chatIds` 约束。发送时,由 Agent 进程读取本地文件并传输内容;下载时,由 Agent 进程创建输出文件。代理不接受 Agent 指定的代理端本地路径,而是在私有临时目录中处理中转文件,并在正常结束或失败时将其删除。若进程异常终止,可能会遗留临时文件,因此部署方应保护并按需清理代理账户的临时目录。
|
|
57
57
|
|
|
58
|
+
收藏表情属于账号级资源:`stickers-list`、`sticker-add`、`sticker-add-file`、`sticker-remove`、`sticker-move` 和 `sticker-download` 均需在 `allow` 中分别授权并开启 `allowGlobal`。`sticker-send` 另按 `chatIds` 限制目标会话。批量导出使用 `stickers-list` 和 `sticker-download`;上传和下载由调用方读写自己的文件,代理校验下载的表情属于当前账号的收藏,并应用 `maxFileBytes`。
|
|
59
|
+
|
|
58
60
|
如需限制 Agent 可访问的本地目录,部署方应通过配置 Agent 的系统账户或容器权限来实现。策略文件中的会话与大小限制不会约束 Agent 自身的文件系统,也无法阻止其向代理发送已读取的数据。请仅向 Agent 挂载或开放其业务所需的目录,禁止其读取 Cookie 及其他敏感文件。
|
|
59
61
|
|
|
60
62
|
在受限代理模式下执行下载时,须提供 `history` 返回的消息 `position`、消息 ID 与资源键。代理会重新读取该会话的对应位置,仅在三者完全匹配时才执行下载;若无法核对,则会拒绝请求。普通直连模式不要求提供 `--position`。
|
package/docs/os-delegation.md
CHANGED
|
@@ -20,6 +20,8 @@
|
|
|
20
20
|
|
|
21
21
|
文件、图片发送及附件下载可分别授权;上传文件由 Agent 进程读取,下载文件由 Agent 进程写入。执行器不接受 Agent 提供的所有者本地路径。下载时须提供 `history` 返回的 `--position`,执行器会核验会话、消息和资源键。单个文件受 `maxFileBytes` 限制;执行器在所有者私有临时目录中处理中转数据,正常结束或失败时删除,异常退出可能留下临时文件。部署方应保护、按需清理临时目录,并根据实际需要配置系统资源限制。
|
|
22
22
|
|
|
23
|
+
收藏表情的上传和下载也使用调用方的文件;对应账号级命令须单独授权并开启 `allowGlobal`。执行器会核验下载目标属于当前账号的收藏,批量导出需要分别授权列表和下载命令。
|
|
24
|
+
|
|
23
25
|
## 启动器与 sudoers 示例
|
|
24
26
|
|
|
25
27
|
将 LarkMate 包及依赖安装在 Agent 无法修改的受保护位置,将以下启动器放在同样受保护的位置。示例路径均须替换为实际绝对路径;Node.js 可执行文件和其依赖也不能由 Agent 修改。固定工作目录并清空环境,避免调用者通过环境变量或当前目录影响执行器。
|
package/package.json
CHANGED
package/proto/lark.proto
CHANGED
|
@@ -242,6 +242,37 @@ message EmojiResourceSet {
|
|
|
242
242
|
}
|
|
243
243
|
message PullEmojiResourcesV2Response { repeated EmojiResourceSet emojiResourceSet = 1; }
|
|
244
244
|
|
|
245
|
+
message StickerSummary {
|
|
246
|
+
optional string title = 1;
|
|
247
|
+
optional string description = 2;
|
|
248
|
+
map<string, string> i18nTitles = 3;
|
|
249
|
+
map<string, string> i18nDescriptions = 4;
|
|
250
|
+
}
|
|
251
|
+
message StickerRecord {
|
|
252
|
+
optional string key = 1;
|
|
253
|
+
optional int32 position = 2;
|
|
254
|
+
optional string fsUnit = 3;
|
|
255
|
+
optional ImageSet image = 4;
|
|
256
|
+
optional StickerSummary summary = 5;
|
|
257
|
+
optional int32 mode = 6;
|
|
258
|
+
optional bool hasPaid = 7;
|
|
259
|
+
optional string stickerSetId = 8;
|
|
260
|
+
optional string stickerId = 9;
|
|
261
|
+
}
|
|
262
|
+
message PullStickersRequest { optional int32 position = 1; optional int32 count = 2; }
|
|
263
|
+
message PullStickersResponse { repeated StickerRecord stickers = 1; optional int64 updateTime = 2; }
|
|
264
|
+
message PutStickersRequest { repeated StickerRecord stickers = 1; optional int32 addType = 2; repeated string imageKeys = 3; }
|
|
265
|
+
message StickerDuplicate { optional int32 duplicateType = 1; optional string duplicateKey = 2; }
|
|
266
|
+
message PutStickersResponse { repeated StickerRecord stickers = 1; repeated StickerDuplicate dupStickers = 2; }
|
|
267
|
+
message DeleteStickersRequest { repeated StickerRecord stickers = 1; }
|
|
268
|
+
message DeleteStickersResponse { repeated StickerRecord stickers = 1; }
|
|
269
|
+
message PatchStickersRequest { repeated StickerRecord stickers = 1; }
|
|
270
|
+
message PatchStickersResponse { repeated StickerRecord stickers = 1; }
|
|
271
|
+
message StickerContent {
|
|
272
|
+
optional string key = 4; optional int32 width = 5; optional int32 height = 6;
|
|
273
|
+
optional string fsUnit = 8; optional string stickerSetId = 9; optional string stickerId = 10;
|
|
274
|
+
}
|
|
275
|
+
|
|
245
276
|
// For A (hyperlink) elements.
|
|
246
277
|
message AnchorProperty {
|
|
247
278
|
optional string href = 1;
|
|
@@ -625,7 +656,8 @@ message ImageContent {
|
|
|
625
656
|
optional ImageSet image = 1;
|
|
626
657
|
optional ImageSetV2 imageV2 = 2;
|
|
627
658
|
}
|
|
628
|
-
message
|
|
659
|
+
message ImageDetail { optional string key = 1; optional int32 width = 3; optional int32 height = 4; optional int32 size = 10; optional string fsUnit = 11; }
|
|
660
|
+
message ImageSet { optional string key = 1; optional ImageDetail origin = 2; optional ImageDetail thumbnail = 3; optional string imageKey = 4; optional ImageDetail middle = 5; optional ImageDetail thumbnailWebp = 6; }
|
|
629
661
|
message ImageSetV2 { optional string imageKey = 1; }
|
|
630
662
|
|
|
631
663
|
// Personal message-list controls (web gateway).
|
|
@@ -24,6 +24,8 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
|
|
|
24
24
|
|
|
25
25
|
历史消息的 `segments` 保留文本、提及、链接和飞书表情代码,`title` 是带标题消息的标题;`textIncomplete` 表示正文未能完整解析,汇总中的 `incompleteText` 是此类消息数。飞书原生表情在纯文本中以 `:代码:` 表示。
|
|
26
26
|
|
|
27
|
+
单个表情消息的 `resource` 包含表情 ID 和资源键,可用于识别或收藏该表情。
|
|
28
|
+
|
|
27
29
|
`search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
|
|
28
30
|
|
|
29
31
|
使用受限代理或系统用户委托下载时,还须传入目标消息的 `--position`,取值为 `history` 返回的 `position`;执行器会核验消息和资源是否属于授权会话。文件大小受策略的 `maxFileBytes` 限制。
|
|
@@ -25,6 +25,21 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
|
|
|
25
25
|
|
|
26
26
|
使用 `emoji-list` 按名称或代码查询可用的飞书原生表情;`send` 的 `--emoji` 可重复指定,每个 `:代码:` 会转成正文表情。普通 Unicode 表情直接写入文本即可。受限代理和 API key 调用 `emoji-list` 时需要允许该命令和全局访问。
|
|
27
27
|
|
|
28
|
+
个人收藏的单个表情是独立的消息类型,可查询、发送、添加、移除或下载:
|
|
29
|
+
|
|
30
|
+
```sh
|
|
31
|
+
larkmate stickers-list
|
|
32
|
+
larkmate sticker-send --chat "$CHAT_ID" --id "$STICKER_ID"
|
|
33
|
+
larkmate sticker-add --key "$STICKER_KEY"
|
|
34
|
+
larkmate sticker-add-file --file ./sticker.gif
|
|
35
|
+
larkmate sticker-remove --id "$STICKER_ID"
|
|
36
|
+
larkmate sticker-move --id "$STICKER_ID" --position 1
|
|
37
|
+
larkmate sticker-download --id "$STICKER_ID" --output ./sticker.gif
|
|
38
|
+
larkmate stickers-export --output ./my-stickers
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
列表中的 `previewUrl` 可用于识别表情;`history` 的表情消息提供资源键。`sticker-move` 的位置从 1 开始,1 表示置顶;移动前检查收藏是否变化,提交后读回结果。若结果未确认,先查询收藏顺序再决定是否重试。批量导出要求输出目录不存在,保存原文件并生成带格式和结果的 `manifest.json`;`partial` 表示部分下载失败。受限代理或系统用户委托需要分别授权使用的命令,收藏的查询和管理需要 `allowGlobal`,发送还需要目标会话权限;下载和添加本地文件由调用方读写文件,并受 `maxFileBytes` 限制。批量导出需要同时授权 `stickers-list` 和 `sticker-download`。
|
|
42
|
+
|
|
28
43
|
`send-rich` 的 JSON 使用 `segments` 数组,支持文本、链接、用户提及和表情;可选 `title` 用于发送带标题的消息:
|
|
29
44
|
|
|
30
45
|
```json
|
package/src/agent-broker.js
CHANGED
|
@@ -5,12 +5,14 @@ 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
|
+
import { handleFileRequest, brokerUpload, brokerDownload, brokerStickerDownload } from './agent-files.js';
|
|
9
9
|
|
|
10
10
|
// The socket policy is enforced in this process, never by the calling agent.
|
|
11
11
|
// An explicit mapping prevents callers from reaching arbitrary object methods.
|
|
12
12
|
const routes = {
|
|
13
13
|
status: ['client', 'status', 'global'], search: ['client', 'search', 'global'], 'emoji-list': ['client', 'emojiList', 'global'],
|
|
14
|
+
'stickers-list': ['client', 'stickerList', 'global'], 'sticker-add': ['client', 'addSticker', 'global'],
|
|
15
|
+
'sticker-remove': ['client', 'removeSticker', 'global'], 'sticker-move': ['client', 'moveSticker', 'global'], 'sticker-send': ['client', 'sendSticker', 'chatObject'],
|
|
14
16
|
'calendars': ['calendar','calendars','global'], 'calendar-search': ['calendar','searchCalendars','global'],
|
|
15
17
|
'calendar-busy': ['calendar','busy','global'], 'calendar-suggest': ['calendar','suggest','global'],
|
|
16
18
|
'calendar-events': ['calendar','events','global'], 'event-get': ['calendar','event','global'], 'calendar-rooms': ['calendar','rooms','global'],
|
|
@@ -63,15 +65,16 @@ const routes = {
|
|
|
63
65
|
'send-file': ['files', 'upload', 'file'], 'send-image': ['files', 'upload', 'file'],
|
|
64
66
|
'group-avatar-set': ['files', 'upload', 'file'],
|
|
65
67
|
'download-file': ['files', 'download', 'file'],
|
|
68
|
+
'sticker-add-file': ['files', 'upload', 'globalFile'], 'sticker-download': ['files', 'downloadSticker', 'globalFile'],
|
|
66
69
|
};
|
|
67
|
-
const writes = new Set(['send', 'send-rich', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
|
|
70
|
+
const writes = new Set(['send', 'send-rich', 'sticker-add', 'sticker-add-file', 'sticker-remove', 'sticker-move', 'sticker-send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread', 'chat-preferences-set', 'chat-clear-history', 'contact-alias-set', 'contact-note-set', 'group-nickname-set', 'group-avatar-set',
|
|
68
71
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
69
72
|
'group-update', 'group-dissolve', 'group-bot-protection', 'group-settings-set', 'group-admin-add', 'group-admin-remove', 'group-remove', 'group-leave', 'group-owner', 'group-post-set', 'group-link', 'group-request-approve', 'group-request-reject', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
|
|
70
73
|
'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image', 'sidebar-set', 'task-create', 'task-update', 'task-complete', 'task-reopen', 'task-delete', 'event-create', 'event-update', 'event-delete', 'event-share', 'event-reply', 'calendar-create', 'calendar-update', 'calendar-delete', 'calendar-subscribe', 'calendar-unsubscribe']);
|
|
71
74
|
|
|
72
75
|
export function brokerCommands() {
|
|
73
76
|
return Object.entries(routes).map(([command, [, , scope]]) => ({ command,
|
|
74
|
-
scope:
|
|
77
|
+
scope: ['global', 'globalFile'].includes(scope) ? 'global' : scope === 'allMinutes' ? 'global-and-all-minutes'
|
|
75
78
|
: ['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) ? 'global-and-all-chats'
|
|
76
79
|
: scope === 'minute' ? 'minute' : 'chat', mutating: writes.has(command) }));
|
|
77
80
|
}
|
|
@@ -142,6 +145,11 @@ export function authorize(policy, request) {
|
|
|
142
145
|
const args = request.args;
|
|
143
146
|
const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
|
|
144
147
|
if (scope === 'global' && !policy.allowGlobal) denied();
|
|
148
|
+
if (scope === 'globalFile' && (!policy.allowGlobal || args.length !== 1 || !only(args[0], method === 'upload' ? [] : ['stickerId']) || (method === 'downloadSticker' && (typeof args[0].stickerId !== 'string' || !/^[\w.-]{1,200}$/.test(args[0].stickerId))))) denied();
|
|
149
|
+
if (request.command === 'stickers-list' && args.length !== 0) denied();
|
|
150
|
+
if (request.command === 'sticker-add' && (args.length !== 1 || !only(args[0], ['key']))) denied();
|
|
151
|
+
if (request.command === 'sticker-remove' && (args.length !== 1 || !only(args[0], ['stickerId']))) denied();
|
|
152
|
+
if (request.command === 'sticker-move' && (args.length !== 1 || !only(args[0], ['stickerId','position']) || typeof args[0].stickerId !== 'string' || !/^[\w.-]{1,200}$/.test(args[0].stickerId) || !Number.isSafeInteger(args[0].position) || args[0].position < 1)) denied();
|
|
145
153
|
if (['calendar-subscribe', 'calendar-unsubscribe'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].subscribe !== (request.command === 'calendar-subscribe'))) denied();
|
|
146
154
|
if (['group-request-approve', 'group-request-reject'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].approve !== (request.command === 'group-request-approve'))) denied();
|
|
147
155
|
if (['group-admin-add', 'group-admin-remove'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].enabled !== (request.command === 'group-admin-add'))) denied();
|
|
@@ -160,6 +168,7 @@ export function authorize(policy, request) {
|
|
|
160
168
|
if (scope === 'chatObject' || scope === 'send') {
|
|
161
169
|
if (args.length !== 1 || !object(args[0]) || !chatAllowed(args[0].chatId)) denied();
|
|
162
170
|
const keys = scope === 'send' ? (method === 'sendRich' ? ['chatId', 'segments', 'title', 'replyTo', 'replyRoot'] : ['chatId', 'text', 'mentions', 'emojis', 'replyTo', 'replyRoot'])
|
|
171
|
+
: method === 'sendSticker' ? ['chatId', 'stickerId']
|
|
163
172
|
: method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
|
|
164
173
|
: method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
|
|
165
174
|
: method === 'updateGroup' ? ['chatId', 'name', 'description']
|
|
@@ -293,8 +302,9 @@ export async function brokerCall(socketPath, request, tokenFile) {
|
|
|
293
302
|
export function brokerProxy(socketPath, service, getCommand, tokenFile) {
|
|
294
303
|
return new Proxy({}, { get(_target, method) {
|
|
295
304
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
296
|
-
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
|
|
305
|
+
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar', 'addStickerFile'].includes(method)) return options => brokerUpload(socketPath, tokenFile, getCommand(), options);
|
|
297
306
|
if (service === 'client' && method === 'downloadFile') return options => brokerDownload(socketPath, tokenFile, options);
|
|
307
|
+
if (service === 'client' && method === 'downloadSticker') return options => brokerStickerDownload(socketPath, tokenFile, options);
|
|
298
308
|
return (...args) => brokerCall(socketPath, { command: getCommand(), service, method, args }, tokenFile);
|
|
299
309
|
} });
|
|
300
310
|
}
|
package/src/agent-files.js
CHANGED
|
@@ -24,12 +24,16 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
|
|
|
24
24
|
let meta;
|
|
25
25
|
try { meta = JSON.parse(Buffer.from(req.headers['x-larkmate-file'], 'base64url').toString('utf8')); } catch { bad(); }
|
|
26
26
|
command = meta?.command;
|
|
27
|
-
const
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
27
|
+
const stickerUpload = command === 'sticker-add-file', stickerDownload = command === 'sticker-download';
|
|
28
|
+
const upload = ['send-file', 'send-image', 'group-avatar-set', 'sticker-add-file'].includes(command);
|
|
29
|
+
const keys = stickerUpload ? ['command', 'name', 'size'] : stickerDownload ? ['command', 'stickerId']
|
|
30
|
+
: upload ? ['command', 'chatId', 'name', 'size'] : ['command', 'chatId', 'messageId', 'key', 'position'];
|
|
31
|
+
if (!only(meta, keys) || (!upload && !stickerDownload && command !== 'download-file')) bad();
|
|
32
|
+
authorize(policy, { command, service: 'files', method: upload ? 'upload' : stickerDownload ? 'downloadSticker' : 'download',
|
|
33
|
+
args: [stickerUpload ? {} : stickerDownload ? { stickerId: meta.stickerId } : { chatId: meta.chatId }] });
|
|
34
|
+
if (!stickerUpload && !stickerDownload) requireInt64Id(meta.chatId, 'chat ID');
|
|
31
35
|
if (upload) {
|
|
32
|
-
if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (['send-image', 'group-avatar-set'].includes(command) && meta.size > 10 * 1024 * 1024)) bad();
|
|
36
|
+
if (!safeName(meta.name) || !Number.isSafeInteger(meta.size) || meta.size < 1 || meta.size > policy.maxFileBytes || (['send-image', 'group-avatar-set', 'sticker-add-file'].includes(command) && meta.size > 10 * 1024 * 1024)) bad();
|
|
33
37
|
dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
|
|
34
38
|
const path = join(dir, meta.name);
|
|
35
39
|
const file = await open(path, 'wx', 0o600);
|
|
@@ -45,8 +49,19 @@ export async function handleFileRequest({ req, res, policy, getServices, authori
|
|
|
45
49
|
const { client } = await getServices();
|
|
46
50
|
if (res.destroyed) return;
|
|
47
51
|
dispatched = true;
|
|
48
|
-
const data = await client[command === 'send-file' ? 'sendFile' : command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: meta.chatId, path });
|
|
52
|
+
const data = await client[command === 'send-file' ? 'sendFile' : command === 'send-image' ? 'sendImage' : stickerUpload ? 'addStickerFile' : 'setGroupAvatar'](stickerUpload ? { path } : { chatId: meta.chatId, path });
|
|
49
53
|
answer(200, { ok: true, data });
|
|
54
|
+
} else if (stickerDownload) {
|
|
55
|
+
const { client } = await getServices();
|
|
56
|
+
dir = await mkdtemp(join(tmpdir(), 'larkmate-transfer-'));
|
|
57
|
+
const path = join(dir, 'download');
|
|
58
|
+
const result = await client.downloadSticker({ stickerId: meta.stickerId, output: path, maxBytes: policy.maxFileBytes });
|
|
59
|
+
const size = (await stat(path)).size;
|
|
60
|
+
if (size > policy.maxFileBytes || size !== result.bytes) throw new FeishuError('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
|
|
61
|
+
if (res.destroyed) return;
|
|
62
|
+
res.writeHead(200, { 'content-type': 'application/octet-stream', 'content-length': String(size), 'cache-control': 'no-store', 'connection': 'close',
|
|
63
|
+
'x-larkmate-mime': result.mime, 'x-larkmate-extension': result.extension });
|
|
64
|
+
await pipeline(createReadStream(path), res);
|
|
50
65
|
} else {
|
|
51
66
|
requireInt64Id(meta.messageId, 'message ID');
|
|
52
67
|
if (typeof meta.key !== 'string' || !/^[\w.-]{1,200}$/.test(meta.key) || !Number.isInteger(meta.position) || meta.position < 1 || meta.position > 2147483647) bad();
|
|
@@ -142,3 +157,33 @@ export async function brokerDownload(socketPath, tokenFile, { chatId, messageId,
|
|
|
142
157
|
req.end();
|
|
143
158
|
});
|
|
144
159
|
}
|
|
160
|
+
|
|
161
|
+
export async function brokerStickerDownload(socketPath, tokenFile, { stickerId, output }) {
|
|
162
|
+
if (typeof stickerId !== 'string' || !/^[\w.-]{1,200}$/.test(stickerId)) throw new FeishuError('INVALID_ARGUMENT', 'A valid sticker ID is required.');
|
|
163
|
+
if (typeof output !== 'string' || !output.trim()) throw new FeishuError('INVALID_ARGUMENT', 'An output path is required.');
|
|
164
|
+
const token = await loadBrokerToken(tokenFile);
|
|
165
|
+
const req = fileRequest(socketPath, token, { command: 'sticker-download', stickerId });
|
|
166
|
+
return await new Promise((resolve, reject) => {
|
|
167
|
+
let done = false;
|
|
168
|
+
const finish = (error, data) => { if (done) return; done = true; error ? reject(error) : resolve(data); };
|
|
169
|
+
req.on('response', async res => {
|
|
170
|
+
if (res.statusCode !== 200) { try { return finish(await errorResponse(res)); } catch { return finish(new FeishuError('BROKER_INVALID_RESPONSE', 'Invalid broker response.')); } }
|
|
171
|
+
let file, bytes = 0;
|
|
172
|
+
try {
|
|
173
|
+
const length = Number(res.headers['content-length']);
|
|
174
|
+
if (!Number.isSafeInteger(length) || length < 0 || length > MAX) throw new Error('invalid length');
|
|
175
|
+
try { file = await open(output, 'wx', 0o600); }
|
|
176
|
+
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.')); }
|
|
177
|
+
for await (const chunk of res) { bytes += chunk.length; if (bytes > length) throw new Error('too large'); await file.writeFile(chunk); }
|
|
178
|
+
if (bytes !== length) throw new Error('incomplete');
|
|
179
|
+
const extension = ['png','jpg','gif','webp','bin'].includes(res.headers['x-larkmate-extension']) ? res.headers['x-larkmate-extension'] : 'bin';
|
|
180
|
+
const mime = ({png:'image/png',jpg:'image/jpeg',gif:'image/gif',webp:'image/webp',bin:'application/octet-stream'})[extension];
|
|
181
|
+
finish(null, { output, bytes, stickerId, mime, extension });
|
|
182
|
+
} catch { finish(new FeishuError('DOWNLOAD_INCOMPLETE', 'The download stopped; the output file is incomplete.', { output, bytes })); }
|
|
183
|
+
finally { await file?.close(); }
|
|
184
|
+
});
|
|
185
|
+
req.on('timeout', () => req.destroy());
|
|
186
|
+
req.on('error', () => finish(new FeishuError('BROKER_UNAVAILABLE', 'Cannot connect to the broker.')));
|
|
187
|
+
req.end();
|
|
188
|
+
});
|
|
189
|
+
}
|
package/src/client.js
CHANGED
|
@@ -5,6 +5,7 @@ import { downloadFile } from './download.js';
|
|
|
5
5
|
import { randomUUID } from 'node:crypto';
|
|
6
6
|
import { open } from 'node:fs/promises';
|
|
7
7
|
import { buildRichText, readRichText, requireEmojiKey } from './rich-text.js';
|
|
8
|
+
import { Stickers } from './stickers.js';
|
|
8
9
|
|
|
9
10
|
function ids(values, label) {
|
|
10
11
|
if (!Array.isArray(values)) throw new FeishuError('INVALID_ARGUMENT', `${label} must be a list.`);
|
|
@@ -26,6 +27,14 @@ function decodedPayload(gateway, response, type, operation) {
|
|
|
26
27
|
export class LarkMateClient {
|
|
27
28
|
constructor(gateway) { this.gateway = gateway; }
|
|
28
29
|
|
|
30
|
+
async stickerList() { return new Stickers(this.gateway).list(); }
|
|
31
|
+
async sendSticker(options) { return new Stickers(this.gateway).send(options); }
|
|
32
|
+
async addSticker(options) { return new Stickers(this.gateway).add(options); }
|
|
33
|
+
async addStickerFile(options) { return new Stickers(this.gateway).addFile(options); }
|
|
34
|
+
async removeSticker(options) { return new Stickers(this.gateway).remove(options); }
|
|
35
|
+
async moveSticker(options) { return new Stickers(this.gateway).move(options); }
|
|
36
|
+
async downloadSticker(options) { return new Stickers(this.gateway).download(options); }
|
|
37
|
+
|
|
29
38
|
async emojiList({ query } = {}) {
|
|
30
39
|
if (query != null && (typeof query !== 'string' || query.length > 200)) throw new FeishuError('INVALID_ARGUMENT', 'emoji query must be at most 200 characters.');
|
|
31
40
|
const response = await this.gateway.call(142, 'PullEmojiResourcesV2Request', { needUserTenantResources: true, accessType: 1 },
|
|
@@ -338,6 +347,13 @@ export class LarkMateClient {
|
|
|
338
347
|
: { key: content.imageV2?.imageKey || content.image?.imageKey || content.image?.key || null };
|
|
339
348
|
} catch { /* Leave unknown resources unparsed. */ }
|
|
340
349
|
}
|
|
350
|
+
if (message.content?.length && message.type === 10) {
|
|
351
|
+
try {
|
|
352
|
+
const content = this.gateway.decode('StickerContent', message.content);
|
|
353
|
+
resource = { key: content.key || null, stickerId: content.stickerId || null, stickerSetId: content.stickerSetId || null,
|
|
354
|
+
width: content.width || null, height: content.height || null };
|
|
355
|
+
} catch { /* Leave unknown sticker resources unparsed. */ }
|
|
356
|
+
}
|
|
341
357
|
return { id: String(message.id || ''), position: Number(position), rootId: message.rootId || null, parentId: message.parentId || null,
|
|
342
358
|
senderId: message.fromId || '', type: message.type, title, text, segments, textIncomplete,
|
|
343
359
|
createTime: Object.hasOwn(message, 'createTime') ? String(message.createTime) : null, resource };
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { mkdir, writeFile, link, unlink } from 'node:fs/promises';
|
|
2
|
+
import { join } from 'node:path';
|
|
3
|
+
import { FeishuError } from './errors.js';
|
|
4
|
+
|
|
5
|
+
// All file paths remain in the caller process, including for delegated clients.
|
|
6
|
+
export async function exportStickers(client, { output, limit } = {}) {
|
|
7
|
+
if (typeof output !== 'string' || !output.trim()) throw new FeishuError('INVALID_ARGUMENT', 'An output directory is required.');
|
|
8
|
+
if (limit != null && (!Number.isSafeInteger(limit) || limit < 1)) throw new FeishuError('INVALID_ARGUMENT', 'limit must be a positive integer.');
|
|
9
|
+
const collection=await client.stickerList();
|
|
10
|
+
const items=limit == null ? collection.items : collection.items.slice(0,limit);
|
|
11
|
+
try { await mkdir(output,{mode:0o700}); }
|
|
12
|
+
catch(error) { throw new FeishuError('EXPORT_WRITE_FAILED',error.code==='EEXIST'?'Output directory already exists; choose a new path.':'Could not create the output directory.'); }
|
|
13
|
+
const results=new Array(items.length); let next=0;
|
|
14
|
+
const worker=async()=>{while(next<items.length){const index=next++,item=items[index],id=item.id || item.key;
|
|
15
|
+
const name=String(index+1).padStart(4,'0')+'-'+(typeof id==='string'&&/^[\w.-]{1,200}$/.test(id)?id:'unknown');
|
|
16
|
+
const partial=join(output,`${name}.partial`);
|
|
17
|
+
try{const result=await client.downloadSticker({stickerId:id,output:partial});
|
|
18
|
+
const extension=['png','jpg','gif','webp','bin'].includes(result.extension)?result.extension:'bin';
|
|
19
|
+
const filename=`${name}.${extension}`;await link(partial,join(output,filename));await unlink(partial);
|
|
20
|
+
results[index]={...item,status:'saved',file:filename,bytes:result.bytes,mime:result.mime};
|
|
21
|
+
}catch(error){results[index]={...item,status:'failed',error:error.code||'DOWNLOAD_FAILED'};}
|
|
22
|
+
}};
|
|
23
|
+
try {
|
|
24
|
+
await Promise.all(Array.from({length:Math.min(3,items.length)},worker));
|
|
25
|
+
const failed=results.filter(x=>x.status==='failed').length;
|
|
26
|
+
const manifest={version:1,collectionSize:collection.items.length,requested:items.length,saved:items.length-failed,failed,updateTime:collection.updateTime,items:results};
|
|
27
|
+
await writeFile(join(output,'manifest.json'),JSON.stringify(manifest,null,2)+'\n',{flag:'wx',mode:0o600});
|
|
28
|
+
return {status:failed?'partial':'exported',output,collectionSize:collection.items.length,requested:items.length,saved:items.length-failed,failed,manifest:join(output,'manifest.json')};
|
|
29
|
+
} catch(error) { throw new FeishuError('EXPORT_INCOMPLETE','Sticker export did not finish; inspect the output directory.',{output,cause:error.code||'WRITE_FAILED'}); }
|
|
30
|
+
}
|
|
@@ -63,6 +63,11 @@ export async function callOsDelegate({ owner, launcher, request, inputPath, outp
|
|
|
63
63
|
if (spawnError || !parsed) throw unavailable();
|
|
64
64
|
if (outputPath != null) {
|
|
65
65
|
if (bytes !== parsed.size) fail('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
|
|
66
|
+
if (request.command === 'sticker-download') {
|
|
67
|
+
const extension = ['png','jpg','gif','webp','bin'].includes(parsed.extension) ? parsed.extension : 'bin';
|
|
68
|
+
const mime = ({png:'image/png',jpg:'image/jpeg',gif:'image/gif',webp:'image/webp',bin:'application/octet-stream'})[extension];
|
|
69
|
+
return { output: outputPath, bytes, stickerId: request.args[0].stickerId, mime, extension };
|
|
70
|
+
}
|
|
66
71
|
return { output: outputPath, bytes, messageId: request.args[0].messageId };
|
|
67
72
|
}
|
|
68
73
|
return parsed.data;
|
|
@@ -79,9 +84,13 @@ export function osDelegateProxy(owner, launcher, service, getCommand) {
|
|
|
79
84
|
if (method === 'then' || typeof method !== 'string') return undefined;
|
|
80
85
|
return (...args) => {
|
|
81
86
|
const command = getCommand();
|
|
82
|
-
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar'].includes(method)) {
|
|
87
|
+
if (service === 'client' && ['sendFile', 'sendImage', 'setGroupAvatar', 'addStickerFile'].includes(method)) {
|
|
83
88
|
const { chatId, path } = args[0];
|
|
84
|
-
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [{ chatId }] }, inputPath: path });
|
|
89
|
+
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'upload', args: [method === 'addStickerFile' ? {} : { chatId }] }, inputPath: path });
|
|
90
|
+
}
|
|
91
|
+
if (service === 'client' && method === 'downloadSticker') {
|
|
92
|
+
const { stickerId, output } = args[0];
|
|
93
|
+
return callOsDelegate({ owner, launcher, request: { command, service: 'files', method: 'downloadSticker', args: [{ stickerId }] }, outputPath: output });
|
|
85
94
|
}
|
|
86
95
|
if (service === 'client' && method === 'downloadFile') {
|
|
87
96
|
const { chatId, messageId, key, position, output } = args[0];
|
package/src/os-delegate.js
CHANGED
|
@@ -79,14 +79,14 @@ export async function checkDelegation({ profile, uid, request, file }) {
|
|
|
79
79
|
}
|
|
80
80
|
|
|
81
81
|
export async function invokeDelegated({ profile, uid, request, getServices, filePath }) {
|
|
82
|
-
const fileOp = ['send-file', 'send-image', 'group-avatar-set', 'download-file'].includes(request?.command);
|
|
82
|
+
const fileOp = ['send-file', 'send-image', 'group-avatar-set', 'download-file', 'sticker-add-file', 'sticker-download'].includes(request?.command);
|
|
83
83
|
if (fileOp && request.service !== 'files') noAccess();
|
|
84
84
|
if (!fileOp && request.service === 'files') noAccess();
|
|
85
85
|
let file;
|
|
86
|
-
if (['send-file', 'send-image', 'group-avatar-set'].includes(request.command)) {
|
|
86
|
+
if (['send-file', 'send-image', 'group-avatar-set', 'sticker-add-file'].includes(request.command)) {
|
|
87
87
|
if (!filePath || !nameOk(request.fileName)) fail('INVALID_REQUEST', 'Invalid file transfer.');
|
|
88
88
|
const info = await stat(filePath);
|
|
89
|
-
if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (['send-image', 'group-avatar-set'].includes(request.command) && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
|
|
89
|
+
if (!info.isFile() || info.size < 1 || info.size > profile.policy.maxFileBytes || (['send-image', 'group-avatar-set', 'sticker-add-file'].includes(request.command) && info.size > 10 * 1024 * 1024)) fail('FILE_TOO_LARGE', 'The file exceeds the configured limit.');
|
|
90
90
|
const hash = createHash('sha256'); for await (const chunk of createReadStream(filePath)) hash.update(chunk);
|
|
91
91
|
file = { name: request.fileName, size: info.size, sha256: hash.digest('hex') };
|
|
92
92
|
}
|
|
@@ -108,10 +108,10 @@ export async function invokeDelegated({ profile, uid, request, getServices, file
|
|
|
108
108
|
}
|
|
109
109
|
const client = services.client, o = args[0];
|
|
110
110
|
if (method === 'upload') {
|
|
111
|
-
try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : rpc.command === 'send-image' ? 'sendImage' : 'setGroupAvatar']({ chatId: o.chatId, path: filePath }) }; }
|
|
111
|
+
try { return { data: await client[rpc.command === 'send-file' ? 'sendFile' : rpc.command === 'send-image' ? 'sendImage' : rpc.command === 'sticker-add-file' ? 'addStickerFile' : 'setGroupAvatar'](rpc.command === 'sticker-add-file' ? { path: filePath } : { chatId: o.chatId, path: filePath }) }; }
|
|
112
112
|
catch (error) { if (!(error instanceof FeishuError)) fail('EFFECT_UNKNOWN', 'The delegated write could not be confirmed; inspect before retrying.'); throw error; }
|
|
113
113
|
}
|
|
114
|
-
return { download: true, client, options: o };
|
|
114
|
+
return { download: true, client, options: o, command: rpc.command };
|
|
115
115
|
}
|
|
116
116
|
|
|
117
117
|
// The privileged helper parses one framed request and terminates; it never opens a listening socket.
|
|
@@ -128,7 +128,7 @@ export async function serveOne({ input, output, uid, profile, getServices }) {
|
|
|
128
128
|
try { request = JSON.parse(header.subarray(0, end).toString('utf8')); } catch { fail('INVALID_REQUEST', 'Invalid request.'); }
|
|
129
129
|
data = header.subarray(end + 1); header = null;
|
|
130
130
|
if (!only(request, ['command', 'service', 'method', 'args', 'fileName', 'size'])) fail('INVALID_REQUEST', 'Invalid request.');
|
|
131
|
-
const upload = ['send-file', 'send-image', 'group-avatar-set'].includes(request.command);
|
|
131
|
+
const upload = ['send-file', 'send-image', 'group-avatar-set', 'sticker-add-file'].includes(request.command);
|
|
132
132
|
if (upload) {
|
|
133
133
|
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.');
|
|
134
134
|
const { size, fileName, ...rpc } = request;
|
|
@@ -153,15 +153,19 @@ export async function serveOne({ input, output, uid, profile, getServices }) {
|
|
|
153
153
|
outcome = await invokeDelegated({ profile, uid, request: rpc, getServices, filePath: path });
|
|
154
154
|
if (!outcome.download) { output.write(JSON.stringify({ ok: true, data: outcome.data }) + '\n'); return; }
|
|
155
155
|
const o = outcome.options;
|
|
156
|
-
if (
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
156
|
+
if (outcome.command !== 'sticker-download') {
|
|
157
|
+
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.');
|
|
158
|
+
const page = await outcome.client.history({ chatId: o.chatId, start: o.position, limit: 1 });
|
|
159
|
+
const item = page.items?.[0];
|
|
160
|
+
if (!item || item.position !== o.position || item.id !== o.messageId || item.resource?.key !== o.key) noAccess();
|
|
161
|
+
}
|
|
160
162
|
temp = await mkdtemp(join(tmpdir(), 'larkmate-os-transfer-')); path = join(temp, 'download');
|
|
161
|
-
const result =
|
|
163
|
+
const result = outcome.command === 'sticker-download'
|
|
164
|
+
? await outcome.client.downloadSticker({ stickerId: o.stickerId, output: path, maxBytes: profile.policy.maxFileBytes })
|
|
165
|
+
: await outcome.client.downloadFile({ chatId: o.chatId, messageId: o.messageId, key: o.key, output: path, maxBytes: profile.policy.maxFileBytes });
|
|
162
166
|
const info = await stat(path);
|
|
163
167
|
if (info.size !== result.bytes || info.size > profile.policy.maxFileBytes) fail('DOWNLOAD_INCOMPLETE', 'The downloaded file is incomplete.');
|
|
164
|
-
output.write(JSON.stringify({ ok: true, size: info.size }) + '\n');
|
|
168
|
+
output.write(JSON.stringify({ ok: true, size: info.size, ...(outcome.command === 'sticker-download' ? { extension: result.extension } : {}) }) + '\n');
|
|
165
169
|
started = true;
|
|
166
170
|
for await (const chunk of createReadStream(path)) if (!output.write(chunk)) await new Promise(resolve => output.once('drain', resolve));
|
|
167
171
|
} catch (error) {
|
package/src/stickers.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { open } from 'node:fs/promises';
|
|
2
|
+
import { FeishuError, requireInt64Id } from './errors.js';
|
|
3
|
+
import { uploadFile } from './upload.js';
|
|
4
|
+
import { shortId } from './gateway.js';
|
|
5
|
+
|
|
6
|
+
const VERSION = '8.5.0';
|
|
7
|
+
const validKey = key => typeof key === 'string' && /^[\w.-]{1,200}$/.test(key);
|
|
8
|
+
function invalid() { throw new FeishuError('INVALID_ARGUMENT', 'A valid sticker ID or key is required.'); }
|
|
9
|
+
function mimeInfo(head) {
|
|
10
|
+
if (head.subarray(0,8).equals(Buffer.from('89504e470d0a1a0a','hex'))) return { mime:'image/png', extension:'png' };
|
|
11
|
+
if (head.length>=3 && head[0]===0xff && head[1]===0xd8 && head[2]===0xff) return { mime:'image/jpeg', extension:'jpg' };
|
|
12
|
+
if (head.length>=6 && ['GIF87a','GIF89a'].includes(head.subarray(0,6).toString('ascii'))) return { mime:'image/gif', extension:'gif' };
|
|
13
|
+
if (head.length>=12 && head.subarray(0,4).toString('ascii')==='RIFF' && head.subarray(8,12).toString('ascii')==='WEBP') return { mime:'image/webp', extension:'webp' };
|
|
14
|
+
return { mime:'application/octet-stream', extension:'bin' };
|
|
15
|
+
}
|
|
16
|
+
export class Stickers {
|
|
17
|
+
constructor(gateway) { this.gateway=gateway; }
|
|
18
|
+
async rawList() {
|
|
19
|
+
const response=await this.gateway.call(103,'PullStickersRequest',{position:0,count:50},{version:VERSION,operation:'stickers-list'});
|
|
20
|
+
if (!Object.hasOwn(response.packet, 'payload') || response.packet.payload == null) throw new FeishuError('INVALID_RESPONSE','No sticker collection was returned.');
|
|
21
|
+
try { const data=this.gateway.decode('PullStickersResponse',response.packet.payload); return { stickers:data.stickers || [],updateTime:Object.hasOwn(data,'updateTime')?String(data.updateTime):null }; }
|
|
22
|
+
catch { throw new FeishuError('INVALID_RESPONSE','The sticker collection was unreadable.'); }
|
|
23
|
+
}
|
|
24
|
+
async list() {
|
|
25
|
+
const result=await this.rawList();
|
|
26
|
+
return {items:result.stickers.map((s,index)=>({index:index+1,id:s.stickerId || null,key:s.key || null,position:Object.hasOwn(s,'position')?s.position:null,
|
|
27
|
+
mode:s.mode || null,name:s.summary?.i18nTitles?.['zh-CN'] || s.summary?.title || null,width:s.image?.origin?.width || null,height:s.image?.origin?.height || null,
|
|
28
|
+
previewUrl:validKey(s.key)?`https://s3-imfile.feishucdn.com/static-resource/v1/${encodeURIComponent(s.key)}~?image_size=default-small&format=default-small&sticker_format=.webp`:null})),updateTime:result.updateTime};
|
|
29
|
+
}
|
|
30
|
+
async find(id) {
|
|
31
|
+
if (!validKey(id)) invalid();
|
|
32
|
+
const {stickers}=await this.rawList(); const matches=stickers.filter(s=>s.stickerId===id || s.key===id);
|
|
33
|
+
if (matches.length!==1) throw new FeishuError(matches.length?'AMBIGUOUS':'NOT_FOUND',matches.length?'Multiple stickers matched; use their IDs.':'Sticker not found in the current account collection.');
|
|
34
|
+
if (!validKey(matches[0].key)) throw new FeishuError('INVALID_RESPONSE','Sticker resource key was unavailable.');
|
|
35
|
+
return matches[0];
|
|
36
|
+
}
|
|
37
|
+
async send({chatId,stickerId}) {
|
|
38
|
+
requireInt64Id(chatId,'chat ID'); const s=await this.find(stickerId); const cid=shortId();
|
|
39
|
+
const response=await this.gateway.call(5,'PutMessageRequest',{type:10,chatId,cid,isNotified:true,version:1,content:{fileKey:s.key,...(s.stickerId?{stickerId:s.stickerId}:{}),...(s.stickerSetId?{stickerSetId:s.stickerSetId}:{})}},
|
|
40
|
+
{version:VERSION,mutating:true,operation:'sticker-send'});
|
|
41
|
+
let messageId=null;try{if(response.packet.payload?.length){const m=this.gateway.decode('PutMessageResponse',response.packet.payload).message;if(m?.id&&!String(m.id).startsWith('-')&&(!m.chatId||m.chatId===chatId))messageId=String(m.id)}}catch{}
|
|
42
|
+
return {status:messageId?'accepted':'submitted_unconfirmed',chatId,stickerId:s.stickerId||null,messageId,cid,requestId:response.requestId};
|
|
43
|
+
}
|
|
44
|
+
async add({key}) {
|
|
45
|
+
if(!validKey(key)) invalid(); return this.addRequest({stickers:[{key}],addType:1});
|
|
46
|
+
}
|
|
47
|
+
async addFile({path}) {
|
|
48
|
+
const image=await uploadFile(this.gateway,path,{image:true});
|
|
49
|
+
return this.addRequest({imageKeys:[image.key],addType:2});
|
|
50
|
+
}
|
|
51
|
+
async addRequest(body) {
|
|
52
|
+
const response=await this.gateway.call(100,'PutStickersRequest',body,{version:VERSION,mutating:true,operation:'sticker-add'});
|
|
53
|
+
if(!response.packet.payload?.length)return {status:'submitted_unconfirmed',requestId:response.requestId};
|
|
54
|
+
let data;try{data=this.gateway.decode('PutStickersResponse',response.packet.payload)}catch{return {status:'submitted_unconfirmed',requestId:response.requestId}}
|
|
55
|
+
if(data.dupStickers?.length)return {status:'duplicate',requestId:response.requestId};
|
|
56
|
+
const added=data.stickers?.[0];
|
|
57
|
+
return {status:added?.stickerId?'accepted':'submitted_unconfirmed',stickerId:added?.stickerId || null,requestId:response.requestId};
|
|
58
|
+
}
|
|
59
|
+
async remove({stickerId}) {
|
|
60
|
+
const s=await this.find(stickerId);
|
|
61
|
+
const response=await this.gateway.call(101,'DeleteStickersRequest',{stickers:[s]},{version:VERSION,mutating:true,operation:'sticker-remove'});
|
|
62
|
+
try {const after=await this.rawList();if(!after.stickers.some(x=>x.stickerId===s.stickerId && x.key===s.key))return {status:'removed',stickerId:s.stickerId||null,requestId:response.requestId};}catch{}
|
|
63
|
+
return {status:'submitted_unconfirmed',stickerId:s.stickerId||null,requestId:response.requestId};
|
|
64
|
+
}
|
|
65
|
+
async move({stickerId,position}) {
|
|
66
|
+
if (!validKey(stickerId)) invalid();
|
|
67
|
+
if (!Number.isSafeInteger(position) || position < 1) throw new FeishuError('INVALID_ARGUMENT','Position must be a positive integer.');
|
|
68
|
+
const before=await this.rawList(), items=before.stickers;
|
|
69
|
+
if (position>items.length) throw new FeishuError('INVALID_ARGUMENT','Position exceeds the sticker collection size.');
|
|
70
|
+
const matches=items.filter(s=>s.stickerId===stickerId||s.key===stickerId);
|
|
71
|
+
if(matches.length!==1)throw new FeishuError(matches.length?'AMBIGUOUS':'NOT_FOUND',matches.length?'Multiple stickers matched; use their IDs.':'Sticker not found in the current account collection.');
|
|
72
|
+
const ids=items.map(s=>s.stickerId);
|
|
73
|
+
if(ids.some(id=>!validKey(id))||new Set(ids).size!==ids.length)throw new FeishuError('INVALID_RESPONSE','The collection does not have unique sticker IDs; refusing to reorder.');
|
|
74
|
+
if(items.some((s,i)=>!Object.hasOwn(s,'position')||!Number.isInteger(s.position)||s.position<0||(i>0&&items[i-1].position<=s.position))||items.at(-1).position!==0)throw new FeishuError('INVALID_RESPONSE','The complete sticker order could not be established; refusing to reorder.');
|
|
75
|
+
const from=items.indexOf(matches[0]);
|
|
76
|
+
if(from===position-1)return {status:'unchanged',stickerId:matches[0].stickerId,from:from+1,position,total:items.length};
|
|
77
|
+
const desired=[...items];desired.splice(from,1);desired.splice(position-1,0,matches[0]);
|
|
78
|
+
const current=await this.rawList();
|
|
79
|
+
if(JSON.stringify(current.stickers.map(s=>s.stickerId))!==JSON.stringify(ids)||(before.updateTime!==null&¤t.updateTime!==before.updateTime))throw new FeishuError('STICKERS_CHANGED','The sticker collection changed; list it again before reordering.');
|
|
80
|
+
// The legacy gateway requires contiguous descending positions and returns the reverse of the submitted order.
|
|
81
|
+
const stickers=[...desired].reverse().map((s,i)=>({...s,position:desired.length-1-i}));
|
|
82
|
+
const response=await this.gateway.call(102,'PatchStickersRequest',{stickers},{version:VERSION,mutating:true,operation:'sticker-move'});
|
|
83
|
+
try {const after=await this.rawList();if(JSON.stringify(after.stickers.map(s=>s.stickerId))===JSON.stringify(desired.map(s=>s.stickerId)))return {status:'moved',stickerId:matches[0].stickerId,from:from+1,position,total:items.length,requestId:response.requestId};}catch{}
|
|
84
|
+
return {status:'submitted_unconfirmed',stickerId:matches[0].stickerId,from:from+1,position,total:items.length,requestId:response.requestId};
|
|
85
|
+
}
|
|
86
|
+
async download({stickerId,output,maxBytes=100*1024*1024}) {
|
|
87
|
+
if(typeof output!=='string'||!output.trim())throw new FeishuError('INVALID_ARGUMENT','An output path is required.');
|
|
88
|
+
if(!Number.isSafeInteger(maxBytes)||maxBytes<1||maxBytes>100*1024*1024)throw new FeishuError('INVALID_ARGUMENT','Invalid download size limit.');
|
|
89
|
+
const s=await this.find(stickerId);
|
|
90
|
+
const url=`https://s3-imfile.feishucdn.com/static-resource/v1/${encodeURIComponent(s.key)}~`;
|
|
91
|
+
let response;try{response=await this.gateway.fetchImpl(url,{redirect:'manual',headers:{accept:'*/*'},signal:AbortSignal.timeout(this.gateway.timeoutMs)});}catch{throw new FeishuError('DOWNLOAD_FAILED','Could not retrieve the sticker.');}
|
|
92
|
+
if(response.status!==200||!response.body){try{await response.body?.cancel()}catch{}throw new FeishuError('DOWNLOAD_FAILED','Feishu did not return the sticker.',{httpStatus:response.status});}
|
|
93
|
+
let handle;try{handle=await open(output,'wx',0o600)}catch(e){try{await response.body.cancel()}catch{}throw new FeishuError('DOWNLOAD_WRITE_FAILED',e.code==='EEXIST'?'Output file already exists; choose a new path.':'Could not create the output file.')}
|
|
94
|
+
let bytes=0,head=Buffer.alloc(0);
|
|
95
|
+
try {for await(const chunk of response.body){bytes+=chunk.length;if(bytes>maxBytes)throw new FeishuError('FILE_TOO_LARGE','The download exceeds the configured file limit.');if(head.length<12)head=Buffer.concat([head,Buffer.from(chunk).subarray(0,12-head.length)]);await handle.writeFile(chunk)}
|
|
96
|
+
const length=response.headers.get('content-length'),encoding=response.headers.get('content-encoding');
|
|
97
|
+
if(!bytes || (length&&(!encoding||encoding==='identity')&&/^\d+$/.test(length)&&BigInt(bytes)!==BigInt(length)))throw Error('incomplete');
|
|
98
|
+
return {output,bytes,stickerId:s.stickerId||null,...mimeInfo(head)};
|
|
99
|
+
}catch(error){if(error instanceof FeishuError)throw error;throw new FeishuError('DOWNLOAD_INCOMPLETE','Sticker download is incomplete.',{output,bytes})}finally{await handle.close()}
|
|
100
|
+
}
|
|
101
|
+
}
|