@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 CHANGED
@@ -10,7 +10,7 @@
10
10
  - **平台验证码**:`login/platform`,网页生成 6 位验证码,用户把验证码发给任意机器人完成登录(同时可绑定平台账号,支持私聊一步、群聊两步);
11
11
  - **令牌续期**:`login/token`,已保存的登录令牌静默续期,页面刷新自动执行。
12
12
 
13
- 密码哈希采用 PBKDF2-HMAC-SHA256(600k 轮,OWASP 2023 建议);历史无盐 SHA-256 哈希在命中后透明升级。
13
+ 密码哈希采用 PBKDF2-HMAC-SHA256(600k 轮,OWASP 2023 建议);仅接受该格式,历史无盐 SHA-256 哈希不再兼容(存量旧哈希账户须重置密码)。
14
14
 
15
15
  ## 配置项
16
16
 
@@ -64,7 +64,7 @@ Console user authentication for Koishi, ported from `plugins/auth` of the upstre
64
64
  - **Platform verification code** (`login/platform`) — the web page shows a 6-digit code; the user sends it to any bot to log in (optionally binding the platform account; one step in private chat, two steps in groups).
65
65
  - **Token renewal** (`login/token`) — saved tokens renew silently; page refreshes do this automatically.
66
66
 
67
- Password hashing uses PBKDF2-HMAC-SHA256 (600k iterations, OWASP 2023); legacy unsalted SHA-256 hashes are transparently upgraded on first match.
67
+ Password hashing uses PBKDF2-HMAC-SHA256 (600k iterations, OWASP 2023); only that format is accepted — legacy unsalted SHA-256 hashes are no longer compatible (affected accounts must reset their password).
68
68
 
69
69
  ## Configuration
70
70
 
package/lib/index.d.ts CHANGED
@@ -1,40 +1,8 @@
1
1
  import { Binding, Context, Schema, Service, User } from "@koishi-ce/koishi";
2
2
  import { Client, DataService } from "@koishi-ce/console";
3
- //#region src/index.d.ts
4
- declare module "@koishi-ce/koishi" {
5
- interface Context {
6
- auth: AuthService;
7
- }
8
- interface User {
9
- password: string;
10
- /** 客户端控制台配置的 JSON 快照(内容仅由浏览器端解释,服务端透传;建表初始为 null) */
11
- config: object | null;
12
- }
13
- interface Tables {
14
- token: LoginToken;
15
- }
16
- }
17
- declare module "@koishi-ce/console" {
18
- interface Client {
19
- auth?: Auth | undefined;
20
- }
21
- namespace Console {
22
- interface Services {
23
- user: DataService<AuthData>;
24
- }
25
- }
26
- interface Events {
27
- "login/platform"(this: Client, platform: string, pid: string): Promise<UserLogin>;
28
- "login/password"(this: Client, name: string, password: string): void;
29
- "login/token"(this: Client, id: number, token: string): void;
30
- "user/delete-token"(this: Client, inc: number): void;
31
- "user/unbind"(this: Client, platform: string, pid: string): void;
32
- "user/update"(this: Client, data: UserUpdate): void;
33
- "user/logout"(this: Client): void;
34
- }
35
- }
3
+ //#region src/types.d.ts
36
4
  /** token 表记录:一次登录会话的令牌及其来源信息。 */
