koishi-plugin-aakook 0.1.0 → 0.3.0

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/lib/index.js CHANGED
@@ -10,10 +10,10 @@ const store_1 = require("./store");
10
10
  exports.name = 'aakook';
11
11
  // Database: countdowns, links, cursor and pause state must survive reloads. http: calls AA.
12
12
  exports.inject = { required: ['database', 'http'] };
13
- exports.usage = `
14
- 配合 AllianceAuth 插件 **aa-qqbot** 给 KOOK 服务器把门:成员在 KOOK 里拿验证码、用自己的 QQ 发出,机器人按 AA 的判定发放身份组、同步昵称,到期未通过的人会被移出。
15
-
16
- 默认是 **report(只报告)** 模式,不会改动服务器里的任何东西。详细说明见 [README](https://github.com/yilifaer/koishi-plugin-aakook#readme)。
13
+ exports.usage = `
14
+ 配合 AllianceAuth 插件 **aa-qqbot** 给 KOOK 服务器把门:成员在 KOOK 里拿验证码、用自己的 QQ 发出,机器人按 AA 的判定发放身份组、同步昵称,到期未通过的人会被移出。
15
+
16
+ 默认是 **report(只报告)** 模式,不会改动服务器里的任何东西。详细说明见 [README](https://github.com/yilifaer/koishi-plugin-aakook#readme)。
17
17
  `;
18
18
  function apply(ctx, config) {
19
19
  (0, store_1.extendModels)(ctx);
package/lib/kook.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { KookApi, KookMember, KookRole, MemberListResult } from './types';
1
+ import type { ChannelRoles, KookApi, KookChannel, KookMember, KookRole, MemberListResult } from './types';
2
2
  export interface KookUser {
3
3
  id: string;
4
4
  username?: string;
@@ -10,6 +10,35 @@ export interface KookUser {
10
10
  /** Not in the adapter's types, but KOOK returns it in the member list. */
11
11
  nickname?: string;
12
12
  }
13
+ /** A role as KOOK returns it (the docs show `data` as an array for create / update, so both shapes are read). */
14
+ export interface KookRoleObject {
15
+ role_id: number;
16
+ name?: string;
17
+ permissions?: number;
18
+ }
19
+ /** A channel as KOOK returns it (`is_category` may come as a boolean or 0 / 1). */
20
+ export interface KookChannelObject {
21
+ id: string;
22
+ name?: string;
23
+ is_category?: boolean | number;
24
+ parent_id?: string;
25
+ type?: number;
26
+ }
27
+ export interface KookChannelRoleIndex {
28
+ permission_overwrites?: Array<{
29
+ role_id: number | string;
30
+ allow?: number;
31
+ deny?: number;
32
+ }>;
33
+ permission_users?: Array<{
34
+ user?: {
35
+ id?: string;
36
+ };
37
+ allow?: number;
38
+ deny?: number;
39
+ }>;
40
+ permission_sync?: number;
41
+ }
13
42
  export interface KookList<T> {
14
43
  items: T[];
15
44
  meta?: {
@@ -50,6 +79,20 @@ export interface KookInternal {
50
79
  page?: number;
51
80
  page_size?: number;
52
81
  }): Promise<KookList<KookUser>>;
82
+ /** KOOK `POST /guild-role/create`: answers with the new role (`role_id` is a number). */
83
+ createGuildRole(param: {
84
+ guild_id: string;
85
+ name: string;
86
+ }): Promise<KookRoleObject | KookRoleObject[]>;
87
+ /** KOOK `POST /guild-role/update`. */
88
+ updateGuildRole(param: {
89
+ guild_id: string;
90
+ role_id: number;
91
+ name?: string;
92
+ permissions?: number;
93
+ hoist?: number;
94
+ mentionable?: number;
95
+ }): Promise<KookRoleObject | KookRoleObject[]>;
53
96
  getGuildRoleList(param: {
54
97
  guild_id: string;
55
98
  page?: number;
@@ -59,6 +102,35 @@ export interface KookInternal {
59
102
  name: string;
60
103
  permissions: number;
61
104
  }>>;
105
+ /** KOOK `GET /channel/list` (needs `internal.getChannelList`; not in older adapters). */
106
+ getChannelList(param: {
107
+ guild_id: string;
108
+ page?: number;
109
+ page_size?: number;
110
+ }): Promise<KookList<KookChannelObject>>;
111
+ /** KOOK `POST /channel/create`: `type` 1 = text, 2 = voice; `is_category` 1 = category. */
112
+ createChannel(param: {
113
+ guild_id: string;
114
+ parent_id?: string;
115
+ name: string;
116
+ type?: number;
117
+ is_category?: number;
118
+ }): Promise<KookChannelObject>;
119
+ getChannelRoleIndex(param: {
120
+ channel_id: string;
121
+ }): Promise<KookChannelRoleIndex>;
122
+ createChannelRole(param: {
123
+ channel_id: string;
124
+ type: 'role_id' | 'user_id';
125
+ value: string;
126
+ }): Promise<unknown>;
127
+ updateChannelRole(param: {
128
+ channel_id: string;
129
+ type: 'role_id' | 'user_id';
130
+ value: string;
131
+ allow?: number;
132
+ deny?: number;
133
+ }): Promise<unknown>;
62
134
  getUserView(param: {
63
135
  user_id: string;
64
136
  guild_id?: string;
@@ -184,7 +256,22 @@ export declare class KookClient implements KookApi {
184
256
  getMember(guildId: string, userId: string): Promise<KookMember | null>;
185
257
  getMasterId(guildId: string): Promise<string | null>;
186
258
  listRoles(guildId: string): Promise<KookRole[]>;
259
+ createRole(guildId: string, name: string): Promise<KookRole>;
260
+ resetRole(guildId: string, roleId: string): Promise<void>;
261
+ private channelOf;
262
+ listChannels(guildId: string): Promise<KookChannel[]>;
263
+ createChannel(guildId: string, name: string, options?: {
264
+ parentId?: string;
265
+ voice?: boolean;
266
+ category?: boolean;
267
+ }): Promise<KookChannel>;
268
+ setChannelRole(channelId: string, target: {
269
+ type: 'role_id' | 'user_id';
270
+ value: string;
271
+ }, allow: number, deny: number): Promise<void>;
272
+ getChannelRoles(channelId: string): Promise<ChannelRoles>;
187
273
  sendDirect(userId: string, content: string): Promise<boolean>;
188
274
  sendTemp(channelId: string, userId: string, content: string): Promise<boolean>;
189
275
  sendChannel(channelId: string, content: string): Promise<boolean>;
276
+ sendCard(channelId: string, cardJson: string): Promise<string>;
190
277
  }
package/lib/kook.js CHANGED
@@ -182,6 +182,19 @@ function markAdmins(members, roles) {
182
182
  const adminRoles = new Set(roles.filter((r) => r.isAdmin).map((r) => r.id));
183
183
  return members.map((m) => ({ ...m, isAdmin: m.roles.some((r) => adminRoles.has(r)) }));
184
184
  }
185
+ /**
186
+ * Page count of a KOOK list; null = not a list we can trust. A missing `page_total` is only believed when the page
187
+ * is not full (then it is the one and only page): reading page 1 of several would make later items look missing.
188
+ */
189
+ function pageTotalOf(list) {
190
+ if (!Array.isArray(list?.items))
191
+ return null;
192
+ const total = list.meta?.page_total;
193
+ if (typeof total === 'number')
194
+ return Math.max(1, total);
195
+ const size = typeof list.meta?.page_size === 'number' && list.meta.page_size > 0 ? Math.min(PAGE_SIZE, list.meta.page_size) : PAGE_SIZE;
196
+ return list.items.length < size ? 1 : null;
197
+ }
185
198
  function toMember(user) {
186
199
  const id = (0, util_1.normalizeKookId)(user?.id);
187
200
  if (!id)
@@ -283,15 +296,100 @@ class KookClient {
283
296
  let pageTotal = 1;
284
297
  for (let page = 1; page <= pageTotal && page <= MAX_PAGES; page++) {
285
298
  const list = await this.runner.call(() => this.internal().getGuildRoleList({ guild_id: guildId, page, page_size: PAGE_SIZE }));
286
- if (!Array.isArray(list?.items))
299
+ // no page count on a full page = not a list we can trust (reading page 1 only would make roles on later pages look deleted)
300
+ const total = pageTotalOf(list);
301
+ if (total === null)
287
302
  throw new Error('身份组列表格式不对');
288
- pageTotal = Math.max(1, list.meta?.page_total ?? 1);
303
+ pageTotal = total;
289
304
  for (const item of list.items) {
290
305
  roles.push({ id: String(item.role_id), name: String(item.name ?? ''), permissions: Number(item.permissions) || 0, isAdmin: hasAdminPermission(Number(item.permissions) || 0) });
291
306
  }
292
307
  }
293
308
  return roles;
294
309
  }
310
+ async createRole(guildId, name) {
311
+ const internal = this.internal();
312
+ // not tested against the real adapter (it is not installed in this repo): a missing method is a plain Error, so it is reported once
313
+ if (typeof internal.createGuildRole !== 'function')
314
+ throw new Error('KOOK 适配器没有 createGuildRole 方法');
315
+ const answer = await this.runner.call(() => internal.createGuildRole({ guild_id: guildId, name }), { write: true });
316
+ // KOOK's docs show `data` as an array for create / update, the adapter may hand back the object: read both
317
+ const role = Array.isArray(answer) ? answer[0] : answer;
318
+ const id = (0, util_1.normalizeKookId)(role?.role_id);
319
+ if (!id)
320
+ throw new Error('KOOK 没有返回新身份组的 ID');
321
+ const permissions = Number(role.permissions) || 0;
322
+ return { id, name: String(role.name ?? name), permissions, isAdmin: hasAdminPermission(permissions) };
323
+ }
324
+ async resetRole(guildId, roleId) {
325
+ const internal = this.internal();
326
+ if (typeof internal.updateGuildRole !== 'function')
327
+ throw new Error('KOOK 适配器没有 updateGuildRole 方法');
328
+ await this.runner.call(() => internal.updateGuildRole({ guild_id: guildId, role_id: Number(roleId), permissions: 0, hoist: 0, mentionable: 0 }), { write: true });
329
+ }
330
+ channelOf(item) {
331
+ const id = (0, util_1.normalizeKookId)(item?.id);
332
+ if (!id)
333
+ return null;
334
+ return { id, name: String(item.name ?? ''), isCategory: item.is_category === true || item.is_category === 1, parentId: (0, util_1.normalizeKookId)(item.parent_id) ?? '' };
335
+ }
336
+ async listChannels(guildId) {
337
+ const internal = this.internal();
338
+ if (typeof internal.getChannelList !== 'function')
339
+ throw new Error('KOOK 适配器没有 getChannelList 方法');
340
+ const channels = new Map();
341
+ let pageTotal = 1;
342
+ for (let page = 1; page <= pageTotal && page <= MAX_PAGES; page++) {
343
+ const list = await this.runner.call(() => internal.getChannelList({ guild_id: guildId, page, page_size: PAGE_SIZE }));
344
+ const total = pageTotalOf(list);
345
+ if (total === null)
346
+ throw new Error('频道列表格式不对');
347
+ pageTotal = total;
348
+ for (const item of list.items) {
349
+ const channel = this.channelOf(item);
350
+ if (channel)
351
+ channels.set(channel.id, channel);
352
+ }
353
+ }
354
+ return [...channels.values()];
355
+ }
356
+ async createChannel(guildId, name, options = {}) {
357
+ const internal = this.internal();
358
+ if (typeof internal.createChannel !== 'function')
359
+ throw new Error('KOOK 适配器没有 createChannel 方法');
360
+ const param = options.category
361
+ ? { guild_id: guildId, name, is_category: 1 }
362
+ : { guild_id: guildId, name, type: options.voice ? 2 : 1, ...(options.parentId ? { parent_id: options.parentId } : {}) };
363
+ const channel = this.channelOf(await this.runner.call(() => internal.createChannel(param), { write: true }));
364
+ if (!channel)
365
+ throw new Error('KOOK 没有返回新频道的 ID');
366
+ return { ...channel, name: channel.name || name, isCategory: !!options.category };
367
+ }
368
+ async setChannelRole(channelId, target, allow, deny) {
369
+ const internal = this.internal();
370
+ if (typeof internal.updateChannelRole !== 'function' || typeof internal.createChannelRole !== 'function')
371
+ throw new Error('KOOK 适配器没有频道权限方法');
372
+ const update = () => this.runner.call(() => internal.updateChannelRole({ channel_id: channelId, ...target, allow, deny }), { write: true });
373
+ try {
374
+ await update();
375
+ }
376
+ catch (error) {
377
+ // no overwrite for this role / user yet (KOOK says no): make it, then set it. Other errors (offline, 429, network) go up as they are
378
+ if (!isExplicitRejection(error))
379
+ throw error;
380
+ await this.runner.call(() => internal.createChannelRole({ channel_id: channelId, ...target }), { write: true });
381
+ await update();
382
+ }
383
+ }
384
+ async getChannelRoles(channelId) {
385
+ const index = await this.runner.call(() => this.internal().getChannelRoleIndex({ channel_id: channelId }));
386
+ if (!Array.isArray(index?.permission_overwrites))
387
+ throw new Error('频道权限格式不对');
388
+ return {
389
+ roles: index.permission_overwrites.map((r) => ({ id: String(r.role_id), allow: Number(r.allow) || 0, deny: Number(r.deny) || 0 })),
390
+ users: (index.permission_users ?? []).map((u) => ({ id: String(u.user?.id ?? ''), allow: Number(u.allow) || 0, deny: Number(u.deny) || 0 })),
391
+ };
392
+ }
295
393
  async sendDirect(userId, content) {
296
394
  try {
297
395
  await this.runner.call(() => this.internal().createDirectMessage({ target_id: userId, type: 9, content }), { write: true });
@@ -322,5 +420,9 @@ class KookClient {
322
420
  return false;
323
421
  }
324
422
  }
423
+ async sendCard(channelId, cardJson) {
424
+ const result = await this.runner.call(() => this.internal().createMessage({ type: 10, target_id: channelId, content: cardJson }), { write: true });
425
+ return typeof result?.msg_id === 'string' ? result.msg_id : '';
426
+ }
325
427
  }
326
428
  exports.KookClient = KookClient;
package/lib/link.d.ts CHANGED
@@ -11,6 +11,9 @@ export declare function describeStatus(input: {
11
11
  record: MemberRecord | null;
12
12
  roleNames: Record<string, string>;
13
13
  }): string;
14
+ /** `value` of the buttons on the bind card (see card.ts). */
15
+ export declare const BUTTON_BIND = "aakook:bind";
16
+ export declare const BUTTON_STATUS = "aakook:status";
14
17
  export declare class LinkService {
15
18
  private deps;
16
19
  private readonly logger;
@@ -34,13 +37,28 @@ export declare class LinkService {
34
37
  private deliverPrivate;
35
38
  /** A notice for someone outside any command (private only, failure is just logged). */
36
39
  private notifyKook;
37
- /** Only our bot, our server (or a private chat with someone in it), and never bots. */
40
+ /** Typed command: only our bot, our server (or a private chat with someone in it), and never bots. */
38
41
  private gate;
42
+ private admit;
43
+ /**
44
+ * A click on a card button. Facts of @satorijs/adapter-kook 4.8.1: `session.userId` is undefined (a click has no
45
+ * `author_id`), the clicker is `session.event.user` and `extra.body.user_id`, the server and channel are also in the body.
46
+ */
47
+ private onButton;
39
48
  private onBind;
49
+ private bind;
40
50
  private onUnbind;
41
51
  private onStatus;
52
+ private status;
42
53
  private onQqMessage;
54
+ /**
55
+ * Koishi's `session.send` swallows send errors and returns `[]` (or nothing), so a failure is read from the result.
56
+ * With `fallback` (only for 关联成功 / 换绑成功) a failure within 5 seconds of the first try is answered once more with
57
+ * a fixed short sentence; later failures may be timeouts where the message did go out.
58
+ */
43
59
  private qqReply;
60
+ /** Sent = at least one message id came back. A throw counts as a failure too (the steps after the reply must still run). */
61
+ private trySend;
44
62
  private handleCode;
45
63
  /** The database part, run under the lock: delete the code first, then change links. */
46
64
  private applyCode;
package/lib/link.js CHANGED
@@ -4,7 +4,7 @@
4
4
  // The QQ number always comes from the QQ message event (`session.userId`), never from what the user typed.
5
5
  // Nothing here calls AA: after a link changes, `hooks.onLinkChange` lets guard judge the person again.
6
6
  Object.defineProperty(exports, "__esModule", { value: true });
7
- exports.LinkService = exports.CODE_ALPHABET = void 0;
7
+ exports.LinkService = exports.BUTTON_STATUS = exports.BUTTON_BIND = exports.CODE_ALPHABET = void 0;
8
8
  exports.parseCode = parseCode;
9
9
  exports.parseConfirm = parseConfirm;
10
10
  exports.generateCode = generateCode;
@@ -77,6 +77,11 @@ function describeStatus(input) {
77
77
  }
78
78
  // ---------------------------------------------------------------- small helpers
79
79
  const TEN_MINUTES = 10 * 60_000;
80
+ /** A reply that failed this long after the first try is not sent again (it may have gone out after a timeout). */
81
+ const FALLBACK_WINDOW_MS = 5_000;
82
+ const FALLBACK_TEXT = '✅ 关联成功。如果不是你本人操作,请联系管理员';
83
+ /** Last three characters, for logs (never the whole group number or QQ). */
84
+ const tail3 = (value) => String(value ?? '').slice(-3);
80
85
  /** "at most `limit` hits per window" per key, in memory. */
81
86
  class RateLimiter {
82
87
  limit;
@@ -102,6 +107,9 @@ class RateLimiter {
102
107
  return true;
103
108
  }
104
109
  }
110
+ /** `value` of the buttons on the bind card (see card.ts). */
111
+ exports.BUTTON_BIND = 'aakook:bind';
112
+ exports.BUTTON_STATUS = 'aakook:status';
105
113
  class LinkService {
106
114
  deps;
107
115
  logger;
@@ -127,6 +135,10 @@ class LinkService {
127
135
  this.disposers.push(() => command.dispose());
128
136
  // a plain listener, not a middleware: it can never stop other plugins from seeing the message
129
137
  this.disposers.push(ctx.on('message', (session) => this.onQqMessage(session)));
138
+ // clicks on the bind card's buttons: the same paths as the typed commands
139
+ this.disposers.push(ctx.on('interaction/button', (session) => {
140
+ this.onButton(session).catch((error) => this.logger.warn('处理按钮点击出错:%s', (0, util_1.errorText)(error)));
141
+ }));
130
142
  }
131
143
  dispose() {
132
144
  for (const dispose of this.disposers.splice(0))
@@ -203,16 +215,25 @@ class LinkService {
203
215
  this.logger.warn('给 KOOK 用户 %s 的通知私聊失败', userId);
204
216
  }
205
217
  // ---------------------------------------------------------------- KOOK side
206
- /** Only our bot, our server (or a private chat with someone in it), and never bots. */
218
+ /** Typed command: only our bot, our server (or a private chat with someone in it), and never bots. */
207
219
  async gate(session) {
220
+ return this.admit(session, {
221
+ userId: session.userId,
222
+ // whether the author is a bot is in the raw event (`extra.author.bot`); `isBot` of the Satori user is only a fallback
223
+ isBot: session.kook?.extra?.author?.bot === true || !!session.event.user?.isBot,
224
+ direct: !!session.isDirect,
225
+ guildId: session.guildId,
226
+ channelId: session.channelId,
227
+ });
228
+ }
229
+ async admit(session, actor) {
208
230
  const { config, hooks } = this.deps;
209
231
  if (session.platform !== 'kook' || session.selfId !== config.kookBotId)
210
232
  return null;
211
- const userId = session.userId;
212
- // whether the author is a bot is in the raw event (`extra.author.bot`); `isBot` of the Satori user is only a fallback
213
- if (!userId || userId === session.selfId || session.kook?.extra?.author?.bot === true || session.event.user?.isBot)
233
+ const userId = actor.userId;
234
+ if (!userId || userId === session.selfId || actor.isBot)
214
235
  return null;
215
- if (session.isDirect) {
236
+ if (actor.direct) {
216
237
  try {
217
238
  if (!(await hooks.isInGuild(userId)))
218
239
  return null;
@@ -223,14 +244,40 @@ class LinkService {
223
244
  }
224
245
  return { userId, channelId: null };
225
246
  }
226
- if (session.guildId !== config.guildId || !session.channelId)
247
+ if (actor.guildId !== config.guildId || !actor.channelId)
227
248
  return null;
228
- return { userId, channelId: session.channelId };
249
+ return { userId, channelId: actor.channelId };
229
250
  }
230
- async onBind(session) {
231
- const gate = await this.gate(session);
251
+ /**
252
+ * A click on a card button. Facts of @satorijs/adapter-kook 4.8.1: `session.userId` is undefined (a click has no
253
+ * `author_id`), the clicker is `session.event.user` and `extra.body.user_id`, the server and channel are also in the body.
254
+ */
255
+ async onButton(session) {
256
+ const value = session.event?.button?.id;
257
+ if (value !== exports.BUTTON_BIND && value !== exports.BUTTON_STATUS)
258
+ return;
259
+ const body = session.kook?.extra?.body ?? {};
260
+ const clicker = session.userId || session.event?.user?.id || body.user_id;
261
+ const gate = await this.admit(session, {
262
+ userId: clicker ? String(clicker) : undefined,
263
+ isBot: body.user_info?.bot === true || !!session.event?.user?.isBot,
264
+ direct: false,
265
+ guildId: session.guildId || body.guild_id,
266
+ channelId: session.channelId || body.target_id,
267
+ });
232
268
  if (!gate)
233
269
  return;
270
+ if (value === exports.BUTTON_BIND)
271
+ await this.bind(gate);
272
+ else
273
+ await this.status(gate);
274
+ }
275
+ async onBind(session) {
276
+ const gate = await this.gate(session);
277
+ if (gate)
278
+ await this.bind(gate);
279
+ }
280
+ async bind(gate) {
234
281
  const { config, store } = this.deps;
235
282
  const now = this.now;
236
283
  if (!this.bindLimit.hit(gate.userId, now)) {
@@ -281,8 +328,10 @@ class LinkService {
281
328
  }
282
329
  async onStatus(session) {
283
330
  const gate = await this.gate(session);
284
- if (!gate)
285
- return;
331
+ if (gate)
332
+ await this.status(gate);
333
+ }
334
+ async status(gate) {
286
335
  const { store, config } = this.deps;
287
336
  if (!this.statusLimit.hit(gate.userId, this.now)) {
288
337
  await this.deliverPrivate(gate, '请稍后再试。');
@@ -327,12 +376,30 @@ class LinkService {
327
376
  this.logger.warn('处理 QQ 验证码出错:%s', (0, util_1.errorText)(error));
328
377
  }
329
378
  }
330
- async qqReply(session, text) {
379
+ /**
380
+ * Koishi's `session.send` swallows send errors and returns `[]` (or nothing), so a failure is read from the result.
381
+ * With `fallback` (only for 关联成功 / 换绑成功) a failure within 5 seconds of the first try is answered once more with
382
+ * a fixed short sentence; later failures may be timeouts where the message did go out.
383
+ */
384
+ async qqReply(session, text, fallback = false) {
385
+ const started = this.now;
386
+ if (await this.trySend(session, koishi_1.h.text(text)))
387
+ return;
388
+ const group = session.isDirect ? '私聊' : `群 …${tail3(session.guildId ?? session.channelId)}`;
389
+ this.logger.warn('QQ 回复没发出去(%s,QQ …%s)', group, tail3(session.userId));
390
+ if (!fallback || this.now - started > FALLBACK_WINDOW_MS)
391
+ return;
392
+ const content = session.isDirect ? [koishi_1.h.text(FALLBACK_TEXT)] : [koishi_1.h.at(session.userId), koishi_1.h.text(` ${FALLBACK_TEXT}`)];
393
+ if (!(await this.trySend(session, content)))
394
+ this.logger.warn('QQ 补发也没发出去(%s,QQ …%s)', group, tail3(session.userId));
395
+ }
396
+ /** Sent = at least one message id came back. A throw counts as a failure too (the steps after the reply must still run). */
397
+ async trySend(session, content) {
331
398
  try {
332
- await session.send(koishi_1.h.text(text));
399
+ return !!(await session.send(content))?.length;
333
400
  }
334
- catch (error) {
335
- this.logger.warn('QQ 回复失败:%s', (0, util_1.errorText)(error));
401
+ catch {
402
+ return false;
336
403
  }
337
404
  }
338
405
  async handleCode(session, qq, code, confirmed) {
@@ -356,14 +423,14 @@ class LinkService {
356
423
  }
357
424
  case 'linked': {
358
425
  const name = await this.nameOf(outcome.kookId);
359
- await this.qqReply(session, `✅ 已关联 KOOK 账号 ${name}。如果这不是你的 KOOK 账号,请联系管理员`);
426
+ await this.qqReply(session, `✅ 已关联 KOOK 账号 ${name}。如果这不是你的 KOOK 账号,请联系管理员`, true);
360
427
  await this.notifyKook(outcome.kookId, `✅ 已关联 QQ ${(0, notifier_1.maskQq)(outcome.qq)}`);
361
428
  await this.notifyChange({ kind: outcome.oldQq ? 'qq-changed' : 'created', kookId: outcome.kookId, oldQq: outcome.oldQq, newQq: outcome.qq, actor: 'qq' });
362
429
  return;
363
430
  }
364
431
  case 'transferred': {
365
432
  const [newName, oldName] = await Promise.all([this.nameOf(outcome.kookId), this.nameOf(outcome.fromKookId)]);
366
- await this.qqReply(session, `✅ 已把这个 QQ 的关联从 KOOK 账号 ${oldName} 改到 ${newName}。如果这不是你的 KOOK 账号,请联系管理员`);
433
+ await this.qqReply(session, `✅ 已把这个 QQ 的关联从 KOOK 账号 ${oldName} 改到 ${newName}。如果这不是你的 KOOK 账号,请联系管理员`, true);
367
434
  await this.notifyKook(outcome.kookId, `✅ 已关联 QQ ${(0, notifier_1.maskQq)(outcome.qq)}`);
368
435
  await this.notifyKook(outcome.fromKookId, `你的 KOOK 账号和 QQ ${(0, notifier_1.maskQq)(outcome.qq)} 的关联已被转到别的 KOOK 账号;如果不是你本人操作,请联系管理员`);
369
436
  this.deps.hooks.alert(`⚠️ 换绑:QQ ${(0, notifier_1.maskQq)(outcome.qq)} 从 ${oldName} 转到了 ${newName}`);
package/lib/policy.d.ts CHANGED
@@ -1,4 +1,15 @@
1
1
  import type { PlanBatchFn, PolicyConfig } from './types';
2
2
  /** threshold = max(1, min(count, floor(size * pct / 100))); no size known = 0 (no kick is allowed). */
3
3
  export declare function breakerThreshold(memberCount: number | null, config: Pick<PolicyConfig, 'breakerCount' | 'breakerPercent'>): number;
4
+ /** Which whitelist a person is on: KOOK user id, a held KOOK role, or the linked QQ. */
5
+ export type WhitelistHit = {
6
+ kind: 'kook';
7
+ } | {
8
+ kind: 'role';
9
+ roleId: string;
10
+ } | {
11
+ kind: 'qq';
12
+ };
13
+ /** Any one source is enough. `roles` are the person's current role ids as strings; `qq` is the current link (or null). */
14
+ export declare function whitelistHit(config: Pick<PolicyConfig, 'whitelist' | 'whitelistRoles' | 'qqWhitelist'>, kookId: string, roles: readonly string[], qq: string | null): WhitelistHit | null;
4
15
  export declare const planBatch: PlanBatchFn;
package/lib/policy.js CHANGED
@@ -4,6 +4,7 @@
4
4
  Object.defineProperty(exports, "__esModule", { value: true });
5
5
  exports.planBatch = void 0;
6
6
  exports.breakerThreshold = breakerThreshold;
7
+ exports.whitelistHit = whitelistHit;
7
8
  const store_1 = require("./store");
8
9
  const util_1 = require("./util");
9
10
  const HOUR = 3_600_000;
@@ -19,6 +20,17 @@ function breakerThreshold(memberCount, config) {
19
20
  return 0;
20
21
  return Math.max(1, Math.min(config.breakerCount, Math.floor((memberCount * config.breakerPercent) / 100)));
21
22
  }
23
+ /** Any one source is enough. `roles` are the person's current role ids as strings; `qq` is the current link (or null). */
24
+ function whitelistHit(config, kookId, roles, qq) {
25
+ if (config.whitelist.includes(kookId))
26
+ return { kind: 'kook' };
27
+ const roleId = config.whitelistRoles.find((id) => roles.includes(id));
28
+ if (roleId !== undefined)
29
+ return { kind: 'role', roleId };
30
+ if (qq !== null && config.qqWhitelist.includes(qq))
31
+ return { kind: 'qq' };
32
+ return null;
33
+ }
22
34
  function buildDraft(p, input) {
23
35
  const { now, config: cfg } = input;
24
36
  const guildId = input.guild.guildId ?? p.record?.guildId ?? '';
@@ -37,7 +49,7 @@ function buildDraft(p, input) {
37
49
  // Bots are never managed (they have no AA identity).
38
50
  if (m.isBot)
39
51
  return { input: p, kind: 'bot', outcome: 'protected', original, base, ...empty, isProtected: true };
40
- const isProtected = m.isMaster || m.isAdmin || cfg.whitelist.includes(p.kookId);
52
+ const isProtected = m.isMaster || m.isAdmin || whitelistHit(cfg, p.kookId, m.roles, p.qq) !== null;
41
53
  const held = new Set(m.roles);
42
54
  const heldManaged = [cfg.memberRoleId, ...cfg.roleMap.map((e) => e.roleId)].filter((id, i, a) => held.has(id) && a.indexOf(id) === i);
43
55
  const returned = original.leftAt !== null;
@@ -115,6 +127,8 @@ function finalize(d, input, ctx) {
115
127
  return { plan, kickWanted: false };
116
128
  }
117
129
  let rec = judgedRecord(d, now, ctx.released);
130
+ if (d.isProtected)
131
+ rec.protectedAt = now;
118
132
  plan.record = rec;
119
133
  if (ctx.revokeBlocked) {
120
134
  plan.revoke = [];
@@ -139,8 +153,8 @@ function finalize(d, input, ctx) {
139
153
  let start = rec.deadlineStart;
140
154
  let startedNow = false;
141
155
  if (deadline === null) {
142
- // 4 / 5 / 7: new people count from max(firstSeen, activeSince); denied and lost-link people from now
143
- start = d.kind === 'new' ? Math.max(rec.firstSeenAt, guild.activeSince ?? now) : now;
156
+ // 4 / 5 / 7: new people count from max(firstSeen, activeSince, last time protected); denied and lost-link people from now
157
+ start = d.kind === 'new' ? Math.max(rec.firstSeenAt, guild.activeSince ?? now, rec.protectedAt ?? 0) : now;
144
158
  deadline = start + cfg.graceMs;
145
159
  rec.deadlineWhy = d.kind === 'new' ? 'new' : 'denied';
146
160
  rec.finalRemindedAt = null;
@@ -149,11 +163,17 @@ function finalize(d, input, ctx) {
149
163
  plan.countdown = 'started';
150
164
  }
151
165
  else {
152
- // already counting: keep the end time, only the reason may change (new -> denied)
166
+ // already counting: the end time is kept (a bigger graceHours does not extend it), only the reason may change (new -> denied)
153
167
  if (d.kind !== 'new')
154
168
  rec.deadlineWhy = 'denied';
155
169
  if (start === null)
156
170
  start = deadline - cfg.graceMs;
171
+ // a smaller graceHours shortens it. A deadline that was moved by an extension is tied to its final reminder: left alone.
172
+ // Overdue by the new length: the final reminder below still comes first (with its extension), and the kick rules
173
+ // need it to be at least an hour old and newer than enforceSince, so nobody is kicked on the strength of the new length alone.
174
+ const extended = (rec.extendedAt !== null && rec.extendedAt >= start) || (rec.returnExtendedAt !== null && rec.returnExtendedAt >= start);
175
+ if (!extended)
176
+ deadline = Math.min(deadline, start + cfg.graceMs);
157
177
  }
158
178
  rec.deadlineStart = start;
159
179
  // 8. reminders
package/lib/store.d.ts CHANGED
@@ -33,6 +33,7 @@ interface MemberRow {
33
33
  returnExtendedAt: Date | null;
34
34
  leftAt: Date | null;
35
35
  kickedByBot: boolean;
36
+ protectedAt: Date | null;
36
37
  lastCheckedAt: Date | null;
37
38
  lastResult: string;
38
39
  }
@@ -87,6 +88,10 @@ export declare const kvKeys: {
87
88
  failures: (guildId: string) => string;
88
89
  /** `(person, note)` -> when it was last put into a report (once a day). */
89
90
  notes: (guildId: string) => string;
91
+ /** Corp ticker -> KOOK role id of the roles the plugin made (or claimed); the only roles it ever touches for corps. */
92
+ corpRoles: (guildId: string) => string;
93
+ /** Corp ticker -> the channel group made for it (`CorpChannelEntry`); a group is never made twice, a deleted one never again. */
94
+ corpChannels: (guildId: string) => string;
90
95
  };
91
96
  export declare class Store {
92
97
  private ctx;
package/lib/store.js CHANGED
@@ -44,6 +44,7 @@ function extendModels(ctx) {
44
44
  returnExtendedAt: { type: 'timestamp', nullable: true },
45
45
  leftAt: { type: 'timestamp', nullable: true },
46
46
  kickedByBot: { type: 'boolean', initial: false },
47
+ protectedAt: { type: 'timestamp', nullable: true },
47
48
  lastCheckedAt: { type: 'timestamp', nullable: true },
48
49
  lastResult: { type: 'text', initial: '' },
49
50
  }, { primary: ['guildId', 'kookId'] });
@@ -91,6 +92,7 @@ function rowToMember(row) {
91
92
  returnExtendedAt: ms(row.returnExtendedAt),
92
93
  leftAt: ms(row.leftAt),
93
94
  kickedByBot: !!row.kickedByBot,
95
+ protectedAt: ms(row.protectedAt),
94
96
  lastCheckedAt: ms(row.lastCheckedAt),
95
97
  lastResult: parseResult(row.lastResult),
96
98
  };
@@ -113,6 +115,7 @@ function memberToRow(record) {
113
115
  returnExtendedAt: date(record.returnExtendedAt),
114
116
  leftAt: date(record.leftAt),
115
117
  kickedByBot: record.kickedByBot,
118
+ protectedAt: date(record.protectedAt),
116
119
  lastCheckedAt: date(record.lastCheckedAt),
117
120
  lastResult: record.lastResult ? JSON.stringify(record.lastResult) : '',
118
121
  };
@@ -122,7 +125,7 @@ function newMemberRecord(guildId, kookId, firstSeenAt) {
122
125
  return {
123
126
  guildId, kookId, firstSeenAt,
124
127
  everLinked: false, deadline: null, deadlineWhy: null, deadlineStart: null, reason: '',
125
- finalRemindedAt: null, newRemindedAt: null, releasedKick: false, releasedRevoke: false, extendedAt: null, returnExtendedAt: null, leftAt: null, kickedByBot: false,
128
+ finalRemindedAt: null, newRemindedAt: null, releasedKick: false, releasedRevoke: false, extendedAt: null, returnExtendedAt: null, leftAt: null, kickedByBot: false, protectedAt: null,
126
129
  lastCheckedAt: null, lastResult: null,
127
130
  };
128
131
  }
@@ -149,6 +152,10 @@ exports.kvKeys = {
149
152
  failures: (guildId) => `failures:${guildId}`,
150
153
  /** `(person, note)` -> when it was last put into a report (once a day). */
151
154
  notes: (guildId) => `notes:${guildId}`,
155
+ /** Corp ticker -> KOOK role id of the roles the plugin made (or claimed); the only roles it ever touches for corps. */
156
+ corpRoles: (guildId) => `corpRoles:${guildId}`,
157
+ /** Corp ticker -> the channel group made for it (`CorpChannelEntry`); a group is never made twice, a deleted one never again. */
158
+ corpChannels: (guildId) => `corpChannels:${guildId}`,
152
159
  };
153
160
  class Store {
154
161
  ctx;