dsh-quay-bot 1.0.2 → 1.0.4
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 +28 -105
- package/botscreen/requirements.txt +1 -1
- package/client.js +3 -2
- package/cordis.patch.yml +1 -1
- package/host/api.js +4 -0
- package/host/remote.js +285 -8
- package/host/screen.js +22 -86
- package/package.json +35 -32
- package/remote/bin/dsh-remote.mjs +435 -0
- package/remote/package.json +27 -0
- package/remote/src/config.mjs +183 -0
- package/remote/src/crypto.mjs +220 -0
- package/remote/src/keys.mjs +226 -0
- package/remote/src/proxy.mjs +1028 -0
- package/remote/src/sessions.mjs +163 -0
- package/remote/src/shim.js +838 -0
- package/remote/src/supervisor.mjs +207 -0
- package/remote/src/tunnel.mjs +533 -0
- package/remote/src/upstream.mjs +403 -0
- package/remote/src/util.mjs +149 -0
- package/remote/src/ws.mjs +313 -0
- package/LICENSE +0 -21
- package/avatar/build.mjs +0 -81
- package/avatar/gallery/droid.json +0 -14
- package/avatar/gallery/ghost.json +0 -14
- package/avatar/gallery/grok-pod.json +0 -14
- package/avatar/gallery/guardian.json +0 -14
- package/avatar/gallery/mecha.json +0 -14
- package/avatar/gallery/mochi.json +0 -14
- package/avatar/gallery/neko.json +0 -14
- package/avatar/gallery/orbiter.json +0 -14
- package/avatar/gallery/relay.json +0 -14
- package/avatar/gallery/spark.json +0 -14
- package/avatar/src/bot/clay.ts +0 -135
- package/avatar/src/bot/effects.ts +0 -100
- package/avatar/src/bot/grok-bot.ts +0 -626
- package/avatar/src/bot/index.ts +0 -15
- package/avatar/src/bot/palettes.ts +0 -62
- package/avatar/src/bot/ring.ts +0 -219
- package/avatar/src/bot/scheduler.ts +0 -239
- package/avatar/src/bot/shapes.ts +0 -277
- package/avatar/src/bot/spring.ts +0 -196
- package/avatar/src/core/color.ts +0 -92
- package/avatar/src/core/eyes.ts +0 -297
- package/avatar/src/core/field.ts +0 -482
- package/avatar/src/core/frame.ts +0 -655
- package/avatar/src/core/fx.ts +0 -375
- package/avatar/src/core/index.ts +0 -49
- package/avatar/src/core/paint.ts +0 -331
- package/avatar/src/core/path.ts +0 -495
- package/avatar/src/core/pose.ts +0 -581
- package/avatar/src/core/svg.ts +0 -98
- package/avatar/src/core/types.ts +0 -153
- package/avatar/src/core/validate.ts +0 -296
- package/avatar/src/core/volume.ts +0 -681
- package/avatar/src/entry.ts +0 -260
- package/bin/doctor.mjs +0 -148
- package/botscreen/requirements-offline.txt +0 -11
- package/market/index.json +0 -41
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 上游 DSH web 发现与自动续期。
|
|
3
|
+
*
|
|
4
|
+
* DSH 每个 web 进程只有一枚内存态 launch token,且浏览器 cookie 有 30 天绝对寿命。
|
|
5
|
+
* 本模块:
|
|
6
|
+
* 1) 从 dsh web 日志(或显式配置)发现 端口 + launch token;
|
|
7
|
+
* 2) 用 launch token 换取上游会话 cookie,由 relay 统一持有并注入;
|
|
8
|
+
* 3) cookie 临近过期或上游返回 401 时自动重新换取(= token 自动续期,浏览器无感);
|
|
9
|
+
* 4) 检测 dsh 重启(日志出现新 token / 进程端口变化)后自动重新绑定。
|
|
10
|
+
*/
|
|
11
|
+
import { open, stat } from 'node:fs/promises'
|
|
12
|
+
import { existsSync } from 'node:fs'
|
|
13
|
+
import { readdir, readFile as readFileSyncSafe } from 'node:fs/promises'
|
|
14
|
+
import net from 'node:net'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
import { formatCookie, httpRequest, parseSetCookie, readJson, sleep } from './util.mjs'
|
|
17
|
+
|
|
18
|
+
const TOKEN_RE = /http:\/\/([0-9A-Za-z._-]+|\[[0-9a-fA-F:]+\]):(\d+)\/\?token=([A-Za-z0-9_-]{16,})/g
|
|
19
|
+
const COOKIE_PREFIX = 'dsh-auth-'
|
|
20
|
+
|
|
21
|
+
function normalizeConnectHost(raw) {
|
|
22
|
+
const cleaned = String(raw ?? '').trim().replace(/^\[|\]$/gu, '')
|
|
23
|
+
if (!cleaned || cleaned === '0.0.0.0' || cleaned === '::') return '127.0.0.1'
|
|
24
|
+
return cleaned
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function probeTcp(host, port, timeoutMs = 500) {
|
|
28
|
+
return new Promise((resolve) => {
|
|
29
|
+
const socket = net.createConnection({ host: normalizeConnectHost(host), port })
|
|
30
|
+
let settled = false
|
|
31
|
+
const done = (ok) => {
|
|
32
|
+
if (settled) return
|
|
33
|
+
settled = true
|
|
34
|
+
socket.destroy()
|
|
35
|
+
resolve(ok)
|
|
36
|
+
}
|
|
37
|
+
socket.setTimeout(timeoutMs)
|
|
38
|
+
socket.once('connect', () => done(true))
|
|
39
|
+
socket.once('timeout', () => done(false))
|
|
40
|
+
socket.once('error', () => done(false))
|
|
41
|
+
})
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
async function readTail(path, bytes = 4 * 1024 * 1024) {
|
|
45
|
+
const handle = await open(path, 'r')
|
|
46
|
+
try {
|
|
47
|
+
const info = await handle.stat()
|
|
48
|
+
const start = Math.max(0, info.size - bytes)
|
|
49
|
+
const length = info.size - start
|
|
50
|
+
const buffer = Buffer.alloc(length)
|
|
51
|
+
await handle.read(buffer, 0, length, start)
|
|
52
|
+
return buffer.toString('utf8')
|
|
53
|
+
} finally {
|
|
54
|
+
await handle.close()
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function parseLaunchEndpoint(text) {
|
|
59
|
+
let last = null
|
|
60
|
+
for (const match of String(text).matchAll(TOKEN_RE)) {
|
|
61
|
+
last = {
|
|
62
|
+
host: normalizeConnectHost(match[1]),
|
|
63
|
+
port: Number(match[2]),
|
|
64
|
+
launchToken: match[3],
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return last
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function parseLaunchLine(text) {
|
|
71
|
+
const found = parseLaunchEndpoint(text)
|
|
72
|
+
return found ? { port: found.port, launchToken: found.launchToken } : null
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export class Upstream {
|
|
76
|
+
constructor({ config, logger }) {
|
|
77
|
+
this.config = config
|
|
78
|
+
this.logger = logger
|
|
79
|
+
this.info = {
|
|
80
|
+
host: normalizeConnectHost(config.upstream.host),
|
|
81
|
+
port: config.upstream.port ?? null,
|
|
82
|
+
launchToken: config.upstream.launchToken ?? null,
|
|
83
|
+
logPath: config.upstream.log ?? null,
|
|
84
|
+
cookie: null,
|
|
85
|
+
authless: false,
|
|
86
|
+
cookieExpiresAt: null,
|
|
87
|
+
cookieRefreshedAt: null,
|
|
88
|
+
lastError: null,
|
|
89
|
+
lastDiscoverAt: null,
|
|
90
|
+
discoveries: 0,
|
|
91
|
+
bootstraps: 0,
|
|
92
|
+
}
|
|
93
|
+
this.logCache = new Map() // logPath -> { mtimeMs, size, found }
|
|
94
|
+
this.refreshing = null
|
|
95
|
+
this.timer = null
|
|
96
|
+
this.stopped = false
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
get origin() {
|
|
100
|
+
return `http://${this.info.host}:${this.info.port}`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
get ready() {
|
|
104
|
+
return Boolean(this.info.port && (this.info.cookie || this.info.authless))
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
async start() {
|
|
108
|
+
await this.ensure({ force: true }).catch((error) => {
|
|
109
|
+
this.info.lastError = String(error?.message ?? error)
|
|
110
|
+
this.logger?.warn?.('upstream bootstrap failed; will retry', { error: this.info.lastError })
|
|
111
|
+
})
|
|
112
|
+
this.timer = setInterval(() => {
|
|
113
|
+
this.ensure().catch((error) => {
|
|
114
|
+
this.info.lastError = String(error?.message ?? error)
|
|
115
|
+
this.logger?.warn?.('upstream refresh failed', { error: this.info.lastError })
|
|
116
|
+
})
|
|
117
|
+
}, this.config.upstream.discoverIntervalMs)
|
|
118
|
+
this.timer.unref?.()
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
stop() {
|
|
122
|
+
this.stopped = true
|
|
123
|
+
if (this.timer) clearInterval(this.timer)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** 串行化:同一时刻只跑一次发现/续期。 */
|
|
127
|
+
ensure({ force = false } = {}) {
|
|
128
|
+
if (this.refreshing) return this.refreshing
|
|
129
|
+
this.refreshing = this.#ensureInner({ force }).finally(() => {
|
|
130
|
+
this.refreshing = null
|
|
131
|
+
})
|
|
132
|
+
return this.refreshing
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async #ensureInner({ force }) {
|
|
136
|
+
if (this.stopped) return
|
|
137
|
+
const discovered = await this.#discover()
|
|
138
|
+
const nextHost = discovered.host ? normalizeConnectHost(discovered.host) : this.info.host
|
|
139
|
+
const hostChanged = nextHost !== this.info.host
|
|
140
|
+
const portChanged = Boolean(discovered.port) && discovered.port !== this.info.port
|
|
141
|
+
const tokenChanged = Boolean(discovered.launchToken) && discovered.launchToken !== this.info.launchToken
|
|
142
|
+
if (discovered.host) this.info.host = nextHost
|
|
143
|
+
if (discovered.port) this.info.port = discovered.port
|
|
144
|
+
if (discovered.launchToken) this.info.launchToken = discovered.launchToken
|
|
145
|
+
if (discovered.logPath) this.info.logPath = discovered.logPath
|
|
146
|
+
|
|
147
|
+
// 免日志兜底路径:当宿主 dsh-botmode 直接写入了 upstream-hint.json(如裸跑 dsh web 或 Electron 内嵌网关)
|
|
148
|
+
if (discovered.fromHint && (discovered.cookie || discovered.authless)) {
|
|
149
|
+
const cookieChanged = (discovered.cookie ?? null) !== this.info.cookie
|
|
150
|
+
const authlessChanged = Boolean(discovered.authless) !== this.info.authless
|
|
151
|
+
if (force || hostChanged || portChanged || cookieChanged || authlessChanged || !this.ready) {
|
|
152
|
+
this.info.cookie = discovered.cookie ?? null
|
|
153
|
+
this.info.authless = Boolean(discovered.authless)
|
|
154
|
+
this.info.cookieExpiresAt = Date.now() + 24 * 3_600_000
|
|
155
|
+
this.info.cookieRefreshedAt = Date.now()
|
|
156
|
+
this.info.bootstraps += 1
|
|
157
|
+
this.info.lastError = null
|
|
158
|
+
this.logger?.info?.('upstream bound via host hint (no log file required)', {
|
|
159
|
+
host: this.info.host,
|
|
160
|
+
port: this.info.port,
|
|
161
|
+
authMode: this.info.authless ? 'none' : 'cookie',
|
|
162
|
+
bootstraps: this.info.bootstraps,
|
|
163
|
+
})
|
|
164
|
+
}
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
const now = Date.now()
|
|
169
|
+
const skew = this.config.upstream.cookieRenewSkewSeconds * 1000
|
|
170
|
+
const expiring = !this.info.cookieExpiresAt || this.info.cookieExpiresAt - skew < now
|
|
171
|
+
if (!force && !hostChanged && !portChanged && !tokenChanged && !expiring) return
|
|
172
|
+
|
|
173
|
+
if (!this.info.port || !this.info.launchToken) {
|
|
174
|
+
throw new Error('未发现 dsh web 端口或 launch token')
|
|
175
|
+
}
|
|
176
|
+
await this.#bootstrap()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
async #probeAuthless(host, port) {
|
|
180
|
+
try {
|
|
181
|
+
const response = await httpRequest(`http://${host}:${port}/botmode/api/state`, {
|
|
182
|
+
redirect: 'manual',
|
|
183
|
+
timeoutMs: 2_000,
|
|
184
|
+
})
|
|
185
|
+
return response.status === 200
|
|
186
|
+
} catch {
|
|
187
|
+
return false
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
async #readHostHint() {
|
|
192
|
+
const stateDir = this.config?.stateDir
|
|
193
|
+
if (!stateDir) return null
|
|
194
|
+
const hintPath = join(stateDir, 'upstream-hint.json')
|
|
195
|
+
if (!existsSync(hintPath)) return null
|
|
196
|
+
const hint = readJson(hintPath, null)
|
|
197
|
+
const host = normalizeConnectHost(hint?.host)
|
|
198
|
+
const port = Number(hint?.port)
|
|
199
|
+
const cookie = typeof hint?.cookie === 'string' && hint.cookie.trim() ? hint.cookie.trim() : null
|
|
200
|
+
const launchToken = typeof hint?.launchToken === 'string' && hint.launchToken.trim() ? hint.launchToken.trim() : null
|
|
201
|
+
const authMode = hint?.authMode === 'none' ? 'none' : null
|
|
202
|
+
if (!Number.isInteger(port) || port <= 0 || (!cookie && !launchToken && authMode !== 'none')) return null
|
|
203
|
+
if (!(await probeTcp(host, port))) return null
|
|
204
|
+
if (!cookie && !launchToken && authMode === 'none') {
|
|
205
|
+
if (!(await this.#probeAuthless(host, port))) return null
|
|
206
|
+
return {
|
|
207
|
+
host,
|
|
208
|
+
port,
|
|
209
|
+
launchToken: null,
|
|
210
|
+
cookie: null,
|
|
211
|
+
authless: true,
|
|
212
|
+
fromHint: true,
|
|
213
|
+
mtimeMs: Number(hint?.updatedAt) || Date.now(),
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
host,
|
|
218
|
+
port,
|
|
219
|
+
launchToken,
|
|
220
|
+
cookie,
|
|
221
|
+
authless: false,
|
|
222
|
+
fromHint: !launchToken && Boolean(cookie),
|
|
223
|
+
mtimeMs: Number(hint?.updatedAt) || Date.now(),
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async #readLogCandidate(logPath) {
|
|
228
|
+
if (!logPath || !existsSync(logPath)) return null
|
|
229
|
+
try {
|
|
230
|
+
const info = await stat(logPath)
|
|
231
|
+
const cached = this.logCache.get(logPath)
|
|
232
|
+
if (cached && cached.mtimeMs === info.mtimeMs && cached.size === info.size) {
|
|
233
|
+
return cached.found ? { ...cached.found, mtimeMs: info.mtimeMs, logPath } : null
|
|
234
|
+
}
|
|
235
|
+
const found = parseLaunchEndpoint(await readTail(logPath))
|
|
236
|
+
this.logCache.set(logPath, { mtimeMs: info.mtimeMs, size: info.size, found })
|
|
237
|
+
if (found) {
|
|
238
|
+
this.info.discoveries += 1
|
|
239
|
+
return { ...found, mtimeMs: info.mtimeMs, logPath }
|
|
240
|
+
}
|
|
241
|
+
return null
|
|
242
|
+
} catch (error) {
|
|
243
|
+
this.logger?.warn?.('read upstream log failed', { logPath, error: String(error?.message ?? error) })
|
|
244
|
+
return null
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async #discover() {
|
|
249
|
+
this.info.lastDiscoverAt = Date.now()
|
|
250
|
+
if (this.config.upstream.mode === 'fixed') {
|
|
251
|
+
return {
|
|
252
|
+
host: normalizeConnectHost(this.config.upstream.host),
|
|
253
|
+
port: this.config.upstream.port,
|
|
254
|
+
launchToken: this.config.upstream.launchToken,
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
// 显式指定了单一日志文件时严格只读取该日志(兼容自定义部署与测试隔离)。
|
|
258
|
+
if (this.config.upstream.log) {
|
|
259
|
+
const explicit = await this.#readLogCandidate(this.config.upstream.log)
|
|
260
|
+
if (explicit) return explicit
|
|
261
|
+
const procs = await this.#listRunningDshWeb()
|
|
262
|
+
if (procs.length > 0) {
|
|
263
|
+
const newest = procs[0]
|
|
264
|
+
return { host: newest.host, port: newest.port, launchToken: this.info.launchToken }
|
|
265
|
+
}
|
|
266
|
+
return {}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// 自动检索模式:扫描所有候选日志并与当前存活的 dsh web 进程匹配,绝不新开网关。
|
|
270
|
+
const candidateLogs = Array.isArray(this.config.upstream.logs) ? this.config.upstream.logs : []
|
|
271
|
+
const candidates = []
|
|
272
|
+
for (const logPath of candidateLogs) {
|
|
273
|
+
const item = await this.#readLogCandidate(logPath)
|
|
274
|
+
if (item) candidates.push(item)
|
|
275
|
+
}
|
|
276
|
+
if (candidates.length === 1) {
|
|
277
|
+
if (await probeTcp(candidates[0].host, candidates[0].port)) return candidates[0]
|
|
278
|
+
const hint = await this.#readHostHint()
|
|
279
|
+
return hint ?? candidates[0]
|
|
280
|
+
}
|
|
281
|
+
if (candidates.length > 1) {
|
|
282
|
+
const procs = await this.#listRunningDshWeb()
|
|
283
|
+
const scored = await Promise.all(candidates.map(async (item, index) => {
|
|
284
|
+
const alive = await probeTcp(item.host, item.port)
|
|
285
|
+
const exactProc = procs.some((p) => p.port === item.port && (!p.host || p.host === item.host))
|
|
286
|
+
const hostMatch = procs.some((p) => p.host && p.host === item.host)
|
|
287
|
+
const score = (alive ? 1000 : 0) + (exactProc ? 500 : 0) + (hostMatch ? 100 : 0) - index
|
|
288
|
+
return { item, alive, score }
|
|
289
|
+
}))
|
|
290
|
+
scored.sort((a, b) => (b.score - a.score) || (b.item.mtimeMs - a.item.mtimeMs))
|
|
291
|
+
if (scored[0].alive) return scored[0].item
|
|
292
|
+
const hint = await this.#readHostHint()
|
|
293
|
+
return hint ?? scored[0].item
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
const hint = await this.#readHostHint()
|
|
297
|
+
if (hint) return hint
|
|
298
|
+
|
|
299
|
+
const procs = await this.#listRunningDshWeb()
|
|
300
|
+
if (procs.length > 0) {
|
|
301
|
+
return { host: procs[0].host, port: procs[0].port, launchToken: this.info.launchToken }
|
|
302
|
+
}
|
|
303
|
+
return {}
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** 扫描 /proc 找出当前存活的 dsh web 进程(最新优先,仅 Linux 支持)。 */
|
|
307
|
+
async #listRunningDshWeb() {
|
|
308
|
+
if (process.platform !== 'linux') return []
|
|
309
|
+
let entries = []
|
|
310
|
+
try {
|
|
311
|
+
entries = await readdir('/proc')
|
|
312
|
+
} catch {
|
|
313
|
+
return []
|
|
314
|
+
}
|
|
315
|
+
const found = []
|
|
316
|
+
for (const entry of entries) {
|
|
317
|
+
if (!/^\d+$/u.test(entry)) continue
|
|
318
|
+
let cmd
|
|
319
|
+
try {
|
|
320
|
+
cmd = (await readFileSyncSafe(`/proc/${entry}/cmdline`)).toString('utf8').split('\0').filter(Boolean)
|
|
321
|
+
} catch {
|
|
322
|
+
continue
|
|
323
|
+
}
|
|
324
|
+
const at = cmd.findIndex((part) => part === 'web')
|
|
325
|
+
if (at === -1 || !cmd.some((part) => part.endsWith('/dsh') || part === 'dsh')) continue
|
|
326
|
+
const hostAt = cmd.indexOf('--host')
|
|
327
|
+
const host = hostAt !== -1 && cmd[hostAt + 1] ? normalizeConnectHost(cmd[hostAt + 1]) : null
|
|
328
|
+
const portAt = cmd.indexOf('--port')
|
|
329
|
+
const rawPort = portAt !== -1 ? Number(cmd[portAt + 1]) : null
|
|
330
|
+
const port = Number.isInteger(rawPort) && rawPort > 0 ? rawPort : null
|
|
331
|
+
let startedAt = 0
|
|
332
|
+
try {
|
|
333
|
+
startedAt = (await stat(`/proc/${entry}`)).birthtimeMs
|
|
334
|
+
} catch {}
|
|
335
|
+
found.push({ pid: Number(entry), host, port, startedAt })
|
|
336
|
+
}
|
|
337
|
+
found.sort((a, b) => (b.port ? 1 : 0) - (a.port ? 1 : 0) || b.startedAt - a.startedAt)
|
|
338
|
+
return found
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
async #bootstrap() {
|
|
342
|
+
const url = `${this.origin}/?token=${encodeURIComponent(this.info.launchToken)}`
|
|
343
|
+
const response = await httpRequest(url, { redirect: 'manual', timeoutMs: 10_000 })
|
|
344
|
+
if (response.status !== 303 && response.status !== 200) {
|
|
345
|
+
throw new Error(`launch token 被拒绝: HTTP ${response.status}`)
|
|
346
|
+
}
|
|
347
|
+
const cookies = parseSetCookie(response.headers).filter(
|
|
348
|
+
(cookie) => cookie.name.startsWith(COOKIE_PREFIX) || (cookie.httpOnly && cookie.maxAge),
|
|
349
|
+
)
|
|
350
|
+
if (cookies.length === 0) {
|
|
351
|
+
if (response.status === 200) {
|
|
352
|
+
// 上游可能直接接受 token(部分版本),退回 URL 注入模式
|
|
353
|
+
this.info.cookie = null
|
|
354
|
+
this.info.cookieExpiresAt = Date.now() + 3_600_000
|
|
355
|
+
this.logger?.warn?.('upstream did not set a session cookie; relying on token injection')
|
|
356
|
+
return
|
|
357
|
+
}
|
|
358
|
+
throw new Error('上游未返回会话 cookie')
|
|
359
|
+
}
|
|
360
|
+
const cookie = cookies[0]
|
|
361
|
+
const maxAgeMs = Number.isFinite(cookie.maxAge) ? cookie.maxAge * 1000 : 30 * 86_400_000
|
|
362
|
+
this.info.cookie = formatCookie(cookie)
|
|
363
|
+
this.info.cookieExpiresAt = Date.now() + maxAgeMs
|
|
364
|
+
this.info.cookieRefreshedAt = Date.now()
|
|
365
|
+
this.info.bootstraps += 1
|
|
366
|
+
this.info.lastError = null
|
|
367
|
+
this.logger?.info?.('upstream cookie refreshed', {
|
|
368
|
+
host: this.info.host,
|
|
369
|
+
port: this.info.port,
|
|
370
|
+
cookie: cookie.name,
|
|
371
|
+
expiresAt: new Date(this.info.cookieExpiresAt).toISOString(),
|
|
372
|
+
bootstraps: this.info.bootstraps,
|
|
373
|
+
})
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** 上游 401 时调用:立刻重新换取 cookie。 */
|
|
377
|
+
async onUnauthorized() {
|
|
378
|
+
this.logger?.warn?.('upstream returned 401/403; re-bootstrapping')
|
|
379
|
+
await this.ensure({ force: true })
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
/** 等待上游可用(用于启动顺序)。 */
|
|
383
|
+
async waitReady({ timeoutMs = 30_000 } = {}) {
|
|
384
|
+
const deadline = Date.now() + timeoutMs
|
|
385
|
+
while (Date.now() < deadline) {
|
|
386
|
+
if (this.ready) return true
|
|
387
|
+
await this.ensure().catch(() => {})
|
|
388
|
+
if (this.ready) return true
|
|
389
|
+
await sleep(500)
|
|
390
|
+
}
|
|
391
|
+
return false
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
describe() {
|
|
395
|
+
return {
|
|
396
|
+
...this.info,
|
|
397
|
+
cookie: this.info.cookie ? `${this.info.cookie.split('=')[0]}=<redacted>` : null,
|
|
398
|
+
cookieExpiresAt: this.info.cookieExpiresAt ? new Date(this.info.cookieExpiresAt).toISOString() : null,
|
|
399
|
+
cookieRefreshedAt: this.info.cookieRefreshedAt ? new Date(this.info.cookieRefreshedAt).toISOString() : null,
|
|
400
|
+
ready: this.ready,
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
}
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 通用工具:base64url、原子写、日志、HTTP 小工具。
|
|
3
|
+
*/
|
|
4
|
+
import { createHash, randomBytes as nodeRandom, timingSafeEqual } from 'node:crypto'
|
|
5
|
+
import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, writeSync } from 'node:fs'
|
|
6
|
+
import { dirname, join } from 'node:path'
|
|
7
|
+
|
|
8
|
+
export const b64u = (buf) => Buffer.from(buf).toString('base64url')
|
|
9
|
+
export const unb64u = (str) => Buffer.from(String(str), 'base64url')
|
|
10
|
+
export const randomBytes = (n) => nodeRandom(n)
|
|
11
|
+
export const randomToken = (n = 32) => b64u(nodeRandom(n))
|
|
12
|
+
export const sha256 = (buf) => createHash('sha256').update(buf).digest()
|
|
13
|
+
|
|
14
|
+
export function safeEqual(a, b) {
|
|
15
|
+
const left = Buffer.isBuffer(a) ? a : Buffer.from(String(a))
|
|
16
|
+
const right = Buffer.isBuffer(b) ? b : Buffer.from(String(b))
|
|
17
|
+
if (left.length !== right.length) return false
|
|
18
|
+
return timingSafeEqual(left, right)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))
|
|
22
|
+
|
|
23
|
+
export async function waitFor(predicate, { timeoutMs = 10_000, intervalMs = 200, label = 'condition' } = {}) {
|
|
24
|
+
const deadline = Date.now() + timeoutMs
|
|
25
|
+
let lastError
|
|
26
|
+
while (Date.now() < deadline) {
|
|
27
|
+
try {
|
|
28
|
+
const value = await predicate()
|
|
29
|
+
if (value) return value
|
|
30
|
+
} catch (error) {
|
|
31
|
+
lastError = error
|
|
32
|
+
}
|
|
33
|
+
await sleep(intervalMs)
|
|
34
|
+
}
|
|
35
|
+
throw new Error(`waitFor ${label} timed out after ${timeoutMs}ms${lastError ? `: ${lastError.message}` : ''}`)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function readJson(path, fallback = null) {
|
|
39
|
+
try {
|
|
40
|
+
return JSON.parse(readFileSync(path, 'utf8'))
|
|
41
|
+
} catch {
|
|
42
|
+
return fallback
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** 写入临时文件 → fsync → rename,避免半截 JSON。 */
|
|
47
|
+
export function writeJsonAtomic(path, value, { mode = 0o600 } = {}) {
|
|
48
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
49
|
+
const tmp = join(dirname(path), `.${process.pid}.${Date.now()}.tmp`)
|
|
50
|
+
const payload = `${JSON.stringify(value, null, 2)}\n`
|
|
51
|
+
const fd = openSync(tmp, 'w', mode)
|
|
52
|
+
try {
|
|
53
|
+
writeSync(fd, payload)
|
|
54
|
+
fsyncSync(fd)
|
|
55
|
+
} finally {
|
|
56
|
+
closeSync(fd)
|
|
57
|
+
}
|
|
58
|
+
try {
|
|
59
|
+
renameSync(tmp, path)
|
|
60
|
+
} catch (error) {
|
|
61
|
+
if (process.platform === 'win32' && (error?.code === 'EPERM' || error?.code === 'EEXIST')) {
|
|
62
|
+
try { rmSync(path, { force: true }) } catch {}
|
|
63
|
+
renameSync(tmp, path)
|
|
64
|
+
} else {
|
|
65
|
+
try { rmSync(tmp, { force: true }) } catch {}
|
|
66
|
+
throw error
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function ensureDir(path) {
|
|
72
|
+
mkdirSync(path, { recursive: true })
|
|
73
|
+
return path
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function createLogger({ stream = process.stdout, name = 'dsh-remote' } = {}) {
|
|
77
|
+
const write = (level, message, fields) => {
|
|
78
|
+
const entry = { ts: new Date().toISOString(), level, msg: message, ...(fields ?? {}) }
|
|
79
|
+
stream.write(`${JSON.stringify(entry)}\n`)
|
|
80
|
+
}
|
|
81
|
+
return {
|
|
82
|
+
info: (msg, fields) => write('info', msg, fields),
|
|
83
|
+
warn: (msg, fields) => write('warn', msg, fields),
|
|
84
|
+
error: (msg, fields) => write('error', msg, fields),
|
|
85
|
+
child: (prefix, extra) => createLogger({ stream, name: `${name}/${prefix}`, ...extra }),
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function parseDuration(text, fallbackMs) {
|
|
90
|
+
if (typeof text === 'number' && Number.isFinite(text)) return text
|
|
91
|
+
if (typeof text !== 'string' || text.trim() === '') return fallbackMs
|
|
92
|
+
const match = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i.exec(text.trim())
|
|
93
|
+
if (!match) return fallbackMs
|
|
94
|
+
const value = Number(match[1])
|
|
95
|
+
const unit = (match[2] ?? 'ms').toLowerCase()
|
|
96
|
+
const factor = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 }[unit] ?? 1
|
|
97
|
+
return Math.round(value * factor)
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 逐条解析 Set-Cookie,返回 [{name, value, maxAge, expires, secure, httpOnly, path}]。 */
|
|
101
|
+
export function parseSetCookie(headers) {
|
|
102
|
+
const list = headers['set-cookie']
|
|
103
|
+
if (!list) return []
|
|
104
|
+
const raw = Array.isArray(list) ? list : [list]
|
|
105
|
+
return raw.map((line) => {
|
|
106
|
+
const parts = String(line).split(';')
|
|
107
|
+
const [pair, ...attrs] = parts
|
|
108
|
+
const eq = pair.indexOf('=')
|
|
109
|
+
const name = pair.slice(0, eq).trim()
|
|
110
|
+
const value = pair.slice(eq + 1).trim()
|
|
111
|
+
const out = { name, value, raw: String(line) }
|
|
112
|
+
for (const attr of attrs) {
|
|
113
|
+
const at = attr.indexOf('=')
|
|
114
|
+
const key = (at === -1 ? attr : attr.slice(0, at)).trim().toLowerCase()
|
|
115
|
+
const val = at === -1 ? '' : attr.slice(at + 1).trim()
|
|
116
|
+
if (key === 'max-age') out.maxAge = Number(val)
|
|
117
|
+
else if (key === 'expires') out.expires = Date.parse(val)
|
|
118
|
+
else if (key === 'secure') out.secure = true
|
|
119
|
+
else if (key === 'httponly') out.httpOnly = true
|
|
120
|
+
else if (key === 'path') out.path = val
|
|
121
|
+
}
|
|
122
|
+
return out
|
|
123
|
+
})
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export function formatCookie(cookie) {
|
|
127
|
+
return `${cookie.name}=${cookie.value}`
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** 极简 HTTP 请求(GET/POST),返回 {status, headers, body}。 */
|
|
131
|
+
export async function httpRequest(url, { method = 'GET', headers = {}, body, timeoutMs = 15_000, redirect = 'manual' } = {}) {
|
|
132
|
+
const controller = new AbortController()
|
|
133
|
+
const timer = setTimeout(() => controller.abort(), timeoutMs)
|
|
134
|
+
try {
|
|
135
|
+
const response = await fetch(url, { method, headers, body, redirect, signal: controller.signal })
|
|
136
|
+
const buffer = Buffer.from(await response.arrayBuffer())
|
|
137
|
+
const out = {}
|
|
138
|
+
for (const [key, value] of response.headers.entries()) {
|
|
139
|
+
if (out[key] === undefined) out[key] = value
|
|
140
|
+
else out[key] = [].concat(out[key], value)
|
|
141
|
+
}
|
|
142
|
+
return { status: response.status, headers: out, body: buffer }
|
|
143
|
+
} catch (error) {
|
|
144
|
+
const cause = error?.cause?.message ?? error?.cause?.code
|
|
145
|
+
throw new Error(`request ${url} failed: ${String(error?.message ?? error)}${cause ? ` (${String(cause)})` : ''}`)
|
|
146
|
+
} finally {
|
|
147
|
+
clearTimeout(timer)
|
|
148
|
+
}
|
|
149
|
+
}
|