@yusho/server 0.0.0-stage → 0.1.17

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.
Files changed (115) hide show
  1. package/README.md +135 -2
  2. package/app/appguide.mjs +33 -0
  3. package/app/asr.mjs +82 -0
  4. package/app/assets/agents/claude-192.webp +0 -0
  5. package/app/assets/agents/claude-96.webp +0 -0
  6. package/app/assets/agents/codex-192.webp +0 -0
  7. package/app/assets/agents/codex-96.webp +0 -0
  8. package/app/assets/agents/default-192.webp +0 -0
  9. package/app/assets/agents/default-96.webp +0 -0
  10. package/app/assets/agents/dsh-192.webp +0 -0
  11. package/app/assets/agents/dsh-96.webp +0 -0
  12. package/app/assets/brand/logo.webp +0 -0
  13. package/app/assets/lib/THIRD-PARTY.txt +1 -0
  14. package/app/assets/lib/jsqr.js +10102 -0
  15. package/app/assets/linux/alpine-arm64.tar.gz +0 -0
  16. package/app/assets/linux/alpine-x64.tar.gz +0 -0
  17. package/app/assets/live/claude.livliv +0 -0
  18. package/app/assets/live/dafeiyu.livliv +0 -0
  19. package/app/assets/live/gpt.livliv +0 -0
  20. package/app/assets/live/sho.livliv +0 -0
  21. package/app/assets/live//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
  22. package/app/assets/livliv/LICENSE +202 -0
  23. package/app/assets/livliv/NOTICE +7 -0
  24. package/app/assets/livliv/player.mjs +15 -0
  25. package/app/assets/looks/claude.webp +0 -0
  26. package/app/assets/looks/dafeiyu.webp +0 -0
  27. package/app/assets/looks/gpt.webp +0 -0
  28. package/app/assets/looks//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
  29. package/app/assets/sho/avatar.webp +0 -0
  30. package/app/assets/sho/done.webp +0 -0
  31. package/app/assets/sho/eat.webp +0 -0
  32. package/app/assets/sho/idle-blink.webp +0 -0
  33. package/app/assets/sho/idle.webp +0 -0
  34. package/app/assets/sho/listen.webp +0 -0
  35. package/app/assets/sho/need.webp +0 -0
  36. package/app/assets/sho/work.webp +0 -0
  37. package/app/companion.mjs +519 -0
  38. package/app/diag.mjs +51 -0
  39. package/app/index.html +497 -0
  40. package/app/judge.mjs +103 -0
  41. package/app/lanxfer.mjs +157 -0
  42. package/app/launcher.mjs +2715 -0
  43. package/app/linux.mjs +97 -0
  44. package/app/livliv-pack.mjs +12 -0
  45. package/app/memory.mjs +53 -0
  46. package/app/net.mjs +717 -0
  47. package/app/office.mjs +172 -0
  48. package/app/p2plink.mjs +134 -0
  49. package/app/pcupdate.mjs +55 -0
  50. package/app/plans.mjs +126 -0
  51. package/app/plugins.mjs +79 -0
  52. package/app/realtime.mjs +67 -0
  53. package/app/skills/app-icon/SKILL.md +31 -0
  54. package/app/skills/daily-brief/SKILL.md +29 -0
  55. package/app/skills/expense-review/SKILL.md +28 -0
  56. package/app/skills/make-app/SKILL.md +92 -0
  57. package/app/skills/make-skin/SKILL.md +51 -0
  58. package/app/skills/meeting-notes/SKILL.md +23 -0
  59. package/app/skills/reading-notes/SKILL.md +25 -0
  60. package/app/skills/sho-stickers/SKILL.md +34 -0
  61. package/app/skills/sho-stickers/stickers/eat.webp +0 -0
  62. package/app/skills/sho-stickers/stickers/got-it.webp +0 -0
  63. package/app/skills/sho-stickers/stickers/hi.webp +0 -0
  64. package/app/skills/sho-stickers/stickers/huh.webp +0 -0
  65. package/app/skills/sho-stickers/stickers/on-it.webp +0 -0
  66. package/app/skills/sho-stickers/stickers/yay.webp +0 -0
  67. package/app/skills/sho-stickers/stickers.json +12 -0
  68. package/app/skills/study-plan/SKILL.md +30 -0
  69. package/app/skills/trip-planner/SKILL.md +29 -0
  70. package/app/skills/weekly-report/SKILL.md +30 -0
  71. package/app/skills/workout-plan/SKILL.md +30 -0
  72. package/app/skills/writing-polish/SKILL.md +33 -0
  73. package/app/skills.mjs +173 -0
  74. package/app/skins.mjs +40 -0
  75. package/app/social.mjs +1067 -0
  76. package/app/storage.mjs +143 -0
  77. package/app/tts.mjs +68 -0
  78. package/app/ttslocal.mjs +77 -0
  79. package/app/voices.mjs +102 -0
  80. package/backup.mjs +109 -0
  81. package/bin/yusho.mjs +141 -0
  82. package/connector/lib/api.mjs +14 -0
  83. package/connector/lib/autostart.mjs +40 -0
  84. package/connector/lib/client.js +165 -0
  85. package/connector/lib/connector.mjs +468 -0
  86. package/connector/lib/dsh-acp.mjs +129 -0
  87. package/connector/lib/dsh-headless.patch.yml +4 -0
  88. package/connector/lib/dsh-plugin.mjs +80 -0
  89. package/connector/lib/lanfile.mjs +151 -0
  90. package/connector/lib/nostr.mjs +53 -0
  91. package/connector/lib/page.html +121 -0
  92. package/connector/lib/qr.mjs +4 -0
  93. package/connector/lib/service.mjs +54 -0
  94. package/node_modules/@local/shoal-mobile/lib/index.js +485 -0
  95. package/node_modules/@local/shoal-mobile/lib/polyfill.js +82 -0
  96. package/node_modules/@local/shoal-mobile/lib/session-context.js +34 -0
  97. package/node_modules/@local/shoal-mobile/lib/shell.js +60 -0
  98. package/node_modules/@local/shoal-mobile/lib/web-startup.js +33 -0
  99. package/node_modules/@local/shoal-mobile/package.json +24 -0
  100. package/node_modules/@local/yusho-pc/lib/client.js +9100 -0
  101. package/node_modules/@local/yusho-pc/lib/index.js +3 -0
  102. package/node_modules/@local/yusho-pc/package.json +28 -0
  103. package/node_modules/@local/yusho-web-login/brand/icon-192.webp +0 -0
  104. package/node_modules/@local/yusho-web-login/brand/logo-dark.svg +25 -0
  105. package/node_modules/@local/yusho-web-login/brand.mjs +8 -0
  106. package/node_modules/@local/yusho-web-login/dsh-web-login.mjs +974 -0
  107. package/node_modules/@local/yusho-web-login/lib/client.js +607 -0
  108. package/node_modules/@local/yusho-web-login/login-page.mjs +609 -0
  109. package/node_modules/@local/yusho-web-login/login-store.mjs +708 -0
  110. package/node_modules/@local/yusho-web-login/package.json +25 -0
  111. package/node_modules/@local/yusho-web-login/whale-scene.mjs +509 -0
  112. package/node_modules/@local/yusho-web-login/yusho-scene.mjs +227 -0
  113. package/package.json +38 -4
  114. package/pc.patch.yml +83 -0
  115. package/run.mjs +138 -0
