@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.
- package/README.md +135 -2
- package/app/appguide.mjs +33 -0
- package/app/asr.mjs +82 -0
- package/app/assets/agents/claude-192.webp +0 -0
- package/app/assets/agents/claude-96.webp +0 -0
- package/app/assets/agents/codex-192.webp +0 -0
- package/app/assets/agents/codex-96.webp +0 -0
- package/app/assets/agents/default-192.webp +0 -0
- package/app/assets/agents/default-96.webp +0 -0
- package/app/assets/agents/dsh-192.webp +0 -0
- package/app/assets/agents/dsh-96.webp +0 -0
- package/app/assets/brand/logo.webp +0 -0
- package/app/assets/lib/THIRD-PARTY.txt +1 -0
- package/app/assets/lib/jsqr.js +10102 -0
- package/app/assets/linux/alpine-arm64.tar.gz +0 -0
- package/app/assets/linux/alpine-x64.tar.gz +0 -0
- package/app/assets/live/claude.livliv +0 -0
- package/app/assets/live/dafeiyu.livliv +0 -0
- package/app/assets/live/gpt.livliv +0 -0
- package/app/assets/live/sho.livliv +0 -0
- package/app/assets/live//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
- package/app/assets/livliv/LICENSE +202 -0
- package/app/assets/livliv/NOTICE +7 -0
- package/app/assets/livliv/player.mjs +15 -0
- package/app/assets/looks/claude.webp +0 -0
- package/app/assets/looks/dafeiyu.webp +0 -0
- package/app/assets/looks/gpt.webp +0 -0
- package/app/assets/looks//345/275/242/350/261/241/346/235/245/346/272/220.md +5 -0
- package/app/assets/sho/avatar.webp +0 -0
- package/app/assets/sho/done.webp +0 -0
- package/app/assets/sho/eat.webp +0 -0
- package/app/assets/sho/idle-blink.webp +0 -0
- package/app/assets/sho/idle.webp +0 -0
- package/app/assets/sho/listen.webp +0 -0
- package/app/assets/sho/need.webp +0 -0
- package/app/assets/sho/work.webp +0 -0
- package/app/companion.mjs +519 -0
- package/app/diag.mjs +51 -0
- package/app/index.html +497 -0
- package/app/judge.mjs +103 -0
- package/app/lanxfer.mjs +157 -0
- package/app/launcher.mjs +2715 -0
- package/app/linux.mjs +97 -0
- package/app/livliv-pack.mjs +12 -0
- package/app/memory.mjs +53 -0
- package/app/net.mjs +717 -0
- package/app/office.mjs +172 -0
- package/app/p2plink.mjs +134 -0
- package/app/pcupdate.mjs +55 -0
- package/app/plans.mjs +126 -0
- package/app/plugins.mjs +79 -0
- package/app/realtime.mjs +67 -0
- package/app/skills/app-icon/SKILL.md +31 -0
- package/app/skills/daily-brief/SKILL.md +29 -0
- package/app/skills/expense-review/SKILL.md +28 -0
- package/app/skills/make-app/SKILL.md +92 -0
- package/app/skills/make-skin/SKILL.md +51 -0
- package/app/skills/meeting-notes/SKILL.md +23 -0
- package/app/skills/reading-notes/SKILL.md +25 -0
- package/app/skills/sho-stickers/SKILL.md +34 -0
- package/app/skills/sho-stickers/stickers/eat.webp +0 -0
- package/app/skills/sho-stickers/stickers/got-it.webp +0 -0
- package/app/skills/sho-stickers/stickers/hi.webp +0 -0
- package/app/skills/sho-stickers/stickers/huh.webp +0 -0
- package/app/skills/sho-stickers/stickers/on-it.webp +0 -0
- package/app/skills/sho-stickers/stickers/yay.webp +0 -0
- package/app/skills/sho-stickers/stickers.json +12 -0
- package/app/skills/study-plan/SKILL.md +30 -0
- package/app/skills/trip-planner/SKILL.md +29 -0
- package/app/skills/weekly-report/SKILL.md +30 -0
- package/app/skills/workout-plan/SKILL.md +30 -0
- package/app/skills/writing-polish/SKILL.md +33 -0
- package/app/skills.mjs +173 -0
- package/app/skins.mjs +40 -0
- package/app/social.mjs +1067 -0
- package/app/storage.mjs +143 -0
- package/app/tts.mjs +68 -0
- package/app/ttslocal.mjs +77 -0
- package/app/voices.mjs +102 -0
- package/backup.mjs +109 -0
- package/bin/yusho.mjs +141 -0
- package/connector/lib/api.mjs +14 -0
- package/connector/lib/autostart.mjs +40 -0
- package/connector/lib/client.js +165 -0
- package/connector/lib/connector.mjs +468 -0
- package/connector/lib/dsh-acp.mjs +129 -0
- package/connector/lib/dsh-headless.patch.yml +4 -0
- package/connector/lib/dsh-plugin.mjs +80 -0
- package/connector/lib/lanfile.mjs +151 -0
- package/connector/lib/nostr.mjs +53 -0
- package/connector/lib/page.html +121 -0
- package/connector/lib/qr.mjs +4 -0
- package/connector/lib/service.mjs +54 -0
- package/node_modules/@local/shoal-mobile/lib/index.js +485 -0
- package/node_modules/@local/shoal-mobile/lib/polyfill.js +82 -0
- package/node_modules/@local/shoal-mobile/lib/session-context.js +34 -0
- package/node_modules/@local/shoal-mobile/lib/shell.js +60 -0
- package/node_modules/@local/shoal-mobile/lib/web-startup.js +33 -0
- package/node_modules/@local/shoal-mobile/package.json +24 -0
- package/node_modules/@local/yusho-pc/lib/client.js +9100 -0
- package/node_modules/@local/yusho-pc/lib/index.js +3 -0
- package/node_modules/@local/yusho-pc/package.json +28 -0
- package/node_modules/@local/yusho-web-login/brand/icon-192.webp +0 -0
- package/node_modules/@local/yusho-web-login/brand/logo-dark.svg +25 -0
- package/node_modules/@local/yusho-web-login/brand.mjs +8 -0
- package/node_modules/@local/yusho-web-login/dsh-web-login.mjs +974 -0
- package/node_modules/@local/yusho-web-login/lib/client.js +607 -0
- package/node_modules/@local/yusho-web-login/login-page.mjs +609 -0
- package/node_modules/@local/yusho-web-login/login-store.mjs +708 -0
- package/node_modules/@local/yusho-web-login/package.json +25 -0
- package/node_modules/@local/yusho-web-login/whale-scene.mjs +509 -0
- package/node_modules/@local/yusho-web-login/yusho-scene.mjs +227 -0
- package/package.json +38 -4
- package/pc.patch.yml +83 -0
- package/run.mjs +138 -0
|
@@ -0,0 +1,974 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-web-login — a password gate with a settings surface for `dsh web`.
|
|
3
|
+
*
|
|
4
|
+
* Registers an exact '/' route, which the webserver matches ahead of the
|
|
5
|
+
* frontend-static fallback that normally serves the SPA index. It therefore
|
|
6
|
+
* owns the root path and can:
|
|
7
|
+
* - GET/HEAD '/' without a session -> render the password form
|
|
8
|
+
* - POST '/' -> check the password and mint the session
|
|
9
|
+
* cookie server-side (the launch token
|
|
10
|
+
* never appears in a URL, so it never
|
|
11
|
+
* reaches the nginx access log)
|
|
12
|
+
* - GET/HEAD '/?token=...' -> honoured only for direct loopback
|
|
13
|
+
* requests (not through the proxy)
|
|
14
|
+
* - GET/HEAD '/' with a session -> serve the real app index
|
|
15
|
+
*
|
|
16
|
+
* It also owns the '/_web-login' prefix:
|
|
17
|
+
* - GET /_web-login/bg | /logo | /video uploaded media (public: the login
|
|
18
|
+
* page needs them before auth)
|
|
19
|
+
* - GET /_web-login/preview operator preview of the login page
|
|
20
|
+
* - GET /_web-login/api/settings settings, ledger, audit trail
|
|
21
|
+
* - POST /_web-login/api/settings background / appearance / logo / ban policy
|
|
22
|
+
* - POST /_web-login/api/password change the password
|
|
23
|
+
* - POST /_web-login/api/password/reset install a random password, shown once
|
|
24
|
+
* - POST /_web-login/api/{background,logo,video}/upload replace one upload
|
|
25
|
+
* - POST /_web-login/api/video/remove delete the uploaded video
|
|
26
|
+
* - POST /_web-login/api/bans/unban drop a ban
|
|
27
|
+
* - POST /_web-login/api/sessions/revoke-all rotate the session key and restart
|
|
28
|
+
* Everything under /api and /preview requires an authenticated session.
|
|
29
|
+
*
|
|
30
|
+
* Abuse controls on POST '/': per-address rate limit, a global throttle for
|
|
31
|
+
* addresses that never logged in, a bounded scrypt queue, exponential reply
|
|
32
|
+
* delay after failures, and the ban ledger.
|
|
33
|
+
*
|
|
34
|
+
* The boot password is DSH_WEB_LOGIN_PASSWORD, else this plugin's `password`
|
|
35
|
+
* config value; that plaintext is only a fallback for a store that has no hash
|
|
36
|
+
* yet (see login-store.mjs). A missing password leaves the gate closed.
|
|
37
|
+
*/
|
|
38
|
+
|
|
39
|
+
import { createHash, randomBytes } from 'node:crypto'
|
|
40
|
+
import { createReadStream, createWriteStream } from 'node:fs'
|
|
41
|
+
import { mkdir, readFile, readdir, rename, rm, stat } from 'node:fs/promises'
|
|
42
|
+
import { createRequire } from 'node:module'
|
|
43
|
+
import { dirname, join } from 'node:path'
|
|
44
|
+
import { fileURLToPath } from 'node:url'
|
|
45
|
+
import {
|
|
46
|
+
ANIMATIONS,
|
|
47
|
+
BACKGROUND_PRESETS,
|
|
48
|
+
BAN_DURATIONS,
|
|
49
|
+
BAN_THRESHOLDS,
|
|
50
|
+
CARD_STYLES,
|
|
51
|
+
INTROS,
|
|
52
|
+
LAYOUTS,
|
|
53
|
+
LOGO_MODES,
|
|
54
|
+
LoginStore,
|
|
55
|
+
MAX_PASSWORD_LENGTH,
|
|
56
|
+
MEDIA_PATHS,
|
|
57
|
+
MIN_PASSWORD_LENGTH,
|
|
58
|
+
ipKey,
|
|
59
|
+
} from './login-store.mjs'
|
|
60
|
+
import { bannedPage, formatRemaining, loginPage, logoMarkup, pageSecurityHeaders } from './login-page.mjs'
|
|
61
|
+
|
|
62
|
+
/** Stable Cordis plugin name. */
|
|
63
|
+
export const name = 'web-login'
|
|
64
|
+
|
|
65
|
+
/** Services required before the login gate can claim the root route. */
|
|
66
|
+
export const inject = ['webServer', 'connection', 'connection.authentication']
|
|
67
|
+
|
|
68
|
+
/** Upper bound on a submitted form / JSON body, in bytes. */
|
|
69
|
+
const MAX_BODY_BYTES = 16 * 1024
|
|
70
|
+
|
|
71
|
+
/** Per-slot upload policy: byte cap and accepted media kinds. */
|
|
72
|
+
const UPLOAD_SLOTS = {
|
|
73
|
+
background: { max: 20 * 1024 * 1024, kinds: ['png', 'jpg', 'webp', 'gif', 'avif', 'svg'] },
|
|
74
|
+
logo: { max: 2 * 1024 * 1024, kinds: ['png', 'jpg', 'webp', 'gif', 'avif', 'svg'] },
|
|
75
|
+
video: { max: 100 * 1024 * 1024, kinds: ['mp4', 'webm'] },
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const MIME_BY_EXT = new Map([
|
|
79
|
+
['png', 'image/png'],
|
|
80
|
+
['jpg', 'image/jpeg'],
|
|
81
|
+
['webp', 'image/webp'],
|
|
82
|
+
['gif', 'image/gif'],
|
|
83
|
+
['avif', 'image/avif'],
|
|
84
|
+
['svg', 'image/svg+xml'],
|
|
85
|
+
['mp4', 'video/mp4'],
|
|
86
|
+
['webm', 'video/webm'],
|
|
87
|
+
])
|
|
88
|
+
|
|
89
|
+
/** Rate limits on password attempts. */
|
|
90
|
+
const PER_IP_WINDOW_MS = 60 * 1000
|
|
91
|
+
const PER_IP_MAX = 8
|
|
92
|
+
const GLOBAL_UNKNOWN_WINDOW_MS = 60 * 1000
|
|
93
|
+
const GLOBAL_UNKNOWN_MAX = 30
|
|
94
|
+
/** Concurrent scrypt verifications, and how many may wait behind them. */
|
|
95
|
+
const VERIFY_CONCURRENCY = 2
|
|
96
|
+
const VERIFY_QUEUE = 16
|
|
97
|
+
/** Reply delay after the n-th failure: 400ms doubling, capped. */
|
|
98
|
+
const FAILURE_DELAY_BASE_MS = 400
|
|
99
|
+
const FAILURE_DELAY_MAX_MS = 5000
|
|
100
|
+
|
|
101
|
+
const HERE = dirname(fileURLToPath(import.meta.url))
|
|
102
|
+
// 鱼Sho:密码哈希、封禁和访问记录、上传的背景都放在数据目录(YUSHO_WEB_LOGIN_DIR,yusho 命令设),装在 npm 目录里会被更新清掉
|
|
103
|
+
const DATA_DIR = process.env.YUSHO_WEB_LOGIN_DIR || HERE
|
|
104
|
+
const STATE_FILE = join(DATA_DIR, 'state.json')
|
|
105
|
+
const UPLOAD_DIR = join(DATA_DIR, 'assets')
|
|
106
|
+
|
|
107
|
+
const API_PREFIX = '/_web-login'
|
|
108
|
+
/** 随包的品牌图:地址里的名字 → 文件 */
|
|
109
|
+
const BRAND_FILES = new Map([['logo.svg', { name: 'logo-dark.svg', type: 'image/svg+xml' }], ['icon.webp', { name: 'icon-192.webp', type: 'image/webp' }]])
|
|
110
|
+
/** 进程里自己发的那一次 token 交换(发 cookie 用),中间件看到它直接放过 */
|
|
111
|
+
const INTERNAL = Symbol('yusho-web-login.internal')
|
|
112
|
+
const PREVIEW_PATH = `${API_PREFIX}/preview`
|
|
113
|
+
const MEDIA_SLOT_BY_PATH = new Map(Object.entries(MEDIA_PATHS).map(([slot, path]) => [path, slot]))
|
|
114
|
+
|
|
115
|
+
const require = createRequire(import.meta.url)
|
|
116
|
+
|
|
117
|
+
function resolveDistIndex() {
|
|
118
|
+
const pkg = require.resolve('@deepseek-ai/dsh-web-frontend/package.json')
|
|
119
|
+
return join(dirname(pkg), 'dist', 'index.html')
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function configuredPassword(config) {
|
|
123
|
+
const env = process.env.DSH_WEB_LOGIN_PASSWORD
|
|
124
|
+
if (typeof env === 'string' && env.length > 0) return env
|
|
125
|
+
if (config && typeof config.password === 'string' && config.password.length > 0) return config.password
|
|
126
|
+
return undefined
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function headerValue(req, name) {
|
|
130
|
+
const value = req.headers[name]
|
|
131
|
+
return Array.isArray(value) ? value[0] : value
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* Whether the request arrived through the reverse proxy. The dsh server
|
|
136
|
+
* listens on loopback only; nginx always sets X-Real-IP, a direct local
|
|
137
|
+
* client (curl on the host, the restart verifier) does not.
|
|
138
|
+
*/
|
|
139
|
+
function isProxied(req) {
|
|
140
|
+
return headerValue(req, 'x-real-ip') !== undefined || headerValue(req, 'x-forwarded-for') !== undefined
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/**
|
|
144
|
+
* The client address to key the ban ledger on.
|
|
145
|
+
*
|
|
146
|
+
* nginx sets `X-Real-IP` from `$remote_addr` (not client controlled) and
|
|
147
|
+
* appends the real peer as the LAST `X-Forwarded-For` entry. A client-supplied
|
|
148
|
+
* `X-Forwarded-For` arrives *prepended*, so its first element is
|
|
149
|
+
* attacker-controlled and must never be trusted here.
|
|
150
|
+
* @param {import('node:http').IncomingMessage} req - the request.
|
|
151
|
+
* @returns {string} the address, or 'unknown'.
|
|
152
|
+
*/
|
|
153
|
+
function clientIpOf(req) {
|
|
154
|
+
const real = headerValue(req, 'x-real-ip')
|
|
155
|
+
if (typeof real === 'string' && real.trim().length > 0) return real.trim()
|
|
156
|
+
const forwarded = req.headers['x-forwarded-for']
|
|
157
|
+
const forwardedValue = Array.isArray(forwarded) ? forwarded.join(',') : forwarded
|
|
158
|
+
if (typeof forwardedValue === 'string' && forwardedValue.length > 0) {
|
|
159
|
+
const parts = forwardedValue.split(',').map((part) => part.trim()).filter(Boolean)
|
|
160
|
+
const last = parts[parts.length - 1]
|
|
161
|
+
if (last !== undefined) return last
|
|
162
|
+
}
|
|
163
|
+
return req.socket?.remoteAddress ?? 'unknown'
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Read a small request body up to a byte cap.
|
|
168
|
+
* @returns {Promise<Buffer>} the raw body.
|
|
169
|
+
*/
|
|
170
|
+
function readBody(req, limit) {
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
let size = 0
|
|
173
|
+
const chunks = []
|
|
174
|
+
req.on('data', (chunk) => {
|
|
175
|
+
size += chunk.length
|
|
176
|
+
if (size > limit) {
|
|
177
|
+
req.removeAllListeners('data')
|
|
178
|
+
req.resume()
|
|
179
|
+
reject(Object.assign(new Error('request body too large'), { tooLarge: true }))
|
|
180
|
+
return
|
|
181
|
+
}
|
|
182
|
+
chunks.push(chunk)
|
|
183
|
+
})
|
|
184
|
+
req.on('end', () => resolve(Buffer.concat(chunks)))
|
|
185
|
+
req.on('error', reject)
|
|
186
|
+
})
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
async function readJson(req) {
|
|
190
|
+
const payload = await readBody(req, MAX_BODY_BYTES)
|
|
191
|
+
return JSON.parse(payload.toString('utf8'))
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
const BASE_HEADERS = { 'cache-control': 'no-store', 'x-content-type-options': 'nosniff' }
|
|
195
|
+
|
|
196
|
+
function sendJson(res, status, value, extra = {}) {
|
|
197
|
+
const body = `${JSON.stringify(value)}\n`
|
|
198
|
+
res.writeHead(status, {
|
|
199
|
+
...BASE_HEADERS,
|
|
200
|
+
'content-type': 'application/json; charset=utf-8',
|
|
201
|
+
'content-length': Buffer.byteLength(body),
|
|
202
|
+
...extra,
|
|
203
|
+
})
|
|
204
|
+
res.end(body)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function sendHtml(res, status, html, nonce, method, extra = {}) {
|
|
208
|
+
res.writeHead(status, { ...BASE_HEADERS, ...pageSecurityHeaders(nonce), 'content-type': 'text/html; charset=utf-8', ...extra })
|
|
209
|
+
res.end(method === 'HEAD' ? undefined : html)
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
213
|
+
|
|
214
|
+
/** Consume and discard whatever is left of a request body. */
|
|
215
|
+
function drain(req) {
|
|
216
|
+
return new Promise((resolve) => {
|
|
217
|
+
if (req.readableEnded) { resolve(); return }
|
|
218
|
+
req.on('end', resolve)
|
|
219
|
+
req.on('error', resolve)
|
|
220
|
+
req.resume()
|
|
221
|
+
})
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** Sliding-window counter keyed by string, with a hard cap on tracked keys. */
|
|
225
|
+
class WindowCounter {
|
|
226
|
+
#hits = new Map()
|
|
227
|
+
#window
|
|
228
|
+
#cap
|
|
229
|
+
constructor(windowMs, cap = 20000) {
|
|
230
|
+
this.#window = windowMs
|
|
231
|
+
this.#cap = cap
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/** Record one hit; returns the hits inside the window including this one. */
|
|
235
|
+
hit(key, now = Date.now()) {
|
|
236
|
+
const recent = (this.#hits.get(key) ?? []).filter((at) => now - at < this.#window)
|
|
237
|
+
recent.push(now)
|
|
238
|
+
this.#hits.delete(key)
|
|
239
|
+
this.#hits.set(key, recent)
|
|
240
|
+
if (this.#hits.size > this.#cap) this.#hits.delete(this.#hits.keys().next().value)
|
|
241
|
+
return recent.length
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Milliseconds until the oldest hit in the window for `key` expires. */
|
|
245
|
+
retryAfter(key, now = Date.now()) {
|
|
246
|
+
const recent = this.#hits.get(key) ?? []
|
|
247
|
+
return recent.length === 0 ? 0 : Math.max(0, this.#window - (now - recent[0]))
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/** A counting semaphore with a bounded wait queue. */
|
|
252
|
+
class Gate {
|
|
253
|
+
#active = 0
|
|
254
|
+
#queue = []
|
|
255
|
+
#limit
|
|
256
|
+
#depth
|
|
257
|
+
constructor(limit, depth) {
|
|
258
|
+
this.#limit = limit
|
|
259
|
+
this.#depth = depth
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Run `task` under the gate, or return undefined at once when the queue is full. */
|
|
263
|
+
async run(task) {
|
|
264
|
+
if (this.#active >= this.#limit) {
|
|
265
|
+
if (this.#queue.length >= this.#depth) return { rejected: true }
|
|
266
|
+
await new Promise((resolve) => this.#queue.push(resolve))
|
|
267
|
+
}
|
|
268
|
+
this.#active += 1
|
|
269
|
+
try {
|
|
270
|
+
return { value: await task() }
|
|
271
|
+
} finally {
|
|
272
|
+
this.#active -= 1
|
|
273
|
+
this.#queue.shift()?.()
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Identify an upload by its first bytes; the declared content type is not trusted. */
|
|
279
|
+
function sniffMedia(head) {
|
|
280
|
+
if (head.length >= 8 && head.readUInt32BE(0) === 0x89504e47) return 'png'
|
|
281
|
+
if (head.length >= 3 && head[0] === 0xff && head[1] === 0xd8 && head[2] === 0xff) return 'jpg'
|
|
282
|
+
if (head.length >= 6 && /^GIF8[79]a/u.test(head.subarray(0, 6).toString('latin1'))) return 'gif'
|
|
283
|
+
if (head.length >= 12 && head.subarray(0, 4).toString('latin1') === 'RIFF' && head.subarray(8, 12).toString('latin1') === 'WEBP') return 'webp'
|
|
284
|
+
if (head.length >= 4 && head.readUInt32BE(0) === 0x1a45dfa3) return 'webm'
|
|
285
|
+
if (head.length >= 12 && head.subarray(4, 8).toString('latin1') === 'ftyp') {
|
|
286
|
+
const brand = head.subarray(8, 12).toString('latin1')
|
|
287
|
+
if (brand === 'avif' || brand === 'avis') return 'avif'
|
|
288
|
+
if (/^(isom|iso[2-9]|mp4[12]|avc1|dash|MSNV|M4V |mp71)$/u.test(brand)) return 'mp4'
|
|
289
|
+
return undefined
|
|
290
|
+
}
|
|
291
|
+
const text = head.subarray(0, 512).toString('utf8').replace(/^\uFEFF/u, '').trimStart()
|
|
292
|
+
if (/^(<\?xml[^>]*>\s*)?(<!--[\s\S]*?-->\s*)*(<!DOCTYPE svg[^>]*>\s*)?<svg[\s>]/iu.test(text)) return 'svg'
|
|
293
|
+
return undefined
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** SVG can carry script; refuse the constructs that execute, even though it is served sandboxed. */
|
|
297
|
+
function svgIsInert(text) {
|
|
298
|
+
return !/<script|<foreignObject|javascript:|\son[a-z]+\s*=|<iframe|<embed|<object/iu.test(text)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
export function apply(ctx, config) {
|
|
302
|
+
const password = configuredPassword(config)
|
|
303
|
+
if (password === undefined) {
|
|
304
|
+
ctx.logger?.warn('web-login: no password configured (set DSH_WEB_LOGIN_PASSWORD); the gate stays closed')
|
|
305
|
+
}
|
|
306
|
+
// Honouring ?token= through the proxy re-opens the door this gate exists to
|
|
307
|
+
// close; it stays off unless the operator opts in.
|
|
308
|
+
const allowProxiedToken = config?.allowProxiedToken === true
|
|
309
|
+
|
|
310
|
+
const store = new LoginStore({
|
|
311
|
+
file: typeof config?.stateFile === 'string' && config.stateFile.length > 0 ? config.stateFile : STATE_FILE,
|
|
312
|
+
fallbackPassword: password,
|
|
313
|
+
})
|
|
314
|
+
const uploadDir = typeof config?.uploadDir === 'string' && config.uploadDir.length > 0 ? config.uploadDir : UPLOAD_DIR
|
|
315
|
+
const ready = store.load()
|
|
316
|
+
|
|
317
|
+
const perIp = new WindowCounter(PER_IP_WINDOW_MS)
|
|
318
|
+
const globalUnknown = new WindowCounter(GLOBAL_UNKNOWN_WINDOW_MS, 1)
|
|
319
|
+
const verifyGate = new Gate(VERIFY_CONCURRENCY, VERIFY_QUEUE)
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Security events go to stderr as well as the plugin logger: `ctx.logger`
|
|
323
|
+
* output does not reach journald (see /opt/dsh-local/INCIDENTS.md), and an
|
|
324
|
+
* operator investigating an incident should find them with
|
|
325
|
+
* `journalctl -u dsh-web | grep web-login`.
|
|
326
|
+
*/
|
|
327
|
+
const audit = (level, message) => {
|
|
328
|
+
ctx.logger?.[level]?.(`web-login: ${message}`)
|
|
329
|
+
process.stderr.write(`web-login[${level}]: ${message}\n`)
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
// DSH 0.2.3:登录状态由 connection.authentication 判断(浏览器 cookie、API 凭据都算)
|
|
333
|
+
const isAuthenticated = (req) => {
|
|
334
|
+
try { const a = ctx.connection.authentication.authenticate({ headers: req.headers, method: req.method, url: req.url }); return a !== undefined && a.peer !== undefined } catch { return false }
|
|
335
|
+
}
|
|
336
|
+
/** 这个进程的启动口令(DSH 的 token 登录地址里那个),只在进程里用,不放进任何地址 */
|
|
337
|
+
const launchToken = () => {
|
|
338
|
+
let base = 'http://127.0.0.1/'
|
|
339
|
+
try { base = ctx.webServer.getOrigin() + '/' } catch {}
|
|
340
|
+
const entries = []
|
|
341
|
+
try { ctx.emit(ctx.webServer, 'webserver/entry-url', base, entries) } catch {}
|
|
342
|
+
for (const e of entries) { try { const t = new URL(e.url).searchParams.get('token'); if (t) return t } catch {} }
|
|
343
|
+
return undefined
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/**
|
|
347
|
+
* Mint the browser-session cookie without sending the launch token anywhere.
|
|
348
|
+
* BrowserAuth only mints through its `?token=` exchange, so the exchange is
|
|
349
|
+
* run in-process against a captured response.
|
|
350
|
+
* @returns {string|undefined} the Set-Cookie value.
|
|
351
|
+
*/
|
|
352
|
+
const mintSessionCookie = async (req) => {
|
|
353
|
+
const token = launchToken()
|
|
354
|
+
if (token === undefined) return undefined
|
|
355
|
+
let captured
|
|
356
|
+
const sink = {
|
|
357
|
+
destroyed: false, headersSent: false, writableEnded: false,
|
|
358
|
+
writeHead(status, headers) { captured = { status, headers: headers ?? {} }; sink.headersSent = true; return sink },
|
|
359
|
+
setHeader() {}, getHeader() { return undefined }, end() { sink.writableEnded = true }, write() { return true },
|
|
360
|
+
on() { return sink }, once() { return sink }, off() { return sink },
|
|
361
|
+
}
|
|
362
|
+
const fake = { method: 'GET', url: `/?token=${encodeURIComponent(token)}`, headers: { ...req.headers }, [INTERNAL]: true }
|
|
363
|
+
await ctx.waterfall(ctx.webServer, 'webserver/request', fake, sink, async () => {})
|
|
364
|
+
const raw = captured?.status === 303 ? captured.headers['set-cookie'] ?? captured.headers['Set-Cookie'] : undefined
|
|
365
|
+
const list = (Array.isArray(raw) ? raw : typeof raw === 'string' ? [raw] : []).filter((c) => typeof c === 'string')
|
|
366
|
+
if (list.length === 0) return undefined
|
|
367
|
+
// 公网的请求只经 https 的反向代理进来,cookie 可以要求 TLS
|
|
368
|
+
return isProxied(req) ? list.map((c) => (/;\s*Secure/iu.test(c) ? c : `${c}; Secure`)) : list
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
/** Same-origin check for state-changing requests (defence in depth beside SameSite=Strict). */
|
|
373
|
+
const isSameOrigin = (req) => {
|
|
374
|
+
const site = headerValue(req, 'sec-fetch-site')
|
|
375
|
+
if (site !== undefined && site !== 'same-origin' && site !== 'none') return false
|
|
376
|
+
const origin = headerValue(req, 'origin')
|
|
377
|
+
if (origin === undefined) return true
|
|
378
|
+
try {
|
|
379
|
+
return new URL(origin).host === headerValue(req, 'host')
|
|
380
|
+
} catch {
|
|
381
|
+
return false
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
// --- uploads --------------------------------------------------------------
|
|
386
|
+
|
|
387
|
+
const findUpload = async (slot) => {
|
|
388
|
+
try {
|
|
389
|
+
const entries = await readdir(uploadDir)
|
|
390
|
+
const file = entries.find((entry) => entry.startsWith(`${slot}.`) && MIME_BY_EXT.has(entry.slice(slot.length + 1)))
|
|
391
|
+
if (file === undefined) return undefined
|
|
392
|
+
const path = join(uploadDir, file)
|
|
393
|
+
const info = await stat(path)
|
|
394
|
+
const ext = file.slice(slot.length + 1)
|
|
395
|
+
const etag = createHash('sha1').update(`${file}:${info.size}:${info.mtimeMs}`).digest('base64url').slice(0, 16)
|
|
396
|
+
return { path, ext, size: info.size, etag, url: `${MEDIA_PATHS[slot]}?v=${etag}` }
|
|
397
|
+
} catch {
|
|
398
|
+
return undefined
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
/**
|
|
403
|
+
* Stream one upload to disk, verify its leading bytes, then swap it into
|
|
404
|
+
* the slot atomically. Memory use stays flat whatever the file size.
|
|
405
|
+
*/
|
|
406
|
+
const storeUpload = async (req, slot) => {
|
|
407
|
+
const policy = UPLOAD_SLOTS[slot]
|
|
408
|
+
const declared = Number(headerValue(req, 'content-length'))
|
|
409
|
+
const limitText = `${Math.round(policy.max / 1024 / 1024)}MB`
|
|
410
|
+
if (Number.isFinite(declared) && declared > policy.max) {
|
|
411
|
+
// Read and discard the body before answering: replying mid-upload makes
|
|
412
|
+
// the browser report a network error instead of this message.
|
|
413
|
+
await drain(req)
|
|
414
|
+
return { ok: false, status: 413, error: `文件超过 ${limitText}` }
|
|
415
|
+
}
|
|
416
|
+
await mkdir(uploadDir, { recursive: true })
|
|
417
|
+
const temp = join(uploadDir, `.upload-${slot}-${randomBytes(6).toString('hex')}.tmp`)
|
|
418
|
+
const out = createWriteStream(temp, { mode: 0o644 })
|
|
419
|
+
let size = 0
|
|
420
|
+
let head = Buffer.alloc(0)
|
|
421
|
+
let failure
|
|
422
|
+
try {
|
|
423
|
+
await new Promise((resolve, reject) => {
|
|
424
|
+
req.on('data', (chunk) => {
|
|
425
|
+
if (failure !== undefined) return // over the cap: keep draining, write nothing
|
|
426
|
+
size += chunk.length
|
|
427
|
+
if (head.length < 1024) head = Buffer.concat([head, chunk.subarray(0, 1024 - head.length)])
|
|
428
|
+
if (size > policy.max) {
|
|
429
|
+
failure = { status: 413, error: `文件超过 ${limitText}` }
|
|
430
|
+
out.end()
|
|
431
|
+
return
|
|
432
|
+
}
|
|
433
|
+
if (!out.write(chunk)) {
|
|
434
|
+
req.pause()
|
|
435
|
+
out.once('drain', () => req.resume())
|
|
436
|
+
}
|
|
437
|
+
})
|
|
438
|
+
req.on('end', () => (failure === undefined ? out.end(resolve) : resolve()))
|
|
439
|
+
req.on('error', reject)
|
|
440
|
+
out.on('error', reject)
|
|
441
|
+
})
|
|
442
|
+
if (failure === undefined && size === 0) failure = { status: 400, error: '文件内容为空' }
|
|
443
|
+
const kind = failure === undefined ? sniffMedia(head) : undefined
|
|
444
|
+
if (failure === undefined && (kind === undefined || !policy.kinds.includes(kind))) {
|
|
445
|
+
failure = { status: 400, error: `文件内容不是支持的格式(可用:${policy.kinds.join(' / ')})` }
|
|
446
|
+
}
|
|
447
|
+
if (failure === undefined && kind === 'svg') {
|
|
448
|
+
const text = await readFile(temp, 'utf8')
|
|
449
|
+
if (!svgIsInert(text)) failure = { status: 400, error: 'SVG 含脚本或事件属性,已拒绝' }
|
|
450
|
+
}
|
|
451
|
+
if (failure !== undefined) {
|
|
452
|
+
await rm(temp, { force: true })
|
|
453
|
+
return { ok: false, ...failure }
|
|
454
|
+
}
|
|
455
|
+
const existing = await findUpload(slot)
|
|
456
|
+
const target = join(uploadDir, `${slot}.${kind}`)
|
|
457
|
+
await rename(temp, target)
|
|
458
|
+
if (existing !== undefined && existing.path !== target) await rm(existing.path, { force: true })
|
|
459
|
+
return { ok: true, ext: kind, bytes: size }
|
|
460
|
+
} catch (error) {
|
|
461
|
+
await rm(temp, { force: true })
|
|
462
|
+
throw error
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
/**
|
|
467
|
+
* Serve one uploaded file with validators and byte ranges (Safari will not
|
|
468
|
+
* play a video whose server ignores Range).
|
|
469
|
+
*/
|
|
470
|
+
const serveUpload = async (req, res, url, slot) => {
|
|
471
|
+
const upload = await findUpload(slot)
|
|
472
|
+
if (upload === undefined) {
|
|
473
|
+
res.writeHead(404, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8' })
|
|
474
|
+
res.end(`no ${slot} uploaded`)
|
|
475
|
+
return
|
|
476
|
+
}
|
|
477
|
+
const etag = `"${upload.etag}"`
|
|
478
|
+
const headers = {
|
|
479
|
+
'content-type': MIME_BY_EXT.get(upload.ext) ?? 'application/octet-stream',
|
|
480
|
+
'x-content-type-options': 'nosniff',
|
|
481
|
+
'cross-origin-resource-policy': 'same-origin',
|
|
482
|
+
etag,
|
|
483
|
+
'accept-ranges': 'bytes',
|
|
484
|
+
// Versioned URLs never change bytes; unversioned ones revalidate.
|
|
485
|
+
'cache-control': url.searchParams.get('v') === upload.etag ? 'public, max-age=31536000, immutable' : 'no-cache',
|
|
486
|
+
...(upload.ext === 'svg' ? { 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; img-src data:; sandbox" } : {}),
|
|
487
|
+
}
|
|
488
|
+
if (headerValue(req, 'if-none-match') === etag) {
|
|
489
|
+
res.writeHead(304, headers)
|
|
490
|
+
res.end()
|
|
491
|
+
return
|
|
492
|
+
}
|
|
493
|
+
const range = /^bytes=(\d*)-(\d*)$/u.exec(headerValue(req, 'range') ?? '')
|
|
494
|
+
const ifRange = headerValue(req, 'if-range')
|
|
495
|
+
if (range !== null && (ifRange === undefined || ifRange === etag) && (range[1] !== '' || range[2] !== '')) {
|
|
496
|
+
let start = range[1] === '' ? upload.size - Number(range[2]) : Number(range[1])
|
|
497
|
+
let end = range[1] === '' || range[2] === '' ? upload.size - 1 : Number(range[2])
|
|
498
|
+
start = Math.max(0, start)
|
|
499
|
+
end = Math.min(end, upload.size - 1)
|
|
500
|
+
if (start > end || start >= upload.size) {
|
|
501
|
+
res.writeHead(416, { ...headers, 'content-range': `bytes */${upload.size}` })
|
|
502
|
+
res.end()
|
|
503
|
+
return
|
|
504
|
+
}
|
|
505
|
+
res.writeHead(206, { ...headers, 'content-range': `bytes ${start}-${end}/${upload.size}`, 'content-length': end - start + 1 })
|
|
506
|
+
if (req.method === 'HEAD') { res.end(); return }
|
|
507
|
+
createReadStream(upload.path, { start, end }).on('error', () => res.destroy()).pipe(res)
|
|
508
|
+
return
|
|
509
|
+
}
|
|
510
|
+
res.writeHead(200, { ...headers, 'content-length': upload.size })
|
|
511
|
+
if (req.method === 'HEAD') { res.end(); return }
|
|
512
|
+
createReadStream(upload.path).on('error', () => res.destroy()).pipe(res)
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
/** Everything the login page needs, read fresh per render. */
|
|
516
|
+
const pageInputs = async (overrides = {}) => {
|
|
517
|
+
await ready
|
|
518
|
+
const [background, logo, video] = await Promise.all([findUpload('background'), findUpload('logo'), findUpload('video')])
|
|
519
|
+
return {
|
|
520
|
+
background: overrides.background ?? store.background,
|
|
521
|
+
appearance: store.appearance,
|
|
522
|
+
logo: logoMarkup(store.logo, logo?.url),
|
|
523
|
+
media: {
|
|
524
|
+
background: background?.url,
|
|
525
|
+
video: video?.url,
|
|
526
|
+
videoType: video === undefined ? undefined : MIME_BY_EXT.get(video.ext),
|
|
527
|
+
// The whale scene re-forms an uploaded logo out of particles.
|
|
528
|
+
logo: store.logo.mode === 'image' ? logo?.url : undefined,
|
|
529
|
+
},
|
|
530
|
+
}
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
const nonce = () => randomBytes(16).toString('base64')
|
|
534
|
+
|
|
535
|
+
const banMessage = (ban) => ban.permanent
|
|
536
|
+
? '该地址已被永久封禁。'
|
|
537
|
+
: `该地址已被封禁,剩余时间:${formatRemaining(ban.remainingMs)}。`
|
|
538
|
+
|
|
539
|
+
const renderBanned = async (req, res, ban, ip) => {
|
|
540
|
+
const n = nonce()
|
|
541
|
+
sendHtml(res, 403, bannedPage({ nonce: n, appearance: store.appearance, ban, ip: ipKey(ip) }), n, req.method)
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
// --- POST / -----------------------------------------------------------------
|
|
545
|
+
|
|
546
|
+
const handleLogin = async (req, res, ip, wantsJson) => {
|
|
547
|
+
const reject = async (status, message, extra = {}, fatal = false) => {
|
|
548
|
+
if (wantsJson) {
|
|
549
|
+
sendJson(res, status, { ok: false, message, ...(fatal ? { fatal: true } : {}) }, extra)
|
|
550
|
+
return
|
|
551
|
+
}
|
|
552
|
+
const n = nonce()
|
|
553
|
+
sendHtml(res, status, loginPage({ nonce: n, ...(await pageInputs()), errorMessage: message }), n, 'GET', extra)
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
const ban = store.activeBan(ip)
|
|
557
|
+
if (ban !== undefined) {
|
|
558
|
+
req.resume()
|
|
559
|
+
if (wantsJson) {
|
|
560
|
+
sendJson(res, 403, { ok: false, message: banMessage(ban), fatal: true })
|
|
561
|
+
return
|
|
562
|
+
}
|
|
563
|
+
await renderBanned(req, res, ban, ip)
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
if (!isSameOrigin(req)) {
|
|
568
|
+
req.resume()
|
|
569
|
+
await reject(403, '请求来源不合法')
|
|
570
|
+
return
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
const key = ipKey(ip)
|
|
574
|
+
if (perIp.hit(key) > PER_IP_MAX) {
|
|
575
|
+
req.resume()
|
|
576
|
+
const wait = Math.ceil(perIp.retryAfter(key) / 1000)
|
|
577
|
+
await reject(429, `尝试过于频繁,请 ${wait} 秒后再试`, { 'retry-after': String(wait) })
|
|
578
|
+
return
|
|
579
|
+
}
|
|
580
|
+
if (!store.isKnown(ip) && globalUnknown.hit('all') > GLOBAL_UNKNOWN_MAX) {
|
|
581
|
+
req.resume()
|
|
582
|
+
const wait = Math.ceil(globalUnknown.retryAfter('all') / 1000)
|
|
583
|
+
await reject(429, `登录请求过多,系统处于防护状态,请 ${wait} 秒后再试`, { 'retry-after': String(wait) })
|
|
584
|
+
return
|
|
585
|
+
}
|
|
586
|
+
|
|
587
|
+
let submitted = ''
|
|
588
|
+
try {
|
|
589
|
+
submitted = new URLSearchParams((await readBody(req, MAX_BODY_BYTES)).toString('utf8')).get('password') ?? ''
|
|
590
|
+
} catch {
|
|
591
|
+
submitted = ''
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
const outcome = submitted.length === 0 || submitted.length > MAX_PASSWORD_LENGTH
|
|
595
|
+
? { value: false }
|
|
596
|
+
: await verifyGate.run(() => store.verifyPassword(submitted))
|
|
597
|
+
if (outcome.rejected === true) {
|
|
598
|
+
await reject(503, '服务繁忙,请稍后再试', { 'retry-after': '5' })
|
|
599
|
+
return
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
if (outcome.value === true) {
|
|
603
|
+
const cookie = await mintSessionCookie(req)
|
|
604
|
+
if (cookie === undefined) {
|
|
605
|
+
audit('error', `password accepted for ${key} but the session cookie could not be minted`)
|
|
606
|
+
await reject(500, '登录服务异常:无法签发会话')
|
|
607
|
+
return
|
|
608
|
+
}
|
|
609
|
+
store.recordLogin(ip, headerValue(req, 'user-agent'))
|
|
610
|
+
audit('info', `login ok from ${key}`)
|
|
611
|
+
const headers = { 'set-cookie': cookie, 'referrer-policy': 'no-referrer' }
|
|
612
|
+
if (wantsJson) {
|
|
613
|
+
sendJson(res, 200, { ok: true, redirect: './' }, headers)
|
|
614
|
+
return
|
|
615
|
+
}
|
|
616
|
+
res.writeHead(303, { ...BASE_HEADERS, ...headers, location: './' })
|
|
617
|
+
res.end()
|
|
618
|
+
return
|
|
619
|
+
}
|
|
620
|
+
|
|
621
|
+
const failures = store.failureCount(ip)
|
|
622
|
+
const result = store.recordFailure(ip)
|
|
623
|
+
if (result.banned !== undefined) audit('warn', `banned ${key} (${result.banned.label}) after ${result.count} failed attempts`)
|
|
624
|
+
// Slow every next guess from this address down; the delay holds no scrypt slot.
|
|
625
|
+
await sleep(Math.min(FAILURE_DELAY_MAX_MS, FAILURE_DELAY_BASE_MS * 2 ** Math.min(failures, 8)))
|
|
626
|
+
const freshBan = store.activeBan(ip)
|
|
627
|
+
const failure = '密码不正确,请重试'
|
|
628
|
+
if (freshBan === undefined) {
|
|
629
|
+
const left = store.banPolicy.enabled ? store.banPolicy.threshold - result.count : undefined
|
|
630
|
+
await reject(401, left !== undefined && left <= 2 && left > 0 ? `${failure}(再错 ${left} 次将被封禁)` : failure)
|
|
631
|
+
return
|
|
632
|
+
}
|
|
633
|
+
await reject(401, `${failure} ${banMessage(freshBan)}`, {}, true)
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// --- '/' ------------------------------------------------------------------
|
|
637
|
+
|
|
638
|
+
const handler = async (req, res, next) => {
|
|
639
|
+
const url = new URL(req.url ?? '/', 'http://x')
|
|
640
|
+
await ready
|
|
641
|
+
const ip = clientIpOf(req)
|
|
642
|
+
const wantsJson = String(req.headers.accept ?? '').includes('application/json')
|
|
643
|
+
|
|
644
|
+
if (req.method === 'POST') {
|
|
645
|
+
await handleLogin(req, res, ip, wantsJson)
|
|
646
|
+
return
|
|
647
|
+
}
|
|
648
|
+
|
|
649
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
650
|
+
res.writeHead(405, { ...BASE_HEADERS, allow: 'GET, HEAD, POST' })
|
|
651
|
+
res.end()
|
|
652
|
+
return
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
const ban = store.activeBan(ip)
|
|
656
|
+
if (ban !== undefined) {
|
|
657
|
+
await renderBanned(req, res, ban, ip)
|
|
658
|
+
return
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
if (url.searchParams.has('token')) {
|
|
662
|
+
if (!isProxied(req) || allowProxiedToken) {
|
|
663
|
+
await next()
|
|
664
|
+
return
|
|
665
|
+
}
|
|
666
|
+
// A launch token arriving from the internet is never honoured. Strip it
|
|
667
|
+
// from the address bar either way so it does not linger in history.
|
|
668
|
+
if (isAuthenticated(req)) {
|
|
669
|
+
res.writeHead(303, { ...BASE_HEADERS, location: './', 'referrer-policy': 'no-referrer' })
|
|
670
|
+
res.end()
|
|
671
|
+
return
|
|
672
|
+
}
|
|
673
|
+
audit('warn', `refused a launch-token login from ${ipKey(ip)} through the proxy`)
|
|
674
|
+
res.writeHead(303, { ...BASE_HEADERS, location: './', 'referrer-policy': 'no-referrer' })
|
|
675
|
+
res.end()
|
|
676
|
+
return
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
if (isAuthenticated(req)) {
|
|
680
|
+
await next()
|
|
681
|
+
return
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const n = nonce()
|
|
685
|
+
sendHtml(res, 200, loginPage({ nonce: n, ...(await pageInputs()) }), n, req.method)
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
// --- /_web-login ------------------------------------------------------------
|
|
689
|
+
|
|
690
|
+
const prefixHandler = async (req, res) => {
|
|
691
|
+
const url = new URL(req.url ?? '/', 'http://x')
|
|
692
|
+
const path = url.pathname
|
|
693
|
+
if (!path.startsWith(API_PREFIX)) return false
|
|
694
|
+
await ready
|
|
695
|
+
|
|
696
|
+
// 鱼Sho 的品牌图(登录页「鱼群」用:完整 logo、App 图标):随包带着、谁都能拿(登录前就要显示),只认这两个文件名
|
|
697
|
+
const brandFile = path.startsWith(`${API_PREFIX}/brand/`) ? BRAND_FILES.get(path.slice(API_PREFIX.length + 7)) : undefined
|
|
698
|
+
if (brandFile !== undefined) {
|
|
699
|
+
req.resume()
|
|
700
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') { res.writeHead(405, { ...BASE_HEADERS, allow: 'GET, HEAD' }); res.end(); return true }
|
|
701
|
+
const body = await readFile(join(HERE, 'brand', brandFile.name))
|
|
702
|
+
res.writeHead(200, { 'content-type': brandFile.type, 'content-length': body.length, 'cache-control': 'public, max-age=86400', 'x-content-type-options': 'nosniff' })
|
|
703
|
+
res.end(req.method === 'HEAD' ? undefined : body)
|
|
704
|
+
return true
|
|
705
|
+
}
|
|
706
|
+
const mediaSlot = MEDIA_SLOT_BY_PATH.get(path)
|
|
707
|
+
if (mediaSlot !== undefined) {
|
|
708
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
709
|
+
res.writeHead(405, { ...BASE_HEADERS, allow: 'GET, HEAD' })
|
|
710
|
+
res.end()
|
|
711
|
+
return true
|
|
712
|
+
}
|
|
713
|
+
await serveUpload(req, res, url, mediaSlot)
|
|
714
|
+
return true
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
if (path !== PREVIEW_PATH && !path.startsWith(`${API_PREFIX}/api/`)) {
|
|
718
|
+
sendJson(res, 404, { ok: false, error: 'not found' })
|
|
719
|
+
return true
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
if (!isAuthenticated(req)) {
|
|
723
|
+
req.resume()
|
|
724
|
+
sendJson(res, 401, { ok: false, error: '需要先登录' })
|
|
725
|
+
return true
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
if (path === PREVIEW_PATH) {
|
|
729
|
+
const animation = url.searchParams.get('animation')
|
|
730
|
+
const override = ANIMATIONS.some((entry) => entry.id === animation) ? { background: { mode: 'animation', value: animation } } : {}
|
|
731
|
+
const n = nonce()
|
|
732
|
+
sendHtml(res, 200, loginPage({ nonce: n, ...(await pageInputs(override)), preview: true }), n, req.method)
|
|
733
|
+
return true
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
if (req.method === 'POST' && !isSameOrigin(req)) {
|
|
737
|
+
req.resume()
|
|
738
|
+
sendJson(res, 403, { ok: false, error: '请求来源不合法' })
|
|
739
|
+
return true
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
const route = `${req.method} ${path.slice(`${API_PREFIX}/api/`.length)}`
|
|
743
|
+
const ip = clientIpOf(req)
|
|
744
|
+
const key = ipKey(ip)
|
|
745
|
+
|
|
746
|
+
const withJson = async (task) => {
|
|
747
|
+
let parsed
|
|
748
|
+
try {
|
|
749
|
+
parsed = await readJson(req)
|
|
750
|
+
} catch (error) {
|
|
751
|
+
sendJson(res, error?.tooLarge ? 413 : 400, { ok: false, error: error?.tooLarge ? '请求体过大' : '请求体不是合法 JSON' })
|
|
752
|
+
return
|
|
753
|
+
}
|
|
754
|
+
await task(parsed ?? {})
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
if (route === 'GET settings') {
|
|
758
|
+
const [background, logo, video] = await Promise.all([findUpload('background'), findUpload('logo'), findUpload('video')])
|
|
759
|
+
const upload = (entry) => (entry === undefined ? { present: false, url: null, bytes: 0, ext: null } : { present: true, url: entry.url, bytes: entry.size, ext: entry.ext })
|
|
760
|
+
sendJson(res, 200, {
|
|
761
|
+
ok: true,
|
|
762
|
+
value: {
|
|
763
|
+
background: store.background,
|
|
764
|
+
appearance: store.appearance,
|
|
765
|
+
logo: store.logo,
|
|
766
|
+
ban: store.banPolicy,
|
|
767
|
+
bans: store.listBans(),
|
|
768
|
+
attempts: store.listAttempts(),
|
|
769
|
+
logins: store.listLogins(),
|
|
770
|
+
events: store.listEvents(),
|
|
771
|
+
known: store.listKnown(),
|
|
772
|
+
you: key,
|
|
773
|
+
password: {
|
|
774
|
+
stored: store.hasStoredPassword,
|
|
775
|
+
fallbackConfigured: password !== undefined,
|
|
776
|
+
minLength: MIN_PASSWORD_LENGTH,
|
|
777
|
+
},
|
|
778
|
+
uploads: { background: upload(background), logo: upload(logo), video: upload(video) },
|
|
779
|
+
limits: Object.fromEntries(Object.entries(UPLOAD_SLOTS).map(([slot, policy]) => [slot, { maxBytes: policy.max, kinds: policy.kinds }])),
|
|
780
|
+
protection: {
|
|
781
|
+
perIpPerMinute: PER_IP_MAX,
|
|
782
|
+
unknownPerMinute: GLOBAL_UNKNOWN_MAX,
|
|
783
|
+
proxiedTokenAllowed: allowProxiedToken,
|
|
784
|
+
},
|
|
785
|
+
options: {
|
|
786
|
+
presets: BACKGROUND_PRESETS,
|
|
787
|
+
animations: ANIMATIONS,
|
|
788
|
+
cards: CARD_STYLES,
|
|
789
|
+
layouts: LAYOUTS,
|
|
790
|
+
intros: INTROS,
|
|
791
|
+
thresholds: BAN_THRESHOLDS,
|
|
792
|
+
durations: BAN_DURATIONS,
|
|
793
|
+
logoModes: LOGO_MODES,
|
|
794
|
+
},
|
|
795
|
+
},
|
|
796
|
+
})
|
|
797
|
+
return true
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
if (route === 'POST settings') {
|
|
801
|
+
await withJson(async (parsed) => {
|
|
802
|
+
for (const [field, setter] of [
|
|
803
|
+
['background', (value) => store.setBackground(value)],
|
|
804
|
+
['appearance', (value) => store.setAppearance(value)],
|
|
805
|
+
['ban', (value) => store.setBanPolicy(value)],
|
|
806
|
+
['logo', (value) => store.setLogo(value)],
|
|
807
|
+
]) {
|
|
808
|
+
if (typeof parsed[field] !== 'object' || parsed[field] === null) continue
|
|
809
|
+
if (field === 'background' && parsed.background.mode === 'image' && (await findUpload('background')) === undefined) {
|
|
810
|
+
sendJson(res, 400, { ok: false, error: '还没有上传背景图片' })
|
|
811
|
+
return
|
|
812
|
+
}
|
|
813
|
+
if (field === 'background' && parsed.background.mode === 'video' && parsed.background.value === MEDIA_PATHS.video && (await findUpload('video')) === undefined) {
|
|
814
|
+
sendJson(res, 400, { ok: false, error: '还没有上传视频' })
|
|
815
|
+
return
|
|
816
|
+
}
|
|
817
|
+
const result = setter(parsed[field])
|
|
818
|
+
if (!result.ok) {
|
|
819
|
+
sendJson(res, 400, result)
|
|
820
|
+
return
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
store.recordEvent('settings', ip, Object.keys(parsed).filter((k) => ['background', 'appearance', 'ban', 'logo'].includes(k)).join(','))
|
|
824
|
+
await store.flush()
|
|
825
|
+
audit('info', `settings updated from ${key}`)
|
|
826
|
+
sendJson(res, 200, { ok: true, value: { background: store.background, appearance: store.appearance, ban: store.banPolicy, logo: store.logo } })
|
|
827
|
+
})
|
|
828
|
+
return true
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
if (route === 'POST password/reset') {
|
|
832
|
+
req.resume()
|
|
833
|
+
const result = await store.resetPassword()
|
|
834
|
+
store.recordEvent('password-reset', ip, '已重置为随机密码')
|
|
835
|
+
await store.flush()
|
|
836
|
+
audit('warn', `password RESET to a random value from ${key}`)
|
|
837
|
+
sendJson(res, 200, { ok: true, value: { password: result.password } })
|
|
838
|
+
return true
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
if (route === 'POST password') {
|
|
842
|
+
await withJson(async (parsed) => {
|
|
843
|
+
const current = typeof parsed.currentPassword === 'string' ? parsed.currentPassword : ''
|
|
844
|
+
const next = typeof parsed.newPassword === 'string' ? parsed.newPassword : ''
|
|
845
|
+
const outcome = await verifyGate.run(() => store.changePassword(current, next))
|
|
846
|
+
if (outcome.rejected === true) {
|
|
847
|
+
sendJson(res, 503, { ok: false, error: '服务繁忙,请稍后再试' })
|
|
848
|
+
return
|
|
849
|
+
}
|
|
850
|
+
if (!outcome.value.ok) {
|
|
851
|
+
audit('warn', `password change from ${key} rejected: ${outcome.value.error}`)
|
|
852
|
+
sendJson(res, 400, outcome.value)
|
|
853
|
+
return
|
|
854
|
+
}
|
|
855
|
+
store.recordEvent('password-changed', ip, '')
|
|
856
|
+
await store.flush()
|
|
857
|
+
audit('info', `password changed from ${key}`)
|
|
858
|
+
sendJson(res, 200, { ok: true })
|
|
859
|
+
})
|
|
860
|
+
return true
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
if (route === 'POST bans/unban') {
|
|
864
|
+
await withJson(async (parsed) => {
|
|
865
|
+
const target = String(parsed.ip ?? '').slice(0, 64)
|
|
866
|
+
if (target.length === 0) {
|
|
867
|
+
sendJson(res, 400, { ok: false, error: '缺少 ip' })
|
|
868
|
+
return
|
|
869
|
+
}
|
|
870
|
+
const removed = store.unban(target)
|
|
871
|
+
if (removed) store.recordEvent('unban', ip, target)
|
|
872
|
+
await store.flush()
|
|
873
|
+
audit('info', `ban removed for ${target} from ${key} (present=${removed})`)
|
|
874
|
+
sendJson(res, 200, { ok: true, value: { removed, bans: store.listBans() } })
|
|
875
|
+
})
|
|
876
|
+
return true
|
|
877
|
+
}
|
|
878
|
+
|
|
879
|
+
const upload = /^POST (background|logo|video)\/upload$/u.exec(route)
|
|
880
|
+
if (upload !== null) {
|
|
881
|
+
const slot = upload[1]
|
|
882
|
+
const stored = await storeUpload(req, slot)
|
|
883
|
+
if (!stored.ok) {
|
|
884
|
+
sendJson(res, stored.status, { ok: false, error: stored.error })
|
|
885
|
+
return true
|
|
886
|
+
}
|
|
887
|
+
const result = slot === 'logo'
|
|
888
|
+
? store.setLogo({ mode: 'image', value: MEDIA_PATHS.logo })
|
|
889
|
+
: store.setBackground({ mode: slot === 'video' ? 'video' : 'image', value: MEDIA_PATHS[slot] })
|
|
890
|
+
if (!result.ok) {
|
|
891
|
+
sendJson(res, 400, result)
|
|
892
|
+
return true
|
|
893
|
+
}
|
|
894
|
+
store.recordEvent('upload', ip, `${slot}.${stored.ext} ${(stored.bytes / 1024 / 1024).toFixed(1)}MB`)
|
|
895
|
+
await store.flush()
|
|
896
|
+
audit('info', `${slot} uploaded from ${key} (${stored.bytes} bytes, ${stored.ext})`)
|
|
897
|
+
const fresh = await findUpload(slot)
|
|
898
|
+
sendJson(res, 200, { ok: true, value: { url: fresh?.url ?? null } })
|
|
899
|
+
return true
|
|
900
|
+
}
|
|
901
|
+
|
|
902
|
+
if (route === 'POST video/remove') {
|
|
903
|
+
req.resume()
|
|
904
|
+
const existing = await findUpload('video')
|
|
905
|
+
if (existing !== undefined) await rm(existing.path, { force: true })
|
|
906
|
+
if (store.background.mode === 'video' && store.background.value === MEDIA_PATHS.video) {
|
|
907
|
+
store.setBackground({ mode: 'preset', value: 'aurora' })
|
|
908
|
+
}
|
|
909
|
+
store.recordEvent('upload', ip, '删除上传的视频')
|
|
910
|
+
await store.flush()
|
|
911
|
+
sendJson(res, 200, { ok: true, value: { removed: existing !== undefined } })
|
|
912
|
+
return true
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
if (route === 'POST sessions/revoke-all') {
|
|
916
|
+
await withJson(async (parsed) => {
|
|
917
|
+
if (parsed.confirm !== 'REVOKE') {
|
|
918
|
+
sendJson(res, 400, { ok: false, error: '缺少确认' })
|
|
919
|
+
return
|
|
920
|
+
}
|
|
921
|
+
const credentials = ctx.get?.('credentials')
|
|
922
|
+
if (credentials === undefined || typeof credentials.modifyRecord !== 'function') {
|
|
923
|
+
sendJson(res, 500, { ok: false, error: '凭据服务不可用,无法轮换会话密钥' })
|
|
924
|
+
return
|
|
925
|
+
}
|
|
926
|
+
const { credentialKey } = await import('@deepseek-ai/dsh-credentials')
|
|
927
|
+
const secret = randomBytes(32).toString('base64url')
|
|
928
|
+
await credentials.modifyRecord(credentialKey('client-connection', 'browser-session'), () => Promise.resolve({
|
|
929
|
+
kind: 'grant',
|
|
930
|
+
payload: { version: 1, secret },
|
|
931
|
+
}))
|
|
932
|
+
store.recordEvent('revoke-all', ip, '轮换会话密钥并重启')
|
|
933
|
+
await store.flush()
|
|
934
|
+
audit('warn', `ALL sessions revoked from ${key}: session key rotated, restarting dsh web`)
|
|
935
|
+
sendJson(res, 200, { ok: true, value: { restarting: true } })
|
|
936
|
+
// The running BrowserAuth holds the old key in memory; only a restart
|
|
937
|
+
// drops it. systemd (Restart=always) brings the service back.
|
|
938
|
+
setTimeout(() => process.kill(process.pid, 'SIGTERM'), 800).unref?.()
|
|
939
|
+
})
|
|
940
|
+
return true
|
|
941
|
+
}
|
|
942
|
+
|
|
943
|
+
req.resume()
|
|
944
|
+
sendJson(res, 404, { ok: false, error: `未知接口:${route}` })
|
|
945
|
+
return true
|
|
946
|
+
}
|
|
947
|
+
|
|
948
|
+
// 没登录的浏览器:除了登录页和它要用的图片,什么都拿不到;页面请求带回登录页。
|
|
949
|
+
// 不经代理的本机请求(鱼Sho 内核、yusho url 打开的地址)照旧交给 DSH 自己的验证
|
|
950
|
+
const loopback = (req) => { const a = req.socket?.remoteAddress ?? ''; return a === '127.0.0.1' || a === '::1' || a === '::ffff:127.0.0.1' }
|
|
951
|
+
ctx.on('webserver/request', async (req, res, next) => {
|
|
952
|
+
if (req[INTERNAL]) return next()
|
|
953
|
+
const path = new URL(req.url ?? '/', 'http://x').pathname
|
|
954
|
+
if (path === API_PREFIX || path.startsWith(`${API_PREFIX}/`)) { await prefixHandler(req, res); return }
|
|
955
|
+
if (path === '/') {
|
|
956
|
+
try { await handler(req, res, next) } catch (error) {
|
|
957
|
+
audit('error', `gate failed: ${error?.stack ?? error}`)
|
|
958
|
+
if (!res.headersSent) { res.writeHead(500, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8' }); res.end('登录服务出错了') }
|
|
959
|
+
}
|
|
960
|
+
return
|
|
961
|
+
}
|
|
962
|
+
if (isAuthenticated(req) || (!isProxied(req) && loopback(req))) return next()
|
|
963
|
+
req.resume?.()
|
|
964
|
+
const accept = String(req.headers.accept ?? '')
|
|
965
|
+
if ((req.method === 'GET' || req.method === 'HEAD') && accept.includes('text/html')) {
|
|
966
|
+
res.writeHead(303, { ...BASE_HEADERS, location: '/', 'referrer-policy': 'no-referrer' })
|
|
967
|
+
res.end()
|
|
968
|
+
return
|
|
969
|
+
}
|
|
970
|
+
res.writeHead(401, { ...BASE_HEADERS, 'content-type': 'text/plain; charset=utf-8' })
|
|
971
|
+
res.end('unauthorized')
|
|
972
|
+
}, true)
|
|
973
|
+
ctx.effect(() => () => { void store.flush() }, 'web-login: flush state on dispose')
|
|
974
|
+
}
|