37
- export interface LoginToken {
5
+ interface LoginToken {
38
6
  /** 自增主键(删除指定会话用) */
39
7
  inc: number;
40
8
  /** 所属用户 id */
@@ -53,7 +21,7 @@ export interface LoginToken {
53
21
  address: string;
54
22
  }
55
23
  /** 下发到客户端的登录态(user 数据服务的单条形态,不含 tokens/bindings 明细)。 */
56
- export type Auth = Pick<LoginToken, "token" | "expiredAt"> & Pick<User, "id" | "name" | "authority" | "config">;
24
+ type Auth = Pick<LoginToken, "token" | "expiredAt"> & Pick<User, "id" | "name" | "authority" | "config">;
57
25
  /** user 数据服务下发给客户端的完整鉴权数据:登录态 + 会话列表 + 绑定列表。 */
58
26
  interface AuthData extends Auth {
59
27
  tokens: Omit<LoginToken, "token" | "id">[];
@@ -61,19 +29,55 @@ interface AuthData extends Auth {
61
29
  }
62
30
  /** 登录方式:平台验证码 / 用户密码 / 已存令牌续期。 */
63
31
  type LoginType = "platform" | "password" | "token";
32
+ /** login/platform 事件的返回值:待登录用户信息 + 一次性验证码及其过期时间。 */
33
+ interface UserLogin extends Pick<User, "id" | "name"> {
34
+ token: string;
35
+ expiredAt: number;
36
+ }
37
+ /** user/update 事件允许修改的用户字段。 */
38
+ type UserUpdate = Partial<Pick<User, "name" | "password" | "config">>;
39
+ //#endregion
40
+ //#region src/crypto.d.ts
64
41
  /**
65
42
  * 生成指定长度的随机令牌字符串。
66
43
  * @param length 令牌长度,默认 40
67
44
  * @returns 从字符表随机取字符拼接成的字符串
68
45
  */
69
46
  export declare function randomId(length?: number): string;
70
- /** login/platform 事件的返回值:待登录用户信息 + 一次性验证码及其过期时间。 */
71
- export interface UserLogin extends Pick<User, "id" | "name"> {
72
- token: string;
73
- expiredAt: number;
47
+ //#endregion
48
+ //#region src/index.d.ts
49
+ declare module "@koishi-ce/koishi" {
50
+ interface Context {
51
+ auth: AuthService;
52
+ }
53
+ interface User {
54
+ password: string;
55
+ /** 客户端控制台配置的 JSON 快照(内容仅由浏览器端解释,服务端透传;建表初始为 null) */
56
+ config: object | null;
57
+ }
58
+ interface Tables {
59
+ token: LoginToken;
60
+ }
61
+ }
62
+ declare module "@koishi-ce/console" {
63
+ interface Client {
64
+ auth?: Auth | undefined;
65
+ }
66
+ namespace Console {
67
+ interface Services {
68
+ user: DataService<AuthData>;
69
+ }
70
+ }
71
+ interface Events {
72
+ "login/platform"(this: Client, platform: string, pid: string): Promise<UserLogin>;
73
+ "login/password"(this: Client, name: string, password: string): void;
74
+ "login/token"(this: Client, id: number, token: string): void;
75
+ "user/delete-token"(this: Client, inc: number): void;
76
+ "user/unbind"(this: Client, platform: string, pid: string): void;
77
+ "user/update"(this: Client, data: UserUpdate): void;
78
+ "user/logout"(this: Client): void;
79
+ }
74
80
  }
75
- /** user/update 事件允许修改的用户字段。 */
76
- export type UserUpdate = Partial<Pick<User, "name" | "password" | "config">>;
77
81
  /**
78
82
  * 鉴权服务:维护控制台客户端的登录态。
79
83
  *
@@ -104,8 +108,6 @@ declare class AuthService extends Service {
104
108
  * 过期时长由 authTokenExpire 配置决定。
105
109
  */
106
110
  createToken(client: Client, type: LoginType, user: Pick<User, "id" | "name" | "authority" | "config">): Promise<void>;
107
- /** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
108
- initLogin(): void;
109
111
  }
110
112
  declare namespace AuthService {
111
113
  interface Admin {
@@ -120,4 +122,4 @@ declare namespace AuthService {
120
122
  }
121
123
  }
122
124
  //#endregion
123
- export { AuthService as default };
125
+ export { type Auth, type LoginToken, type UserLogin, type UserUpdate, AuthService as default };
package/lib/index.mjs CHANGED
@@ -1,17 +1,8 @@
1
- import { createHash, pbkdf2Sync, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
2
1
  import { resolve } from "node:path";
3
2
  import { Schema, Service, Time, omit } from "@koishi-ce/koishi";
4
3
  import zhCN from "./assets/zh-CN-DChWGTwa.yml";
5
- //#region src/index.ts
6
- /**
7
- * auth 插件(服务端):控制台登录鉴权。
8
- *
9
- * 向应用注入 ctx.auth 服务(AuthService):扩展 user 表的 password 字段
10
- * 并建立 token 会话表,支持用户密码 / 平台验证码 / 已存令牌三种登录方式,
11
- * 维护每个 WebSocket 客户端的登录态(client.auth),并按登录用户的权限
12
- * 拦截 console 事件。浏览器端对应实现在 ../client/(登录页、个人资料页、
13
- * 配置同步对话框)。
14
- */
4
+ import { pbkdf2Sync, randomBytes, randomInt, timingSafeEqual } from "node:crypto";
5
+ //#region src/crypto.ts
15
6
  const letters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
16
7
  /**
17
8
  * 生成指定长度的随机令牌字符串。
@@ -38,23 +29,161 @@ function toHash(password) {
38
29
  /**
39
30
  * 校验明文密码与库中存储是否匹配。
40
31
  *
41
- * 兼容两种存储格式:
42
- * - `pbkdf2$...` 新格式:按存储的盐与迭代次数重派生,恒定时间比较;
43
- * - 64 位十六进制旧格式:历史上无盐 SHA-256,仅用于校验(命中后由调用方
44
- * 透明升级为 PBKDF2),同样以恒定时间比较。
32
+ * 仅接受 `pbkdf2$...` 格式:按存储的盐与迭代次数重派生,恒定时间比较;
33
+ * 其余形态(含历史上游遗留的无盐 SHA-256 十六进制)一律不匹配。
45
34
  */
46
35
  function verifyPassword(password, stored) {
47
- if (stored.startsWith("pbkdf2$")) {
48
- const [, rounds, saltHex, dkHex] = stored.split("$");
49
- if (!rounds || !saltHex || !dkHex) return false;
50
- const expected = Buffer.from(dkHex, "hex");
51
- const actual = pbkdf2Sync(password, Buffer.from(saltHex, "hex"), Number(rounds), expected.length, "sha256");
52
- return timingSafeEqual(actual, expected);
53
- }
54
- if (!/^[0-9a-f]{64}$/i.test(stored)) return false;
55
- const actual = createHash("sha256").update(password).digest();
56
- return timingSafeEqual(actual, Buffer.from(stored, "hex"));
36
+ if (!stored.startsWith("pbkdf2$")) return false;
37
+ const [, rounds, saltHex, dkHex] = stored.split("$");
38
+ if (!rounds || !saltHex || !dkHex) return false;
39
+ const expected = Buffer.from(dkHex, "hex");
40
+ const actual = pbkdf2Sync(password, Buffer.from(saltHex, "hex"), Number(rounds), expected.length, "sha256");
41
+ return timingSafeEqual(actual, expected);
42
+ }
43
+ //#endregion
44
+ //#region src/login.ts
45
+ /** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
46
+ function initLogin(auth) {
47
+ const self = auth;
48
+ const { ctx, config } = auth;
49
+ const states = {};
50
+ ctx.console.addListener("login/password", async function(name, password) {
51
+ const [user] = await ctx.database.get("user", { name }, [
52
+ "password",
53
+ "name",
54
+ "id",
55
+ "authority",
56
+ "config"
57
+ ]);
58
+ if (!user?.password || !verifyPassword(password, user.password)) throw new Error("用户名或密码错误。");
59
+ await self.createToken(this, "password", omit(user, ["password"]));
60
+ });
61
+ ctx.console.addListener("login/token", async function(aid, token) {
62
+ const [data] = await ctx.database.get("token", {
63
+ id: aid,
64
+ token
65
+ }, ["expiredAt"]);
66
+ if (!data || data.expiredAt <= Date.now()) throw new Error("令牌已失效。");
67
+ const [user] = await ctx.database.get("user", { id: aid }, [
68
+ "id",
69
+ "name",
70
+ "authority",
71
+ "config"
72
+ ]);
73
+ if (!user) throw new Error("用户不存在。");
74
+ await ctx.database.set("token", { token }, { lastUsedAt: /* @__PURE__ */ new Date() });
75
+ await self.setAuth(this, {
76
+ ...user,
77
+ ...data,
78
+ token
79
+ });
80
+ });
81
+ ctx.console.addListener("login/platform", async function(platform, userId) {
82
+ const user = await ctx.database.getUser(platform, userId, ["id", "name"]);
83
+ if (!user) throw new Error("找不到此账户。");
84
+ if (this.auth?.id === user.id) throw new Error("你已经绑定了此账户。");
85
+ const key = `${platform}:${userId}`;
86
+ const token = String(randomInt(0, 1e6)).padStart(6, "0");
87
+ const expiredAt = Date.now() + config.loginTokenExpire;
88
+ states[key] = [
89
+ token,
90
+ expiredAt,
91
+ this
92
+ ];
93
+ const listener = () => {
94
+ delete states[key];
95
+ dispose();
96
+ this.socket.removeEventListener("close", dispose);
97
+ };
98
+ const dispose = ctx.setTimeout(() => {
99
+ const state = states[key];
100
+ if (state && state[1] >= Date.now()) listener();
101
+ }, config.loginTokenExpire);
102
+ this.socket.addEventListener("close", listener);
103
+ return {
104
+ id: user.id,
105
+ name: user.name,
106
+ token,
107
+ expiredAt
108
+ };
109
+ });
110
+ ctx.middleware(async (session, next) => {
111
+ const state = states[session.uid];
112
+ if (!state || state[0] !== session.stripped.content) return next();
113
+ const { platform, userId: pid } = session;
114
+ if (!pid) return next();
115
+ if (state[2].auth) {
116
+ await ctx.database.set("binding", {
117
+ platform,
118
+ pid
119
+ }, { aid: state[2].auth.id });
120
+ return self.setAuth(state[2], state[2].auth);
121
+ } else {
122
+ const user = await session.observeUser([
123
+ "id",
124
+ "name",
125
+ "authority",
126
+ "config"
127
+ ]);
128
+ return self.createToken(state[2], "platform", user);
129
+ }
130
+ }, true);
131
+ ctx.on("console/intercept", async (client, listener) => {
132
+ if (!listener.authority) return false;
133
+ if (!client.auth) return true;
134
+ if (client.auth.expiredAt <= Date.now()) return true;
135
+ if (client.auth.authority < listener.authority) return true;
136
+ return false;
137
+ });
138
+ ctx.console.addListener("user/delete-token", async function(inc) {
139
+ if (!this.auth) throw new Error("请先登录。");
140
+ const [data] = await ctx.database.get("token", {
141
+ id: this.auth.id,
142
+ inc
143
+ });
144
+ if (!data) throw new Error("令牌不存在。");
145
+ await ctx.database.remove("token", { inc });
146
+ await self.setAuth(this);
147
+ });
148
+ ctx.console.addListener("user/logout", async function() {
149
+ if (this.auth) await ctx.database.remove("token", { token: this.auth.token });
150
+ await self.setAuth(this, void 0);
151
+ });
152
+ ctx.console.addListener("user/update", async function(data) {
153
+ if (!this.auth) throw new Error("请先登录。");
154
+ if (data.password) data.password = toHash(data.password);
155
+ await ctx.database.set("user", { id: this.auth.id }, data);
156
+ Object.assign(this.auth, data);
157
+ await self.setAuth(this, void 0, true);
158
+ });
159
+ ctx.console.addListener("user/unbind", async function(platform, pid) {
160
+ if (!this.auth) throw new Error("请先登录。");
161
+ const bindings = await ctx.database.get("binding", { aid: this.auth.id });
162
+ const binding = bindings.find((item) => item.platform === platform && item.pid === pid);
163
+ if (!binding) throw new Error("绑定不存在。");
164
+ if (binding.aid !== binding.bid) await ctx.database.set("binding", {
165
+ platform,
166
+ pid
167
+ }, { aid: binding.bid });
168
+ else if (bindings.filter((item) => item.aid === item.bid).length === 1) throw new Error("无法解除绑定。");
169
+ else await ctx.database.remove("binding", {
170
+ platform,
171
+ pid
172
+ });
173
+ await self.setAuth(this);
174
+ });
57
175
  }