@@ -0,0 +1,708 @@
1
+ /**
2
+ * Persistent state for the `dsh web` login gate: the password, the login-page
3
+ * appearance, the per-address failed-attempt / ban ledger, and a small audit
4
+ * trail.
5
+ *
6
+ * Everything lives in one JSON file beside the plugin so that restarting
7
+ * `dsh web` never drops a ban or resets the operator's password. Writes are
8
+ * atomic (temp file + rename), serialized, and coalesced: a burst of failed
9
+ * logins costs one write per second instead of one per request.
10
+ *
11
+ * Version-1 files (the original plugin) load unchanged: every key they carry
12
+ * keeps its meaning, and the keys added since default in.
13
+ */
14
+
15
+ import { createHash, randomBytes, randomInt, scrypt, timingSafeEqual } from 'node:crypto'
16
+ import { isIPv4, isIPv6 } from 'node:net'
17
+ import { chmod, readFile, rename, writeFile } from 'node:fs/promises'
18
+
19
+ /** Bumped when the on-disk shape changes in a way older code cannot read. */
20
+ const STATE_VERSION = 2
21
+
22
+ /** scrypt cost. Runs on the libuv pool (async), never on the event loop. */
23
+ const SCRYPT = { N: 16384, r: 8, p: 1, maxmem: 64 * 1024 * 1024 }
24
+ const SCRYPT_KEYLEN = 64
25
+
26
+ /** Longest password the gate will hash; anything longer is a plain failure. */
27
+ export const MAX_PASSWORD_LENGTH = 256
28
+
29
+ /** Shortest password a change accepts. */
30
+ export const MIN_PASSWORD_LENGTH = 8
31
+
32
+ /** Failure counters older than this are treated as stale and dropped. */
33
+ const ATTEMPT_WINDOW_MS = 24 * 60 * 60 * 1000
34
+
35
+ /** How long an address that logged in successfully counts as "known". */
36
+ const KNOWN_TTL_MS = 30 * 24 * 60 * 60 * 1000
37
+
38
+ /** Ledger caps: a flood of distinct addresses must not grow the file without bound. */
39
+ const MAX_ATTEMPTS = 5000
40
+ const MAX_TIMED_BANS = 5000
41
+ const MAX_PERMANENT_BANS = 2000
42
+ const MAX_KNOWN = 50
43
+ const MAX_LOGINS = 50
44
+ const MAX_EVENTS = 100
45
+
46
+ /** Delay before coalesced counter writes land. */
47
+ const PERSIST_DEBOUNCE_MS = 1000
48
+
49
+ /** Selectable failed-attempt thresholds before an address is banned. */
50
+ export const BAN_THRESHOLDS = [3, 5, 10, 15]
51
+
52
+ /** Selectable ban durations. `ms: null` means permanent. */
53
+ export const BAN_DURATIONS = [
54
+ { id: '5m', label: '5 分钟', ms: 5 * 60 * 1000 },
55
+ { id: '15m', label: '15 分钟', ms: 15 * 60 * 1000 },
56
+ { id: '1h', label: '1 小时', ms: 60 * 60 * 1000 },
57
+ { id: '2h', label: '2 小时', ms: 2 * 60 * 60 * 1000 },
58
+ { id: '24h', label: '24 小时', ms: 24 * 60 * 60 * 1000 },
59
+ { id: 'permanent', label: '永久封禁', ms: null },
60
+ ]
61
+
62
+ const DURATION_BY_ID = new Map(BAN_DURATIONS.map((entry) => [entry.id, entry]))
63
+
64
+ /** Shipped login-page gradients. `value` is raw CSS background-image syntax. */
65
+ export const BACKGROUND_PRESETS = [
66
+ { id: 'aurora', label: '极光', value: 'linear-gradient(135deg,#4f46e5,#0ea5e9 55%,#db2777)' },
67
+ { id: 'midnight', label: '午夜', value: 'linear-gradient(160deg,#0f172a,#1e293b 62%,#0b1120)' },
68
+ { id: 'ember', label: '熔岩', value: 'linear-gradient(150deg,#7c2d12,#b91c1c 55%,#f59e0b)' },
69
+ { id: 'forest', label: '深林', value: 'linear-gradient(150deg,#052e16,#166534 55%,#0d9488)' },
70
+ { id: 'violet', label: '紫罗兰', value: 'linear-gradient(140deg,#2e1065,#6d28d9 50%,#c026d3)' },
71
+ { id: 'graphite', label: '石墨', value: 'linear-gradient(150deg,#09090b,#27272a 60%,#3f3f46)' },
72
+ { id: 'sunset', label: '日落', value: 'linear-gradient(160deg,#1e1b4b,#be185d 55%,#fb923c)' },
73
+ { id: 'ocean', label: '深蓝', value: 'linear-gradient(170deg,#020617,#0c4a6e 55%,#0891b2)' },
74
+ ]
75
+
76
+ const PRESET_BY_ID = new Map(BACKGROUND_PRESETS.map((entry) => [entry.id, entry]))
77
+
78
+ /** Built-in animated backgrounds, drawn by the login page itself (no assets, no CDN). */
79
+ export const ANIMATIONS = [
80
+ { id: 'yusho', label: '深海·Sho 酱(鱼Sho)', hint: 'Sho 酱的 logo 浮在深海里,气泡往上冒、光束摇晃、星星闪;打字冒小泡,输错泛红,登录成功她头顶喷一道水' },
81
+ { id: 'whale', label: '鲸灵粒子', hint: 'WebGL 粒子在深海中汇聚成鲸鱼、标题与你的 Logo;打字泛起涟漪,输错红色冲击波,登录成功聚爆成光' },
82
+ { id: 'constellation', label: '星座粒子', hint: '漂浮的光点彼此连线,跟随鼠标聚拢' },
83
+ { id: 'aurora', label: '流动极光', hint: '缓慢流动的极光色带(纯 CSS,最省电)' },
84
+ { id: 'deepsea', label: '深海鲸游', hint: '光束、上浮气泡,DeepSeek 鲸鱼缓缓游过' },
85
+ ]
86
+
87
+ const ANIMATION_IDS = new Set(ANIMATIONS.map((entry) => entry.id))
88
+
89
+ /** Accepted background modes. */
90
+ export const BACKGROUND_MODES = ['preset', 'color', 'animation', 'image', 'video', 'url']
91
+
92
+ /** Card looks the login form can wear. */
93
+ export const CARD_STYLES = [
94
+ { id: 'glass', label: '毛玻璃' },
95
+ { id: 'solid', label: '实色' },
96
+ { id: 'minimal', label: '极简' },
97
+ { id: 'neon', label: '霓虹' },
98
+ ]
99
+
100
+ /** Where the card sits on the page. */
101
+ export const LAYOUTS = [
102
+ { id: 'center', label: '居中' },
103
+ { id: 'left', label: '靠左' },
104
+ { id: 'right', label: '靠右' },
105
+ ]
106
+
107
+ /** How the card enters the page. */
108
+ export const INTROS = [
109
+ { id: 'rise', label: '上浮' },
110
+ { id: 'zoom', label: '缩放' },
111
+ { id: 'fade', label: '淡入' },
112
+ { id: 'none', label: '无' },
113
+ ]
114
+
115
+ /**
116
+ * Accepted login-page logo modes.
117
+ * lock — the shipped padlock glyph
118
+ * brand — the official DeepSeek fish mark
119
+ * image — an uploaded image
120
+ * url — a remote image
121
+ * none — no mark
122
+ */
123
+ export const LOGO_MODES = ['yusho', 'lock', 'brand', 'image', 'url', 'none']
124
+
125
+ /** Local paths the uploaded media are served from. */
126
+ export const MEDIA_PATHS = {
127
+ background: '/_web-login/bg',
128
+ logo: '/_web-login/logo',
129
+ video: '/_web-login/video',
130
+ }
131
+
132
+ const DEFAULT_APPEARANCE = {
133
+ card: 'glass',
134
+ layout: 'center',
135
+ intro: 'rise',
136
+ accent: '#4D6BFE',
137
+ overlay: 0,
138
+ blur: 0,
139
+ title: '鱼Sho',
140
+ subtitle: '请输入访问密码以继续',
141
+ }
142
+
143
+ const DEFAULT_STATE = {
144
+ version: STATE_VERSION,
145
+ password: null,
146
+ background: { mode: 'animation', value: 'yusho' }, // 鱼Sho:默认用「鱼群」
147
+ appearance: DEFAULT_APPEARANCE,
148
+ // Default to the official mark: a bare padlock says nothing about what the
149
+ // gate protects, and this is the identity the rest of the product shows.
150
+ logo: { mode: 'yusho', value: '' },
151
+ ban: { enabled: true, threshold: 5, duration: '15m' },
152
+ bans: {},
153
+ attempts: {},
154
+ known: {},
155
+ logins: [],
156
+ events: [],
157
+ }
158
+
159
+ const HEX_COLOR = /^#[0-9a-f]{3}(?:[0-9a-f]{3})?$/iu
160
+ const HTTP_URL = /^https?:\/\/[^\s"'<>\\]+$/iu
161
+ const HTTPS_URL = /^https:\/\/[^\s"'<>\\]+$/iu
162
+ /** Visible text the operator may put on the card: no control characters, no markup. */
163
+ const PLAIN_TEXT = /^[^\u0000-\u001f\u007f<>]*$/u
164
+
165
+ /** Alphabet for generated reset passwords: no look-alikes (0/O, 1/l/I). */
166
+ const RESET_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789'
167
+ const RESET_LENGTH = 16
168
+
169
+ function scryptAsync(password, salt, keylen) {
170
+ return new Promise((resolve, reject) => {
171
+ scrypt(password, salt, keylen, SCRYPT, (error, derived) => (error ? reject(error) : resolve(derived)))
172
+ })
173
+ }
174
+
175
+ /** Constant-time comparison over SHA-256 digests, for the plaintext fallback. */
176
+ function plaintextEquals(a, b) {
177
+ return timingSafeEqual(
178
+ createHash('sha256').update(a, 'utf8').digest(),
179
+ createHash('sha256').update(b, 'utf8').digest(),
180
+ )
181
+ }
182
+
183
+ /**
184
+ * Hash a password with a fresh salt.
185
+ * @param {string} password - the plaintext password.
186
+ * @returns {Promise<{algo: string, salt: string, hash: string}>} the storable record.
187
+ */
188
+ async function hashPassword(password) {
189
+ const salt = randomBytes(16).toString('hex')
190
+ const derived = await scryptAsync(password, salt, SCRYPT_KEYLEN)
191
+ return { algo: 'scrypt', salt, hash: derived.toString('hex') }
192
+ }
193
+
194
+ /**
195
+ * Verify a password against a stored record.
196
+ * @param {string} password - the submitted plaintext.
197
+ * @param {{salt: string, hash: string}} record - the stored record.
198
+ * @returns {Promise<boolean>} whether the password matches.
199
+ */
200
+ async function verifyHashed(password, record) {
201
+ const expected = Buffer.from(record.hash, 'hex')
202
+ if (expected.length === 0) return false
203
+ const derived = await scryptAsync(password, record.salt, expected.length)
204
+ return timingSafeEqual(derived, expected)
205
+ }
206
+
207
+ /** Expand an IPv6 address into its eight 16-bit groups. */
208
+ function ipv6Groups(address) {
209
+ let text = address
210
+ // An embedded IPv4 tail (::ffff:1.2.3.4) becomes two hex groups.
211
+ const v4 = /(\d+\.\d+\.\d+\.\d+)$/u.exec(text)
212
+ if (v4 !== null) {
213
+ const octets = v4[1].split('.').map(Number)
214
+ text = `${text.slice(0, v4.index)}${((octets[0] << 8) | octets[1]).toString(16)}:${((octets[2] << 8) | octets[3]).toString(16)}`
215
+ }
216
+ const [head, tail] = text.split('::')
217
+ const left = head === '' ? [] : head.split(':')
218
+ const right = tail === undefined || tail === '' ? [] : tail.split(':')
219
+ const fill = tail === undefined ? [] : new Array(8 - left.length - right.length).fill('0')
220
+ return [...left, ...fill, ...right].map((group) => parseInt(group, 16) || 0)
221
+ }
222
+
223
+ /**
224
+ * The ledger key for a client address. IPv4 keys are the address itself;
225
+ * IPv6 keys are the /64 the address sits in, because one subscriber is handed
226
+ * a whole /64 and could otherwise rotate through 2^64 fresh keys to dodge a ban.
227
+ * @param {string} ip - the client address.
228
+ * @returns {string} the key.
229
+ */
230
+ export function ipKey(ip) {
231
+ if (typeof ip !== 'string') return 'unknown'
232
+ const trimmed = ip.trim()
233
+ if (trimmed.startsWith('::ffff:') && isIPv4(trimmed.slice(7))) return trimmed.slice(7)
234
+ if (isIPv4(trimmed)) return trimmed
235
+ const bare = trimmed.split('%')[0]
236
+ if (isIPv6(bare)) {
237
+ const groups = ipv6Groups(bare)
238
+ if (groups[0] === 0 && groups[1] === 0 && groups[2] === 0 && groups[3] === 0 && groups[4] === 0 && groups[5] === 0xffff) {
239
+ return `${groups[6] >> 8}.${groups[6] & 255}.${groups[7] >> 8}.${groups[7] & 255}`
240
+ }
241
+ if (groups.slice(0, 7).every((group) => group === 0)) return bare // loopback / unspecified
242
+ return `${groups.slice(0, 4).map((group) => group.toString(16)).join(':')}::/64`
243
+ }
244
+ return trimmed.length > 0 ? trimmed.slice(0, 64) : 'unknown'
245
+ }
246
+
247
+ /** Keep the newest `cap` entries of a dict, judged by `stamp(entry)`. */
248
+ function capDict(dict, cap, stamp) {
249
+ const keys = Object.keys(dict)
250
+ if (keys.length <= cap) return dict
251
+ const kept = keys.sort((a, b) => stamp(dict[b]) - stamp(dict[a])).slice(0, cap)
252
+ return Object.fromEntries(kept.map((key) => [key, dict[key]]))
253
+ }
254
+
255
+ function clampInt(value, min, max) {
256
+ return Number.isInteger(value) && value >= min && value <= max
257
+ }
258
+
259
+ /** Truncate a user agent to something worth showing in an audit row. */
260
+ function shortAgent(agent) {
261
+ if (typeof agent !== 'string') return ''
262
+ return agent.replace(/[\u0000-\u001f\u007f]/gu, '').slice(0, 160)
263
+ }
264
+
265
+ /**
266
+ * The login gate's state, loaded once and mutated in place.
267
+ */
268
+ export class LoginStore {
269
+ #file
270
+ #fallbackPassword
271
+ #state
272
+ #writing = Promise.resolve()
273
+ #timer
274
+
275
+ /**
276
+ * @param {object} options - construction inputs.
277
+ * @param {string} options.file - absolute path of the JSON state file.
278
+ * @param {string|undefined} options.fallbackPassword - plaintext password used only while no hash is stored (from env or plugin config).
279
+ */
280
+ constructor({ file, fallbackPassword }) {
281
+ this.#file = file
282
+ this.#fallbackPassword = fallbackPassword
283
+ this.#state = structuredClone(DEFAULT_STATE)
284
+ }
285
+
286
+ /** Read the state file into memory, tolerating a missing or corrupt file. */
287
+ async load() {
288
+ let raw
289
+ try {
290
+ raw = await readFile(this.#file, 'utf8')
291
+ } catch (error) {
292
+ if (error?.code !== 'ENOENT') throw error
293
+ return this
294
+ }
295
+ let parsed
296
+ try {
297
+ parsed = JSON.parse(raw)
298
+ } catch {
299
+ return this
300
+ }
301
+ if (parsed === null || typeof parsed !== 'object') return this
302
+ const dict = (value) => (value && typeof value === 'object' && !Array.isArray(value) ? value : {})
303
+ const list = (value) => (Array.isArray(value) ? value : [])
304
+ this.#state = {
305
+ ...structuredClone(DEFAULT_STATE),
306
+ password: parsed.password ?? null,
307
+ background: { ...DEFAULT_STATE.background, ...dict(parsed.background) },
308
+ appearance: { ...DEFAULT_APPEARANCE, ...dict(parsed.appearance) },
309
+ logo: { ...DEFAULT_STATE.logo, ...dict(parsed.logo) },
310
+ ban: { ...DEFAULT_STATE.ban, ...dict(parsed.ban) },
311
+ bans: dict(parsed.bans),
312
+ attempts: dict(parsed.attempts),
313
+ known: dict(parsed.known),
314
+ logins: list(parsed.logins).slice(0, MAX_LOGINS),
315
+ events: list(parsed.events).slice(0, MAX_EVENTS),
316
+ version: STATE_VERSION,
317
+ }
318
+ return this
319
+ }
320
+
321
+ /** Drop stale counters and expired bans, then apply the ledger caps. */
322
+ #prune() {
323
+ const now = Date.now()
324
+ const state = this.#state
325
+ for (const [key, entry] of Object.entries(state.attempts)) {
326
+ if (now - (entry?.lastAt ?? 0) > ATTEMPT_WINDOW_MS) delete state.attempts[key]
327
+ }
328
+ for (const [key, entry] of Object.entries(state.bans)) {
329
+ if (entry?.permanent !== true && (entry?.until ?? 0) <= now) delete state.bans[key]
330
+ }
331
+ for (const [key, entry] of Object.entries(state.known)) {
332
+ if (now - (entry?.lastAt ?? 0) > KNOWN_TTL_MS) delete state.known[key]
333
+ }
334
+ state.attempts = capDict(state.attempts, MAX_ATTEMPTS, (entry) => entry?.lastAt ?? 0)
335
+ const permanent = {}
336
+ const timed = {}
337
+ for (const [key, entry] of Object.entries(state.bans)) (entry?.permanent === true ? permanent : timed)[key] = entry
338
+ state.bans = {
339
+ ...capDict(permanent, MAX_PERMANENT_BANS, (entry) => entry?.at ?? 0),
340
+ ...capDict(timed, MAX_TIMED_BANS, (entry) => entry?.at ?? 0),
341
+ }
342
+ state.known = capDict(state.known, MAX_KNOWN, (entry) => entry?.lastAt ?? 0)
343
+ }
344
+
345
+ /** Serialize one atomic write. Later writes always land after earlier ones. */
346
+ #persistNow() {
347
+ if (this.#timer !== undefined) {
348
+ clearTimeout(this.#timer)
349
+ this.#timer = undefined
350
+ }
351
+ this.#prune()
352
+ const body = `${JSON.stringify(this.#state, null, 2)}\n`
353
+ const temp = `${this.#file}.tmp`
354
+ this.#writing = this.#writing
355
+ .then(() => writeFile(temp, body, { encoding: 'utf8', mode: 0o600 })
356
+ // The temp file may predate this write with a wider mode, and `rename`
357
+ // carries the temp's mode onto the destination, so force 0600: the
358
+ // state file holds the password hash.
359
+ .then(() => chmod(temp, 0o600))
360
+ .then(() => rename(temp, this.#file)))
361
+ .catch(() => undefined)
362
+ return this.#writing
363
+ }
364
+
365
+ /** Coalesce frequent counter updates into one write per debounce window. */
366
+ #persistSoon() {
367
+ if (this.#timer !== undefined) return
368
+ this.#timer = setTimeout(() => {
369
+ this.#timer = undefined
370
+ void this.#persistNow()
371
+ }, PERSIST_DEBOUNCE_MS)
372
+ this.#timer.unref?.()
373
+ }
374
+
375
+ /**
376
+ * Write everything pending and wait for it to land. Handlers that report a
377
+ * change as saved await this first.
378
+ * @returns {Promise<void>} resolves once the write queue drains.
379
+ */
380
+ flush() {
381
+ return this.#persistNow()
382
+ }
383
+
384
+ /** Whether a password is set by a stored hash rather than the fallback. */
385
+ get hasStoredPassword() {
386
+ return this.#state.password !== null
387
+ }
388
+
389
+ /**
390
+ * Check a submitted password. Async: the scrypt work runs on the thread pool.
391
+ * @param {string} submitted - the plaintext to check.
392
+ * @returns {Promise<boolean>} whether the gate should open.
393
+ */
394
+ async verifyPassword(submitted) {
395
+ if (typeof submitted !== 'string' || submitted.length === 0 || submitted.length > MAX_PASSWORD_LENGTH) return false
396
+ if (this.#state.password !== null) {
397
+ try {
398
+ return await verifyHashed(submitted, this.#state.password)
399
+ } catch {
400
+ return false
401
+ }
402
+ }
403
+ const expected = this.#fallbackPassword
404
+ if (typeof expected !== 'string' || expected.length === 0) return false
405
+ return plaintextEquals(submitted, expected)
406
+ }
407
+
408
+ /** The login-page background as stored. */
409
+ get background() {
410
+ return { ...this.#state.background }
411
+ }
412
+
413
+ /** The login-page look (card, layout, intro, colours, copy) as stored. */
414
+ get appearance() {
415
+ return { ...this.#state.appearance }
416
+ }
417
+
418
+ /** The login-page logo as stored. */
419
+ get logo() {
420
+ return { ...this.#state.logo }
421
+ }
422
+
423
+ /** The ban policy as stored. */
424
+ get banPolicy() {
425
+ return { ...this.#state.ban }
426
+ }
427
+
428
+ /** Live bans, most recent first. */
429
+ listBans() {
430
+ const now = Date.now()
431
+ return Object.entries(this.#state.bans)
432
+ .map(([ip, entry]) => ({
433
+ ip,
434
+ permanent: entry.permanent === true,
435
+ until: entry.permanent === true ? null : (entry.until ?? 0),
436
+ remainingMs: entry.permanent === true ? null : Math.max(0, (entry.until ?? 0) - now),
437
+ at: entry.at ?? 0,
438
+ }))
439
+ .filter((entry) => entry.permanent || entry.remainingMs > 0)
440
+ .sort((a, b) => b.at - a.at)
441
+ }
442
+
443
+ /** Failure counters that have not yet crossed the threshold, most recent first. */
444
+ listAttempts() {
445
+ const now = Date.now()
446
+ return Object.entries(this.#state.attempts)
447
+ .map(([ip, entry]) => ({
448
+ ip,
449
+ count: entry.count ?? 0,
450
+ lastAt: entry.lastAt ?? 0,
451
+ remainingMs: Math.max(0, ATTEMPT_WINDOW_MS - (now - (entry.lastAt ?? 0))),
452
+ }))
453
+ .filter((entry) => entry.count > 0 && entry.remainingMs > 0)
454
+ .sort((a, b) => b.lastAt - a.lastAt)
455
+ }
456
+
457
+ /** Recent successful logins, newest first. */
458
+ listLogins() {
459
+ return this.#state.logins.map((entry) => ({ ...entry }))
460
+ }
461
+
462
+ /** Recent security events (bans, password and settings changes), newest first. */
463
+ listEvents() {
464
+ return this.#state.events.map((entry) => ({ ...entry }))
465
+ }
466
+
467
+ /** Addresses that logged in successfully within the known-address window. */
468
+ listKnown() {
469
+ return Object.entries(this.#state.known)
470
+ .map(([ip, entry]) => ({ ip, lastAt: entry.lastAt ?? 0 }))
471
+ .sort((a, b) => b.lastAt - a.lastAt)
472
+ }
473
+
474
+ /**
475
+ * Whether an address logged in successfully recently. Known addresses skip
476
+ * the global throttle that applies to everyone else.
477
+ * @param {string} ip - the client address.
478
+ * @returns {boolean} whether the address is known.
479
+ */
480
+ isKnown(ip) {
481
+ const entry = this.#state.known[ipKey(ip)]
482
+ return entry !== undefined && Date.now() - (entry.lastAt ?? 0) <= KNOWN_TTL_MS
483
+ }
484
+
485
+ /**
486
+ * Append one security event to the audit trail.
487
+ * @param {string} kind - event kind, e.g. 'banned', 'password-changed'.
488
+ * @param {string} ip - the address that caused it.
489
+ * @param {string} [detail] - short human-readable detail.
490
+ */
491
+ recordEvent(kind, ip, detail = '') {
492
+ this.#state.events.unshift({ at: Date.now(), kind, ip: ipKey(ip), detail: String(detail).slice(0, 200) })
493
+ this.#state.events.length = Math.min(this.#state.events.length, MAX_EVENTS)
494
+ this.#persistSoon()
495
+ }
496
+
497
+ /**
498
+ * The ban currently in force for an address, if any.
499
+ * @param {string} ip - the client address.
500
+ * @returns {{permanent: boolean, until: number|null, remainingMs: number|null}|undefined} the active ban.
501
+ */
502
+ activeBan(ip) {
503
+ const key = ipKey(ip)
504
+ const entry = this.#state.bans[key]
505
+ if (entry === undefined) return undefined
506
+ if (entry.permanent === true) return { permanent: true, until: null, remainingMs: null }
507
+ const remaining = (entry.until ?? 0) - Date.now()
508
+ if (remaining <= 0) {
509
+ delete this.#state.bans[key]
510
+ this.#persistSoon()
511
+ return undefined
512
+ }
513
+ return { permanent: false, until: entry.until, remainingMs: remaining }
514
+ }
515
+
516
+ /**
517
+ * Failures recorded for an address in the current window.
518
+ * @param {string} ip - the client address.
519
+ * @returns {number} the count.
520
+ */
521
+ failureCount(ip) {
522
+ const entry = this.#state.attempts[ipKey(ip)]
523
+ if (entry === undefined || Date.now() - (entry.lastAt ?? 0) > ATTEMPT_WINDOW_MS) return 0
524
+ return entry.count ?? 0
525
+ }
526
+
527
+ /**
528
+ * Record one failed password attempt and ban the address when it crosses the
529
+ * configured threshold.
530
+ * @param {string} ip - the client address.
531
+ * @returns {{count: number, threshold: number, banned: object|undefined}} the new counter state.
532
+ */
533
+ recordFailure(ip) {
534
+ const key = ipKey(ip)
535
+ const policy = this.#state.ban
536
+ const now = Date.now()
537
+ const previous = this.#state.attempts[key]
538
+ const fresh = previous === undefined || now - (previous.lastAt ?? 0) > ATTEMPT_WINDOW_MS
539
+ const count = fresh ? 1 : (previous.count ?? 0) + 1
540
+ this.#state.attempts[key] = { count, firstAt: fresh ? now : (previous.firstAt ?? now), lastAt: now }
541
+
542
+ let banned
543
+ if (policy.enabled === true && count >= policy.threshold) {
544
+ const duration = DURATION_BY_ID.get(policy.duration) ?? DURATION_BY_ID.get('15m')
545
+ delete this.#state.attempts[key]
546
+ this.#state.bans[key] = duration.ms === null
547
+ ? { permanent: true, until: null, at: now }
548
+ : { permanent: false, until: now + duration.ms, at: now }
549
+ banned = { permanent: duration.ms === null, duration: duration.id, label: duration.label }
550
+ this.recordEvent('banned', ip, `连续 ${count} 次密码错误,封禁 ${duration.label}`)
551
+ }
552
+ this.#persistSoon()
553
+ return { count, threshold: policy.threshold, banned }
554
+ }
555
+
556
+ /**
557
+ * Record a successful login: clear the counter, remember the address, and
558
+ * append it to the login history.
559
+ * @param {string} ip - the client address.
560
+ * @param {string} [agent] - the User-Agent header.
561
+ */
562
+ recordLogin(ip, agent) {
563
+ const key = ipKey(ip)
564
+ const now = Date.now()
565
+ delete this.#state.attempts[key]
566
+ this.#state.known[key] = { lastAt: now }
567
+ this.#state.logins.unshift({ at: now, ip: key, agent: shortAgent(agent) })
568
+ this.#state.logins.length = Math.min(this.#state.logins.length, MAX_LOGINS)
569
+ this.#persistSoon()
570
+ }
571
+
572
+ /**
573
+ * Drop a ban.
574
+ * @param {string} ip - the address or ledger key.
575
+ * @returns {boolean} whether a ban was present.
576
+ */
577
+ unban(ip) {
578
+ const key = this.#state.bans[ip] !== undefined ? ip : ipKey(ip)
579
+ if (this.#state.bans[key] === undefined) return false
580
+ delete this.#state.bans[key]
581
+ this.#persistSoon()
582
+ return true
583
+ }
584
+
585
+ /**
586
+ * Replace the login-page background.
587
+ * @param {{mode: string, value: string}} background - the new setting.
588
+ * @returns {{ok: true}|{ok: false, error: string}} the validation outcome.
589
+ */
590
+ setBackground(background) {
591
+ const mode = background?.mode
592
+ const value = background?.value
593
+ if (!BACKGROUND_MODES.includes(mode)) return { ok: false, error: `未知的背景模式:${String(mode)}` }
594
+ if (typeof value !== 'string' || value.length === 0 || value.length > 2048) {
595
+ return { ok: false, error: '背景取值缺失或过长' }
596
+ }
597
+ if (mode === 'preset' && !PRESET_BY_ID.has(value)) return { ok: false, error: `未知预设:${value}` }
598
+ if (mode === 'color' && !HEX_COLOR.test(value)) return { ok: false, error: '颜色需为 #rgb 或 #rrggbb' }
599
+ if (mode === 'animation' && !ANIMATION_IDS.has(value)) return { ok: false, error: `未知动画:${value}` }
600
+ if (mode === 'url' && !HTTP_URL.test(value)) return { ok: false, error: '图片地址需以 http:// 或 https:// 开头,且不能含空格或引号' }
601
+ if (mode === 'image' && value !== MEDIA_PATHS.background) return { ok: false, error: '内置图片地址不合法' }
602
+ // A remote video must be https: the page itself is served over https, and
603
+ // browsers refuse mixed-content media.
604
+ if (mode === 'video' && value !== MEDIA_PATHS.video && !HTTPS_URL.test(value)) {
605
+ return { ok: false, error: '视频地址需为上传的视频,或以 https:// 开头的链接' }
606
+ }
607
+ this.#state.background = { mode, value }
608
+ this.#persistSoon()
609
+ return { ok: true }
610
+ }
611
+
612
+ /**
613
+ * Merge a partial change into the login-page look.
614
+ * @param {object} change - any subset of the appearance fields.
615
+ * @returns {{ok: true}|{ok: false, error: string}} the validation outcome.
616
+ */
617
+ setAppearance(change) {
618
+ if (change === null || typeof change !== 'object') return { ok: false, error: '外观设置格式不正确' }
619
+ const next = { ...this.#state.appearance }
620
+ const pick = (field, check, error) => {
621
+ if (change[field] === undefined) return undefined
622
+ if (!check(change[field])) return error
623
+ next[field] = change[field]
624
+ return undefined
625
+ }
626
+ const failure = pick('card', (v) => CARD_STYLES.some((entry) => entry.id === v), '未知卡片样式')
627
+ ?? pick('layout', (v) => LAYOUTS.some((entry) => entry.id === v), '未知布局')
628
+ ?? pick('intro', (v) => INTROS.some((entry) => entry.id === v), '未知入场动画')
629
+ ?? pick('accent', (v) => typeof v === 'string' && HEX_COLOR.test(v), '主题色需为 #rgb 或 #rrggbb')
630
+ ?? pick('overlay', (v) => clampInt(v, 0, 85), '遮罩浓度需为 0–85 的整数')
631
+ ?? pick('blur', (v) => clampInt(v, 0, 24), '背景模糊需为 0–24 的整数')
632
+ ?? pick('title', (v) => typeof v === 'string' && v.trim().length > 0 && v.length <= 40 && PLAIN_TEXT.test(v), '标题需为 1–40 个字符,且不能包含 < > 或控制字符')
633
+ ?? pick('subtitle', (v) => typeof v === 'string' && v.length <= 80 && PLAIN_TEXT.test(v), '副标题最多 80 个字符,且不能包含 < > 或控制字符')
634
+ if (failure !== undefined) return { ok: false, error: failure }
635
+ this.#state.appearance = next
636
+ this.#persistSoon()
637
+ return { ok: true }
638
+ }
639
+
640
+ /**
641
+ * Replace the login-page logo.
642
+ * @param {{mode: string, value: string}} logo - the new setting.
643
+ * @returns {{ok: true}|{ok: false, error: string}} the validation outcome.
644
+ */
645
+ setLogo(logo) {
646
+ const mode = logo?.mode
647
+ const value = logo?.value
648
+ if (!LOGO_MODES.includes(mode)) return { ok: false, error: `未知的 logo 模式:${String(mode)}` }
649
+ if (mode === 'image' && value !== MEDIA_PATHS.logo) return { ok: false, error: '内置 logo 地址不合法' }
650
+ if (mode === 'url' && (typeof value !== 'string' || value.length > 2048 || !HTTP_URL.test(value))) {
651
+ return { ok: false, error: 'logo 地址需以 http:// 或 https:// 开头,且不能含空格或引号' }
652
+ }
653
+ this.#state.logo = { mode, value: mode === 'url' ? value : '' }
654
+ this.#persistSoon()
655
+ return { ok: true }
656
+ }
657
+
658
+ /**
659
+ * Replace the failed-attempt / ban policy.
660
+ * @param {object} policy - the new policy.
661
+ * @returns {{ok: true}|{ok: false, error: string}} the validation outcome.
662
+ */
663
+ setBanPolicy(policy) {
664
+ const enabled = policy?.enabled
665
+ const threshold = policy?.threshold
666
+ const duration = policy?.duration
667
+ if (typeof enabled !== 'boolean') return { ok: false, error: 'enabled 必须是布尔值' }
668
+ if (!BAN_THRESHOLDS.includes(threshold)) return { ok: false, error: `失败次数只能是 ${BAN_THRESHOLDS.join(' / ')}` }
669
+ if (!DURATION_BY_ID.has(duration)) return { ok: false, error: `未知封禁时长:${String(duration)}` }
670
+ this.#state.ban = { enabled, threshold, duration }
671
+ this.#persistSoon()
672
+ return { ok: true }
673
+ }
674
+
675
+ /**
676
+ * Change the password after verifying the current one.
677
+ * @param {string} currentPassword - the password in force now.
678
+ * @param {string} nextPassword - the replacement.
679
+ * @returns {Promise<{ok: true}|{ok: false, error: string}>} the outcome.
680
+ */
681
+ async changePassword(currentPassword, nextPassword) {
682
+ if (!(await this.verifyPassword(currentPassword))) return { ok: false, error: '原密码不正确' }
683
+ if (typeof nextPassword !== 'string' || nextPassword.length < MIN_PASSWORD_LENGTH) {
684
+ return { ok: false, error: `新密码至少 ${MIN_PASSWORD_LENGTH} 位` }
685
+ }
686
+ if (nextPassword.length > MAX_PASSWORD_LENGTH) return { ok: false, error: '新密码过长' }
687
+ if (/[\u0000-\u001f\u007f]/u.test(nextPassword)) return { ok: false, error: '新密码不能包含换行或控制字符' }
688
+ if (nextPassword === currentPassword) return { ok: false, error: '新密码不能与原密码相同' }
689
+ this.#state.password = await hashPassword(nextPassword)
690
+ this.#persistSoon()
691
+ return { ok: true }
692
+ }
693
+
694
+ /**
695
+ * Install a freshly generated random password without checking the one in
696
+ * force — the "I forgot it" escape hatch. The value is returned exactly once
697
+ * and never stored in plaintext; callers gate this behind an authenticated
698
+ * session and an explicit confirmation.
699
+ * @returns {Promise<{ok: true, password: string}>} the outcome.
700
+ */
701
+ async resetPassword() {
702
+ let password = ''
703
+ for (let i = 0; i < RESET_LENGTH; i += 1) password += RESET_ALPHABET[randomInt(RESET_ALPHABET.length)]
704
+ this.#state.password = await hashPassword(password)
705
+ this.#persistSoon()
706
+ return { ok: true, password }
707
+ }
708
+ }