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