larkmate 0.1.9 → 0.1.11
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 +7 -1
- package/bin/larkmate.js +96 -5
- package/bin/os-delegate-helper.js +31 -0
- package/docs/agent-broker.md +1 -1
- package/docs/ai-install.md +3 -1
- package/docs/os-delegation.example.json +21 -0
- package/docs/os-delegation.md +65 -0
- package/package.json +1 -1
- package/proto/lark.proto +41 -0
- package/proto/todo-schema.json +1 -0
- package/skills/larkmate/SKILL.md +5 -2
- package/skills/larkmate/references/chats.md +9 -1
- package/skills/larkmate/references/tasks.md +22 -0
- package/skills/larkmate/references/writes.md +1 -1
- package/src/agent-broker.js +9 -2
- package/src/feed-groups.js +82 -0
- package/src/gateway.js +12 -2
- package/src/os-delegate-client.js +94 -0
- package/src/os-delegate.js +172 -0
- package/src/sidebar-filters.js +80 -0
- package/src/tasks.js +112 -0
package/skills/larkmate/SKILL.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: larkmate
|
|
3
|
-
description: 使用 LarkMate
|
|
3
|
+
description: 使用 LarkMate 以当前飞书网页版用户身份管理会话、搜索与操作消息、收发文件及图片、管理群组和飞书任务,以及查询录制妙记、申请访问权限和导出文字记录。当用户要求使用 LarkMate 或需要执行上述个人飞书操作时使用;不负责飞书文档或日历。
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# LarkMate
|
|
@@ -9,12 +9,15 @@ 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)。
|
|
15
17
|
- 发送与管理消息、文件、图片、表情和收藏,管理群组及成员: [发送与群组](references/writes.md)。
|
|
18
|
+
- 查询和管理飞书任务、任务视图及成员: [飞书任务](references/tasks.md)。
|
|
16
19
|
- 查找录制妙记、导出文字记录、查询或申请访问权限: [录制妙记](references/minutes.md)。
|
|
17
20
|
|
|
18
21
|
命令输出 JSON:成功为 `ok: true`,失败为 `ok: false`,检查退出码和错误信息。飞书网页客户端数字 ID 与开放平台 ID 不同;按实际查询结果选定对象,名称相近时先消歧。列表和搜索有分页或扫描范围,无法读取的内容、缺失结果和权限错误应如实说明。
|
|
19
22
|
|
|
20
|
-
`chat-open`
|
|
23
|
+
`chat-open` 会打开或创建私聊;发送、修改消息、表情、收藏、群组、会话状态、任务及妙记权限申请等命令也会修改数据,请按用户的实际意图操作。写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed` 或部分成功时,先查询实际状态,避免重复提交。不要将消息已发送当作对方已读。
|
|
@@ -7,6 +7,10 @@ larkmate search-messages --query '消息关键词' --cursor "$NEXT_CURSOR"
|
|
|
7
7
|
larkmate chats --limit 50
|
|
8
8
|
larkmate chats --cursor "$NEXT_CURSOR"
|
|
9
9
|
larkmate chats --parent "$BOX_ID"
|
|
10
|
+
larkmate group-query --group unread --pages 3
|
|
11
|
+
larkmate group-query --group at_me --query '关键词'
|
|
12
|
+
larkmate sidebar-list
|
|
13
|
+
larkmate sidebar-set --filter muted --visibility show --position 2
|
|
10
14
|
larkmate chat-info --chat "$CHAT_ID"
|
|
11
15
|
larkmate history --chat "$CHAT_ID" --limit 50 --pages 3
|
|
12
16
|
larkmate message-link --chat "$CHAT_ID" --message "$MESSAGE_ID"
|
|
@@ -20,7 +24,7 @@ larkmate messages-export --chat "$CHAT_ID" --sender "$MEMBER_ID" --after 1700000
|
|
|
20
24
|
|
|
21
25
|
`search-messages` 用于在当前用户可访问的会话范围内进行跨会话搜索,可使用 `nextCursor` 配合相同的查询条件继续翻页;具体搜索范围和结果由飞书服务决定。`message-link` 返回飞书生成的原生消息链接。`download-file` 根据 `history` 返回的资源键将文件或图片下载至新文件,不会覆盖已有文件;若下载中断,输出文件将不完整。`favorites` 用于读取收藏列表首页,其中 `hasMore` 表示可能仍有未返回的收藏。
|
|
22
26
|
|
|
23
|
-
|
|
27
|
+
使用受限代理或系统用户委托下载时,还须传入目标消息的 `--position`,取值为 `history` 返回的 `position`;执行器会核验消息和资源是否属于授权会话。文件大小受策略的 `maxFileBytes` 限制。
|
|
24
28
|
|
|
25
29
|
`messages-export` 会自动向前分页至会话最早位置,并按从新到旧的顺序输出 Markdown 或 JSON Lines。该命令支持 `--sender`、`--query`,以及以 Unix 秒为单位的 `--after` 和 `--before`;筛选范围仅限指定会话。可通过 `--max-pages` 限制页数,导出结束时需检查 `reachedBeginning`、`nextStart`、`nextLimit`、`omittedPositions` 和 `missingTimestamps`。
|
|
26
30
|
|
|
@@ -43,3 +47,7 @@ larkmate label-remove --label "$LABEL_ID" --chat "$CHAT_ID"
|
|
|
43
47
|
```
|
|
44
48
|
|
|
45
49
|
`mark` 对应聊天右键菜单的旗帜“标记”。`read` 会推进到调用时最新可见位置并清除手动未读标记;`unread` 可能把已完成会话放回收件箱。标签创建、重命名和删除分别使用 `label-create`、`label-rename`、`label-delete`,会话成员调整仅支持手动标签。删除标签会删除整个个人标签。
|
|
50
|
+
|
|
51
|
+
`group-query` 支持消息、未读、免打扰、@我、单聊、群组、话题群、云文档、话题和已完成分组;可按名称筛选,使用 `nextCursor` 继续扫描。收纳盒需以 `--parent` 单独查询,`unknownState` 表示无法确定状态的数量。@我通过未读提及消息匹配会话,可能与飞书界面显示不同。标记和标签分别用 `marked`、`labels` 和 `label-chats` 查询。
|
|
52
|
+
|
|
53
|
+
`sidebar-set` 可以显示、隐藏或排序分组,并设置其在消息分组中的展示规则和 @所有人选项;使用 `larkmate sidebar-set --help` 查看参数。修改前先查询当前设置。
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
# 飞书任务
|
|
2
|
+
|
|
3
|
+
`task-center` 查询任务中心及视图;`tasks-list` 支持 mine、followed、all、created、assigned 和 completed 视图。可按关键词搜索、读取、新建、编辑、完成、重开和删除任务。
|
|
4
|
+
|
|
5
|
+
`tasks-list` 使用返回的 `nextCursor` 继续分页;任务列表发生变化时需从头查询。注意 `missing` 和 `serverReportedAllTasks`,不要把服务端未返回的任务当成不存在。
|
|
6
|
+
|
|
7
|
+
```sh
|
|
8
|
+
larkmate task-center
|
|
9
|
+
larkmate tasks-list --scope mine --limit 50
|
|
10
|
+
larkmate tasks-list --scope mine --cursor "$NEXT_CURSOR"
|
|
11
|
+
larkmate task-search --query '关键词'
|
|
12
|
+
larkmate task-get --id "$TASK_ID"
|
|
13
|
+
larkmate task-create --title '任务标题' --description '说明' --due '2026-12-01T18:00:00+08:00' --assignee "$USER_ID" --follower "$FOLLOWER_ID"
|
|
14
|
+
larkmate task-update --id "$TASK_ID" --due '2026-12-02T18:00:00+08:00' --add-assignee "$USER_ID"
|
|
15
|
+
larkmate task-complete --id "$TASK_ID"
|
|
16
|
+
larkmate task-reopen --id "$TASK_ID"
|
|
17
|
+
larkmate task-delete --id "$TASK_ID"
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
开始和截止时间可用毫秒时间戳或 ISO 日期;更新时用 `0` 清除时间。创建支持全天、重复规则、所属清单和积分等选项,使用 `task-create --help` 查看。`--json` 可从调用方本地文件或标准输入读取完整 `todo_entities.InputTask` JSON,提供提醒、子任务、附件引用和自定义字段等高级配置;字段结构参照包内 `proto/todo-schema.json`。常用参数覆盖 JSON 中对应字段。更新支持标题、描述、时间、重复规则、里程碑、积分、负责人和关注人;`--commits-json` 接受高级字段的原生提交数组(`key`、`dataType`、Base64 编码的 `added`/`deleted`),结构参照同一协议文件。高级字段能否使用由飞书接口和当前用户权限决定。
|
|
21
|
+
|
|
22
|
+
写入返回 `EFFECT_UNKNOWN`、`submitted_unconfirmed`、部分成功或拒绝时,先重新读取任务并核对状态,不要盲目重试。任务创建、修改、完成和删除会改变飞书数据,只在用户授权范围内操作。
|
|
@@ -19,7 +19,7 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
|
|
|
19
19
|
|
|
20
20
|
文件须为非空普通文件且不超过 100 MiB。`accepted` 表示服务器返回相应 ID,`submitted_unconfirmed` 表示未可靠确认接收;不确定时先检查实际状态再决定是否重试。
|
|
21
21
|
|
|
22
|
-
|
|
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
|
|
package/src/agent-broker.js
CHANGED
|
@@ -11,6 +11,12 @@ import { handleFileRequest, brokerUpload, brokerDownload } from './agent-files.j
|
|
|
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'],
|
|
14
|
+
'group-query': ['feeds', 'query', 'allChats'],
|
|
15
|
+
'task-center': ['tasks', 'center', 'global'], 'tasks-list': ['tasks', 'list', 'global'],
|
|
16
|
+
'task-search': ['tasks', 'search', 'global'], 'task-get': ['tasks', 'get', 'global'],
|
|
17
|
+
'task-create': ['tasks', 'create', 'global'], 'task-update': ['tasks', 'update', 'global'],
|
|
18
|
+
'task-complete': ['tasks', 'complete', 'global'], 'task-reopen': ['tasks', 'complete', 'global'], 'task-delete': ['tasks', 'delete', 'global'],
|
|
19
|
+
'sidebar-list': ['sidebar', 'list', 'global'], 'sidebar-set': ['sidebar', 'set', 'allChats'],
|
|
14
20
|
'search-messages': ['client', 'searchMessages', 'allChats'], chats: ['client', 'chats', 'allChats'],
|
|
15
21
|
pinned: ['controls', 'pinned', 'allChats'], marked: ['controls', 'marked', 'allChats'],
|
|
16
22
|
labels: ['controls', 'labels', 'allChats'], 'label-chats': ['controls', 'labelChats', 'allChats'],
|
|
@@ -44,7 +50,7 @@ const routes = {
|
|
|
44
50
|
const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
|
|
45
51
|
'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
|
|
46
52
|
'group-update', 'group-dissolve', 'group-bot-protection', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
|
|
47
|
-
'favorite-remove', 'reaction-add', 'reaction-remove', 'minutes-request-access', 'send-file', 'send-image']);
|
|
53
|
+
'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']);
|
|
48
54
|
|
|
49
55
|
export function brokerCommands() {
|
|
50
56
|
return Object.entries(routes).map(([command, [, , scope]]) => ({ command,
|
|
@@ -116,9 +122,10 @@ export function authorize(policy, request) {
|
|
|
116
122
|
const args = request.args;
|
|
117
123
|
const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
|
|
118
124
|
if (scope === 'global' && !policy.allowGlobal) denied();
|
|
125
|
+
if (['task-complete', 'task-reopen'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].completed !== (request.command === 'task-complete'))) denied();
|
|
119
126
|
if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
|
|
120
127
|
if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
|
|
121
|
-
if (scope === 'file' && (args.length !== 1 || !only(args[0], ['chatId']) || !chatAllowed(args[0].chatId))) denied();
|
|
128
|
+
if (scope === 'file' && (args.length !== 1 || !only(args[0], method === 'download' ? ['chatId', 'messageId', 'key', 'position'] : ['chatId']) || !chatAllowed(args[0].chatId))) denied();
|
|
122
129
|
if (['labelTrue', 'labelFalse'].includes(scope) && (args.length !== 3 || args[2] !== (scope === 'labelTrue'))) denied();
|
|
123
130
|
if (['reactionAdd', 'reactionRemove'].includes(scope) && (args.length !== 1 || !only(args[0], ['messageId', 'emoji', 'remove']) || args[0].remove !== (scope === 'reactionRemove'))) denied();
|
|
124
131
|
if (['chatArg', 'chatTrue', 'chatFalse'].includes(scope)) {
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { FeishuError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
const valid = new Set(['messages', 'unread', 'muted', 'at_me', 'p2p', 'group', 'topic_group', 'docs', 'threads', 'done']);
|
|
4
|
+
const numeric = value => typeof value === 'string' && /^\d{1,19}$/.test(value);
|
|
5
|
+
const own = (o, k) => !!o && Object.hasOwn(o, k);
|
|
6
|
+
|
|
7
|
+
export class FeedGroups {
|
|
8
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
9
|
+
async atMessages() {
|
|
10
|
+
const p = await this.gateway.call(96, 'PullUnreadAtMessageIdsRequest', {}, { operation: 'group-query' });
|
|
11
|
+
if (!own(p.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Unread mention data was not returned.');
|
|
12
|
+
const ids = this.gateway.decode('PullUnreadAtMessageIdsResponse', p.packet.payload).messageIds;
|
|
13
|
+
const byChat = new Map(); let missing = 0;
|
|
14
|
+
for (let i = 0; i < ids.length; i += 100) {
|
|
15
|
+
const r = await this.gateway.call(8, 'PullMessagesByIdsRequest', { messageIds: ids.slice(i, i + 100) }, { operation: 'group-query' });
|
|
16
|
+
if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Mention messages were not returned.');
|
|
17
|
+
const messages = this.gateway.decode('PullMessagesByIdsResponse', r.packet.payload).messages;
|
|
18
|
+
for (const id of ids.slice(i, i + 100)) {
|
|
19
|
+
const m = messages[id]; if (!m?.chatId) { missing++; continue; }
|
|
20
|
+
const list = byChat.get(m.chatId) || []; list.push(id); byChat.set(m.chatId, list);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
return { byChat, missing, total: ids.length };
|
|
24
|
+
}
|
|
25
|
+
async page({ group, cursor, parent, limit }) {
|
|
26
|
+
const r = await this.gateway.call(1000, 'PullFeedCardsRequest', { type: group === 'done' ? 2 : 1,
|
|
27
|
+
pullType: cursor ? 2 : 1, count: limit, ...(cursor ? { cursor } : {}), ...(parent ? { parentCardId: parent } : {}) },
|
|
28
|
+
{ operation: 'group-query', version: '5.7.0' });
|
|
29
|
+
if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Feed page was not returned.');
|
|
30
|
+
return this.gateway.decode('PullFeedCardsResponse', r.packet.payload);
|
|
31
|
+
}
|
|
32
|
+
async query({ group, query, limit = 100, pages = 20, cursor, parent } = {}) {
|
|
33
|
+
if (!valid.has(group) || !Number.isInteger(limit) || limit < 1 || limit > 100 || !Number.isInteger(pages) || pages < 1 || pages > 100 ||
|
|
34
|
+
(query != null && typeof query !== 'string') || (cursor != null && !numeric(cursor)) || (parent != null && !numeric(parent))) {
|
|
35
|
+
throw new FeishuError('INVALID_ARGUMENT', 'Invalid group query or pagination.');
|
|
36
|
+
}
|
|
37
|
+
const mention = group === 'at_me' ? await this.atMessages() : null;
|
|
38
|
+
let next = cursor, items = [], boxes = [], scanned = 0, unknown = 0; const seen = new Set();
|
|
39
|
+
for (let i = 0; i < pages; i++) {
|
|
40
|
+
const page = await this.page({ group, cursor: next, parent, limit });
|
|
41
|
+
const settings = {};
|
|
42
|
+
if (group === 'muted') {
|
|
43
|
+
const ids = page.cards.filter(c => c.type === 1).map(c => c.id);
|
|
44
|
+
if (ids.length) {
|
|
45
|
+
const r = await this.gateway.call(62, 'PullChatSettingsRequest', { chatIds: ids }, { operation: 'group-query' });
|
|
46
|
+
if (!own(r.packet, 'payload')) throw new FeishuError('INVALID_RESPONSE', 'Notification settings were not returned.');
|
|
47
|
+
Object.assign(settings, this.gateway.decode('PullChatSettingsResponse', r.packet.payload).chatSettings);
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
for (const card of page.cards) {
|
|
51
|
+
if (card.type === 5) { boxes.push({ id: String(card.id) }); continue; }
|
|
52
|
+
const id = String(card.id), chat = page.chats[id], doc = page.docFeeds[id], thread = page.threads[id];
|
|
53
|
+
let item;
|
|
54
|
+
if (card.type === 1) {
|
|
55
|
+
const count = own(chat, 'newMessageCount') ? chat.newMessageCount : null;
|
|
56
|
+
const manual = card.feedCardField ? (card.feedCardField.markAsUnread?.unread ?? false) : null;
|
|
57
|
+
const unread = count > 0 || manual === true ? true : count === 0 && manual === false ? false : null;
|
|
58
|
+
item = { id, type: ({ 1: 'p2p', 2: 'group', 3: 'topic_group' })[chat?.type] || 'unknown', name: chat?.name || '', unread, unreadCount: count };
|
|
59
|
+
if (group === 'muted') item.muted = own(settings[id], 'isRemind') ? !settings[id].isRemind : null;
|
|
60
|
+
if (mention?.byChat.has(id)) item.atMessageIds = mention.byChat.get(id);
|
|
61
|
+
} else if (card.type === 3) item = { id, type: 'docs', name: doc?.title || '', unreadCount: own(doc, 'newMessageCount') ? doc.newMessageCount : null, url: doc?.url || null };
|
|
62
|
+
else if (card.type === 4) item = { id, type: 'threads', name: thread?.topic || '', chatId: thread?.channelId || null, unreadCount: own(thread, 'newMessageCount') ? thread.newMessageCount : null };
|
|
63
|
+
else continue;
|
|
64
|
+
scanned++;
|
|
65
|
+
if (group === 'unread') {
|
|
66
|
+
const state = item.type === 'docs' || item.type === 'threads' ? (item.unreadCount == null ? null : item.unreadCount > 0) : item.unread;
|
|
67
|
+
if (state == null) { unknown++; continue; } if (!state) continue;
|
|
68
|
+
} else if (group === 'muted') { if (item.muted == null) { unknown++; continue; } if (!item.muted) continue; }
|
|
69
|
+
else if (group === 'at_me') { if (!mention.byChat.has(id)) continue; }
|
|
70
|
+
else if (!['messages', 'done'].includes(group) && item.type !== group) continue;
|
|
71
|
+
if (query && !item.name.toLocaleLowerCase().includes(query.toLocaleLowerCase())) continue;
|
|
72
|
+
items.push(item);
|
|
73
|
+
}
|
|
74
|
+
const cursorValue = own(page, 'nextCursor') && String(page.nextCursor) !== '0' ? String(page.nextCursor) : null;
|
|
75
|
+
if (!cursorValue) { next = null; break; }
|
|
76
|
+
if (seen.has(cursorValue) || cursorValue === next) throw new FeishuError('PAGINATION_INCOMPLETE', 'Feed pagination repeated its cursor.');
|
|
77
|
+
seen.add(cursorValue); next = cursorValue;
|
|
78
|
+
}
|
|
79
|
+
return { group, items, boxes, scanned, unknownState: unknown, nextCursor: next ?? null, complete: next == null,
|
|
80
|
+
...(mention ? { mentionMessages: mention.total, unmappedMentionMessages: mention.missing } : {}) };
|
|
81
|
+
}
|
|
82
|
+
}
|
package/src/gateway.js
CHANGED
|
@@ -1,9 +1,12 @@
|
|
|
1
1
|
import { randomBytes, randomUUID } from 'node:crypto';
|
|
2
2
|
import { fileURLToPath } from 'node:url';
|
|
3
3
|
import protobuf from 'protobufjs';
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
4
5
|
import { FeishuError } from './errors.js';
|
|
5
6
|
|
|
6
7
|
const protoFile = fileURLToPath(new URL('../proto/lark.proto', import.meta.url));
|
|
8
|
+
const todoProtoFile = fileURLToPath(new URL('../proto/todo-schema.json', import.meta.url));
|
|
9
|
+
let todoProtoPromise;
|
|
7
10
|
const defaults = {
|
|
8
11
|
csrf: 'https://internal-api-lark-api.feishu.cn/accounts/csrf',
|
|
9
12
|
user: 'https://internal-api-lark-api.feishu.cn/accounts/web/user',
|
|
@@ -104,7 +107,7 @@ export class Gateway {
|
|
|
104
107
|
}
|
|
105
108
|
|
|
106
109
|
encode(name, data) {
|
|
107
|
-
const type = this.proto.lookupType(name);
|
|
110
|
+
const type = (name.startsWith('todo.') || name.startsWith('todo_entities.') ? this.todoProto : this.proto).lookupType(name);
|
|
108
111
|
const message = type.fromObject(data);
|
|
109
112
|
const error = type.verify(message);
|
|
110
113
|
if (error) throw new FeishuError('PROTOCOL_INPUT_INVALID', `Invalid ${name} payload.`);
|
|
@@ -112,7 +115,7 @@ export class Gateway {
|
|
|
112
115
|
}
|
|
113
116
|
|
|
114
117
|
decode(name, bytes) {
|
|
115
|
-
return this.proto.lookupType(name).decode(bytes);
|
|
118
|
+
return (name.startsWith('todo.') || name.startsWith('todo_entities.') ? this.todoProto : this.proto).lookupType(name).decode(bytes);
|
|
116
119
|
}
|
|
117
120
|
|
|
118
121
|
async uploadRequest(path, body, contentType) {
|
|
@@ -151,8 +154,15 @@ export class Gateway {
|
|
|
151
154
|
return { data, requestId };
|
|
152
155
|
}
|
|
153
156
|
|
|
157
|
+
async ensureTodoProto() {
|
|
158
|
+
todoProtoPromise ||= readFile(todoProtoFile, 'utf8').then(text => protobuf.Root.fromJSON(JSON.parse(text)));
|
|
159
|
+
this.todoProto = await todoProtoPromise;
|
|
160
|
+
return this.todoProto;
|
|
161
|
+
}
|
|
162
|
+
|
|
154
163
|
async call(command, requestType, body, { version = '2.7.0', mutating = false, operation } = {}) {
|
|
155
164
|
await this.authenticate();
|
|
165
|
+
if (requestType.startsWith('todo.')) await this.ensureTodoProto();
|
|
156
166
|
const requestId = randomUUID();
|
|
157
167
|
const packet = this.encode('Packet', {
|
|
158
168
|
payloadType: 1, cmd: command, cid: requestId,
|
|
@@ -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(); }
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { FeishuError } from './errors.js';
|
|
2
|
+
|
|
3
|
+
export const SIDEBAR_FILTERS = Object.freeze({ at_me: 1, unread: 2, delayed: 3, docs: 4, p2p: 5, group: 6, bot: 7,
|
|
4
|
+
help_desk: 8, topic_group: 9, done: 10, crypto_chat: 11, muted: 12, labels: 13, team: 14, marked: 15,
|
|
5
|
+
threads: 16, unread_over_days: 17, calendar_meetings: 18, instant_meetings: 19, messages: 25, expired_fold: 26 });
|
|
6
|
+
const byId = Object.fromEntries(Object.entries(SIDEBAR_FILTERS).map(([name, id]) => [id, name]));
|
|
7
|
+
const rules = { always: 1, new: 2, never: 3 };
|
|
8
|
+
const msgTypes = { all: 1, at_me: 2, at_all: 3, star_contacts: 4 };
|
|
9
|
+
const invalid = () => { throw new FeishuError('INVALID_ARGUMENT', 'Invalid sidebar filter or settings.'); };
|
|
10
|
+
const idFor = input => typeof input === 'string' && Object.hasOwn(SIDEBAR_FILTERS, input) ? SIDEBAR_FILTERS[input] : /^\d+$/.test(String(input)) && Number(input) > 0 && Number(input) <= 2147483647 ? Number(input) : invalid();
|
|
11
|
+
|
|
12
|
+
export class SidebarFilters {
|
|
13
|
+
constructor(gateway) { this.gateway = gateway; }
|
|
14
|
+
async raw() {
|
|
15
|
+
const res = await this.gateway.call(7022, 'PullSidebarFilterSettingRequest', { needAllFilters: true }, { operation: 'sidebar-list' });
|
|
16
|
+
if (!res.packet.payload?.length) throw new FeishuError('INVALID_RESPONSE', 'No sidebar settings were returned.');
|
|
17
|
+
let p; try { p = this.gateway.decode('PullSidebarFilterSettingResponse', res.packet.payload); } catch { throw new FeishuError('INVALID_RESPONSE', 'Sidebar settings were unreadable.'); }
|
|
18
|
+
if (!p.setting || !Array.isArray(p.setting.usedFilters)) throw new FeishuError('INVALID_RESPONSE', 'Sidebar filter settings were absent.');
|
|
19
|
+
return p;
|
|
20
|
+
}
|
|
21
|
+
view(p) {
|
|
22
|
+
const used = p.setting.usedFilters.map(x => x.systemFilter);
|
|
23
|
+
const available = [...new Set([...used, ...p.allFilters.map(x => x.systemFilter)])].filter(x => Number.isInteger(x) && x > 0);
|
|
24
|
+
const display = p.setting.filterDisplayFeedRule || {};
|
|
25
|
+
return { items: available.map(id => ({ id, name: byId[id] || `unknown_${id}`, shown: used.includes(id),
|
|
26
|
+
position: used.includes(id) ? used.indexOf(id) + 1 : null,
|
|
27
|
+
displayRule: display[id] ? { mainRule: display[id].mainRule ?? null, msgTypes: display[id].msgTypes || [] } : null })),
|
|
28
|
+
showFilter: p.setting.showFilter ?? null, showMuteFilter: p.setting.showMuteFilter ?? null,
|
|
29
|
+
showAtAllInAtFilter: p.setting.showAtAllInAtFilter ?? null, flagSortingRule: p.setting.flagSortingRule ?? null, commonlyUsedFilters: p.setting.commonlyUsedFilters?.map(x => x.systemFilter) || [], version: p.setting.version?.toString() ?? null };
|
|
30
|
+
}
|
|
31
|
+
async list() { return this.view(await this.raw()); }
|
|
32
|
+
async set({ filter, visibility, position, display, messageTypes, atAll, showFilter, showMuteFilter, flagSortingRule, commonlyUsedFilters }) {
|
|
33
|
+
const id = idFor(filter);
|
|
34
|
+
if (visibility != null && !['show', 'hide'].includes(visibility)) invalid();
|
|
35
|
+
if (position != null && (!Number.isInteger(position) || position < 1)) invalid();
|
|
36
|
+
if (display != null && !Object.hasOwn(rules, display)) invalid();
|
|
37
|
+
if (messageTypes != null && (!Array.isArray(messageTypes) || messageTypes.some(x => !Object.hasOwn(msgTypes, x)) || new Set(messageTypes).size !== messageTypes.length)) invalid();
|
|
38
|
+
if (messageTypes != null && display == null) invalid();
|
|
39
|
+
if (atAll != null && typeof atAll !== 'boolean') invalid();
|
|
40
|
+
if (atAll != null && id !== SIDEBAR_FILTERS.at_me) invalid();
|
|
41
|
+
if ([showFilter, showMuteFilter].some(x => x != null && typeof x !== 'boolean')) invalid();
|
|
42
|
+
if (flagSortingRule != null && (!Number.isInteger(flagSortingRule) || flagSortingRule < 0 || flagSortingRule > 2147483647)) invalid();
|
|
43
|
+
if (commonlyUsedFilters != null && (!Array.isArray(commonlyUsedFilters) || new Set(commonlyUsedFilters.map(idFor)).size !== commonlyUsedFilters.length)) invalid();
|
|
44
|
+
if (visibility == null && position == null && display == null && atAll == null && showFilter == null && showMuteFilter == null && flagSortingRule == null && commonlyUsedFilters == null) invalid();
|
|
45
|
+
const before = await this.raw(), available = new Set([...before.allFilters, ...before.setting.usedFilters].map(x => x.systemFilter));
|
|
46
|
+
if (!available.has(id)) invalid();
|
|
47
|
+
let ids = before.setting.usedFilters.map(x => x.systemFilter);
|
|
48
|
+
if (new Set(ids).size !== ids.length) throw new FeishuError('INVALID_RESPONSE', 'Sidebar order contains duplicates.');
|
|
49
|
+
const fields = [], request = { clientSupportVersion: before.setting.version?.toString() || '0' };
|
|
50
|
+
if (visibility != null || position != null) {
|
|
51
|
+
if (visibility === 'hide') ids = ids.filter(x => x !== id);
|
|
52
|
+
if (visibility === 'show' && !ids.includes(id)) ids.push(id);
|
|
53
|
+
if (position != null) {
|
|
54
|
+
if (!ids.includes(id) || position > ids.length) invalid();
|
|
55
|
+
ids = ids.filter(x => x !== id); ids.splice(position - 1, 0, id);
|
|
56
|
+
}
|
|
57
|
+
request.usedFilters = ids.map(systemFilter => ({ systemFilter })); fields.push(2);
|
|
58
|
+
}
|
|
59
|
+
let selectedMessageTypes;
|
|
60
|
+
if (display != null) {
|
|
61
|
+
selectedMessageTypes = messageTypes ? messageTypes.map(x => msgTypes[x]) : [...(before.setting.filterDisplayFeedRule?.[id]?.msgTypes || [])];
|
|
62
|
+
request.filterDisplayFeedRule = { ...before.setting.filterDisplayFeedRule,
|
|
63
|
+
[id]: { mainRule: rules[display], msgTypes: selectedMessageTypes } }; fields.push(8);
|
|
64
|
+
}
|
|
65
|
+
if (atAll != null) { request.showAtAllInAtFilter = atAll; fields.push(5); }
|
|
66
|
+
if (showFilter != null) { request.showFilter = showFilter; fields.push(1); }
|
|
67
|
+
if (showMuteFilter != null) { request.showMuteFilter = showMuteFilter; fields.push(3); }
|
|
68
|
+
if (flagSortingRule != null) { request.flagSortingRule = flagSortingRule; fields.push(7); }
|
|
69
|
+
if (commonlyUsedFilters != null) { const common = commonlyUsedFilters.map(idFor); if (common.some(x => !available.has(x))) invalid(); request.commonlyUsedFilters = common.map(systemFilter => ({ systemFilter })); fields.push(6); }
|
|
70
|
+
request.updateFields = fields;
|
|
71
|
+
await this.gateway.call(7023, 'PutSidebarFilterSettingRequest', request, { mutating: true, operation: 'sidebar-set' });
|
|
72
|
+
let after; try { after = await this.raw(); } catch { return { status: 'submitted_unconfirmed', filter: id }; }
|
|
73
|
+
const view = this.view(after), item = view.items.find(x => x.id === id);
|
|
74
|
+
const orderOk = !fields.includes(2) || JSON.stringify(after.setting.usedFilters.map(x => x.systemFilter)) === JSON.stringify(ids);
|
|
75
|
+
const displayOk = display == null || (item?.displayRule?.mainRule === rules[display] && JSON.stringify(item.displayRule.msgTypes) === JSON.stringify(selectedMessageTypes));
|
|
76
|
+
const atAllOk = atAll == null || view.showAtAllInAtFilter === atAll;
|
|
77
|
+
const extraOk = (showFilter == null || view.showFilter === showFilter) && (showMuteFilter == null || view.showMuteFilter === showMuteFilter) && (flagSortingRule == null || view.flagSortingRule === flagSortingRule) && (commonlyUsedFilters == null || JSON.stringify(view.commonlyUsedFilters) === JSON.stringify(commonlyUsedFilters.map(idFor)));
|
|
78
|
+
return { status: orderOk && displayOk && atAllOk && extraOk ? 'updated' : 'submitted_unconfirmed', filter: item };
|
|
79
|
+
}
|
|
80
|
+
}
|