@koishi-ce/plugin-auth 1.1.1 → 1.1.3
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 +2 -2
- package/lib/index.d.ts +46 -44
- package/lib/index.mjs +155 -158
- package/package.json +4 -4
- package/src/__tests__/helpers.ts +272 -0
- package/src/__tests__/intercept.test.ts +102 -0
- package/src/__tests__/login.test.ts +237 -0
- package/src/__tests__/user-events.test.ts +189 -0
- package/src/__tests__/verification.test.ts +122 -0
- package/src/crypto.ts +77 -0
- package/src/index.ts +19 -374
- package/src/login.ts +243 -0
- package/src/types.ts +52 -0
- package/src/__tests__/index.test.ts +0 -797
package/src/index.ts
CHANGED
|
@@ -12,13 +12,6 @@
|
|
|
12
12
|
* 配置同步对话框)。
|
|
13
13
|
*/
|
|
14
14
|
|
|
15
|
-
import {
|
|
16
|
-
createHash,
|
|
17
|
-
pbkdf2Sync,
|
|
18
|
-
randomBytes,
|
|
19
|
-
randomInt,
|
|
20
|
-
timingSafeEqual,
|
|
21
|
-
} from "node:crypto";
|
|
22
15
|
import { resolve } from "node:path";
|
|
23
16
|
import type {
|
|
24
17
|
Client,
|
|
@@ -27,13 +20,22 @@ import type {
|
|
|
27
20
|
import {
|
|
28
21
|
type Binding,
|
|
29
22
|
type Context,
|
|
30
|
-
omit,
|
|
31
23
|
Schema,
|
|
32
24
|
Service,
|
|
33
25
|
Time,
|
|
34
26
|
type User,
|
|
35
27
|
} from "@koishi-ce/koishi";
|
|
36
28
|
import zhCN from "../locales/zh-CN.yml";
|
|
29
|
+
import { randomId, toHash } from "./crypto.ts";
|
|
30
|
+
import { initLogin } from "./login.ts";
|
|
31
|
+
import type {
|
|
32
|
+
Auth,
|
|
33
|
+
AuthData,
|
|
34
|
+
LoginToken,
|
|
35
|
+
LoginType,
|
|
36
|
+
UserLogin,
|
|
37
|
+
UserUpdate,
|
|
38
|
+
} from "./types.ts";
|
|
37
39
|
|
|
38
40
|
declare module "@koishi-ce/koishi" {
|
|
39
41
|
interface Context {
|
|
@@ -91,131 +93,6 @@ declare module "@koishi-ce/console" {
|
|
|
91
93
|
}
|
|
92
94
|
}
|
|
93
95
|
|
|
94
|
-
/** token 表记录:一次登录会话的令牌及其来源信息。 */
|
|
95
|
-
export interface LoginToken {
|
|
96
|
-
/** 自增主键(删除指定会话用) */
|
|
97
|
-
inc: number;
|
|
98
|
-
/** 所属用户 id */
|
|
99
|
-
id: number;
|
|
100
|
-
/** 登录方式 */
|
|
101
|
-
type: LoginType;
|
|
102
|
-
/** 随机令牌(唯一索引) */
|
|
103
|
-
token: string;
|
|
104
|
-
/** 过期时间戳(毫秒) */
|
|
105
|
-
expiredAt: number;
|
|
106
|
-
createdAt: Date;
|
|
107
|
-
lastUsedAt: Date;
|
|
108
|
-
/** 登录时的 User-Agent */
|
|
109
|
-
userAgent: string;
|
|
110
|
-
/** 登录时的来源 IP */
|
|
111
|
-
address: string;
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
/** 下发到客户端的登录态(user 数据服务的单条形态,不含 tokens/bindings 明细)。 */
|
|
115
|
-
export type Auth = Pick<LoginToken, "token" | "expiredAt"> &
|
|
116
|
-
Pick<User, "id" | "name" | "authority" | "config">;
|
|
117
|
-
|
|
118
|
-
/** user 数据服务下发给客户端的完整鉴权数据:登录态 + 会话列表 + 绑定列表。 */
|
|
119
|
-
interface AuthData extends Auth {
|
|
120
|
-
tokens: Omit<LoginToken, "token" | "id">[];
|
|
121
|
-
bindings: Omit<Binding, "aid">[];
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
/** 登录方式:平台验证码 / 用户密码 / 已存令牌续期。 */
|
|
125
|
-
type LoginType = "platform" | "password" | "token";
|
|
126
|
-
|
|
127
|
-
// 随机令牌的字符表(数字 + 大小写字母)
|
|
128
|
-
const letters =
|
|
129
|
-
"0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
130
|
-
|
|
131
|
-
/**
|
|
132
|
-
* 生成指定长度的随机令牌字符串。
|
|
133
|
-
* @param length 令牌长度,默认 40
|
|
134
|
-
* @returns 从字符表随机取字符拼接成的字符串
|
|
135
|
-
*/
|
|
136
|
-
export function randomId(length = 40) {
|
|
137
|
-
// 登录令牌的安全敏感源:randomBytes(CSPRNG)+ 拒绝采样消除模偏差
|
|
138
|
-
// (256 % 62 != 0),格式契约(字符表与长度)保持不变
|
|
139
|
-
let out = "";
|
|
140
|
-
while (out.length < length) {
|
|
141
|
-
// 两倍余量覆盖拒绝采样损耗,极端涨落由外层 while 兜底补取
|
|
142
|
-
for (const byte of randomBytes(length * 2)) {
|
|
143
|
-
if (out.length >= length) break;
|
|
144
|
-
if (byte >= 248) continue;
|
|
145
|
-
out += letters[byte % letters.length] ?? "";
|
|
146
|
-
}
|
|
147
|
-
}
|
|
148
|
-
return out;
|
|
149
|
-
}
|
|
150
|
-
|
|
151
|
-
/** login/platform 事件的返回值:待登录用户信息 + 一次性验证码及其过期时间。 */
|
|
152
|
-
export interface UserLogin
|
|
153
|
-
extends Pick<User, "id" | "name"> {
|
|
154
|
-
token: string;
|
|
155
|
-
expiredAt: number;
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
/** user/update 事件允许修改的用户字段。 */
|
|
159
|
-
export type UserUpdate = Partial<
|
|
160
|
-
Pick<User, "name" | "password" | "config">
|
|
161
|
-
>;
|
|
162
|
-
|
|
163
|
-
/** PBKDF2-HMAC-SHA256 迭代次数(OWASP 2023 建议 600k;登录低频,开销可接受) */
|
|
164
|
-
const PBKDF2_ROUNDS = 600_000;
|
|
165
|
-
|
|
166
|
-
/** 新格式密码哈希:`pbkdf2$<rounds>$<salt-hex>$<dk-hex>`(加盐 + 慢哈希)。 */
|
|
167
|
-
function toHash(password: string) {
|
|
168
|
-
const salt = randomBytes(16);
|
|
169
|
-
const dk = pbkdf2Sync(
|
|
170
|
-
password,
|
|
171
|
-
salt,
|
|
172
|
-
PBKDF2_ROUNDS,
|
|
173
|
-
32,
|
|
174
|
-
"sha256",
|
|
175
|
-
);
|
|
176
|
-
return `pbkdf2$${PBKDF2_ROUNDS}$${salt.toString("hex")}$${dk.toString("hex")}`;
|
|
177
|
-
}
|
|
178
|
-
|
|
179
|
-
/**
|
|
180
|
-
* 校验明文密码与库中存储是否匹配。
|
|
181
|
-
*
|
|
182
|
-
* 兼容两种存储格式:
|
|
183
|
-
* - `pbkdf2$...` 新格式:按存储的盐与迭代次数重派生,恒定时间比较;
|
|
184
|
-
* - 64 位十六进制旧格式:历史上无盐 SHA-256,仅用于校验(命中后由调用方
|
|
185
|
-
* 透明升级为 PBKDF2),同样以恒定时间比较。
|
|
186
|
-
*/
|
|
187
|
-
function verifyPassword(
|
|
188
|
-
password: string,
|
|
189
|
-
stored: string,
|
|
190
|
-
): boolean {
|
|
191
|
-
if (stored.startsWith("pbkdf2$")) {
|
|
192
|
-
const [, rounds, saltHex, dkHex] = stored.split("$");
|
|
193
|
-
if (!rounds || !saltHex || !dkHex) return false;
|
|
194
|
-
const expected = Buffer.from(dkHex, "hex");
|
|
195
|
-
const actual = pbkdf2Sync(
|
|
196
|
-
password,
|
|
197
|
-
Buffer.from(saltHex, "hex"),
|
|
198
|
-
Number(rounds),
|
|
199
|
-
expected.length,
|
|
200
|
-
"sha256",
|
|
201
|
-
);
|
|
202
|
-
// 长度已按 expected.length 派生,恒定时间比较不会抛错
|
|
203
|
-
return timingSafeEqual(actual, expected);
|
|
204
|
-
}
|
|
205
|
-
// 旧格式:裸 SHA-256 十六进制。
|
|
206
|
-
// 无盐 SHA-256 只用于存量密码的**校验**(不可删,删了旧用户无法登录),
|
|
207
|
-
// 命中后由调用方透明升级为 PBKDF2;新建密码一律走 toHash(pbkdf2$ 格式),
|
|
208
|
-
// 故此处非弱哈希存储,属误报(Default setup 不支持注释抑制,须在平台 dismiss)。
|
|
209
|
-
if (!/^[0-9a-f]{64}$/i.test(stored)) return false;
|
|
210
|
-
const actual = createHash("sha256")
|
|
211
|
-
.update(password)
|
|
212
|
-
.digest();
|
|
213
|
-
return timingSafeEqual(
|
|
214
|
-
actual,
|
|
215
|
-
Buffer.from(stored, "hex"),
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
|
|
219
96
|
/**
|
|
220
97
|
* 鉴权服务:维护控制台客户端的登录态。
|
|
221
98
|
*
|
|
@@ -307,7 +184,7 @@ class AuthService extends Service {
|
|
|
307
184
|
prod: resolve(import.meta.dir, "../dist"),
|
|
308
185
|
});
|
|
309
186
|
|
|
310
|
-
|
|
187
|
+
initLogin(this);
|
|
311
188
|
}
|
|
312
189
|
|
|
313
190
|
/** 启动时按配置确保管理员账户(id = 0)存在。 */
|
|
@@ -419,246 +296,6 @@ class AuthService extends Service {
|
|
|
419
296
|
token,
|
|
420
297
|
});
|
|
421
298
|
}
|
|
422
|
-
|
|
423
|
-
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
424
|
-
initLogin() {
|
|
425
|
-
const self = this;
|
|
426
|
-
const { ctx, config } = this;
|
|
427
|
-
// 平台验证码登录的进行中状态:键为 `${platform}:${userId}`,
|
|
428
|
-
// 值为 [验证码, 过期时间, 发起登录的客户端]
|
|
429
|
-
const states: Record<string, [string, number, Client]> =
|
|
430
|
-
{};
|
|
431
|
-
|
|
432
|
-
// 用户密码登录:校验通过后签发新令牌;
|
|
433
|
-
// 命中旧的无盐 SHA-256 存储时透明升级为 PBKDF2
|
|
434
|
-
ctx.console.addListener(
|
|
435
|
-
"login/password",
|
|
436
|
-
async function (name, password) {
|
|
437
|
-
const [user] = await ctx.database.get(
|
|
438
|
-
"user",
|
|
439
|
-
{ name },
|
|
440
|
-
["password", "name", "id", "authority", "config"],
|
|
441
|
-
);
|
|
442
|
-
if (
|
|
443
|
-
!user?.password ||
|
|
444
|
-
!verifyPassword(password, user.password)
|
|
445
|
-
)
|
|
446
|
-
throw new Error("用户名或密码错误。");
|
|
447
|
-
if (!user.password.startsWith("pbkdf2$")) {
|
|
448
|
-
await ctx.database.set("user", user.id, {
|
|
449
|
-
password: toHash(password),
|
|
450
|
-
});
|
|
451
|
-
}
|
|
452
|
-
await self.createToken(
|
|
453
|
-
this,
|
|
454
|
-
"password",
|
|
455
|
-
omit(user, ["password"]),
|
|
456
|
-
);
|
|
457
|
-
},
|
|
458
|
-
);
|
|
459
|
-
|
|
460
|
-
// 已存令牌续期登录:本地记录的令牌未过期即恢复登录态,
|
|
461
|
-
// 同时刷新该令牌的最后访问时间
|
|
462
|
-
ctx.console.addListener(
|
|
463
|
-
"login/token",
|
|
464
|
-
async function (aid, token) {
|
|
465
|
-
const [data] = await ctx.database.get(
|
|
466
|
-
"token",
|
|
467
|
-
{ id: aid, token },
|
|
468
|
-
["expiredAt"],
|
|
469
|
-
);
|
|
470
|
-
if (!data || data.expiredAt <= Date.now())
|
|
471
|
-
throw new Error("令牌已失效。");
|
|
472
|
-
const [user] = await ctx.database.get(
|
|
473
|
-
"user",
|
|
474
|
-
{ id: aid },
|
|
475
|
-
["id", "name", "authority", "config"],
|
|
476
|
-
);
|
|
477
|
-
if (!user) throw new Error("用户不存在。");
|
|
478
|
-
await ctx.database.set(
|
|
479
|
-
"token",
|
|
480
|
-
{ token },
|
|
481
|
-
{ lastUsedAt: new Date() },
|
|
482
|
-
);
|
|
483
|
-
await self.setAuth(this, {
|
|
484
|
-
...user,
|
|
485
|
-
...data,
|
|
486
|
-
token,
|
|
487
|
-
});
|
|
488
|
-
},
|
|
489
|
-
);
|
|
490
|
-
|
|
491
|
-
// 平台账户登录(第一步):校验平台账号存在后生成一次性验证码,
|
|
492
|
-
// 用户把验证码发给任意机器人即可完成登录/绑定(见下方中间件)。
|
|
493
|
-
// 状态在验证码过期或客户端断开时清理
|
|
494
|
-
ctx.console.addListener(
|
|
495
|
-
"login/platform",
|
|
496
|
-
async function (platform, userId) {
|
|
497
|
-
const user = await ctx.database.getUser(
|
|
498
|
-
platform,
|
|
499
|
-
userId,
|
|
500
|
-
["id", "name"],
|
|
501
|
-
);
|
|
502
|
-
if (!user) throw new Error("找不到此账户。");
|
|
503
|
-
if (this.auth?.id === user.id)
|
|
504
|
-
throw new Error("你已经绑定了此账户。");
|
|
505
|
-
|
|
506
|
-
const key = `${platform}:${userId}`;
|
|
507
|
-
// 固定 6 位数字验证码(padStart 补零);原 Math.random 实现
|
|
508
|
-
// 在短小数串时不足 6 位,且非 CSPRNG
|
|
509
|
-
const token = String(
|
|
510
|
-
randomInt(0, 1_000_000),
|
|
511
|
-
).padStart(6, "0");
|
|
512
|
-
const expiredAt =
|
|
513
|
-
Date.now() + config.loginTokenExpire;
|
|
514
|
-
states[key] = [token, expiredAt, this];
|
|
515
|
-
|
|
516
|
-
// 客户端断开或验证码超时即作废本次登录状态
|
|
517
|
-
const listener = () => {
|
|
518
|
-
delete states[key];
|
|
519
|
-
dispose();
|
|
520
|
-
this.socket.removeEventListener("close", dispose);
|
|
521
|
-
};
|
|
522
|
-
const dispose = ctx.setTimeout(() => {
|
|
523
|
-
const state = states[key];
|
|
524
|
-
if (state && state[1] >= Date.now()) listener();
|
|
525
|
-
}, config.loginTokenExpire);
|
|
526
|
-
this.socket.addEventListener("close", listener);
|
|
527
|
-
|
|
528
|
-
return {
|
|
529
|
-
id: user.id,
|
|
530
|
-
name: user.name,
|
|
531
|
-
token,
|
|
532
|
-
expiredAt,
|
|
533
|
-
};
|
|
534
|
-
},
|
|
535
|
-
);
|
|
536
|
-
|
|
537
|
-
// 平台账户登录(第二步):前置中间件捕获用户发给机器人的验证码——
|
|
538
|
-
// 客户端已登录则把该平台账号绑定到当前用户,否则为平台对应用户签发令牌
|
|
539
|
-
ctx.middleware(async (session, next) => {
|
|
540
|
-
const state = states[session.uid];
|
|
541
|
-
if (!state || state[0] !== session.stripped.content) {
|
|
542
|
-
return next();
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
const { platform, userId: pid } = session;
|
|
546
|
-
// states 的键由 `${platform}:${userId}` 构成,能命中即说明 userId 存在
|
|
547
|
-
if (!pid) return next();
|
|
548
|
-
if (state[2].auth) {
|
|
549
|
-
await ctx.database.set(
|
|
550
|
-
"binding",
|
|
551
|
-
{ platform, pid },
|
|
552
|
-
{ aid: state[2].auth.id },
|
|
553
|
-
);
|
|
554
|
-
return self.setAuth(state[2], state[2].auth);
|
|
555
|
-
} else {
|
|
556
|
-
const user = await session.observeUser([
|
|
557
|
-
"id",
|
|
558
|
-
"name",
|
|
559
|
-
"authority",
|
|
560
|
-
"config",
|
|
561
|
-
]);
|
|
562
|
-
return self.createToken(state[2], "platform", user);
|
|
563
|
-
}
|
|
564
|
-
}, true);
|
|
565
|
-
|
|
566
|
-
// 拦截带 authority 要求的 console 事件:未登录、令牌过期或
|
|
567
|
-
// 权限不足时拒绝(返回 true 表示拦截)
|
|
568
|
-
ctx.on(
|
|
569
|
-
"console/intercept",
|
|
570
|
-
async (client, listener) => {
|
|
571
|
-
if (!listener.authority) return false;
|
|
572
|
-
if (!client.auth) return true;
|
|
573
|
-
if (client.auth.expiredAt <= Date.now())
|
|
574
|
-
return true;
|
|
575
|
-
if (client.auth.authority < listener.authority)
|
|
576
|
-
return true;
|
|
577
|
-
return false;
|
|
578
|
-
},
|
|
579
|
-
);
|
|
580
|
-
|
|
581
|
-
// 删除指定登录会话(登出其它设备)
|
|
582
|
-
ctx.console.addListener(
|
|
583
|
-
"user/delete-token",
|
|
584
|
-
async function (inc) {
|
|
585
|
-
if (!this.auth) throw new Error("请先登录。");
|
|
586
|
-
const [data] = await ctx.database.get("token", {
|
|
587
|
-
id: this.auth.id,
|
|
588
|
-
inc,
|
|
589
|
-
});
|
|
590
|
-
if (!data) throw new Error("令牌不存在。");
|
|
591
|
-
await ctx.database.remove("token", { inc });
|
|
592
|
-
await self.setAuth(this);
|
|
593
|
-
},
|
|
594
|
-
);
|
|
595
|
-
|
|
596
|
-
// 退出登录:删除当前令牌并清除登录态
|
|
597
|
-
ctx.console.addListener(
|
|
598
|
-
"user/logout",
|
|
599
|
-
async function () {
|
|
600
|
-
if (this.auth) {
|
|
601
|
-
await ctx.database.remove("token", {
|
|
602
|
-
token: this.auth.token,
|
|
603
|
-
});
|
|
604
|
-
}
|
|
605
|
-
await self.setAuth(this, undefined);
|
|
606
|
-
},
|
|
607
|
-
);
|
|
608
|
-
|
|
609
|
-
// 修改用户资料(用户名 / 密码 / 配置),密码先哈希再落库
|
|
610
|
-
ctx.console.addListener(
|
|
611
|
-
"user/update",
|
|
612
|
-
async function (data) {
|
|
613
|
-
if (!this.auth) throw new Error("请先登录。");
|
|
614
|
-
if (data.password)
|
|
615
|
-
data.password = toHash(data.password);
|
|
616
|
-
await ctx.database.set(
|
|
617
|
-
"user",
|
|
618
|
-
{ id: this.auth.id },
|
|
619
|
-
data,
|
|
620
|
-
);
|
|
621
|
-
Object.assign(this.auth, data);
|
|
622
|
-
await self.setAuth(this, undefined, true);
|
|
623
|
-
},
|
|
624
|
-
);
|
|
625
|
-
|
|
626
|
-
// 解绑平台账号:绑到别的用户时改指回其主账号;是自身主账号且
|
|
627
|
-
// 仅剩一个自绑定时拒绝解绑(避免用户失去登录途径),否则删除记录
|
|
628
|
-
ctx.console.addListener(
|
|
629
|
-
"user/unbind",
|
|
630
|
-
async function (platform, pid) {
|
|
631
|
-
if (!this.auth) throw new Error("请先登录。");
|
|
632
|
-
const bindings = await ctx.database.get("binding", {
|
|
633
|
-
aid: this.auth.id,
|
|
634
|
-
});
|
|
635
|
-
// 客户端仅对已列出的绑定发起解绑,查找必命中,未命中视为异常状态
|
|
636
|
-
const binding = bindings.find(
|
|
637
|
-
(item) =>
|
|
638
|
-
item.platform === platform && item.pid === pid,
|
|
639
|
-
);
|
|
640
|
-
if (!binding) throw new Error("绑定不存在。");
|
|
641
|
-
if (binding.aid !== binding.bid) {
|
|
642
|
-
await ctx.database.set(
|
|
643
|
-
"binding",
|
|
644
|
-
{ platform, pid },
|
|
645
|
-
{ aid: binding.bid },
|
|
646
|
-
);
|
|
647
|
-
} else if (
|
|
648
|
-
bindings.filter((item) => item.aid === item.bid)
|
|
649
|
-
.length === 1
|
|
650
|
-
) {
|
|
651
|
-
throw new Error("无法解除绑定。");
|
|
652
|
-
} else {
|
|
653
|
-
await ctx.database.remove("binding", {
|
|
654
|
-
platform,
|
|
655
|
-
pid,
|
|
656
|
-
});
|
|
657
|
-
}
|
|
658
|
-
await self.setAuth(this);
|
|
659
|
-
},
|
|
660
|
-
);
|
|
661
|
-
}
|
|
662
299
|
}
|
|
663
300
|
|
|
664
301
|
// 纯类型 namespace(仅含接口,erasableSyntaxOnly 允许),与上面的 class 合并声明
|
|
@@ -677,4 +314,12 @@ namespace AuthService {
|
|
|
677
314
|
}
|
|
678
315
|
}
|
|
679
316
|
|
|
317
|
+
export { randomId } from "./crypto.ts";
|
|
318
|
+
export type {
|
|
319
|
+
Auth,
|
|
320
|
+
LoginToken,
|
|
321
|
+
UserLogin,
|
|
322
|
+
UserUpdate,
|
|
323
|
+
} from "./types.ts";
|
|
324
|
+
|
|
680
325
|
export default AuthService;
|
package/src/login.ts
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
1
|
+
// SPDX-License-Identifier: AGPL-3.0-only
|
|
2
|
+
// Copyright (c) 2019-present Shigma and Koishijs contributors.
|
|
3
|
+
// Copyright (c) 2026-present Koishi-CE contributors.
|
|
4
|
+
|
|
5
|
+
// upstream: koishijs/webui plugins/auth/src/index.ts initLogin 段(上游为单文件 plugin-auth 4.1.7,本仓拆分时抽离至本文件并参数化 this→auth,同步时以其整体 diff 对照本目录)
|
|
6
|
+
|
|
7
|
+
import { randomInt } from "node:crypto";
|
|
8
|
+
import type { Client } from "@koishi-ce/console";
|
|
9
|
+
import { type Context, omit } from "@koishi-ce/koishi";
|
|
10
|
+
import { toHash, verifyPassword } from "./crypto.ts";
|
|
11
|
+
import type AuthService from "./index.ts";
|
|
12
|
+
|
|
13
|
+
/** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
|
|
14
|
+
export function initLogin(auth: AuthService) {
|
|
15
|
+
const self = auth;
|
|
16
|
+
// Service 基类的 ctx 为 protected,initLogin 拆出类体外后不可直接
|
|
17
|
+
// 点访问;以交叉类型视图标注解构来源(运行时仍取实例上的同一属性,
|
|
18
|
+
// 无任何行为差异),config 本为公开成员,一并随解构取出
|
|
19
|
+
const { ctx, config } = auth as AuthService & {
|
|
20
|
+
ctx: Context;
|
|
21
|
+
};
|
|
22
|
+
// 平台验证码登录的进行中状态:键为 `${platform}:${userId}`,
|
|
23
|
+
// 值为 [验证码, 过期时间, 发起登录的客户端]
|
|
24
|
+
const states: Record<string, [string, number, Client]> =
|
|
25
|
+
{};
|
|
26
|
+
|
|
27
|
+
// 用户密码登录:校验通过后签发新令牌
|
|
28
|
+
ctx.console.addListener(
|
|
29
|
+
"login/password",
|
|
30
|
+
async function (name, password) {
|
|
31
|
+
const [user] = await ctx.database.get(
|
|
32
|
+
"user",
|
|
33
|
+
{ name },
|
|
34
|
+
["password", "name", "id", "authority", "config"],
|
|
35
|
+
);
|
|
36
|
+
if (
|
|
37
|
+
!user?.password ||
|
|
38
|
+
!verifyPassword(password, user.password)
|
|
39
|
+
)
|
|
40
|
+
throw new Error("用户名或密码错误。");
|
|
41
|
+
await self.createToken(
|
|
42
|
+
this,
|
|
43
|
+
"password",
|
|
44
|
+
omit(user, ["password"]),
|
|
45
|
+
);
|
|
46
|
+
},
|
|
47
|
+
);
|
|
48
|
+
|
|
49
|
+
// 已存令牌续期登录:本地记录的令牌未过期即恢复登录态,
|
|
50
|
+
// 同时刷新该令牌的最后访问时间
|
|
51
|
+
ctx.console.addListener(
|
|
52
|
+
"login/token",
|
|
53
|
+
async function (aid, token) {
|
|
54
|
+
const [data] = await ctx.database.get(
|
|
55
|
+
"token",
|
|
56
|
+
{ id: aid, token },
|
|
57
|
+
["expiredAt"],
|
|
58
|
+
);
|
|
59
|
+
if (!data || data.expiredAt <= Date.now())
|
|
60
|
+
throw new Error("令牌已失效。");
|
|
61
|
+
const [user] = await ctx.database.get(
|
|
62
|
+
"user",
|
|
63
|
+
{ id: aid },
|
|
64
|
+
["id", "name", "authority", "config"],
|
|
65
|
+
);
|
|
66
|
+
if (!user) throw new Error("用户不存在。");
|
|
67
|
+
await ctx.database.set(
|
|
68
|
+
"token",
|
|
69
|
+
{ token },
|
|
70
|
+
{ lastUsedAt: new Date() },
|
|
71
|
+
);
|
|
72
|
+
await self.setAuth(this, {
|
|
73
|
+
...user,
|
|
74
|
+
...data,
|
|
75
|
+
token,
|
|
76
|
+
});
|
|
77
|
+
},
|
|
78
|
+
);
|
|
79
|
+
|
|
80
|
+
// 平台账户登录(第一步):校验平台账号存在后生成一次性验证码,
|
|
81
|
+
// 用户把验证码发给任意机器人即可完成登录/绑定(见下方中间件)。
|
|
82
|
+
// 状态在验证码过期或客户端断开时清理
|
|
83
|
+
ctx.console.addListener(
|
|
84
|
+
"login/platform",
|
|
85
|
+
async function (platform, userId) {
|
|
86
|
+
const user = await ctx.database.getUser(
|
|
87
|
+
platform,
|
|
88
|
+
userId,
|
|
89
|
+
["id", "name"],
|
|
90
|
+
);
|
|
91
|
+
if (!user) throw new Error("找不到此账户。");
|
|
92
|
+
if (this.auth?.id === user.id)
|
|
93
|
+
throw new Error("你已经绑定了此账户。");
|
|
94
|
+
|
|
95
|
+
const key = `${platform}:${userId}`;
|
|
96
|
+
// 固定 6 位数字验证码(padStart 补零);原 Math.random 实现
|
|
97
|
+
// 在短小数串时不足 6 位,且非 CSPRNG
|
|
98
|
+
const token = String(
|
|
99
|
+
randomInt(0, 1_000_000),
|
|
100
|
+
).padStart(6, "0");
|
|
101
|
+
const expiredAt =
|
|
102
|
+
Date.now() + config.loginTokenExpire;
|
|
103
|
+
states[key] = [token, expiredAt, this];
|
|
104
|
+
|
|
105
|
+
// 客户端断开或验证码超时即作废本次登录状态
|
|
106
|
+
const listener = () => {
|
|
107
|
+
delete states[key];
|
|
108
|
+
dispose();
|
|
109
|
+
this.socket.removeEventListener("close", dispose);
|
|
110
|
+
};
|
|
111
|
+
const dispose = ctx.setTimeout(() => {
|
|
112
|
+
const state = states[key];
|
|
113
|
+
if (state && state[1] >= Date.now()) listener();
|
|
114
|
+
}, config.loginTokenExpire);
|
|
115
|
+
this.socket.addEventListener("close", listener);
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
id: user.id,
|
|
119
|
+
name: user.name,
|
|
120
|
+
token,
|
|
121
|
+
expiredAt,
|
|
122
|
+
};
|
|
123
|
+
},
|
|
124
|
+
);
|
|
125
|
+
|
|
126
|
+
// 平台账户登录(第二步):前置中间件捕获用户发给机器人的验证码——
|
|
127
|
+
// 客户端已登录则把该平台账号绑定到当前用户,否则为平台对应用户签发令牌
|
|
128
|
+
ctx.middleware(async (session, next) => {
|
|
129
|
+
const state = states[session.uid];
|
|
130
|
+
if (!state || state[0] !== session.stripped.content) {
|
|
131
|
+
return next();
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const { platform, userId: pid } = session;
|
|
135
|
+
// states 的键由 `${platform}:${userId}` 构成,能命中即说明 userId 存在
|
|
136
|
+
if (!pid) return next();
|
|
137
|
+
if (state[2].auth) {
|
|
138
|
+
await ctx.database.set(
|
|
139
|
+
"binding",
|
|
140
|
+
{ platform, pid },
|
|
141
|
+
{ aid: state[2].auth.id },
|
|
142
|
+
);
|
|
143
|
+
return self.setAuth(state[2], state[2].auth);
|
|
144
|
+
} else {
|
|
145
|
+
const user = await session.observeUser([
|
|
146
|
+
"id",
|
|
147
|
+
"name",
|
|
148
|
+
"authority",
|
|
149
|
+
"config",
|
|
150
|
+
]);
|
|
151
|
+
return self.createToken(state[2], "platform", user);
|
|
152
|
+
}
|
|
153
|
+
}, true);
|
|
154
|
+
|
|
155
|
+
// 拦截带 authority 要求的 console 事件:未登录、令牌过期或
|
|
156
|
+
// 权限不足时拒绝(返回 true 表示拦截)
|
|
157
|
+
ctx.on("console/intercept", async (client, listener) => {
|
|
158
|
+
if (!listener.authority) return false;
|
|
159
|
+
if (!client.auth) return true;
|
|
160
|
+
if (client.auth.expiredAt <= Date.now()) return true;
|
|
161
|
+
if (client.auth.authority < listener.authority)
|
|
162
|
+
return true;
|
|
163
|
+
return false;
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
// 删除指定登录会话(登出其它设备)
|
|
167
|
+
ctx.console.addListener(
|
|
168
|
+
"user/delete-token",
|
|
169
|
+
async function (inc) {
|
|
170
|
+
if (!this.auth) throw new Error("请先登录。");
|
|
171
|
+
const [data] = await ctx.database.get("token", {
|
|
172
|
+
id: this.auth.id,
|
|
173
|
+
inc,
|
|
174
|
+
});
|
|
175
|
+
if (!data) throw new Error("令牌不存在。");
|
|
176
|
+
await ctx.database.remove("token", { inc });
|
|
177
|
+
await self.setAuth(this);
|
|
178
|
+
},
|
|
179
|
+
);
|
|
180
|
+
|
|
181
|
+
// 退出登录:删除当前令牌并清除登录态
|
|
182
|
+
ctx.console.addListener("user/logout", async function () {
|
|
183
|
+
if (this.auth) {
|
|
184
|
+
await ctx.database.remove("token", {
|
|
185
|
+
token: this.auth.token,
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
await self.setAuth(this, undefined);
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
// 修改用户资料(用户名 / 密码 / 配置),密码先哈希再落库
|
|
192
|
+
ctx.console.addListener(
|
|
193
|
+
"user/update",
|
|
194
|
+
async function (data) {
|
|
195
|
+
if (!this.auth) throw new Error("请先登录。");
|
|
196
|
+
if (data.password)
|
|
197
|
+
data.password = toHash(data.password);
|
|
198
|
+
await ctx.database.set(
|
|
199
|
+
"user",
|
|
200
|
+
{ id: this.auth.id },
|
|
201
|
+
data,
|
|
202
|
+
);
|
|
203
|
+
Object.assign(this.auth, data);
|
|
204
|
+
await self.setAuth(this, undefined, true);
|
|
205
|
+
},
|
|
206
|
+
);
|
|
207
|
+
|
|
208
|
+
// 解绑平台账号:绑到别的用户时改指回其主账号;是自身主账号且
|
|
209
|
+
// 仅剩一个自绑定时拒绝解绑(避免用户失去登录途径),否则删除记录
|
|
210
|
+
ctx.console.addListener(
|
|
211
|
+
"user/unbind",
|
|
212
|
+
async function (platform, pid) {
|
|
213
|
+
if (!this.auth) throw new Error("请先登录。");
|
|
214
|
+
const bindings = await ctx.database.get("binding", {
|
|
215
|
+
aid: this.auth.id,
|
|
216
|
+
});
|
|
217
|
+
// 客户端仅对已列出的绑定发起解绑,查找必命中,未命中视为异常状态
|
|
218
|
+
const binding = bindings.find(
|
|
219
|
+
(item) =>
|
|
220
|
+
item.platform === platform && item.pid === pid,
|
|
221
|
+
);
|
|
222
|
+
if (!binding) throw new Error("绑定不存在。");
|
|
223
|
+
if (binding.aid !== binding.bid) {
|
|
224
|
+
await ctx.database.set(
|
|
225
|
+
"binding",
|
|
226
|
+
{ platform, pid },
|
|
227
|
+
{ aid: binding.bid },
|
|
228
|
+
);
|
|
229
|
+
} else if (
|
|
230
|
+
bindings.filter((item) => item.aid === item.bid)
|
|
231
|
+
.length === 1
|
|
232
|
+
) {
|
|
233
|
+
throw new Error("无法解除绑定。");
|
|
234
|
+
} else {
|
|
235
|
+
await ctx.database.remove("binding", {
|
|
236
|
+
platform,
|
|
237
|
+
pid,
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
await self.setAuth(this);
|
|
241
|
+
},
|
|
242
|
+
);
|
|
243
|
+
}
|