larkmate 0.1.13 → 0.1.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -53,11 +53,13 @@ npx --registry=https://registry.npmjs.org/ skills add NWYLZW/larkmate --skill la
53
53
  - [x] 给消息添加和取消表情回应
54
54
  - [x] 获取消息链接
55
55
  - 群聊
56
- - [x] 查询群信息和成员
57
- - [x] 修改群名称和介绍、解散群聊
58
- - [x] 邀请成员和机器人
59
- - [x] 查询和设置机器人的移除限制
60
- - [ ] 移除成员或退出群聊
56
+ - [x] 查询群信息、成员、管理员和入退群记录
57
+ - [x] 邀请、移除成员,退出或解散群聊
58
+ - [x] 管理员设置和群主转让
59
+ - [x] 查询和调整入群审批、发言、邀请及其他群设置
60
+ - [x] 创建群邀请链接,查询和处理入群申请
61
+ - [x] 查询群公告、查询和设置机器人的移除限制
62
+ - [ ] 修改群公告
61
63
  - 飞书任务
62
64
  - [x] 查询任务中心与任务视图,按关键词搜索任务
63
65
  - [x] 新建、编辑、完成、重开和删除任务
package/bin/larkmate.js CHANGED
@@ -14,10 +14,11 @@ import { SidebarFilters } from '../src/sidebar-filters.js';
14
14
  import { FeedGroups } from '../src/feed-groups.js';
15
15
  import { Tasks } from '../src/tasks.js';
16
16
  import { Calendar } from '../src/calendar.js';
17
+ import { GroupManagement, groupSettingsSchema } from '../src/group-management.js';
17
18
 
18
19
  const defaultTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
19
20
  const program = new Command();
20
- program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.13');
21
+ program.name('larkmate').description('Operate Feishu as the logged-in user.').version('0.1.14');
21
22
  program.option('--credentials-file <path>', 'read LarkMate credentials.json');
22
23
  program.option('--broker <path>', 'use a restricted local broker socket (or LARKMATE_BROKER)');
23
24
  program.option('--broker-token-file <path>', 'read the agent token (or LARKMATE_BROKER_TOKEN_FILE)');
@@ -73,6 +74,7 @@ async function sidebar() {
73
74
  return new SidebarFilters(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) }));
74
75
  }
75
76
 