176
+ //#endregion
177
+ //#region src/index.ts
178
+ /**
179
+ * auth 插件(服务端):控制台登录鉴权。
180
+ *
181
+ * 向应用注入 ctx.auth 服务(AuthService):扩展 user 表的 password 字段
182
+ * 并建立 token 会话表,支持用户密码 / 平台验证码 / 已存令牌三种登录方式,
183
+ * 维护每个 WebSocket 客户端的登录态(client.auth),并按登录用户的权限
184
+ * 拦截 console 事件。浏览器端对应实现在 ../client/(登录页、个人资料页、
185
+ * 配置同步对话框)。
186
+ */
58
187
  /**
59
188
  * 鉴权服务:维护控制台客户端的登录态。
60
189
  *
@@ -105,7 +234,7 @@ var AuthService = class AuthService extends Service {
105
234
  dev: resolve(import.meta.dir, "../client/index.ts"),
106
235
  prod: resolve(import.meta.dir, "../dist")
107
236
  });
108
- this.initLogin();
237
+ initLogin(this);
109
238
  }
110
239
  /** 启动时按配置确保管理员账户(id = 0)存在。 */
111
240
  async start() {
@@ -189,138 +318,6 @@ var AuthService = class AuthService extends Service {
189
318
  token
190
319
  });
