@wenbin_wb/dsh-bridge 2.4.0 → 2.5.1

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.
@@ -0,0 +1,470 @@
1
+ // lib/auth/manager.js
2
+ // 远程访问安全认证管理器:密码加盐哈希、Session 管理、免密安全 Token、防暴力破解与全协议鉴权拦截
3
+
4
+ import { randomBytes, pbkdf2Sync, timingSafeEqual } from 'node:crypto'
5
+
6
+ const DEFAULT_SESSION_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000 // 30 天
7
+ const MAX_FAILED_ATTEMPTS = 5
8
+ const LOCKOUT_PERIOD_MS = 60 * 1000 // 连续失败封禁 60 秒
9
+
10
+ export class AuthManager {
11
+ /**
12
+ * @param {object} opts
13
+ * @param {object} [opts.config]
14
+ * @param {boolean} [opts.config.enabled=false]
15
+ * @param {'token_and_password'|'password_only'|'token_only'} [opts.config.mode='token_and_password']
16
+ * @param {string} [opts.config.passwordHash]
17
+ * @param {string} [opts.config.passwordSalt]
18
+ * @param {string} [opts.config.secretToken]
19
+ * @param {boolean} [opts.config.allowLoopback=true]
20
+ * @param {(patch: object) => Promise<void>|void} [opts.onPersist]
21
+ * @param {object} [opts.logger]
22
+ */
23
+ constructor({ config = {}, onPersist, logger = console } = {}) {
24
+ this.logger = logger
25
+ this.onPersist = onPersist
26
+
27
+ this.enabled = Boolean(config.enabled)
28
+ this.mode = config.mode || 'token_and_password'
29
+ this.scope = config.scope || 'all' // 'all' | 'public_only' | 'lan_only'
30
+ this.adminPolicy = config.adminPolicy || 'password_unlock' // 'password_unlock' | 'local_only' | 'open'
31
+ this.passwordHash = config.passwordHash || ''
32
+ this.passwordSalt = config.passwordSalt || ''
33
+ this.adminPasswordHash = config.adminPasswordHash || ''
34
+ this.adminPasswordSalt = config.adminPasswordSalt || ''
35
+ this.secretToken = config.secretToken || this._generateToken()
36
+ this.allowLoopback = config.allowLoopback !== false
37
+ // 内部隧道专用鉴权密钥(内存生成,用于辨别本地自建隧道转发流量与真实本机访问)
38
+ this.internalTunnelSecret = randomBytes(24).toString('hex')
39
+
40
+ // Session 内存存储:sessionToken -> { createdAt, expiresAt }
41
+ this.sessions = new Map()
42
+ // 管理员解锁 Session 内存存储:adminToken -> { createdAt, expiresAt }
43
+ this.adminSessions = new Map()
44
+ // 防暴力破解:ip -> { failedCount, lockUntil }
45
+ this.rateLimits = new Map()
46
+
47
+ // 定期清理过期 Session (每小时)
48
+ this._cleanupTimer = setInterval(() => this._cleanupExpired(), 60 * 60 * 1000)
49
+ if (this._cleanupTimer.unref) this._cleanupTimer.unref()
50
+ }
51
+
52
+ _generateToken() {
53
+ return 'dsh_' + randomBytes(18).toString('hex')
54
+ }
55
+
56
+ _hashPassword(password, salt) {
57
+ return pbkdf2Sync(String(password), salt, 10000, 32, 'sha256').toString('hex')
58
+ }
59
+
60
+ get hasPassword() {
61
+ return Boolean(this.passwordHash && this.passwordSalt)
62
+ }
63
+
64
+ get hasAdminPassword() {
65
+ return Boolean(this.adminPasswordHash && this.adminPasswordSalt)
66
+ }
67
+
68
+ /**
69
+ * 获取安全认证状态(默认脱敏保护,防止普通接口泄露完整 Secret Token)
70
+ */
71
+ getStatus({ masked = true } = {}) {
72
+ let token = this.secretToken;
73
+ if (masked && token) {
74
+ token = `${token.slice(0, 8)}****************`;
75
+ }
76
+ return {
77
+ enabled: this.enabled,
78
+ mode: this.mode,
79
+ scope: this.scope,
80
+ adminPolicy: this.adminPolicy,
81
+ hasPassword: this.hasPassword,
82
+ hasAdminPassword: this.hasAdminPassword,
83
+ secretToken: token,
84
+ allowLoopback: this.allowLoopback,
85
+ }
86
+ }
87
+
88
+ /**
89
+ * 仅限经过鉴权的管理员会话或公开策略下获取原始未脱敏 Secret Token
90
+ */
91
+ getRawSecretToken(adminToken) {
92
+ if (this.adminPolicy !== 'open') {
93
+ const hasAnyPassword = this.hasAdminPassword || this.hasPassword
94
+ if (hasAnyPassword && (!adminToken || !this.validateAdminSession(adminToken))) {
95
+ return null
96
+ }
97
+ }
98
+ return this.secretToken
99
+ }
100
+
101
+ /**
102
+ * 公开状态查询(供未认证访客/登录页使用,严格不包含 secretToken)
103
+ */
104
+ getPublicStatus() {
105
+ return {
106
+ enabled: this.enabled,
107
+ mode: this.mode,
108
+ scope: this.scope,
109
+ adminPolicy: this.adminPolicy,
110
+ hasPassword: this.hasPassword,
111
+ hasAdminPassword: this.hasAdminPassword,
112
+ allowLoopback: this.allowLoopback,
113
+ }
114
+ }
115
+
116
+ async setEnabled(enabled) {
117
+ this.enabled = Boolean(enabled)
118
+ this.sessions.clear()
119
+ this.adminSessions.clear()
120
+ await this._persist()
121
+ }
122
+
123
+ async setMode(mode) {
124
+ if (['token_and_password', 'password_only', 'token_only'].includes(mode)) {
125
+ this.mode = mode
126
+ // 切换认证模式时清空所有现有 Session,确保新策略立即对所有设备生效
127
+ this.sessions.clear()
128
+ this.adminSessions.clear()
129
+ await this._persist()
130
+ }
131
+ }
132
+
133
+ async setScope(scope) {
134
+ if (['all', 'public_only', 'lan_only'].includes(scope)) {
135
+ this.scope = scope
136
+ this.sessions.clear()
137
+ this.adminSessions.clear()
138
+ await this._persist()
139
+ }
140
+ }
141
+
142
+ async setAdminPolicy(policy) {
143
+ if (['password_unlock', 'local_only', 'open'].includes(policy)) {
144
+ this.adminPolicy = policy
145
+ this.adminSessions.clear()
146
+ await this._persist()
147
+ }
148
+ }
149
+
150
+ // 设置外部访客访问密码
151
+ async setPassword(password) {
152
+ if (!password) {
153
+ this.passwordHash = ''
154
+ this.passwordSalt = ''
155
+ } else {
156
+ const salt = randomBytes(16).toString('hex')
157
+ const hash = this._hashPassword(password, salt)
158
+ this.passwordHash = hash
159
+ this.passwordSalt = salt
160
+ }
161
+ // 更改访问密码时使所有普通访客 Session 失效
162
+ this.sessions.clear()
163
+ await this._persist()
164
+ }
165
+
166
+ // 设置后台管理员密码
167
+ async setAdminPassword(password) {
168
+ if (!password) {
169
+ this.adminPasswordHash = ''
170
+ this.adminPasswordSalt = ''
171
+ } else {
172
+ const salt = randomBytes(16).toString('hex')
173
+ const hash = this._hashPassword(password, salt)
174
+ this.adminPasswordHash = hash
175
+ this.adminPasswordSalt = salt
176
+ }
177
+ // 更改管理密码时使所有远程管理员解锁 Session 失效
178
+ this.adminSessions.clear()
179
+ await this._persist()
180
+ }
181
+
182
+ async regenerateSecretToken() {
183
+ this.secretToken = this._generateToken()
184
+ this.sessions.clear()
185
+ await this._persist()
186
+ return this.secretToken
187
+ }
188
+
189
+ // 管理员解锁控制
190
+ createAdminSession(maxAgeMs = 30 * 60 * 1000) {
191
+ const adminToken = randomBytes(24).toString('hex')
192
+ const now = Date.now()
193
+ this.adminSessions.set(adminToken, {
194
+ createdAt: now,
195
+ expiresAt: now + maxAgeMs,
196
+ })
197
+ return adminToken
198
+ }
199
+
200
+ validateAdminSession(adminToken) {
201
+ if (!adminToken) return false
202
+ const sess = this.adminSessions.get(adminToken)
203
+ if (!sess) return false
204
+ if (Date.now() > sess.expiresAt) {
205
+ this.adminSessions.delete(adminToken)
206
+ return false
207
+ }
208
+ return true
209
+ }
210
+
211
+ revokeAdminSession(adminToken) {
212
+ if (adminToken) this.adminSessions.delete(adminToken)
213
+ }
214
+
215
+ verifyAdminPassword(inputPassword, clientIp = '') {
216
+ if (this.isIpBlocked(clientIp)) {
217
+ return { success: false, error: '尝试次数过多,请稍后再试' }
218
+ }
219
+
220
+ const targetHash = this.adminPasswordHash || this.passwordHash
221
+ const targetSalt = this.adminPasswordSalt || this.passwordSalt
222
+
223
+ if (!targetHash || !targetSalt) {
224
+ return { success: true }
225
+ }
226
+
227
+ const inputHash = this._hashPassword(inputPassword, targetSalt)
228
+ const bufA = Buffer.from(inputHash, 'hex')
229
+ const bufB = Buffer.from(targetHash, 'hex')
230
+
231
+ if (bufA.length === bufB.length && timingSafeEqual(bufA, bufB)) {
232
+ this.recordSuccess(clientIp)
233
+ return { success: true }
234
+ }
235
+
236
+ this.recordFailedAttempt(clientIp)
237
+ return { success: false, error: '管理员密码错误' }
238
+ }
239
+
240
+ unlockAdmin(password, clientIp = '') {
241
+ if (this.adminPolicy === 'local_only') {
242
+ return { ok: false, error: '当前已配置为仅限电脑本机管理设置' }
243
+ }
244
+ const hasAnyPassword = this.hasAdminPassword || this.hasPassword
245
+ if (!hasAnyPassword) {
246
+ const adminToken = this.createAdminSession()
247
+ return { ok: true, adminToken }
248
+ }
249
+ const verify = this.verifyAdminPassword(password, clientIp)
250
+ if (verify.success) {
251
+ const adminToken = this.createAdminSession()
252
+ return { ok: true, adminToken }
253
+ }
254
+ return { ok: false, error: verify.error || '管理员密码错误' }
255
+ }
256
+
257
+ async _persist() {
258
+ if (typeof this.onPersist === 'function') {
259
+ try {
260
+ await this.onPersist({
261
+ enabled: this.enabled,
262
+ mode: this.mode,
263
+ scope: this.scope,
264
+ adminPolicy: this.adminPolicy,
265
+ passwordHash: this.passwordHash,
266
+ passwordSalt: this.passwordSalt,
267
+ adminPasswordHash: this.adminPasswordHash,
268
+ adminPasswordSalt: this.adminPasswordSalt,
269
+ secretToken: this.secretToken,
270
+ allowLoopback: this.allowLoopback,
271
+ })
272
+ } catch (err) {
273
+ this.logger.error?.('[dsh-bridge auth] persist failed:', err?.message ?? err)
274
+ }
275
+ }
276
+ }
277
+
278
+ // ---- 认证校验逻辑 ----
279
+
280
+ /**
281
+ * 校验客户端密码
282
+ */
283
+ verifyPassword(inputPassword, clientIp = '') {
284
+ if (this.isIpBlocked(clientIp)) {
285
+ return { success: false, error: '尝试次数过多,请稍后再试' }
286
+ }
287
+
288
+ // 严禁 token_only 模式下通过密码登录接口获取 Session
289
+ if (this.mode === 'token_only') {
290
+ return { success: false, error: '当前仅允许专属安全 Token 扫码访问,不支持密码登录' }
291
+ }
292
+
293
+ if (!this.hasPassword) {
294
+ // 若处于仅密码模式但尚未设置密码,不允许直接空白登录
295
+ if (this.mode === 'password_only') {
296
+ return { success: false, error: '管理员尚未设置访问密码,请先在控制台中设置密码' }
297
+ }
298
+ return { success: true }
299
+ }
300
+
301
+ const inputHash = this._hashPassword(inputPassword, this.passwordSalt)
302
+ const bufA = Buffer.from(inputHash, 'hex')
303
+ const bufB = Buffer.from(this.passwordHash, 'hex')
304
+
305
+ if (bufA.length === bufB.length && timingSafeEqual(bufA, bufB)) {
306
+ this.recordSuccess(clientIp)
307
+ return { success: true }
308
+ }
309
+
310
+ this.recordFailedAttempt(clientIp)
311
+ return { success: false, error: '访问密码错误' }
312
+ }
313
+
314
+ /**
315
+ * 校验安全 Token
316
+ */
317
+ validateSecretToken(token) {
318
+ if (!token || !this.secretToken) return false
319
+ const bufA = Buffer.from(String(token))
320
+ const bufB = Buffer.from(String(this.secretToken))
321
+ if (bufA.length !== bufB.length) return false
322
+ return timingSafeEqual(bufA, bufB)
323
+ }
324
+
325
+ /**
326
+ * 创建 Session
327
+ */
328
+ createSession(maxAgeMs = DEFAULT_SESSION_MAX_AGE_MS) {
329
+ const sessionToken = randomBytes(24).toString('hex')
330
+ const now = Date.now()
331
+ this.sessions.set(sessionToken, {
332
+ createdAt: now,
333
+ expiresAt: now + maxAgeMs,
334
+ })
335
+ return sessionToken
336
+ }
337
+
338
+ /**
339
+ * 校验 Session
340
+ */
341
+ validateSession(sessionToken) {
342
+ if (!sessionToken) return false
343
+ const sess = this.sessions.get(sessionToken)
344
+ if (!sess) return false
345
+ if (Date.now() > sess.expiresAt) {
346
+ this.sessions.delete(sessionToken)
347
+ return false
348
+ }
349
+ return true
350
+ }
351
+
352
+ /**
353
+ * 销毁 Session
354
+ */
355
+ revokeSession(sessionToken) {
356
+ if (sessionToken) this.sessions.delete(sessionToken)
357
+ }
358
+
359
+ // ---- 防暴力破解 ----
360
+
361
+ isIpBlocked(ip) {
362
+ if (!ip) return false
363
+ const record = this.rateLimits.get(ip)
364
+ if (!record) return false
365
+ if (record.lockUntil && Date.now() < record.lockUntil) {
366
+ return true
367
+ }
368
+ if (record.lockUntil && Date.now() >= record.lockUntil) {
369
+ this.rateLimits.delete(ip)
370
+ return false
371
+ }
372
+ return false
373
+ }
374
+
375
+ recordFailedAttempt(ip) {
376
+ if (!ip) return
377
+ const now = Date.now()
378
+ const record = this.rateLimits.get(ip) || { failedCount: 0, lockUntil: 0 }
379
+ record.failedCount += 1
380
+ if (record.failedCount >= MAX_FAILED_ATTEMPTS) {
381
+ record.lockUntil = now + LOCKOUT_PERIOD_MS
382
+ this.logger.warn?.(`[dsh-bridge auth] IP ${ip} locked out for 60s due to repeated failed attempts`)
383
+ }
384
+ this.rateLimits.set(ip, record)
385
+ }
386
+
387
+ recordSuccess(ip) {
388
+ if (ip) this.rateLimits.delete(ip)
389
+ }
390
+
391
+ // ---- HTTP / WebSocket 请求总入口鉴权 ----
392
+
393
+ /**
394
+ * 检查请求是否已授权
395
+ * @param {import('node:http').IncomingMessage} req
396
+ * @returns {{ authenticated: boolean, fromToken?: boolean, sessionToken?: string, loopback?: boolean, bypass?: boolean, lanBypass?: boolean, publicBypass?: boolean }}
397
+ */
398
+ verifyRequest(req) {
399
+ // 1. 未开启认证 -> 允许直通
400
+ if (!this.enabled) {
401
+ return { authenticated: true, bypass: true }
402
+ }
403
+
404
+ const remote = req.socket?.remoteAddress || ''
405
+ const isLoopback = (remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1')
406
+
407
+ // 辨别是否来自自建隧道或 Cloudflare 隧道 (只有从 127.0.0.1 传入且带有合法内部凭据/Cloudflare 标头才算)
408
+ const internalTunnelHeader = req.headers?.['x-dsh-internal-tunnel']
409
+ const isCustomTunnel = Boolean(isLoopback && internalTunnelHeader && internalTunnelHeader === this.internalTunnelSecret)
410
+ const isCloudflare = Boolean(isLoopback && (req.headers?.['cf-ray'] || req.headers?.['cf-connecting-ip']))
411
+ const isPublicTunnel = isCustomTunnel || isCloudflare
412
+
413
+ // 2. 本地环回免认证(真正的宿主机物理浏览器 127.0.0.1 访问,非 Tunnel 转发)
414
+ if (this.allowLoopback && isLoopback && !isPublicTunnel) {
415
+ const host = String(req.headers?.host || '')
416
+ if (host.startsWith('127.0.0.1') || host.startsWith('localhost') || host === '') {
417
+ return { authenticated: true, loopback: true }
418
+ }
419
+ }
420
+
421
+ // 3. 检查防护范围 (scope: 'all' | 'public_only' | 'lan_only')
422
+ if (this.scope === 'public_only' && !isPublicTunnel) {
423
+ return { authenticated: true, lanBypass: true }
424
+ }
425
+
426
+ if (this.scope === 'lan_only' && isPublicTunnel) {
427
+ return { authenticated: true, publicBypass: true }
428
+ }
429
+
430
+ // 4. 从 Query 参数中解析 ?auth=token 或 ?token=token (用于扫码免密登录)
431
+ if (this.mode !== 'password_only') {
432
+ try {
433
+ const urlObj = new URL(req.url, 'http://localhost')
434
+ const queryToken = urlObj.searchParams.get('auth') || urlObj.searchParams.get('token')
435
+ if (queryToken && this.validateSecretToken(queryToken)) {
436
+ return { authenticated: true, fromToken: true, secretToken: queryToken }
437
+ }
438
+ } catch {}
439
+ }
440
+
441
+ // 5. 从 Cookie 中解析 Session Token: dsh_bridge_auth=<token>
442
+ const cookieHeader = req.headers?.cookie || ''
443
+ const match = /(?:^|;\s*)dsh_bridge_auth=([a-f0-9]+)/i.exec(cookieHeader)
444
+ if (match) {
445
+ const sessionToken = match[1]
446
+ if (this.validateSession(sessionToken)) {
447
+ return { authenticated: true, sessionToken }
448
+ }
449
+ }
450
+
451
+ // 未授权
452
+ return { authenticated: false }
453
+ }
454
+
455
+ _cleanupExpired() {
456
+ const now = Date.now()
457
+ for (const [t, s] of this.sessions.entries()) {
458
+ if (now > s.expiresAt) this.sessions.delete(t)
459
+ }
460
+ for (const [ip, r] of this.rateLimits.entries()) {
461
+ if (r.lockUntil && now > r.lockUntil) this.rateLimits.delete(ip)
462
+ }
463
+ }
464
+
465
+ dispose() {
466
+ clearInterval(this._cleanupTimer)
467
+ this.sessions.clear()
468
+ this.rateLimits.clear()
469
+ }
470
+ }
@@ -12,6 +12,12 @@ export const BRIDGE_ENDPOINTS = {
12
12
  saveCustomTunnelConfig: 'saveCustomTunnelConfig',
13
13
  checkVersion: 'checkVersion',
14
14
  upgradePlugin: 'upgradePlugin',
15
+ // 访问安全认证(密码保护 / 扫码免密 Token)
16
+ authGetStatus: 'authGetStatus',
17
+ authUpdateConfig: 'authUpdateConfig',
18
+ authRegenerateToken: 'authRegenerateToken',
19
+ authAdminUnlock: 'authAdminUnlock',
20
+ authAdminLock: 'authAdminLock',
15
21
  // 平台管理器(多 IM 平台统一接口)
16
22
  listPlatforms: 'listPlatforms',
17
23
  platformLogin: 'platformLogin',