koishi-plugin-aakook 0.2.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/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,6 +256,20 @@ 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>;
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 });
package/lib/link.d.ts CHANGED
@@ -51,7 +51,14 @@ export declare class LinkService {
51
51
  private onStatus;
52
52
  private status;
53
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
+ */
54
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;
55
62
  private handleCode;
56
63
  /** The database part, run under the lock: delete the code first, then change links. */
57
64
  private applyCode;
package/lib/link.js CHANGED
@@ -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;
@@ -371,12 +376,30 @@ class LinkService {
371
376
  this.logger.warn('处理 QQ 验证码出错:%s', (0, util_1.errorText)(error));
372
377
  }
373
378
  }
374
- 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) {
375
398
  try {
376
- await session.send(koishi_1.h.text(text));
399
+ return !!(await session.send(content))?.length;
377
400
  }
378
- catch (error) {
379
- this.logger.warn('QQ 回复失败:%s', (0, util_1.errorText)(error));
401
+ catch {
402
+ return false;
380
403
  }
381
404
  }
382
405
  async handleCode(session, qq, code, confirmed) {
@@ -400,14 +423,14 @@ class LinkService {
400
423
  }
401
424
  case 'linked': {
402
425
  const name = await this.nameOf(outcome.kookId);
403
- await this.qqReply(session, `✅ 已关联 KOOK 账号 ${name}。如果这不是你的 KOOK 账号,请联系管理员`);
426
+ await this.qqReply(session, `✅ 已关联 KOOK 账号 ${name}。如果这不是你的 KOOK 账号,请联系管理员`, true);
404
427
  await this.notifyKook(outcome.kookId, `✅ 已关联 QQ ${(0, notifier_1.maskQq)(outcome.qq)}`);
405
428
  await this.notifyChange({ kind: outcome.oldQq ? 'qq-changed' : 'created', kookId: outcome.kookId, oldQq: outcome.oldQq, newQq: outcome.qq, actor: 'qq' });
406
429
  return;
407
430
  }
408
431
  case 'transferred': {
409
432
  const [newName, oldName] = await Promise.all([this.nameOf(outcome.kookId), this.nameOf(outcome.fromKookId)]);
410
- await this.qqReply(session, `✅ 已把这个 QQ 的关联从 KOOK 账号 ${oldName} 改到 ${newName}。如果这不是你的 KOOK 账号,请联系管理员`);
433
+ await this.qqReply(session, `✅ 已把这个 QQ 的关联从 KOOK 账号 ${oldName} 改到 ${newName}。如果这不是你的 KOOK 账号,请联系管理员`, true);
411
434
  await this.notifyKook(outcome.kookId, `✅ 已关联 QQ ${(0, notifier_1.maskQq)(outcome.qq)}`);
412
435
  await this.notifyKook(outcome.fromKookId, `你的 KOOK 账号和 QQ ${(0, notifier_1.maskQq)(outcome.qq)} 的关联已被转到别的 KOOK 账号;如果不是你本人操作,请联系管理员`);
413
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;
package/lib/types.d.ts CHANGED
@@ -52,6 +52,8 @@ export interface MemberRecord {
52
52
  /** When the person left the server; null = in the server. */
53
53
  leftAt: number | null;
54
54
  kickedByBot: boolean;
55
+ /** Last time the person was judged protected (whitelist, admin ...); null = never. A never-linked person who loses protection counts the grace period from here. */
56
+ protectedAt: number | null;
55
57
  lastCheckedAt: number | null;
56
58
  /** Latest judgement summary, for the 「状态」 command. */
57
59
  lastResult: StoredResult | null;
@@ -108,6 +110,27 @@ export interface KookRole {
108
110
  /** `permissions` has the administrator bit. */
109
111
  isAdmin: boolean;
110
112
  }
113
+ /** A channel (or category) as seen in the channel list. */
114
+ export interface KookChannel {
115
+ id: string;
116
+ name: string;
117
+ isCategory: boolean;
118
+ /** Category id; '' = none. */
119
+ parentId: string;
120
+ }
121
+ /** Permission overwrites of one channel (ids as strings; allow / deny are KOOK permission bit sets). */
122
+ export interface ChannelRoles {
123
+ roles: Array<{
124
+ id: string;
125
+ allow: number;
126
+ deny: number;
127
+ }>;
128
+ users: Array<{
129
+ id: string;
130
+ allow: number;
131
+ deny: number;
132
+ }>;
133
+ }
111
134
  /** Result of reading the whole member list. */
112
135
  export interface MemberListResult {
113
136
  /** True only if every page was read. When false, no kick and no "left the server" processing may happen. */
@@ -129,6 +152,24 @@ export interface KookApi {
129
152
  /** The user id of the server owner (`master_id` of the guild view), or null when KOOK did not tell. */
130
153
  getMasterId(guildId: string): Promise<string | null>;
131
154
  listRoles(guildId: string): Promise<KookRole[]>;
155
+ /** Make a new server role with this name (KOOK `guild-role/create`); returns it. */
156
+ createRole(guildId: string, name: string): Promise<KookRole>;
157
+ /** Set a role's permissions, hoist and mentionable to 0 (KOOK `guild-role/update`); a new role starts with KOOK's default permissions. */
158
+ resetRole(guildId: string, roleId: string): Promise<void>;
159
+ /** Every channel and category of the server (KOOK `channel/list`). Throws when the answer is not a trustworthy list. */
160
+ listChannels(guildId: string): Promise<KookChannel[]>;
161
+ /** Make a text channel, voice channel or category (a category has no `parentId`). */
162
+ createChannel(guildId: string, name: string, options?: {
163
+ parentId?: string;
164
+ voice?: boolean;
165
+ category?: boolean;
166
+ }): Promise<KookChannel>;
167
+ /** Set one overwrite of a channel (creates it first when the channel has none for this role / user). */
168
+ setChannelRole(channelId: string, target: {
169
+ type: 'role_id' | 'user_id';
170
+ value: string;
171
+ }, allow: number, deny: number): Promise<void>;
172
+ getChannelRoles(channelId: string): Promise<ChannelRoles>;
132
173
  /** Private message; returns false when it could not be delivered (never throws for "cannot DM"). */
133
174
  sendDirect(userId: string, content: string): Promise<boolean>;
134
175
  /** Temp message only `userId` can see in a channel; false when it failed. */
@@ -146,6 +187,10 @@ export interface PolicyConfig {
146
187
  memberRoleId: string;
147
188
  roleMap: RoleMapEntry[];
148
189
  whitelist: string[];
190
+ /** KOOK role ids: holding any of them counts as being on the whitelist. */
191
+ whitelistRoles: string[];
192
+ /** QQ numbers: a person whose linked QQ is in this list counts as being on the whitelist. */
193
+ qqWhitelist: string[];
149
194
  nicknameSync: boolean;
150
195
  keepUnlinkedRoles: boolean;
151
196
  breakerCount: number;
@@ -326,6 +371,6 @@ export interface GuardControl {
326
371
  postCard(actor: string): Promise<string>;
327
372
  }
328
373
  /** Audit actions written to `aakook_audit.action` (the breaker counts `kick` and `revoke-member`). */
329
- export type AuditAction = 'link' | 'unlink' | 'relink' | 'transfer' | 'grant' | 'revoke' | 'revoke-member' | 'nickname' | 'countdown-start' | 'countdown-clear' | 'countdown-extend' | 'remind' | 'kick' | 'kick-released' | 'revoke-member-released' | 'hold' | 'release' | 'pause' | 'resume' | 'mode';
374
+ export type AuditAction = 'link' | 'unlink' | 'relink' | 'transfer' | 'grant' | 'revoke' | 'revoke-member' | 'nickname' | 'countdown-start' | 'countdown-clear' | 'countdown-extend' | 'corp-create' | 'corp-channel' | 'remind' | 'kick' | 'kick-released' | 'revoke-member-released' | 'hold' | 'release' | 'pause' | 'resume' | 'mode';
330
375
  /** The function policy.ts must export. Pure: no clock, no database, no network. */
331
376
  export type PlanBatchFn = (input: PlanInput) => PlanResult;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "koishi-plugin-aakook",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "配合 AllianceAuth 插件 aa-qqbot,通过 QQ 关联给 KOOK 服务器把门:按 AA 判定发放身份组、同步昵称,到期移出不合格的人",
5
5
  "main": "lib/index.js",
6
6
  "typings": "lib/index.d.ts",