@lvxianchao/dsh-web-guard 0.0.0-stage → 2.0.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.
package/lib/admin.js ADDED
@@ -0,0 +1,190 @@
1
+ /**
2
+ * Admin page for dsh-web-guard: a server-rendered settings form.
3
+ *
4
+ * Why server-rendered instead of a harness client module: the plugin stays
5
+ * build-free and version-independent. The page is one HTML string plus normal
6
+ * form posts, so `dsh plugin add` gives operators a working UI without pulling
7
+ * in a bundler or depending on the harness slot API (which is still moving).
8
+ */
9
+
10
+ import { t as copy, ago } from './i18n.js'
11
+
12
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
13
+
14
+ const GITHUB_ICON = `<svg viewBox="0 0 16 16" width="15" height="15" fill="currentColor" aria-hidden="true"><path d="M8 0C3.58 0 0 3.58 0 8c0 3.54 2.29 6.53 5.47 7.59.4.07.55-.17.55-.38 0-.19-.01-.82-.01-1.49-2.01.37-2.53-.49-2.69-.94-.09-.23-.48-.94-.82-1.13-.28-.15-.68-.52-.01-.53.63-.01 1.08.58 1.23.82.72 1.21 1.87.87 2.33.66.07-.52.28-.87.51-1.07-1.78-.2-3.64-.89-3.64-3.95 0-.87.31-1.59.82-2.15-.08-.2-.36-1.02.08-2.12 0 0 .67-.21 2.2.82.64-.18 1.32-.27 2-.27.68 0 1.36.09 2 .27 1.53-1.04 2.2-.82 2.2-.82.44 1.1.16 1.92.08 2.12.51.56.82 1.27.82 2.15 0 3.07-1.87 3.75-3.65 3.95.29.25.54.73.54 1.48 0 1.07-.01 1.93-.01 2.2 0 .21.15.46.55.38A8.012 8.012 0 0016 8c0-4.42-3.58-8-8-8z"/></svg>`
15
+
16
+ const fmtTime = (ms) => {
17
+ if (!ms) return '—'
18
+ const d = new Date(ms)
19
+ const pad = (n) => String(n).padStart(2, '0')
20
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
21
+ }
22
+
23
+ /**
24
+ * Render the admin document.
25
+ * @param {object} options
26
+ * @param {object} options.settings - effective settings shown in the form
27
+ * @param {Array<{ip:string,ua:string,createdAt:number,lastSeen:number,current:boolean}>} options.sessions
28
+ * @param {string} [options.notice] - success line
29
+ * @param {string} [options.error] - error line
30
+ * @param {string} [options.restartNote] - shown when a listened-on value changed
31
+ */
32
+ export function adminPage({ settings, sessions = [], notice = '', error = '', restartNote = '', locale = 'zh' } = {}) {
33
+ const L = copy(locale)
34
+ const s = settings ?? {}
35
+ const rows = sessions.length === 0
36
+ ? `<tr><td colspan="4" class="empty">${esc(L.emptySessions)}</td></tr>`
37
+ : sessions.map((x) => `<tr>
38
+ <td>${esc(x.ip)}${x.current ? ` <span class="tag">${esc(L.current)}</span>` : ''}</td>
39
+ <td class="ua" title="${esc(x.ua)}">${esc(x.ua || '—')}</td>
40
+ <td>${fmtTime(x.lastSeen)}<span class="dim"> · ${esc(ago(x.lastSeen, locale))}</span></td>
41
+ <td class="num">${x.current ? '' : `<button class="link danger" form="kill" name="id" value="${esc(x.id)}">${esc(L.kick)}</button>`}</td>
42
+ </tr>`).join('')
43
+
44
+ return `<!doctype html>
45
+ <html lang="${locale === 'zh' ? 'zh-CN' : 'en'}"><head>
46
+ <meta charset="utf-8">
47
+ <meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
48
+ <meta name="robots" content="noindex,nofollow">
49
+ <meta name="color-scheme" content="dark">
50
+ <title>${esc(L.pageTitleAdmin)}</title>
51
+ <style>
52
+ :root{color-scheme:dark;--bg:#0b0d10;--card:#12151a;--line:#24282e;--text:#e6e8eb;--muted:#8b929c;--accent:#3f6df0;--danger:#ff7b72}
53
+ *{box-sizing:border-box}
54
+ html{background:var(--bg)}
55
+ body{margin:0;min-height:100vh;min-height:100dvh;background:var(--bg);color:var(--text);
56
+ font:15px/1.65 system-ui,-apple-system,"Segoe UI",Roboto,"PingFang SC","Microsoft YaHei",sans-serif;
57
+ -webkit-text-size-adjust:100%;padding:28px 18px max(28px,env(safe-area-inset-bottom))}
58
+ .wrap{width:min(100%,720px);margin:0 auto;padding-bottom:28px}
59
+ header{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:20px;flex-wrap:wrap}
60
+ h1{margin:0;font-size:18px;font-weight:600}
61
+ h1 a.repo{display:inline-flex;align-items:center;gap:9px;color:inherit;text-decoration:none;transition:color .15s}
62
+ h1 a.repo svg{color:var(--muted);transition:color .15s;flex:none}
63
+ h1 a.repo:hover{color:#fff}
64
+ h1 a.repo:hover svg{color:#fff}
65
+ header .links{display:flex;gap:10px;align-items:center;font-size:13px}
66
+ header a{display:inline-flex;align-items:center;padding:8px 16px;border-radius:9px;font-size:13px;
67
+ font-weight:600;text-decoration:none;line-height:1;border:1px solid transparent;transition:.15s}
68
+ header a.primary{background:var(--accent);color:#fff}
69
+ header a.primary:hover{background:#4f7bf5}
70
+ header a.ghost{border-color:var(--line);color:var(--text)}
71
+ header a.ghost:hover{border-color:var(--danger);color:var(--danger)}
72
+ .card{border:1px solid var(--line);border-radius:14px;background:var(--card);padding:20px 22px;margin-bottom:16px}
73
+ .card h2{margin:0 0 4px;font-size:14px;font-weight:600}
74
+ .card p.hint{margin:0 0 16px;color:var(--muted);font-size:12.5px}
75
+ .grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:14px}
76
+ .field{display:flex;flex-direction:column;gap:5px;min-width:0}
77
+ .field.full{grid-column:1 / -1}
78
+ label{font-size:13px;color:#a7aeb8}
79
+ input{width:100%;padding:10px 11px;border-radius:9px;border:1px solid #2c3138;background:#0e1116;color:var(--text);
80
+ font-size:16px;line-height:1.3;outline:none;transition:border-color .15s,box-shadow .15s}
81
+ input:focus{border-color:var(--accent);box-shadow:0 0 0 3px rgba(74,125,255,.18)}
82
+ input:disabled{opacity:.55;cursor:not-allowed}
83
+ .note{color:#5f666f;font-size:12px}
84
+ .actions{display:flex;gap:10px;flex-wrap:wrap;align-items:center;margin-top:4px}
85
+ button{padding:10px 18px;border:0;border-radius:9px;background:var(--accent);color:#fff;font-size:14px;font-weight:600;cursor:pointer}
86
+ button:hover{background:#4a7dff}
87
+ button.ghost{background:#191d22;color:var(--text);border:1px solid var(--line)}
88
+ button.ghost:hover{background:#20252c}
89
+ button.danger{background:#3a1c1c;color:#ffb4ae;border:1px solid #5a2a2a}
90
+ button.danger:hover{background:#4a2222}
91
+ button.link{background:none;border:0;color:var(--accent);font-size:13px;padding:2px 4px;cursor:pointer}
92
+ button.link.danger{color:var(--danger)}
93
+ table{width:100%;border-collapse:collapse;font-size:13px}
94
+ th,td{text-align:left;padding:9px 8px;border-bottom:1px solid #1d2126;vertical-align:top}
95
+ th{color:var(--muted);font-weight:500;font-size:12px}
96
+ tr:last-child td{border-bottom:0}
97
+ td.ua{max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:#a7aeb8}
98
+ td.num{text-align:right;white-space:nowrap}
99
+ td.empty{text-align:center;color:var(--muted);padding:18px}
100
+ .tag{display:inline-block;font-size:11px;padding:1px 6px;border-radius:999px;background:#1d2f52;color:#9db8ff;vertical-align:1px}
101
+ .dim{color:#5f666f}
102
+ .banner{margin:0 0 16px;padding:10px 14px;border-radius:10px;font-size:13px}
103
+ .banner.ok{background:#12271a;color:#8fdca8;border:1px solid #1e4030}
104
+ .banner.bad{background:#2a1616;color:#ffb4ae;border:1px solid #4a2222}
105
+ .banner.warn{background:#2a2312;color:#e8cf94;border:1px solid #4a3d1e}
106
+ body.embedded{background:transparent}
107
+ body.embedded .wrap{width:100%;max-width:none;margin:0;padding:0 4px}
108
+ body.embedded h1{font-size:15px}
109
+ @media (max-width:560px){
110
+ .grid{grid-template-columns:1fr}
111
+ .card{padding:18px 16px}
112
+ td.ua{max-width:120px}
113
+ }
114
+ </style>
115
+ </head><body>
116
+ <div class="wrap">
117
+ <header>
118
+ <h1><a class="repo" href="${esc(s.repo || 'https://github.com/lvxianchao/dsh-web-guard')}" target="_blank" rel="noopener noreferrer" title="GitHub">${GITHUB_ICON}<span>${esc(L.adminTitle)}</span></a></h1>
119
+ <div class="links">
120
+ <a href="/logout" class="ghost">${esc(L.signOut)}</a>
121
+ <a href="/" id="g-back" class="primary">${esc(L.backToDsh)}</a>
122
+ </div>
123
+ </header>
124
+
125
+ ${notice ? `<p class="banner ok">${esc(notice)}</p>` : ''}
126
+ ${error ? `<p class="banner bad">${esc(error)}</p>` : ''}
127
+ ${restartNote ? `<p class="banner warn">${esc(restartNote)}</p>` : ''}
128
+
129
+ <form method="post" action="/__guard/admin" autocomplete="off">
130
+ <section class="card">
131
+ <h2>${esc(L.secPassword)}</h2>
132
+ <p class="hint">${esc(L.hintPassword)}</p>
133
+ <div class="grid">
134
+ <div class="field full"><label for="current">${esc(L.currentPassword)}</label>
135
+ <input id="current" name="current" type="password" autocomplete="current-password" placeholder="${esc(L.currentPasswordPh)}"></div>
136
+ <div class="field"><label for="next">${esc(L.newPassword)}</label>
137
+ <input id="next" name="next" type="password" autocomplete="new-password" placeholder="${esc(L.newPasswordPh)}"></div>
138
+ <div class="field"><label for="confirm">${esc(L.confirmPassword)}</label>
139
+ <input id="confirm" name="confirm" type="password" autocomplete="new-password" placeholder="${esc(L.confirmPasswordPh)}"></div>
140
+ </div>
141
+ </section>
142
+
143
+ <section class="card">
144
+ <h2>${esc(L.secSession)}</h2>
145
+ <p class="hint">${esc(L.hintSession)}</p>
146
+ <div class="grid">
147
+ <div class="field"><label for="sessionDays">${esc(L.sessionDays)}</label>
148
+ <input id="sessionDays" name="sessionDays" type="number" min="0" max="365" step="1" value="${esc(s.sessionDays)}"></div>
149
+ <div class="field"><label for="lockMinutes">${esc(L.lockMinutes)}</label>
150
+ <input id="lockMinutes" name="lockMinutes" type="number" min="1" max="1440" step="1" value="${esc(s.lockMinutes)}"></div>
151
+ <div class="field"><label for="maxAttempts">${esc(L.maxAttempts)}</label>
152
+ <input id="maxAttempts" name="maxAttempts" type="number" min="1" max="50" step="1" value="${esc(s.maxAttempts)}"></div>
153
+ </div>
154
+ </section>
155
+
156
+ <section class="card">
157
+ <h2>${esc(L.secListen)}</h2>
158
+ <p class="hint">${esc(L.hintListen)}</p>
159
+ <div class="grid">
160
+ <div class="field"><label for="listenHost">${esc(L.listenHost)}</label>
161
+ <input id="listenHost" name="listenHost" type="text" value="${esc(s.listenHost)}"></div>
162
+ <div class="field"><label for="listenPort">${esc(L.listenPort)}</label>
163
+ <input id="listenPort" name="listenPort" type="number" min="1" max="65535" value="${esc(s.listenPort)}"></div>
164
+ </div>
165
+ </section>
166
+
167
+ <div class="actions">
168
+ <button type="submit">${esc(L.save)}</button>
169
+ <button type="submit" formaction="/__guard/logout-all" formmethod="post" class="ghost"
170
+ onclick="return confirm('${esc(L.confirmSignOutAll)}')">${esc(L.signOutAll)}</button>
171
+ </div>
172
+ </form>
173
+
174
+ <section class="card" style="margin-top:16px">
175
+ <h2>${esc(L.secSessions)}</h2>
176
+ <p class="hint">${esc(L.hintSessions)}</p>
177
+ <table>
178
+ <thead><tr><th>${esc(L.colSource)}</th><th>${esc(L.colBrowser)}</th><th>${esc(L.colLastSeen)}</th><th></th></tr></thead>
179
+ <tbody>${rows}</tbody>
180
+ </table>
181
+ </section>
182
+
183
+ <form id="kill" method="post" action="/__guard/kill"></form>
184
+
185
+ </div>
186
+ <script>(function(){if(window.self===window.top)return;document.body.classList.add('embedded');
187
+ var b=document.getElementById('g-back');if(!b)return;b.textContent='${esc(L.close)}';
188
+ b.addEventListener('click',function(e){e.preventDefault();try{parent.postMessage('dsh-web-guard:close',location.origin)}catch(_){}});})()</script>
189
+ </body></html>`
190
+ }
package/lib/auth.js ADDED
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Password verification and session storage for dsh-web-guard.
3
+ *
4
+ * Design notes:
5
+ * - Passwords are stored as scrypt `scrypt$N$r$p$salt$key` (same shape the
6
+ * Hermes dashboard uses) so a hash can be pasted into config.
7
+ * - Sessions live in memory: the plugin restarts with dsh, and a restart
8
+ * should force a fresh login anyway. Tokens are stored hashed, so a heap
9
+ * dump does not hand out live sessions.
10
+ * - Every session carries its own expiry and last-seen stamp; the cookie
11
+ * lifetime is fixed at issue time, the server side slides on activity.
12
+ */
13
+ import { randomBytes, createHash, scryptSync, timingSafeEqual } from 'node:crypto'
14
+
15
+ const SCRYPT_N = 16384
16
+ const SCRYPT_R = 8
17
+ const SCRYPT_P = 1
18
+ const KEYLEN = 32
19
+
20
+ /** Hash a plaintext password into the portable scrypt string form. */
21
+ export function hashPassword(password, salt = randomBytes(16)) {
22
+ const key = scryptSync(password, salt, KEYLEN, { N: SCRYPT_N, r: SCRYPT_R, p: SCRYPT_P, maxmem: 64 * 1024 * 1024 })
23
+ return `scrypt$${SCRYPT_N}$${SCRYPT_R}$${SCRYPT_P}$${salt.toString('base64')}$${key.toString('base64')}`
24
+ }
25
+
26
+ /** Verify a password against either the scrypt string or a bare plaintext. */
27
+ export function verifyPassword(password, stored) {
28
+ if (typeof password !== 'string' || typeof stored !== 'string' || stored.length === 0) return false
29
+ if (!stored.startsWith('scrypt$')) {
30
+ // Plaintext config: constant-time compare on equal-length buffers.
31
+ const a = Buffer.from(password)
32
+ const b = Buffer.from(stored)
33
+ if (a.length !== b.length) return false
34
+ return timingSafeEqual(a, b)
35
+ }
36
+ const parts = stored.split('$')
37
+ if (parts.length !== 6) return false
38
+ const [, n, r, p, saltB64, keyB64] = parts
39
+ let expected
40
+ try {
41
+ expected = Buffer.from(keyB64, 'base64')
42
+ } catch {
43
+ return false
44
+ }
45
+ if (expected.length === 0) return false
46
+ const actual = scryptSync(password, Buffer.from(saltB64, 'base64'), expected.length, {
47
+ N: Number(n), r: Number(r), p: Number(p), maxmem: 64 * 1024 * 1024,
48
+ })
49
+ return actual.length === expected.length && timingSafeEqual(actual, expected)
50
+ }
51
+
52
+ const sha256 = (value) => createHash('sha256').update(value).digest('hex')
53
+
54
+ /** In-memory session table with per-IP failure accounting. */
55
+ export class SessionStore {
56
+ /**
57
+ * @param {object} options
58
+ * @param {number} options.sessionDays - session lifetime in days; 0 = browser session only
59
+ * @param {number} options.maxAttempts - failures before a temporary lock
60
+ * @param {number} options.lockMinutes - lock duration in minutes
61
+ */
62
+ constructor({ sessionDays = 7, maxAttempts = 5, lockMinutes = 5 } = {}) {
63
+ this.sessionMs = Math.max(0, sessionDays) * 24 * 60 * 60 * 1000
64
+ this.maxAttempts = Math.max(1, maxAttempts)
65
+ this.lockMs = Math.max(1, lockMinutes) * 60 * 1000
66
+ /** @type {Map<string, {createdAt:number,lastSeen:number,ip:string,ua:string}>} */
67
+ this.sessions = new Map()
68
+ /** @type {Map<string, {fails:number,until:number}>} */
69
+ this.failures = new Map()
70
+ this.timer = setInterval(() => this.sweep(), 10 * 60 * 1000)
71
+ this.timer.unref?.()
72
+ }
73
+
74
+ /** Whether this client is currently locked out. */
75
+ isLocked(ip) {
76
+ const row = this.failures.get(ip)
77
+ if (!row) return false
78
+ if (row.until === 0) return false // below the threshold: keep counting
79
+ if (row.until > Date.now()) return true
80
+ this.failures.delete(ip) // lock expired
81
+ return false
82
+ }
83
+
84
+ /** Record a failed attempt; returns the remaining attempts before lock. */
85
+ recordFailure(ip) {
86
+ const row = this.failures.get(ip) ?? { fails: 0, until: 0 }
87
+ row.fails += 1
88
+ if (row.fails >= this.maxAttempts) {
89
+ row.until = Date.now() + this.lockMs
90
+ row.fails = 0
91
+ }
92
+ this.failures.set(ip, row)
93
+ return Math.max(0, this.maxAttempts - row.fails)
94
+ }
95
+
96
+ clearFailures(ip) {
97
+ this.failures.delete(ip)
98
+ }
99
+
100
+ /** Create a session and return the raw token (only ever held by the client). */
101
+ issue(ip, ua) {
102
+ const token = randomBytes(32).toString('base64url')
103
+ const now = Date.now()
104
+ this.sessions.set(sha256(token), { createdAt: now, lastSeen: now, ip, ua })
105
+ return token
106
+ }
107
+
108
+ /** Resolve a token to its session, sliding last-seen. */
109
+ resolve(token) {
110
+ if (typeof token !== 'string' || token.length === 0) return undefined
111
+ const key = sha256(token)
112
+ const row = this.sessions.get(key)
113
+ if (!row) return undefined
114
+ const now = Date.now()
115
+ const limit = this.sessionMs === 0 ? 12 * 60 * 60 * 1000 : this.sessionMs
116
+ if (now - row.lastSeen > limit) {
117
+ this.sessions.delete(key)
118
+ return undefined
119
+ }
120
+ row.lastSeen = now
121
+ return row
122
+ }
123
+
124
+ revoke(token) {
125
+ if (typeof token === 'string' && token.length > 0) this.sessions.delete(sha256(token))
126
+ }
127
+
128
+ /** List live sessions with a short opaque id (the hashed key prefix). */
129
+ list() {
130
+ const now = Date.now()
131
+ const limit = this.sessionMs === 0 ? 12 * 60 * 60 * 1000 : this.sessionMs
132
+ const out = []
133
+ for (const [key, row] of this.sessions) {
134
+ if (now - row.lastSeen > limit) continue
135
+ out.push({ id: key.slice(0, 16), ip: row.ip, ua: row.ua, createdAt: row.createdAt, lastSeen: row.lastSeen })
136
+ }
137
+ return out.sort((a, b) => b.lastSeen - a.lastSeen)
138
+ }
139
+
140
+ /** Drop one session by the id returned from {@link list}. */
141
+ removeById(id) {
142
+ if (typeof id !== 'string') return false
143
+ for (const key of this.sessions.keys()) {
144
+ if (key.slice(0, 16) === id) {
145
+ this.sessions.delete(key)
146
+ return true
147
+ }
148
+ }
149
+ return false
150
+ }
151
+
152
+ /** Id of the session owning this raw token, for "current" highlighting. */
153
+ idOf(token) {
154
+ if (typeof token !== 'string' || token.length === 0) return ''
155
+ return sha256(token).slice(0, 16)
156
+ }
157
+
158
+ revokeAll() {
159
+ this.sessions.clear()
160
+ }
161
+
162
+ sweep() {
163
+ const now = Date.now()
164
+ const limit = this.sessionMs === 0 ? 12 * 60 * 60 * 1000 : this.sessionMs
165
+ for (const [key, row] of this.sessions) {
166
+ if (now - row.lastSeen > limit) this.sessions.delete(key)
167
+ }
168
+ for (const [ip, row] of this.failures) {
169
+ if (row.until > 0 && row.until < now) this.failures.delete(ip)
170
+ }
171
+ }
172
+
173
+ dispose() {
174
+ clearInterval(this.timer)
175
+ this.sessions.clear()
176
+ this.failures.clear()
177
+ }
178
+ }
package/lib/i18n.js ADDED
@@ -0,0 +1,273 @@
1
+ /**
2
+ * Locale detection and copy for the guard's own pages.
3
+ *
4
+ * The harness stores the operator's language choice in the profile patch file
5
+ * (`- id: locale` → `config.preference`), which is exactly what the settings UI
6
+ * writes when someone switches language. Reading it means the login and admin
7
+ * pages follow the harness instead of guessing from the browser.
8
+ *
9
+ * When no explicit preference exists, the harness falls back to the browser
10
+ * language — and so do we, via Accept-Language.
11
+ */
12
+ import { readFileSync, watch, statSync } from 'node:fs'
13
+ import { basename, dirname } from 'node:path'
14
+
15
+ const SUPPORTED = ['zh', 'en']
16
+
17
+ /**
18
+ * Read the explicit locale preference from a profile patch file.
19
+ * @param {string} patchPath - absolute path to cordis.patch.yml
20
+ * @returns {'zh'|'en'|''} a supported locale id, or '' when unset/unreadable
21
+ */
22
+ export function readPreference(patchPath) {
23
+ if (!patchPath) return ''
24
+ let text
25
+ try {
26
+ text = readFileSync(patchPath, 'utf8')
27
+ } catch {
28
+ return ''
29
+ }
30
+ const lines = text.split('\n')
31
+ let inLocaleRow = false
32
+ let rowIndent = 0
33
+ for (const line of lines) {
34
+ const trimmed = line.trim()
35
+ if (!trimmed || trimmed.startsWith('#')) continue
36
+ const indent = line.length - line.trimStart().length
37
+
38
+ // A new top-level-ish row ends the section we were scanning.
39
+ if (inLocaleRow && /^- /.test(trimmed) && indent <= rowIndent) break
40
+
41
+ if (/^-\s+id:\s*['"]?locale['"]?\s*$/.test(trimmed)) {
42
+ inLocaleRow = true
43
+ rowIndent = indent
44
+ continue
45
+ }
46
+ if (inLocaleRow) {
47
+ const m = trimmed.match(/^preference:\s*['"]?([A-Za-z-]+)['"]?/)
48
+ if (m) return normalize(m[1])
49
+ }
50
+ }
51
+ return ''
52
+ }
53
+
54
+ /** Map an arbitrary tag (`zh-CN`, `en-US`) onto a supported id. */
55
+ export function normalize(tag) {
56
+ const base = String(tag ?? '').toLowerCase().split(/[-_]/)[0]
57
+ return SUPPORTED.includes(base) ? base : ''
58
+ }
59
+
60
+ /**
61
+ * Resolve the page locale: explicit preference first, then Accept-Language.
62
+ * @param {string} patchPath - profile patch file
63
+ * @param {import('node:http').IncomingMessage} [req] - request carrying Accept-Language
64
+ */
65
+ export function detectLocale(patchPath, req) {
66
+ const explicit = readPreference(patchPath)
67
+ if (explicit) return explicit
68
+ const header = String(req?.headers?.['accept-language'] ?? '')
69
+ const first = header.split(',')[0]?.trim()
70
+ return normalize(first) || 'en'
71
+ }
72
+
73
+ /** Relative time in the active language. */
74
+ export function ago(ms, locale) {
75
+ if (!ms) return '—'
76
+ const s = Math.max(0, Math.round((Date.now() - ms) / 1000))
77
+ if (locale === 'zh') {
78
+ if (s < 60) return `${s} 秒前`
79
+ if (s < 3600) return `${Math.round(s / 60)} 分钟前`
80
+ if (s < 86400) return `${Math.round(s / 3600)} 小时前`
81
+ return `${Math.round(s / 86400)} 天前`
82
+ }
83
+ if (s < 60) return `${s}s ago`
84
+ if (s < 3600) return `${Math.round(s / 60)} min ago`
85
+ if (s < 86400) return `${Math.round(s / 3600)} h ago`
86
+ return `${Math.round(s / 86400)} d ago`
87
+ }
88
+
89
+ const ZH = {
90
+ locale: 'zh',
91
+ adminTitle: 'DSH Web Guard',
92
+ pageTitleAdmin: 'DSH Web Guard',
93
+ backToDsh: '返回 DSH',
94
+ close: '关闭',
95
+ signOut: '退出登录',
96
+ secPassword: '登录密码',
97
+ hintPassword: '留空则不修改。修改后其他设备上的会话仍然有效,需要的话用下面的「退出所有设备」。',
98
+ currentPassword: '当前密码',
99
+ currentPasswordPh: '修改密码时必填',
100
+ newPassword: '新密码',
101
+ newPasswordPh: '至少 6 位',
102
+ confirmPassword: '确认新密码',
103
+ confirmPasswordPh: '再输一次',
104
+ secSession: '会话与安全',
105
+ hintSession: '会话有效期从最后一次活动开始计算;改为 0 表示关掉浏览器即失效。',
106
+ sessionDays: '会话有效期(天)',
107
+ lockMinutes: '锁定时间(分钟)',
108
+ maxAttempts: '连续失败次数上限',
109
+ secListen: '监听',
110
+ hintListen: '修改后需要重启 DSH 才生效;填错会导致管理页和外网入口都连不上,确认前先记下原值。',
111
+ listenHost: '监听地址',
112
+ listenPort: '监听端口',
113
+ save: '保存',
114
+ signOutAll: '退出所有设备',
115
+ confirmSignOutAll: '将退出所有设备上的登录,包括当前这个。继续?',
116
+ secSessions: '活跃会话',
117
+ hintSessions: '每个浏览器一条记录。会话存在内存里,重启 DSH 会全部失效。',
118
+ colSource: '来源',
119
+ colBrowser: '浏览器',
120
+ colLastSeen: '最后活动',
121
+ current: '当前',
122
+ kick: '踢出',
123
+ emptySessions: '当前没有其他活跃会话',
124
+ saved: '已保存',
125
+ savedPassword: '已保存,密码已更新',
126
+ restartNote: '监听地址/端口已记录,重启 DSH 后才会生效。',
127
+ errCurrent: '当前密码不正确',
128
+ errShort: '新密码至少 6 位',
129
+ errMismatch: '两次输入的新密码不一致',
130
+ errOrigin: '请求来源不合法',
131
+ kicked: '已踢出该会话',
132
+ kickMissing: '该会话已不存在',
133
+ // login page
134
+ loginSubtitle: '此服务需要密码才能访问',
135
+ passwordLabel: '访问密码',
136
+ passwordPh: '输入密码',
137
+ submit: '进入',
138
+ errWrong: '密码不正确',
139
+ errLocked: '尝试次数过多,请稍后再试',
140
+ loggedOut: '已退出登录',
141
+ signInAgain: '重新登录',
142
+ }
143
+
144
+ const EN = {
145
+ locale: 'en',
146
+ adminTitle: 'DSH Web Guard',
147
+ pageTitleAdmin: 'DSH Web Guard',
148
+ backToDsh: 'Back to DSH',
149
+ close: 'Close',
150
+ signOut: 'Sign out',
151
+ secPassword: 'Password',
152
+ hintPassword: 'Leave blank to keep the current one. Other devices stay signed in — use "Sign out everywhere" below if you want them gone.',
153
+ currentPassword: 'Current password',
154
+ currentPasswordPh: 'Required to change it',
155
+ newPassword: 'New password',
156
+ newPasswordPh: 'At least 6 characters',
157
+ confirmPassword: 'Confirm new password',
158
+ confirmPasswordPh: 'Type it again',
159
+ secSession: 'Sessions and lockout',
160
+ hintSession: 'Lifetime counts from the last activity; 0 means the session ends when the browser closes.',
161
+ sessionDays: 'Session lifetime (days)',
162
+ lockMinutes: 'Lockout duration (minutes)',
163
+ maxAttempts: 'Failed attempts before lockout',
164
+ secListen: 'Listener',
165
+ hintListen: 'Takes effect after a DSH restart. A wrong value locks you out of both this page and the public entry — note the current values first.',
166
+ listenHost: 'Listen address',
167
+ listenPort: 'Listen port',
168
+ save: 'Save',
169
+ signOutAll: 'Sign out everywhere',
170
+ confirmSignOutAll: 'This signs out every device, including this one. Continue?',
171
+ secSessions: 'Active sessions',
172
+ hintSessions: 'One row per browser. Sessions live in memory and are cleared when DSH restarts.',
173
+ colSource: 'Source',
174
+ colBrowser: 'Browser',
175
+ colLastSeen: 'Last seen',
176
+ current: 'this device',
177
+ kick: 'Kick',
178
+ emptySessions: 'No other active sessions',
179
+ saved: 'Saved',
180
+ savedPassword: 'Saved — password updated',
181
+ restartNote: 'Listener change recorded; it takes effect after a DSH restart.',
182
+ errCurrent: 'Current password is incorrect',
183
+ errShort: 'New password must be at least 6 characters',
184
+ errMismatch: 'The new passwords do not match',
185
+ errOrigin: 'Request origin rejected',
186
+ kicked: 'Session kicked',
187
+ kickMissing: 'That session no longer exists',
188
+ // login page
189
+ loginSubtitle: 'This service requires a password',
190
+ passwordLabel: 'Password',
191
+ passwordPh: 'Enter password',
192
+ submit: 'Continue',
193
+ errWrong: 'Incorrect password',
194
+ errLocked: 'Too many attempts — try again later',
195
+ loggedOut: 'Signed out',
196
+ signInAgain: 'Sign in again',
197
+ }
198
+
199
+ const CATALOG = { zh: ZH, en: EN }
200
+
201
+ /** Copy bundle for a locale, falling back to English. */
202
+ export function t(locale) {
203
+ return CATALOG[locale] ?? EN
204
+ }
205
+
206
+ /**
207
+ * Keep the patch file's locale preference in memory.
208
+ *
209
+ * Reading the file per request would block the harness event loop (this plugin
210
+ * shares its process), and a fixed poll interval is a guess in both directions.
211
+ * Instead: read once at startup, then re-read only when the directory reports a
212
+ * change — the harness writes atomically via rename, so watching the directory
213
+ * is what actually catches the replacement. If the platform has no usable
214
+ * watcher, fall back to a slow mtime check on a timer.
215
+ *
216
+ * @param {string} patchPath - absolute path to cordis.patch.yml
217
+ * @returns {{get: () => string, dispose: () => void}}
218
+ */
219
+ export function createLocaleReader(patchPath) {
220
+ let value = readPreference(patchPath)
221
+ let watcher
222
+ let poller
223
+ let mtime = 0
224
+ let debounce
225
+
226
+ const stamp = () => {
227
+ try {
228
+ return statSync(patchPath).mtimeMs
229
+ } catch {
230
+ return 0
231
+ }
232
+ }
233
+ mtime = stamp()
234
+
235
+ const refresh = () => {
236
+ const next = stamp()
237
+ if (next === mtime) return
238
+ mtime = next
239
+ value = readPreference(patchPath)
240
+ }
241
+ const schedule = () => {
242
+ if (debounce) clearTimeout(debounce)
243
+ debounce = setTimeout(refresh, 40)
244
+ debounce.unref?.()
245
+ }
246
+
247
+ try {
248
+ watcher = watch(dirname(patchPath), { persistent: false }, (_event, filename) => {
249
+ if (!filename || String(filename) === basename(patchPath)) schedule()
250
+ })
251
+ watcher.on('error', () => {
252
+ watcher?.close()
253
+ watcher = undefined
254
+ })
255
+ } catch {
256
+ watcher = undefined
257
+ }
258
+
259
+ if (!watcher) {
260
+ // No usable watcher: an inexpensive mtime check every 30s is the safety net.
261
+ poller = setInterval(refresh, 30_000)
262
+ poller.unref?.()
263
+ }
264
+
265
+ return {
266
+ get: () => value,
267
+ dispose: () => {
268
+ if (debounce) clearTimeout(debounce)
269
+ if (poller) clearInterval(poller)
270
+ watcher?.close()
271
+ },
272
+ }
273
+ }