@feiyang666/dsh-mobile-remote 1.8.1 → 1.9.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.
package/lib/password.js CHANGED
@@ -1,218 +1,245 @@
1
- // dsh-mobile-remote — 远程访问密码(本模块,host 侧)。
2
- //
3
- // 职责:
4
- // 1. **远程访问密码的本地安全存储与会话管理**。密码由管理员在本机设置面板
5
- // 设置(本模块路径 ~/.dsh/plugins/dsh-mobile-remote/config.json)。
6
- // 存储时**只存 scrypt 哈希 + 随机盐**,绝不落盘明文。
7
- // 2. **认证会话**:远程访问者输入正确密码后,向浏览器下发一个随机 token,
8
- // host 侧在内存中维护该 token 的过期时间;后续带有效 token 的请求视为
9
- // 已认证,无需重复输入。
10
- //
11
- // 设计要点(通用 / 可自托管):
12
- // - 完全本地,**不依赖任何中转后端**(dsh-update-server / frps / frpc)。
13
- // 任何部署者——包括自建中转服务的用户——都能用本模块给远程访问加密码。
14
- // - 全部使用 Node 内置 crypto,零第三方依赖。
15
- // - 校验采用 timingSafeEqual,避免时序攻击;登录做简单频率限制防爆破。
16
-
17
- import { randomBytes, scryptSync, timingSafeEqual, createHash } from 'node:crypto'
18
- import { homedir } from 'node:os'
19
- import { join } from 'node:path'
20
- import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'
21
-
22
- /** 本模块配置目录(与 external.js 的 externalDir 同级,放 config.json)。 */
23
- function configDir() {
24
- const home = process.env.DSH_HOME || join(homedir(), '.dsh')
25
- return join(home, 'plugins', 'dsh-mobile-remote')
26
- }
27
-
28
- /** 配置文件绝对路径。 */
29
- function configFilePath() {
30
- return join(configDir(), 'config.json')
31
- }
32
-
33
- /** scrypt 派生参数(成本因子,本机校验,取适中值保证安全与速度平衡)。 */
34
- const SCRYPT_N = 16384
35
- const SCRYPT_R = 8
36
- const SCRYPT_P = 1
37
- const KEY_LEN = 32
38
-
39
- /** 会话有效期(毫秒):认证通过后的一段时间内免重复输入。 */
40
- const SESSION_TTL = 24 * 60 * 60 * 1000 // 24h
41
-
42
- /** 登录防爆破:同一 IP 连续失败上限与封禁窗口。 */
43
- const MAX_ATTEMPTS = 8
44
- const LOCK_WINDOW = 10 * 60 * 1000 // 10 分钟
45
-
46
- /* ------------------------------------------------------------------ */
47
- /* 底层读写 */
48
- /* ------------------------------------------------------------------ */
49
-
50
- function readRawConfig() {
51
- try {
52
- const file = configFilePath()
53
- if (!existsSync(file)) return {}
54
- return JSON.parse(readFileSync(file, 'utf8'))
55
- } catch {
56
- return {}
57
- }
58
- }
59
-
60
- function writeRawConfig(obj) {
61
- mkdirSync(configDir(), { recursive: true })
62
- writeFileSync(configFilePath(), JSON.stringify(obj, null, 2), 'utf8')
63
- }
64
-
65
- /* ------------------------------------------------------------------ */
66
- /* 密码设置 / 校验 */
67
- /* ------------------------------------------------------------------ */
68
-
69
- /**
70
- * 推导口令哈希。scrypt(password, salt, KEY_LEN, { N, r, p })。
71
- * 用 HMAC 风格再叠加一个本地 pepper 常量,避免直接逆向比对(可选增强)。
72
- */
73
- function derive(password, salt) {
74
- return scryptSync(String(password), Buffer.from(salt, 'hex'), KEY_LEN, {
75
- N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P,
76
- })
77
- }
78
-
79
- /** 判断是否已设置远程访问密码。 */
80
- export function hasPassword() {
81
- const cfg = readRawConfig()
82
- return !!(cfg && cfg.pwdHash && cfg.pwdSalt)
83
- }
84
-
85
- /**
86
- * 校验口令是否正确。返回 boolean。使用 timingSafeEqual 防时序攻击。
87
- * @param {string} password
88
- */
89
- export function verifyPassword(password) {
90
- const cfg = readRawConfig()
91
- if (!cfg || !cfg.pwdHash || !cfg.pwdSalt) return false
92
- if (typeof password !== 'string' || !password) return false
93
- try {
94
- const expected = Buffer.from(cfg.pwdHash, 'hex')
95
- const actual = derive(password, cfg.pwdSalt)
96
- if (expected.length !== actual.length) return false
97
- return timingSafeEqual(expected, actual)
98
- } catch {
99
- return false
100
- }
101
- }
102
-
103
- /**
104
- * 设置 / 修改远程访问密码。未传或为空表示清除密码(关闭门禁)。
105
- * 仅存哈希 + 盐,绝不落盘明文。
106
- * @param {string|null} password
107
- */
108
- export function setPassword(password) {
109
- const cfg = readRawConfig()
110
- if (!password) {
111
- delete cfg.pwdHash
112
- delete cfg.pwdSalt
113
- // 清除密码的同时清空所有已签发会话
114
- sessions.clear()
115
- // 兼容旧字段
116
- delete cfg.pwdSetAt
117
- writeRawConfig(cfg)
118
- return { ok: true, enabled: false }
119
- }
120
- const salt = randomBytes(16).toString('hex')
121
- const hash = derive(password, salt).toString('hex')
122
- cfg.pwdHash = hash
123
- cfg.pwdSalt = salt
124
- cfg.pwdSetAt = new Date().toISOString()
125
- // 修改密码后旧会话全部失效
126
- sessions.clear()
127
- writeRawConfig(cfg)
128
- return { ok: true, enabled: true }
129
- }
130
-
131
- /** 是否启用远程访问密码门禁。 */
132
- export function isEnabled() {
133
- return hasPassword()
134
- }
135
-
136
- /* ------------------------------------------------------------------ */
137
- /* 认证会话(内存) */
138
- /* ------------------------------------------------------------------ */
139
-
140
- const sessions = new Map() // token -> expiry(ms)
141
-
142
- /** 清掉所有会话(改密 / 重启时调用)。 */
143
- export function clearSessions() {
144
- sessions.clear()
145
- }
146
-
147
- /** 签发一个会话 token。 */
148
- function issueToken() {
149
- return randomBytes(24).toString('base64url')
150
- }
151
-
152
- /**
153
- * 校验口令并签发会话 token(若需要)。成功返回 { ok:true, token };
154
- * 失败返回 { ok:false, error }。
155
- * @param {string} password
156
- * @param {string} [clientIp] 用于防爆破计数
157
- */
158
- export function login(password, clientIp) {
159
- const ip = clientIp || 'unknown'
160
- if (!hasPassword()) {
161
- return { ok: false, error: '远程访问密码尚未设置' }
162
- }
163
- if (isLocked(ip)) {
164
- return { ok: false, error: '尝试次数过多,请稍后再试' }
165
- }
166
- if (!verifyPassword(password)) {
167
- registerFailure(ip)
168
- return { ok: false, error: '密码错误' }
169
- }
170
- clearFailures(ip)
171
- const token = issueToken()
172
- sessions.set(token, Date.now() + SESSION_TTL)
173
- return { ok: true, token }
174
- }
175
-
176
- /** 校验一个会话 token 是否有效(未过期)。 */
177
- export function verifyToken(token) {
178
- if (!token || typeof token !== 'string') return false
179
- const exp = sessions.get(token)
180
- if (!exp) return false
181
- if (Date.now() > exp) {
182
- sessions.delete(token)
183
- return false
184
- }
185
- return true
186
- }
187
-
188
- /** 移除一个会话 token(登出)。 */
189
- export function revokeToken(token) {
190
- if (token) sessions.delete(token)
191
- }
192
-
193
- /* ------------------------------------------------------------------ */
194
- /* 防爆破(按 IP) */
195
- /* ------------------------------------------------------------------ */
196
-
197
- const attempts = new Map() // ip -> { count, lockUntil }
198
-
199
- function isLocked(ip) {
200
- const a = attempts.get(ip)
201
- return a ? (a.lockUntil && Date.now() < a.lockUntil) : false
202
- }
203
-
204
- function registerFailure(ip) {
205
- const now = Date.now()
206
- const prev = attempts.get(ip)
207
- let count = prev ? prev.count : 0
208
- count += 1
209
- if (count >= MAX_ATTEMPTS) {
210
- attempts.set(ip, { count, lockUntil: now + LOCK_WINDOW })
211
- } else {
212
- attempts.set(ip, { count })
213
- }
214
- }
215
-
216
- function clearFailures(ip) {
217
- attempts.delete(ip)
218
- }
1
+ // dsh-mobile-remote — 远程访问密码(本模块,host 侧)。
2
+ //
3
+ // 职责:
4
+ // 1. **远程访问密码的本地安全存储与会话管理**。密码由管理员在本机设置面板
5
+ // 设置(本模块路径 ~/.dsh/plugins/dsh-mobile-remote/config.json)。
6
+ // 存储时**只存 scrypt 哈希 + 随机盐**,绝不落盘明文。
7
+ // 2. **认证会话**:远程访问者输入正确密码后,向浏览器下发一个随机 token,
8
+ // host 侧在内存中维护该 token 的过期时间;后续带有效 token 的请求视为
9
+ // 已认证,无需重复输入。
10
+ //
11
+ // 设计要点(通用 / 可自托管):
12
+ // - 完全本地,**不依赖任何中转后端**(dsh-update-server / frps / frpc)。
13
+ // 任何部署者——包括自建中转服务的用户——都能用本模块给远程访问加密码。
14
+ // - 全部使用 Node 内置 crypto,零第三方依赖。
15
+ // - 校验采用 timingSafeEqual,避免时序攻击;登录做简单频率限制防爆破。
16
+
17
+ import { randomBytes, scryptSync, timingSafeEqual, createHash } from 'node:crypto'
18
+ import { homedir } from 'node:os'
19
+ import { join } from 'node:path'
20
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, rmSync } from 'node:fs'
21
+
22
+ /** 本模块配置目录(与 external.js 的 externalDir 同级,放 config.json)。 */
23
+ function configDir() {
24
+ const home = process.env.DSH_HOME || join(homedir(), '.dsh')
25
+ return join(home, 'plugins', 'dsh-mobile-remote')
26
+ }
27
+
28
+ /** 配置文件绝对路径。 */
29
+ function configFilePath() {
30
+ return join(configDir(), 'config.json')
31
+ }
32
+
33
+ /** scrypt 派生参数(成本因子,本机校验,取适中值保证安全与速度平衡)。 */
34
+ const SCRYPT_N = 16384
35
+ const SCRYPT_R = 8
36
+ const SCRYPT_P = 1
37
+ const KEY_LEN = 32
38
+
39
+ /** 会话有效期(毫秒):认证通过后的一段时间内免重复输入。 */
40
+ const SESSION_TTL = 24 * 60 * 60 * 1000 // 24h
41
+
42
+ /** 登录防爆破:同一 IP 连续失败上限与封禁窗口。 */
43
+ const MAX_ATTEMPTS = 8
44
+ const LOCK_WINDOW = 10 * 60 * 1000 // 10 分钟
45
+
46
+ /* ------------------------------------------------------------------ */
47
+ /* 底层读写 */
48
+ /* ------------------------------------------------------------------ */
49
+
50
+ function readRawConfig() {
51
+ try {
52
+ const file = configFilePath()
53
+ if (!existsSync(file)) return {}
54
+ return JSON.parse(readFileSync(file, 'utf8'))
55
+ } catch {
56
+ return {}
57
+ }
58
+ }
59
+
60
+ function writeRawConfig(obj) {
61
+ mkdirSync(configDir(), { recursive: true })
62
+ writeFileSync(configFilePath(), JSON.stringify(obj, null, 2), 'utf8')
63
+ }
64
+
65
+ /* ------------------------------------------------------------------ */
66
+ /* 密码设置 / 校验 */
67
+ /* ------------------------------------------------------------------ */
68
+
69
+ /**
70
+ * 推导口令哈希。scrypt(password, salt, KEY_LEN, { N, r, p })。
71
+ * 用 HMAC 风格再叠加一个本地 pepper 常量,避免直接逆向比对(可选增强)。
72
+ */
73
+ function derive(password, salt) {
74
+ return scryptSync(String(password), Buffer.from(salt, 'hex'), KEY_LEN, {
75
+ N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P,
76
+ })
77
+ }
78
+
79
+ /** 判断是否已设置远程访问密码。 */
80
+ export function hasPassword() {
81
+ const cfg = readRawConfig()
82
+ return !!(cfg && cfg.pwdHash && cfg.pwdSalt)
83
+ }
84
+
85
+ /**
86
+ * 校验口令是否正确。返回 boolean。使用 timingSafeEqual 防时序攻击。
87
+ * @param {string} password
88
+ */
89
+ export function verifyPassword(password) {
90
+ const cfg = readRawConfig()
91
+ if (!cfg || !cfg.pwdHash || !cfg.pwdSalt) return false
92
+ if (typeof password !== 'string' || !password) return false
93
+ try {
94
+ const expected = Buffer.from(cfg.pwdHash, 'hex')
95
+ const actual = derive(password, cfg.pwdSalt)
96
+ if (expected.length !== actual.length) return false
97
+ return timingSafeEqual(expected, actual)
98
+ } catch {
99
+ return false
100
+ }
101
+ }
102
+
103
+ /**
104
+ * 设置 / 修改远程访问密码。未传或为空表示清除密码(关闭门禁)。
105
+ * 仅存哈希 + 盐,绝不落盘明文。
106
+ * @param {string|null} password
107
+ */
108
+ export function setPassword(password) {
109
+ const cfg = readRawConfig()
110
+ if (!password) {
111
+ delete cfg.pwdHash
112
+ delete cfg.pwdSalt
113
+ // 清除密码的同时清空所有已签发会话
114
+ sessions.clear()
115
+ // 兼容旧字段
116
+ delete cfg.pwdSetAt
117
+ writeRawConfig(cfg)
118
+ return { ok: true, enabled: false }
119
+ }
120
+ const salt = randomBytes(16).toString('hex')
121
+ const hash = derive(password, salt).toString('hex')
122
+ cfg.pwdHash = hash
123
+ cfg.pwdSalt = salt
124
+ cfg.pwdSetAt = new Date().toISOString()
125
+ // 修改密码后旧会话全部失效
126
+ sessions.clear()
127
+ writeRawConfig(cfg)
128
+ return { ok: true, enabled: true }
129
+ }
130
+
131
+ /** 是否启用远程访问密码门禁。 */
132
+ export function isEnabled() {
133
+ return hasPassword()
134
+ }
135
+
136
+ /* ------------------------------------------------------------------ */
137
+ /* 插件本地配置(与密码共用 config.json,未知字段原样保留) */
138
+ /* ------------------------------------------------------------------ */
139
+
140
+ /**
141
+ * 读取插件配置里的一个值(不存在返回 fallback)。
142
+ * @param {string} key
143
+ * @param {*} [fallback]
144
+ */
145
+ export function getSetting(key, fallback = null) {
146
+ const cfg = readRawConfig()
147
+ return Object.prototype.hasOwnProperty.call(cfg, key) ? cfg[key] : fallback
148
+ }
149
+
150
+ /**
151
+ * 写入插件配置里的一个值(保留其它字段,例如密码哈希)。
152
+ * @param {string} key
153
+ * @param {*} value
154
+ */
155
+ export function setSetting(key, value) {
156
+ const cfg = readRawConfig()
157
+ if (value === undefined) delete cfg[key]
158
+ else cfg[key] = value
159
+ writeRawConfig(cfg)
160
+ return value
161
+ }
162
+
163
+ /* ------------------------------------------------------------------ */
164
+ /* 认证会话(内存) */
165
+ /* ------------------------------------------------------------------ */
166
+
167
+ const sessions = new Map() // token -> expiry(ms)
168
+
169
+ /** 清掉所有会话(改密 / 重启时调用)。 */
170
+ export function clearSessions() {
171
+ sessions.clear()
172
+ }
173
+
174
+ /** 签发一个会话 token。 */
175
+ function issueToken() {
176
+ return randomBytes(24).toString('base64url')
177
+ }
178
+
179
+ /**
180
+ * 校验口令并签发会话 token(若需要)。成功返回 { ok:true, token };
181
+ * 失败返回 { ok:false, error }。
182
+ * @param {string} password
183
+ * @param {string} [clientIp] 用于防爆破计数
184
+ */
185
+ export function login(password, clientIp) {
186
+ const ip = clientIp || 'unknown'
187
+ if (!hasPassword()) {
188
+ return { ok: false, error: '远程访问密码尚未设置' }
189
+ }
190
+ if (isLocked(ip)) {
191
+ return { ok: false, error: '尝试次数过多,请稍后再试' }
192
+ }
193
+ if (!verifyPassword(password)) {
194
+ registerFailure(ip)
195
+ return { ok: false, error: '密码错误' }
196
+ }
197
+ clearFailures(ip)
198
+ const token = issueToken()
199
+ sessions.set(token, Date.now() + SESSION_TTL)
200
+ return { ok: true, token }
201
+ }
202
+
203
+ /** 校验一个会话 token 是否有效(未过期)。 */
204
+ export function verifyToken(token) {
205
+ if (!token || typeof token !== 'string') return false
206
+ const exp = sessions.get(token)
207
+ if (!exp) return false
208
+ if (Date.now() > exp) {
209
+ sessions.delete(token)
210
+ return false
211
+ }
212
+ return true
213
+ }
214
+
215
+ /** 移除一个会话 token(登出)。 */
216
+ export function revokeToken(token) {
217
+ if (token) sessions.delete(token)
218
+ }
219
+
220
+ /* ------------------------------------------------------------------ */
221
+ /* 防爆破(按 IP) */
222
+ /* ------------------------------------------------------------------ */
223
+
224
+ const attempts = new Map() // ip -> { count, lockUntil }
225
+
226
+ function isLocked(ip) {
227
+ const a = attempts.get(ip)
228
+ return a ? (a.lockUntil && Date.now() < a.lockUntil) : false
229
+ }
230
+
231
+ function registerFailure(ip) {
232
+ const now = Date.now()
233
+ const prev = attempts.get(ip)
234
+ let count = prev ? prev.count : 0
235
+ count += 1
236
+ if (count >= MAX_ATTEMPTS) {
237
+ attempts.set(ip, { count, lockUntil: now + LOCK_WINDOW })
238
+ } else {
239
+ attempts.set(ip, { count })
240
+ }
241
+ }
242
+
243
+ function clearFailures(ip) {
244
+ attempts.delete(ip)
245
+ }