77
+ async function groups() { const remote = proxy('groups'); return remote || new GroupManagement(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
76
78
  async function calendar() { const remote = proxy('calendar'); return remote || new Calendar(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
77
79
  async function feeds() { const remote = proxy('feeds'); return remote || new FeedGroups(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
78
80
  async function tasks() { const remote = proxy('tasks'); return remote || new Tasks(new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) })); }
@@ -111,7 +113,7 @@ program.command('broker-serve').description('Start a restricted local agent brok
111
113
  let promise;
112
114
  const getServices = () => promise ||= (async () => {
113
115
  const gateway = new Gateway({ cookie: await loadCookie({ file: program.opts().credentialsFile }) });
114
- return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway) };
116
+ return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
115
117
  })().catch(error => { promise = undefined; throw error; });
116
118
  const broker = await startBroker({ socketPath: o.socket, policy, token, getServices });
117
119
  output({ status: 'listening', socket: broker.socketPath });
@@ -429,6 +431,33 @@ program.command('favorites').description('Read the first page of your favorite m
429
431
  .option('--limit <number>', 'maximum items, 1 to 100', '50')
430
432
  .action(async o => output(await (await client()).favorites({ limit: Number(o.limit) })));
431
433
 
434
+ program.command('group-link').description('Create a group invitation link.').requiredOption('--chat <id>').option('--days <number>','validity days','7').option('--unlimited','no expiration')
435
+ .action(async o=>output(await (await groups()).link({chatId:o.chat,days:Number(o.days),unlimited:!!o.unlimited})));
436
+ program.command('group-requests').description('List pending or processed join applications.').requiredOption('--chat <id>').option('--cursor <cursor>','page cursor','0')
437
+ .action(async o=>output(await (await groups()).requests({chatId:o.chat,cursor:o.cursor})));
438
+ for(const [command,approve] of [['group-request-approve',true],['group-request-reject',false]])program.command(command).description('Review a group join application.').requiredOption('--chat <id>').requiredOption('--user <id>')
439
+ .action(async o=>output(await (await groups()).reviewRequest({chatId:o.chat,userId:o.user,approve})));
440
+ program.command('group-post-users').description('List the group posting whitelist.').requiredOption('--chat <id>').action(async o=>output(await (await groups()).postUsers({chatId:o.chat})));
441
+ program.command('group-settings-schema').description('Show supported group settings and values.').action(()=>output(groupSettingsSchema()));
442
+ program.command('group-settings').description('Read group permissions, owner and announcement.').requiredOption('--chat <id>')
443
+ .action(async o=>output(await (await groups()).info({chatId:o.chat})));
444
+ program.command('group-settings-set').description('Update group permissions and other settings.').requiredOption('--chat <id>').requiredOption('--json <path>','settings JSON or - for stdin')
445
+ .action(async o=>output(await (await groups()).setSettings({chatId:o.chat,settings:await readJson(o.json,{})})));
446
+ program.command('group-admins').description('List group administrators.').requiredOption('--chat <id>').action(async o=>output(await (await groups()).admins({chatId:o.chat})));
447
+ for(const [command,enabled] of [['group-admin-add',true],['group-admin-remove',false]])program.command(command).description('Change group administrators.').requiredOption('--chat <id>')
448
+ .requiredOption('--user <id>','repeatable user ID',collect,[]).action(async o=>output(await (await groups()).setAdmins({chatId:o.chat,userIds:o.user,enabled})));
449
+ program.command('group-remove').description('Remove members from a group.').requiredOption('--chat <id>').requiredOption('--member <id>','repeatable member ID',collect,[])
450
+ .action(async o=>output(await (await groups()).remove({chatId:o.chat,userIds:o.member})));
451
+ program.command('group-leave').description('Leave a group as the current user.').requiredOption('--chat <id>').option('--new-owner <id>','transfer ownership if required')
452
+ .action(async o=>output(await (await groups()).leave({chatId:o.chat,newOwnerId:o.newOwner})));
453
+ program.command('group-owner').description('Transfer ownership of a group.').requiredOption('--chat <id>').requiredOption('--user <id>','new owner user ID')
454
+ .action(async o=>output(await (await groups()).setOwner({chatId:o.chat,userId:o.user})));
455
+ program.command('group-post-set').description('Set who can send messages in a group.').requiredOption('--chat <id>').requiredOption('--mode <mode>','anyone, admin or whitelist')
456
+ .option('--add-user <id>','repeatable user ID',collect,[]).option('--remove-user <id>','repeatable user ID',collect,[])
457
+ .action(async o=>output(await (await groups()).setPost({chatId:o.chat,mode:o.mode,addUsers:o.addUser,removeUsers:o.removeUser})));
458
+ program.command('group-join-history').description('Read group join and leave history.').requiredOption('--chat <id>').option('--cursor <cursor>').option('--limit <number>','page size','20')
459
+ .action(async o=>output(await (await groups()).history({chatId:o.chat,cursor:o.cursor,count:Number(o.limit)})));
460
+
432
461
  program.command('group-create').description('Create a group as the user.')
433
462
  .requiredOption('--name <name>', 'group name')
434
463
  .option('--description <text>', 'group description')
@@ -12,6 +12,7 @@ import { SidebarFilters } from '../src/sidebar-filters.js';
12
12
  import { FeedGroups } from '../src/feed-groups.js';
13
13
  import { Tasks } from '../src/tasks.js';
14
14
  import { Calendar } from '../src/calendar.js';
15
+ import { GroupManagement, groupSettingsSchema } from '../src/group-management.js';
15
16
 
16
17
  try {
17
18
  const caller = process.env.SUDO_UID, owner = process.getuid?.();
@@ -22,7 +23,7 @@ try {
22
23
  let services;
23
24
  const getServices = () => services ||= (async () => {
24
25
  const gateway = new Gateway({ cookie: await loadCookie({ file: config.credentialsFile }) });
25
- return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway) };
26
+ return { client: new LarkMateClient(gateway), controls: new SessionControls(gateway), minutes: new Minutes(gateway), sidebar: new SidebarFilters(gateway), feeds: new FeedGroups(gateway), tasks: new Tasks(gateway), calendar: new Calendar(gateway), groups: new GroupManagement(gateway) };
26
27
  })();
27
28
  await serveOne({ input: process.stdin, output: process.stdout, uid: caller, profile, getServices });
28
29
  } catch (error) {
@@ -47,7 +47,7 @@ LarkMate 可以由持有 Cookie 的账户启动本地代理,再让 Agent 使
47
47
 
48
48
  运行 `larkmate broker-commands` 可查看代理支持的全部命令、各自所需的授权范围和是否修改数据。
49
49
 
50
- 按会话限制时,可授权 `chat-info`、`chat-state`、`history`、`messages-export`、`group-members`、`group-bot-info`、`group-update`、`group-dissolve`、`send` 以及会话状态操作:`pin`、`unpin`、`mark`、`unmark`、`mute`、`unmute`、`done`、`inbox`、`box`、`unbox`、`read`、`unread`。其中,`send` 在受限会话配置下仅支持普通文本,不支持 @ 或引用回复。
50
+ 按会话限制时,可授权 `chat-info`、`chat-state`、`history`、`messages-export`、`group-members`、`group-settings`、`group-admins`、`group-join-history`、`group-requests`、`group-post-users`、`group-update`、`group-dissolve`、`send` 以及会话状态操作:`pin`、`unpin`、`mark`、`unmark`、`mute`、`unmute`、`done`、`inbox`、`box`、`unbox`、`read`、`unread`。其中,`send` 在受限会话配置下仅支持普通文本,不支持 @ 或引用回复。群成员移除、退群、群主转让、管理员设置、入群审批、发言权限、群设置和生成邀请链接也可分别授权,并受 `chatIds` 限制。`group-settings-set` 可改变群的多种权限和公开设置,`group-link` 可生成允许他人入群的链接,应仅按需授权。
51
51
 
52
52
  `minutes-export`、`minutes-access-info` 和 `minutes-request-access` 按 `minuteTokens` 限制;申请权限会向妙记所有者提交请求。`minutes-list` 除须在 `allow` 中授权外,还必须同时开启 `allowGlobal` 和 `allowAllMinutes`。
53
53
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "larkmate",
3
- "version": "0.1.13",
3
+ "version": "0.1.14",
4
4
  "description": "A small, user-identity Feishu CLI with a modular gateway client",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",
package/proto/lark.proto CHANGED
@@ -286,14 +286,28 @@ message PatchGroupChatRequest {
286
286
  optional int64 chatId = 1;
287
287
  optional string name = 2;
288
288
  optional string description = 4;
289
+ optional string announcement = 5;
290
+ optional int64 ownerId = 6;
291
+ optional bool offEditInfo = 14;
292
+ optional GroupEntitySetting entitySetting = 16;
293
+ repeated int32 updateEntitySettingFields = 17 [packed=false];
289
294
  optional bool isDissolved = 18;
295
+ optional bool isPublicV2 = 19;
296
+ optional GroupGeneralSetting generalSetting = 21;
297
+ repeated int32 updateGeneralSettingFields = 22 [packed=false];
290
298
  repeated UpdateFields updateFields = 999;
291
299
 
292
300
  enum UpdateFields {
293
301
  UPDATE_FIELDS_UNSPECIFIED = 0;
294
302
  NAME = 1;
295
303
  DESCRIPTION = 3;
304
+ ANNOUNCEMENT = 4;
305
+ OWNER_ID = 5;
306
+ OFF_EDIT_INFO = 14;
307
+ ENTITY_SETTING = 15;
296
308
  IS_DISSOLVED = 16;
309
+ IS_PUBLIC_V2 = 23;
310
+ GENERAL_CHAT_SETTING = 41;
297
311
  }
298
312
  }
299
313
 
@@ -343,12 +357,20 @@ message Chat {
343
357
  optional int32 lastMessagePosition = 15;
344
358
  optional int32 userCount = 16;
345
359
  optional int64 createTime = 18;
360
+ optional int32 role = 20;
361
+ optional bool offEditGroupChatInfo = 23;
346
362
  optional string tenantId = 25;
363
+ optional GroupEntitySetting chatEntitySetting = 28;
347
364
  optional bool isDissolved = 30;
348
365
  optional string lastVisibleMessageId = 32;
349
366
  optional int32 readPosition = 48;
350
367
  optional int32 lastVisibleMessagePosition = 46;
351
368
  optional bool isCrossTenant = 41;
369
+ optional bool isPublicV2 = 109;
370
+ optional int32 postType = 110;
371
+ optional bool allowPost = 111;
372
+ optional bool isAdmin = 126;
373
+ optional GroupGeneralSetting chatGeneralSetting = 136;
352
374
  optional Announcement announcement = 24;
353
375
 
354
376
  enum ChatTypeEnum {
@@ -647,3 +669,43 @@ message PullUnreadAtMessageIdsRequest { optional int32 version = 1; repeated int
647
669
  message PullUnreadAtMessageIdsResponse { repeated string messageIds = 1; map<string, string> messageThreadIds = 2; }
648
670
  message PullMessagesByIdsRequest { repeated string messageIds = 1; }
649
671
  message PullMessagesByIdsResponse { map<string, MessageEntity> messages = 1; }
672
+
673
+ // Group membership and management over the personal-user gateway.
674
+ message DeleteChatChatterRequest { optional string chatId = 1; repeated string chatterIds = 2; optional string newOwnerId = 3; optional DeleteChatChatterOption option = 4; }
675
+ message DeleteChatChatterOption { optional bool withdraw = 1; }
676
+ message DeleteChatChatterResponse { optional Chat chat = 1; optional int64 chatChatterVersion = 2; optional int64 syncCursor = 3; }
677
+ message GroupAdminUser { optional int64 userId = 1; optional int64 orderWeight = 2; }
678
+ message PullChatAdminUsersRequest { optional string chatId = 1; }
679
+ message PullChatAdminUsersResponse { repeated GroupAdminUser adminUsers = 1; optional int64 updateVersion = 2; }
680
+ message PatchChatAdminUsersRequest { optional string chatId = 1; repeated string toAddUserIds = 2; repeated string toDelUserIds = 3; }
681
+ message PatchChatAdminUsersResponse { repeated GroupAdminUser users = 1; optional int64 updateVersion = 3; }
682
+ message PatchChatPostUserRequest { optional string chatId = 1; optional int32 postType = 2; repeated string toAddUserIds = 3; repeated string toDelUserIds = 4; }
683
+ message PatchChatPostUserResponse {}
684
+ message PullChatJoinLeaveHistoryRequest { optional int64 chatId = 1; optional int64 cursor = 2; optional int32 count = 3; }
685
+ message PullChatJoinLeaveHistoryResponse { repeated GroupMembershipHistory chatterHistory = 1; optional bool hasMore = 2; optional string nextCursor = 3; }
686
+ message GroupMembershipHistory { optional string id = 1; optional int32 action = 2; optional int32 event = 3; optional string chatterId = 4; optional string chatId = 5; optional int64 createTime = 6; optional int32 chatterType = 8; }
687
+ message GroupEntitySetting {
688
+ optional int32 addMemberPermissionSetting = 1; optional int32 atAllPermissionSetting = 2;
689
+ optional int32 joinMessageVisibleSetting = 3; optional int32 quitMessageVisibleSetting = 4;
690
+ optional int32 shareCardPermissionSetting = 5; optional int32 addMemberApplySetting = 6;
691
+ optional int32 threadAnonymousSetting = 7; optional int32 messageVisibilitySetting = 8;
692
+ optional GroupAnonymousSetting anonymousSetting = 9; optional int32 createUrgentSetting = 10;
693
+ optional int32 createVideoConferenceSetting = 11; optional int32 pinPermissionSetting = 12;
694
+ optional int32 topNoticePermissionSetting = 13; optional int32 chatTabPermissionSetting = 14;
695
+ optional int32 chatDisplayModeSetting = 15; optional int32 adminPostSetting = 16;
696
+ optional int32 chatPinPermissionSetting = 17; optional int32 userCountVisibleSetting = 18;
697
+ }
698
+ message GroupAnonymousSetting { optional bool isAllowAnonymous = 1; optional bool isVisible = 2; }
699
+ message GroupGeneralSetting { optional GroupRestrictedMode restrictedModePermissionSetting = 1; optional int32 defDisplaySetting = 2; }
700
+ message GroupRestrictedMode { optional bool status = 1; optional int32 transmitPermissionSetting = 2; optional int32 copyPermissionSetting = 3; optional int32 downloadPermissionSetting = 4; optional int32 screenshotPermissionSetting = 5; optional GroupAutoDelete onTimeDelMsgPermissionSetting = 6; optional GroupWhitelist whiteListSetting = 7; }
701
+ message GroupAutoDelete { optional bool status = 1; optional int64 aliveTime = 2; }
702
+ message GroupWhitelist { optional int32 level = 1; repeated int64 addUserIds = 2 [packed=false]; repeated int64 delUserIds = 3 [packed=false]; repeated int64 userIds = 4 [packed=false]; optional bool hitWhitelist = 5; }
703
+ message PullChatPostUserByChatIDRequest { optional string chatId = 1; }
704
+ message PullChatPostUserByChatIDResponse { repeated string userIds = 1; }
705
+ message PullChatLinkTokenRequest { optional string chatId = 1; optional int32 expiredDay = 2; optional string appName = 3; optional bool isUnlimited = 4; optional int32 targetScene = 5; }
706
+ message PullChatLinkTokenResponse { optional string token = 1; optional int64 expireTime = 2; optional string sharedUrl = 3; optional string kouLing = 4; optional bool isUnlimited = 5; }
707
+ message GroupJoinApplication { optional string reason = 1; optional int32 status = 2; optional int64 time = 3; optional int32 applyWays = 4; optional string inviterId = 5; optional string inviteeId = 6; optional string joinToken = 7; optional int64 teamId = 8; optional string teamName = 9; }
708
+ message PullAddChatChatterApplyRequest { optional string chatId = 1; optional int64 cursor = 2; }
709
+ message PullAddChatChatterApplyResponse { repeated GroupJoinApplication applies = 1; optional int64 nextCursor = 2; }
710
+ message PatchAddChatChatterApplyRequest { optional string chatId = 1; optional bool showBanner = 2; optional string inviteeId = 3; optional int32 status = 4; }
711
+ message PatchAddChatChatterApplyResponse {}
@@ -27,6 +27,11 @@ larkmate favorite-remove --favorite "$FAVORITE_ID"
27
27
 
28
28
  ```sh
29
29
  larkmate group-members --chat "$CHAT_ID"
30
+ larkmate group-settings --chat "$CHAT_ID"
31
+ larkmate group-settings-schema
32
+ larkmate group-admins --chat "$CHAT_ID"
33
+ larkmate group-join-history --chat "$CHAT_ID"
34
+ larkmate group-requests --chat "$CHAT_ID"
30
35
  larkmate group-create --name '群名称' --member "$MEMBER_ID"
31
36
  larkmate group-invite --chat "$CHAT_ID" --member "$MEMBER_ID"
32
37
  larkmate group-update --chat "$CHAT_ID" --name '新名称'
@@ -36,3 +41,9 @@ larkmate group-dissolve --chat "$CHAT_ID"
36
41
  ```
37
42
 
38
43
  `--member` 可重复指定。创建或邀请机器人默认限制普通成员移除,`--allow-member-removal` 可关闭该限制。`verified` 只表示机器人移除限制已读回。遇到 `GROUP_CREATED_PARTIAL` 或 `INVITE_PARTIAL` 时,先检查已产生的群或成员变化,不要盲目重复操作。
44
+
45
+ `group-settings` 可读取群主、公告、发言和群权限设置;`group-settings-schema` 列出可修改的字段与值。使用 `group-settings-set --chat "$CHAT_ID" --json <文件>` 修改所需字段,`--json -` 从标准输入读取。它会按字段更新,并可配置入群审批、邀请、@全体、历史消息可见性及受限模式等;修改前先读取当前设置。群公告暂不支持修改。
46
+
47
+ `group-admin-add` 和 `group-admin-remove` 分别设置或撤销管理员;`group-owner` 转让群主,`group-remove` 移除成员,`group-leave` 退出群聊,均需要明确的目标和用户意图。`group-post-set` 配置发言模式,`group-post-users` 查询白名单。`group-requests` 查询入群申请;用 `group-request-approve` 或 `group-request-reject` 处理指定用户的申请。`group-link` 创建可用于入群的邀请链接,应保护链接;默认有效期 7 天。
48
+
49
+ 群操作的可用性受当前用户的群角色和飞书权限限制。对于 `submitted_unconfirmed`、`EFFECT_UNKNOWN` 或部分成功,先查询群设置、成员或申请状态,不盲目重试。
@@ -33,6 +33,11 @@ const routes = {
33
33
  'chat-open': ['client', 'openChat', 'allChats'],
34
34
  'chat-info': ['client', 'chatInfo', 'chatArg'], 'chat-state': ['controls', 'state', 'chatArg'],
35
35
  history: ['client', 'historyPages', 'chatObject'], 'messages-export': ['client', 'historyPages', 'chatObject'],
36
+ 'group-link': ['groups','link','chatObject'], 'group-requests': ['groups','requests','chatObject'], 'group-request-approve': ['groups','reviewRequest','chatObject'], 'group-request-reject': ['groups','reviewRequest','chatObject'], 'group-post-users': ['groups','postUsers','chatObject'],
37
+ 'group-settings': ['groups','info','chatObject'], 'group-settings-set': ['groups','setSettings','chatObject'],
38
+ 'group-admins': ['groups','admins','chatObject'], 'group-admin-add': ['groups','setAdmins','chatObject'], 'group-admin-remove': ['groups','setAdmins','chatObject'],
39
+ 'group-remove': ['groups','remove','chatObject'], 'group-leave': ['groups','leave','chatObject'], 'group-owner': ['groups','setOwner','chatObject'],
40
+ 'group-post-set': ['groups','setPost','chatObject'], 'group-join-history': ['groups','history','chatObject'],
36
41
  'group-members': ['client', 'members', 'chatObject'], 'group-bot-info': ['client', 'botProtection', 'chatObject'],
37
42
  'group-update': ['client', 'updateGroup', 'chatObject'], 'group-dissolve': ['client', 'dissolveGroup', 'chatArg'],
38
43
  'group-create': ['client', 'createGroup', 'allChats'], 'group-invite': ['client', 'invite', 'allChats'],
@@ -55,7 +60,7 @@ const routes = {
55
60
  };
56
61
  const writes = new Set(['send', 'pin', 'unpin', 'mark', 'unmark', 'mute', 'unmute', 'done', 'inbox', 'box', 'unbox', 'read', 'unread',
57
62
  'label-create', 'label-rename', 'label-delete', 'label-add', 'label-remove', 'chat-open', 'group-create', 'group-invite',
58
- 'group-update', 'group-dissolve', 'group-bot-protection', 'message-edit', 'message-forward', 'message-recall', 'favorite-add',
63
+ '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',
59
64
  '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']);
60
65
 
61
66
  export function brokerCommands() {
@@ -129,6 +134,8 @@ export function authorize(policy, request) {
129
134
  const chatAllowed = id => numeric(id) && (policy.allowAllChats || policy.chatIds.includes(id));
130
135
  if (scope === 'global' && !policy.allowGlobal) denied();
131
136
  if (['calendar-subscribe', 'calendar-unsubscribe'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].subscribe !== (request.command === 'calendar-subscribe'))) denied();
137
+ 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();
138
+ 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();
132
139
  if (['task-complete', 'task-reopen'].includes(request.command) && (args.length !== 1 || !object(args[0]) || args[0].completed !== (request.command === 'task-complete'))) denied();
133
140
  if (['allChats', 'labelTrue', 'labelFalse', 'reactionAdd', 'reactionRemove'].includes(scope) && (!policy.allowGlobal || !policy.allowAllChats)) denied();
134
141
  if (scope === 'allMinutes' && (!policy.allowGlobal || !policy.allowAllMinutes)) denied();
@@ -146,7 +153,18 @@ export function authorize(policy, request) {
146
153
  const keys = scope === 'send' ? ['chatId', 'text', 'mentions', 'replyTo', 'replyRoot']
147
154
  : method === 'historyPages' ? ['chatId', 'limit', 'start', 'pages', 'query', 'sender', 'after', 'before']
148
155
  : method === 'members' ? ['chatId', 'cursor', 'offset', 'limit']
149
- : method === 'updateGroup' ? ['chatId', 'name', 'description'] : ['chatId', 'botId'];
156
+ : method === 'updateGroup' ? ['chatId', 'name', 'description']
157
+ : method === 'info' || method === 'admins' || method === 'postUsers' ? ['chatId']
158
+ : method === 'link' ? ['chatId','days','unlimited']
159
+ : method === 'requests' ? ['chatId','cursor']
160
+ : method === 'reviewRequest' ? ['chatId','userId','approve']
161
+ : method === 'setSettings' ? ['chatId','settings']
162
+ : method === 'setAdmins' ? ['chatId','userIds','enabled']
163
+ : method === 'remove' ? ['chatId','userIds']
164
+ : method === 'leave' ? ['chatId','newOwnerId']
165
+ : method === 'setOwner' ? ['chatId','userId']
166
+ : method === 'setPost' ? ['chatId','mode','addUsers','removeUsers']
167
+ : method === 'history' ? ['chatId','cursor','count'] : ['chatId', 'botId'];
150
168
  if (!only(args[0], keys)) denied();
151
169
  // A reply ID may refer to another chat, and mentions can notify additional users.
152
170
  if (scope === 'send' && !policy.allowAllChats && (args[0].replyTo || args[0].replyRoot || (args[0].mentions?.length ?? 0) !== 0)) denied();
@@ -0,0 +1,63 @@
1
+ import { FeishuError, requireInt64Id } from './errors.js';
2
+ const obj = x => x && typeof x === 'object' && !Array.isArray(x);
3
+ const fail = message => { throw new FeishuError('INVALID_ARGUMENT', message); };
4
+ const memberIds = (values, empty=false) => { if(!Array.isArray(values)||(!empty&&!values.length)||values.length>100)fail('Provide between 1 and 100 members.');return [...new Set(values.map(x=>requireInt64Id(x,'member ID')))]; };
5
+ const values = (...names) => Object.fromEntries(names.map((name,i)=>[name,i+1]));
6
+ const entityFields = {
7
+ addMemberPermissionSetting:[1,values('ALL_MEMBERS','ONLY_OWNER')], atAllPermissionSetting:[2,values('ALL_MEMBERS','ONLY_OWNER')],
8
+ joinMessageVisibleSetting:[3,values('ONLY_OWNER','ALL_MEMBERS','NOT_ANYONE')], quitMessageVisibleSetting:[4,values('ONLY_OWNER','ALL_MEMBERS','NOT_ANYONE')],
9
+ shareCardPermissionSetting:[5,values('ALLOWED','NOT_ALLOWED')], addMemberApplySetting:[6,values('NO_APPLY','NEED_APPLY')],
10
+ threadAnonymousSetting:[7,values('INVISIBLE','NOT_ALLOWED','ALLOWED')], messageVisibilitySetting:[8,values('ALL_MESSAGES','ONLY_NEW_MESSAGES')],
11
+ anonymousSetting:[9,null], createUrgentSetting:[10,values('ALL_MEMBERS','ONLY_MANAGER')], createVideoConferenceSetting:[11,values('ALL_MEMBERS','ONLY_MANAGER')],
12
+ pinPermissionSetting:[12,values('ALL_MEMBERS','ONLY_MANAGER')], topNoticePermissionSetting:[14,values('ALL_MEMBERS','ONLY_MANAGER')],
13
+ chatTabPermissionSetting:[15,values('ALL_MEMBERS','ONLY_MANAGER')], chatDisplayModeSetting:[16,values('DEFAULT','THREAD')],
14
+ adminPostSetting:[17,values('ALLOW_POST','BANNED_POST')], chatPinPermissionSetting:[18,values('ALL_MEMBERS','ONLY_MANAGER')], userCountVisibleSetting:[19,values('ALL_MEMBERS','ONLY_MANAGER')],
15
+ };
16
+ function enumValue(input,allowed,key) { let v=typeof input==='string'?allowed[input]:input; if(!Number.isInteger(v)||!Object.values(allowed).includes(v))fail(`Invalid value for ${key}.`);return v; }
17
+ function booleanFields(input,allowed,path) {if(!obj(input)||!Object.keys(input).length||Object.keys(input).some(k=>!allowed.includes(k)||typeof input[k]!=='boolean'))fail(`Invalid ${path}.`);return input;}
18
+ export function buildSettings(input) {
19
+ if(!obj(input)||!Object.keys(input).length||Object.keys(input).some(k=>!['entity','general','offEditInfo','isPublicV2'].includes(k)))fail('Settings must contain supported entity, general, offEditInfo or isPublicV2 fields.');
20
+ const patch={},updateFields=[];
21
+ if(input.entity!=null){if(!obj(input.entity)||!Object.keys(input.entity).length)fail('Entity settings must be a non-empty object.');const setting={},fields=[];
22
+ for(const [key,raw]of Object.entries(input.entity)){const entry=entityFields[key];if(!entry)fail(`Unknown entity setting ${key}.`);setting[key]=entry[1]?enumValue(raw,entry[1],key):booleanFields(raw,['isAllowAnonymous','isVisible'],key);fields.push(entry[0]);}
23
+ patch.entitySetting=setting;patch.updateEntitySettingFields=fields;updateFields.push(15);
24
+ }
25
+ if(input.general!=null){if(!obj(input.general)||!Object.keys(input.general).length||Object.keys(input.general).some(k=>!['defDisplaySetting','restrictedModePermissionSetting'].includes(k)))fail('Invalid general settings.');let general={},fields=[];
26
+ if(input.general.defDisplaySetting!=null){general.defDisplaySetting=enumValue(input.general.defDisplaySetting,values('INPUT_BOX','CHAT_MENU'),'defDisplaySetting');fields.push(6)}
27
+ if(input.general.restrictedModePermissionSetting!=null){let raw=input.general.restrictedModePermissionSetting;if(!obj(raw)||!Object.keys(raw).length)fail('Invalid restricted mode settings.');let nested={};
28
+ for(const [key,value] of Object.entries(raw)){if(key==='status'){if(typeof value!=='boolean')fail('Invalid restricted status.');nested.status=value;fields.push(1)}
29
+ else if(['transmitPermissionSetting','copyPermissionSetting','downloadPermissionSetting','screenshotPermissionSetting'].includes(key)){nested[key]=enumValue(value,values('ALL_MEMBERS','NO_MEMBER'),key);fields.push({transmitPermissionSetting:2,copyPermissionSetting:3,downloadPermissionSetting:4,screenshotPermissionSetting:5}[key])}
30
+ else if(key==='onTimeDelMsgPermissionSetting'){if(!obj(value)||!Object.keys(value).length||Object.keys(value).some(k=>!['status','aliveTime'].includes(k)))fail('Invalid auto-delete settings.');let v={};if(value.status!=null){if(typeof value.status!=='boolean')fail('Invalid auto-delete status.');v.status=value.status;fields.push(7)}if(value.aliveTime!=null){let t=String(value.aliveTime);if(!/^\d{1,18}$/.test(t))fail('Invalid auto-delete time.');v.aliveTime=t;fields.push(8)}nested[key]=v}
31
+ else if(key==='whiteListSetting'){if(!obj(value)||!Object.keys(value).length||Object.keys(value).some(k=>!['level','addUserIds','delUserIds'].includes(k)))fail('Invalid restricted-mode whitelist.');let v={};if(value.level!=null){v.level=enumValue(value.level,values('NO_MEMBER','ONLY_ADMIN_AND_OWNER','MEMBER_LIST'),'whitelist level');fields.push(9)}for(const k of ['addUserIds','delUserIds'])if(value[k]!=null){v[k]=memberIds(value[k]);fields.push(10)}nested[key]=v}
32
+ else fail(`Unknown general setting ${key}.`);
33
+ } general.restrictedModePermissionSetting=nested;
34
+ }
35
+ patch.generalSetting=general;patch.updateGeneralSettingFields=[...new Set(fields)];updateFields.push(41);
36
+ }
37
+ for(const [key,field]of [['offEditInfo',14],['isPublicV2',23]])if(input[key]!=null){if(typeof input[key]!=='boolean')fail(`${key} must be boolean.`);patch[key]=input[key];updateFields.push(field)}
38
+ return {...patch,updateFields};
39
+ }
40
+ function matches(expected,actual) {if(!obj(expected))return String(expected)===String(actual);if(!obj(actual))return false;return Object.entries(expected).every(([k,v])=>Array.isArray(v)?false:Object.hasOwn(actual,k)&&matches(v,actual[k]));}
41
+ export function groupSettingsSchema() { return { entity: Object.fromEntries(Object.entries(entityFields).map(([name,[field,choices]])=>[name,{field,values:choices||{isAllowAnonymous:'boolean',isVisible:'boolean'}}])), general: { defDisplaySetting:values('INPUT_BOX','CHAT_MENU'), restrictedModePermissionSetting: { status:'boolean', transmitPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), copyPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), downloadPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), screenshotPermissionSetting:values('ALL_MEMBERS','NO_MEMBER'), onTimeDelMsgPermissionSetting:{status:'boolean',aliveTime:'duration value'}, whiteListSetting:{level:values('NO_MEMBER','ONLY_ADMIN_AND_OWNER','MEMBER_LIST'),addUserIds:'user ID array',delUserIds:'user ID array'} } }, offEditInfo:'boolean', isPublicV2:'boolean' }; }
42
+ export class GroupManagement {
43
+ constructor(gateway){this.gateway=gateway;}
44
+ async call(cmd,req,body,res,write=false,operation='group'){let r=await this.gateway.call(cmd,req,body,{mutating:write,operation});try{return {data:this.gateway.decode(res,r.packet.payload||new Uint8Array()),requestId:r.requestId}}catch{throw new FeishuError(write?'EFFECT_UNKNOWN':'INVALID_RESPONSE','Group response was unreadable.',{operation,requestId:r.requestId})}}
45
+ async raw(chatId){requireInt64Id(chatId,'chat ID');const {data}=await this.call(64,'PullChatsByIdsRequest',{chatIds:[chatId]},'PullChatsByIdsResponse');let chat=data.chats?.[chatId];if(!chat||String(chat.id)!==chatId)throw new FeishuError('NOT_FOUND','Group not found or inaccessible.');if(![2,3].includes(chat.type))throw new FeishuError('INVALID_ARGUMENT','The target is not a group.');return chat;}
46
+ async info({chatId}){let c=await this.raw(chatId);return {chatId,name:c.name||'',ownerId:c.ownerId||null,role:Object.hasOwn(c,'role')?c.role:null,isAdmin:Object.hasOwn(c,'isAdmin')?c.isAdmin:null,postType:Object.hasOwn(c,'postType')?c.postType:null,allowPost:Object.hasOwn(c,'allowPost')?c.allowPost:null,announcement:c.announcement||null,entity:c.chatEntitySetting||null,general:c.chatGeneralSetting||null,offEditInfo:Object.hasOwn(c,'offEditGroupChatInfo')?c.offEditGroupChatInfo:null,isPublicV2:Object.hasOwn(c,'isPublicV2')?c.isPublicV2:null};}
47
+ async admins({chatId}){requireInt64Id(chatId,'chat ID');let {data}=await this.call(5902,'PullChatAdminUsersRequest',{chatId},'PullChatAdminUsersResponse');return {chatId,items:data.adminUsers.map(x=>({userId:String(x.userId),orderWeight:Object.hasOwn(x,'orderWeight')?String(x.orderWeight):null})),version:Object.hasOwn(data,'updateVersion')?String(data.updateVersion):null};}
48
+ async setAdmins({chatId,userIds,enabled}){requireInt64Id(chatId,'chat ID');if(typeof enabled!=='boolean')fail('Invalid admin action.');let ids=memberIds(userIds);let {requestId}=await this.call(5900,'PatchChatAdminUsersRequest',{chatId,[enabled?'toAddUserIds':'toDelUserIds']:ids},'PatchChatAdminUsersResponse',true,enabled?'group-admin-add':'group-admin-remove');
49
+ try{let current=await this.admins({chatId}),found=new Set(current.items.map(x=>x.userId));return {chatId,requestId,status:ids.every(id=>found.has(id)===enabled)?'updated':'submitted_unconfirmed',items:current.items}}catch{return {chatId,requestId,status:'submitted_unconfirmed'}}}
50
+ async remove({chatId,userIds}){requireInt64Id(chatId,'chat ID');let ids=memberIds(userIds);let me=await this.gateway.authenticate();if(ids.includes(me.id))fail('Use group-leave to leave a group.');await this.raw(chatId);let {data,requestId}=await this.call(45,'DeleteChatChatterRequest',{chatId,chatterIds:ids},'DeleteChatChatterResponse',true,'group-remove');
51
+ if(data.chat?.id&&String(data.chat.id)!==chatId)throw new FeishuError('EFFECT_UNKNOWN','Unexpected group in response.',{requestId});return {chatId,requestId,status:'submitted_unconfirmed',requested:ids};}
52
+ async leave({chatId,newOwnerId}){requireInt64Id(chatId,'chat ID');if(newOwnerId!=null)requireInt64Id(newOwnerId,'new owner ID');let me=await this.gateway.authenticate();if(newOwnerId===me.id)fail('New owner must be another member.');await this.raw(chatId);let {requestId}=await this.call(45,'DeleteChatChatterRequest',{chatId,chatterIds:[me.id],...(newOwnerId?{newOwnerId}:{})},'DeleteChatChatterResponse',true,'group-leave');return {chatId,requestId,status:'submitted_unconfirmed'};}
53
+ async patch({chatId,body,operation}) {const {data,requestId}=await this.call(72,'PatchGroupChatRequest',{chatId,...body},'PatchGroupChatResponse',true,operation);if(!data.chat?.id||String(data.chat.id)!==chatId)throw new FeishuError('EFFECT_UNKNOWN','Group update was not confirmed.',{requestId});return {data,requestId};}
54
+ async setOwner({chatId,userId}) {requireInt64Id(chatId,'chat ID');requireInt64Id(userId,'owner ID');await this.raw(chatId);let {data,requestId}=await this.patch({chatId,body:{ownerId:userId,updateFields:[5]},operation:'group-owner'});return {chatId,requestId,status:String(data.chat.ownerId||'')===userId?'updated':'submitted_unconfirmed'};}
55
+
56
+ async setSettings({chatId,settings}) {requireInt64Id(chatId,'chat ID');let patch=buildSettings(settings);await this.raw(chatId);let {requestId}=await this.patch({chatId,body:patch,operation:'group-settings-set'});try{let after=await this.info({chatId});let ok=(patch.entitySetting==null||matches(patch.entitySetting,after.entity))&&(patch.generalSetting==null||matches(patch.generalSetting,after.general))&&(patch.offEditInfo==null||patch.offEditInfo===after.offEditInfo)&&(patch.isPublicV2==null||patch.isPublicV2===after.isPublicV2);return {chatId,requestId,status:ok?'updated':'submitted_unconfirmed',settings:after}}catch{return {chatId,requestId,status:'submitted_unconfirmed'}}}
57
+ async setPost({chatId,mode,addUsers=[],removeUsers=[]}) {requireInt64Id(chatId,'chat ID');let mapping={anyone:1,admin:2,whitelist:3},postType=mapping[mode];if(!postType)fail('Mode must be anyone, admin or whitelist.');let add=memberIds(addUsers,true),remove=memberIds(removeUsers,true);if(add.some(x=>remove.includes(x)))fail('A member cannot be added and removed together.');await this.raw(chatId);let {requestId}=await this.call(254,'PatchChatPostUserRequest',{chatId,postType,toAddUserIds:add,toDelUserIds:remove},'PatchChatPostUserResponse',true,'group-post-set');try{let c=await this.info({chatId});return {chatId,requestId,status:c.postType===postType&&!add.length&&!remove.length?'updated':'submitted_unconfirmed',postType:c.postType}}catch{return {chatId,requestId,status:'submitted_unconfirmed'}}}
58
+ async postUsers({chatId}){requireInt64Id(chatId,'chat ID');let {data}=await this.call(253,'PullChatPostUserByChatIDRequest',{chatId},'PullChatPostUserByChatIDResponse');return {chatId,userIds:data.userIds};}
59
+ async link({chatId,days=7,unlimited=false}){requireInt64Id(chatId,'chat ID');if(!Number.isInteger(days)||days<1||days>365||typeof unlimited!=='boolean')fail('Invalid link duration.');await this.raw(chatId);let {data,requestId}=await this.call(5055,'PullChatLinkTokenRequest',{chatId,expiredDay:days,isUnlimited:unlimited},'PullChatLinkTokenResponse',true,'group-link');if(!data.sharedUrl&&!data.token)throw new FeishuError('EFFECT_UNKNOWN','No group invitation link was returned.',{requestId});return {chatId,requestId,url:data.sharedUrl||null,token:data.token||null,expireTime:Object.hasOwn(data,'expireTime')?String(data.expireTime):null,unlimited:Object.hasOwn(data,'isUnlimited')?data.isUnlimited:null};}
60
+ async requests({chatId,cursor='0'}){requireInt64Id(chatId,'chat ID');if(typeof cursor!=='string'||!/^\d{1,19}$/.test(cursor))fail('Invalid request cursor.');let {data}=await this.call(258,'PullAddChatChatterApplyRequest',{chatId,cursor},'PullAddChatChatterApplyResponse');return {chatId,items:data.applies.map(x=>({reason:x.reason||'',status:x.status,time:Object.hasOwn(x,'time')?String(x.time):null,applyWays:x.applyWays,inviterId:x.inviterId||null,inviteeId:x.inviteeId||null,teamName:x.teamName||null})),nextCursor:Object.hasOwn(data,'nextCursor')&&String(data.nextCursor)!=='0'?String(data.nextCursor):null};}
61
+ async reviewRequest({chatId,userId,approve}){requireInt64Id(chatId,'chat ID');requireInt64Id(userId,'user ID');if(typeof approve!=='boolean')fail('Invalid request decision.');await this.raw(chatId);let {requestId}=await this.call(259,'PatchAddChatChatterApplyRequest',{chatId,inviteeId:userId,status:approve?1:2},'PatchAddChatChatterApplyResponse',true,approve?'group-request-approve':'group-request-reject');return {chatId,userId,requestId,status:'submitted_unconfirmed'};}
62
+ async history({chatId,cursor,count=20}) {requireInt64Id(chatId,'chat ID');if(!Number.isInteger(count)||count<1||count>100||(cursor!=null&&!/^\d{1,19}$/.test(String(cursor))))fail('Invalid history pagination.');let {data}=await this.call(5029,'PullChatJoinLeaveHistoryRequest',{chatId,count,...(cursor!=null?{cursor:String(cursor)}:{})},'PullChatJoinLeaveHistoryResponse');if(data.hasMore&&!data.nextCursor)throw new FeishuError('PAGINATION_INCOMPLETE','No continuation cursor was returned.');return {chatId,items:data.chatterHistory,hasMore:data.hasMore,nextCursor:data.hasMore?data.nextCursor:null};}
63
+ }