191
320
  }
192
- /** 注册全部登录 / 用户管理事件与权限拦截逻辑(构造时调用)。 */
193
- initLogin() {
194
- const self = this;
195
- const { ctx, config } = this;
196
- const states = {};
197
- ctx.console.addListener("login/password", async function(name, password) {
198
- const [user] = await ctx.database.get("user", { name }, [
199
- "password",
200
- "name",
201
- "id",
202
- "authority",
203
- "config"
204
- ]);
205
- if (!user?.password || !verifyPassword(password, user.password)) throw new Error("用户名或密码错误。");
206
- if (!user.password.startsWith("pbkdf2$")) await ctx.database.set("user", user.id, { password: toHash(password) });
207
- await self.createToken(this, "password", omit(user, ["password"]));
208
- });
209
- ctx.console.addListener("login/token", async function(aid, token) {
210
- const [data] = await ctx.database.get("token", {
211
- id: aid,
212
- token
213
- }, ["expiredAt"]);
214
- if (!data || data.expiredAt <= Date.now()) throw new Error("令牌已失效。");
215
- const [user] = await ctx.database.get("user", { id: aid }, [
216
- "id",
217
- "name",
218
- "authority",
219
- "config"
220
- ]);
221
- if (!user) throw new Error("用户不存在。");
222
- await ctx.database.set("token", { token }, { lastUsedAt: /* @__PURE__ */ new Date() });
223
- await self.setAuth(this, {
224
- ...user,
225
- ...data,
226
- token
227
- });
228
- });
229
- ctx.console.addListener("login/platform", async function(platform, userId) {
230
- const user = await ctx.database.getUser(platform, userId, ["id", "name"]);
231
- if (!user) throw new Error("找不到此账户。");
232
- if (this.auth?.id === user.id) throw new Error("你已经绑定了此账户。");
233
- const key = `${platform}:${userId}`;
234
- const token = String(randomInt(0, 1e6)).padStart(6, "0");
235
- const expiredAt = Date.now() + config.loginTokenExpire;
236
- states[key] = [
237
- token,
238
- expiredAt,
239
- this
240
- ];
241
- const listener = () => {
242
- delete states[key];
243
- dispose();
244
- this.socket.removeEventListener("close", dispose);
245
- };
246
- const dispose = ctx.setTimeout(() => {
247
- const state = states[key];
248
- if (state && state[1] >= Date.now()) listener();
249
- }, config.loginTokenExpire);
250
- this.socket.addEventListener("close", listener);
251
- return {
252
- id: user.id,
253
- name: user.name,
254
- token,
255
- expiredAt
256
- };
257
- });
258
- ctx.middleware(async (session, next) => {
259
- const state = states[session.uid];
260
- if (!state || state[0] !== session.stripped.content) return next();
261
- const { platform, userId: pid } = session;
262
- if (!pid) return next();
263
- if (state[2].auth) {
264
- await ctx.database.set("binding", {
265
- platform,
266
- pid
267
- }, { aid: state[2].auth.id });
268
- return self.setAuth(state[2], state[2].auth);
269
- } else {
270
- const user = await session.observeUser([
271
- "id",
272
- "name",
273
- "authority",
274
- "config"
275
- ]);
276
- return self.createToken(state[2], "platform", user);
277
- }
278
- }, true);
279
- ctx.on("console/intercept", async (client, listener) => {
280
- if (!listener.authority) return false;
281
- if (!client.auth) return true;
282
- if (client.auth.expiredAt <= Date.now()) return true;
283
- if (client.auth.authority < listener.authority) return true;
284
- return false;
285
- });
286
- ctx.console.addListener("user/delete-token", async function(inc) {
287
- if (!this.auth) throw new Error("请先登录。");
288
- const [data] = await ctx.database.get("token", {
289
- id: this.auth.id,
290
- inc
291
- });
292
- if (!data) throw new Error("令牌不存在。");
293
- await ctx.database.remove("token", { inc });
294
- await self.setAuth(this);
295
- });
296
- ctx.console.addListener("user/logout", async function() {
297
- if (this.auth) await ctx.database.remove("token", { token: this.auth.token });
298
- await self.setAuth(this, void 0);
299
- });
300
- ctx.console.addListener("user/update", async function(data) {
301
- if (!this.auth) throw new Error("请先登录。");
302
- if (data.password) data.password = toHash(data.password);
303
- await ctx.database.set("user", { id: this.auth.id }, data);
304
- Object.assign(this.auth, data);
305
- await self.setAuth(this, void 0, true);
306
- });
307
- ctx.console.addListener("user/unbind", async function(platform, pid) {
308
- if (!this.auth) throw new Error("请先登录。");
309
- const bindings = await ctx.database.get("binding", { aid: this.auth.id });
310
- const binding = bindings.find((item) => item.platform === platform && item.pid === pid);
311
- if (!binding) throw new Error("绑定不存在。");
312
- if (binding.aid !== binding.bid) await ctx.database.set("binding", {
313
- platform,
314
- pid
315
- }, { aid: binding.bid });
316
- else if (bindings.filter((item) => item.aid === item.bid).length === 1) throw new Error("无法解除绑定。");
317
- else await ctx.database.remove("binding", {
318
- platform,
319
- pid
320
- });
321
- await self.setAuth(this);
322
- });
323
- }
324
321
  };
325
322
  //#endregion
326
323
  export { AuthService as default, randomId };
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@koishi-ce/plugin-auth",
3
3
  "description": "Console User Authentication",
4
- "version": "1.1.1",
4
+ "version": "1.1.3",
5
5
  "type": "module",
6
6
  "main": "lib/index.mjs",
7
7
  "typings": "lib/index.d.ts",
@@ -54,13 +54,13 @@
54
54
  "@koishi-ce/koishi": "^1.0.0"
55
55
  },
56
56
  "devDependencies": {
57
- "@koishi-ce/plugin-database-memory": "^1.1.0",
58
- "@koishi-ce/client": "^1.2.4",
57
+ "@koishi-ce/plugin-database-memory": "^1.1.1",
58
+ "@koishi-ce/client": "^1.3.0",
59
59
  "vue": "^3.5.12",
60
60
  "vue-router": "^5.2.0"
61
61
  },
62
62
  "dependencies": {
63
- "@koishi-ce/console": "^1.0.1"
63
+ "@koishi-ce/console": "^1.1.0"
64
64
  },
65
65
  "exports": {
66
66
  ".": {