dsh-quay-bot 0.7.4 → 1.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.
Files changed (75) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +105 -28
  3. package/bin/doctor.mjs +148 -0
  4. package/botscreen/requirements-offline.txt +11 -0
  5. package/client.js +1 -2
  6. package/cordis.patch.yml +1 -1
  7. package/host/api.js +0 -4
  8. package/host/remote.js +2 -140
  9. package/host/screen.js +85 -21
  10. package/market/index.json +41 -0
  11. package/package.json +32 -13
  12. package/vendor/wheels/any/annotated_doc-0.0.7-py3-none-any.whl +0 -0
  13. package/vendor/wheels/any/annotated_types-0.8.0-py3-none-any.whl +0 -0
  14. package/vendor/wheels/any/anyio-4.16.0-py3-none-any.whl +0 -0
  15. package/vendor/wheels/any/certifi-2026.11.20-py3-none-any.whl +0 -0
  16. package/vendor/wheels/any/click-8.5.1-py3-none-any.whl +0 -0
  17. package/vendor/wheels/any/fastapi-0.165.0-py3-none-any.whl +0 -0
  18. package/vendor/wheels/any/h11-0.16.0-py3-none-any.whl +0 -0
  19. package/vendor/wheels/any/httpcore-1.0.9-py3-none-any.whl +0 -0
  20. package/vendor/wheels/any/httpx-0.29.0-py3-none-any.whl +0 -0
  21. package/vendor/wheels/any/idna-3.20-py3-none-any.whl +0 -0
  22. package/vendor/wheels/any/mss-10.2.0-py3-none-any.whl +0 -0
  23. package/vendor/wheels/any/opentelemetry_api-1.45.2-py3-none-any.whl +0 -0
  24. package/vendor/wheels/any/pydantic-2.14.4-py3-none-any.whl +0 -0
  25. package/vendor/wheels/any/python_multipart-0.0.34-py3-none-any.whl +0 -0
  26. package/vendor/wheels/any/python_xlib-0.33-py2.py3-none-any.whl +0 -0
  27. package/vendor/wheels/any/six-1.17.0-py2.py3-none-any.whl +0 -0
  28. package/vendor/wheels/any/starlette-1.10.0-py3-none-any.whl +0 -0
  29. package/vendor/wheels/any/typing_extensions-4.16.0-py3-none-any.whl +0 -0
  30. package/vendor/wheels/any/typing_inspection-0.4.5-py3-none-any.whl +0 -0
  31. package/vendor/wheels/any/uvicorn-0.54.0-py3-none-any.whl +0 -0
  32. package/vendor/wheels/linux-aarch64/pillow-12.2.0-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl +0 -0
  33. package/vendor/wheels/linux-aarch64/pydantic_core-2.50.5-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.whl +0 -0
  34. package/vendor/wheels/linux-aarch64/websockets-17.4-cp312-cp312-manylinux2014_aarch64.manylinux_2_17_aarch64.manylinux_2_28_aarch64.whl +0 -0
  35. package/vendor/wheels/linux-x86_64/pillow-12.2.0-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl +0 -0
  36. package/vendor/wheels/linux-x86_64/pydantic_core-2.50.5-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.whl +0 -0
  37. package/vendor/wheels/linux-x86_64/websockets-17.4-cp312-cp312-manylinux1_x86_64.manylinux_2_28_x86_64.manylinux_2_5_x86_64.whl +0 -0
  38. package/botscreen/botscreen/__init__.py +0 -2
  39. package/botscreen/botscreen/__main__.py +0 -5
  40. package/botscreen/botscreen/artifacts.py +0 -388
  41. package/botscreen/botscreen/audit.py +0 -94
  42. package/botscreen/botscreen/cgroup.py +0 -293
  43. package/botscreen/botscreen/config.py +0 -320
  44. package/botscreen/botscreen/desktop/assets/chrome.png +0 -0
  45. package/botscreen/botscreen/desktop/assets/codex.png +0 -0
  46. package/botscreen/botscreen/desktop/assets/drive.png +0 -0
  47. package/botscreen/botscreen/desktop/assets/folder.png +0 -0
  48. package/botscreen/botscreen/desktop/assets/search.png +0 -0
  49. package/botscreen/botscreen/desktop/assets/terminal.png +0 -0
  50. package/botscreen/botscreen/desktop/assets/trash.png +0 -0
  51. package/botscreen/botscreen/desktop/assets/wallpaper.png +0 -0
  52. package/botscreen/botscreen/desktop.py +0 -244
  53. package/botscreen/botscreen/driver.py +0 -832
  54. package/botscreen/botscreen/gateway.py +0 -2089
  55. package/botscreen/botscreen/iconlayer.py +0 -841
  56. package/botscreen/botscreen/mcp_server.py +0 -435
  57. package/botscreen/botscreen/resources.py +0 -494
  58. package/botscreen/botscreen/screen.py +0 -1282
  59. package/botscreen/botscreen/session.py +0 -706
  60. package/botscreen/botscreen/state.py +0 -330
  61. package/botscreen/botscreen/streamer.py +0 -388
  62. package/remote/bin/dsh-remote.mjs +0 -418
  63. package/remote/package.json +0 -27
  64. package/remote/src/config.mjs +0 -183
  65. package/remote/src/crypto.mjs +0 -220
  66. package/remote/src/keys.mjs +0 -226
  67. package/remote/src/proxy.mjs +0 -1028
  68. package/remote/src/sessions.mjs +0 -163
  69. package/remote/src/shim.js +0 -838
  70. package/remote/src/supervisor.mjs +0 -207
  71. package/remote/src/tunnel.mjs +0 -489
  72. package/remote/src/upstream.mjs +0 -372
  73. package/remote/src/util.mjs +0 -139
  74. package/remote/src/ws.mjs +0 -313
  75. package/requirements.txt +0 -8
@@ -1,372 +0,0 @@
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
- cookieExpiresAt: null,
86
- cookieRefreshedAt: null,
87
- lastError: null,
88
- lastDiscoverAt: null,
89
- discoveries: 0,
90
- bootstraps: 0,
91
- }
92
- this.logCache = new Map() // logPath -> { mtimeMs, size, found }
93
- this.refreshing = null
94
- this.timer = null
95
- this.stopped = false
96
- }
97
-
98
- get origin() {
99
- return `http://${this.info.host}:${this.info.port}`
100
- }
101
-
102
- get ready() {
103
- return Boolean(this.info.port && this.info.cookie)
104
- }
105
-
106
- async start() {
107
- await this.ensure({ force: true }).catch((error) => {
108
- this.info.lastError = String(error?.message ?? error)
109
- this.logger?.warn?.('upstream bootstrap failed; will retry', { error: this.info.lastError })
110
- })
111
- this.timer = setInterval(() => {
112
- this.ensure().catch((error) => {
113
- this.info.lastError = String(error?.message ?? error)
114
- this.logger?.warn?.('upstream refresh failed', { error: this.info.lastError })
115
- })
116
- }, this.config.upstream.discoverIntervalMs)
117
- this.timer.unref?.()
118
- }
119
-
120
- stop() {
121
- this.stopped = true
122
- if (this.timer) clearInterval(this.timer)
123
- }
124
-
125
- /** 串行化:同一时刻只跑一次发现/续期。 */
126
- ensure({ force = false } = {}) {
127
- if (this.refreshing) return this.refreshing
128
- this.refreshing = this.#ensureInner({ force }).finally(() => {
129
- this.refreshing = null
130
- })
131
- return this.refreshing
132
- }
133
-
134
- async #ensureInner({ force }) {
135
- if (this.stopped) return
136
- const discovered = await this.#discover()
137
- const nextHost = discovered.host ? normalizeConnectHost(discovered.host) : this.info.host
138
- const hostChanged = nextHost !== this.info.host
139
- const portChanged = Boolean(discovered.port) && discovered.port !== this.info.port
140
- const tokenChanged = Boolean(discovered.launchToken) && discovered.launchToken !== this.info.launchToken
141
- if (discovered.host) this.info.host = nextHost
142
- if (discovered.port) this.info.port = discovered.port
143
- if (discovered.launchToken) this.info.launchToken = discovered.launchToken
144
- if (discovered.logPath) this.info.logPath = discovered.logPath
145
-
146
- // 免日志兜底路径:当宿主 dsh-botmode 直接写入了已鉴权的 upstream-hint.json(如裸跑 dsh web 未重定向日志)
147
- if (discovered.fromHint && discovered.cookie) {
148
- const cookieChanged = discovered.cookie !== this.info.cookie
149
- if (force || hostChanged || portChanged || cookieChanged || !this.info.cookie) {
150
- this.info.cookie = discovered.cookie
151
- this.info.cookieExpiresAt = Date.now() + 24 * 3_600_000
152
- this.info.cookieRefreshedAt = Date.now()
153
- this.info.bootstraps += 1
154
- this.info.lastError = null
155
- this.logger?.info?.('upstream bound via host hint (no log file required)', {
156
- host: this.info.host,
157
- port: this.info.port,
158
- bootstraps: this.info.bootstraps,
159
- })
160
- }
161
- return
162
- }
163
-
164
- const now = Date.now()
165
- const skew = this.config.upstream.cookieRenewSkewSeconds * 1000
166
- const expiring = !this.info.cookieExpiresAt || this.info.cookieExpiresAt - skew < now
167
- if (!force && !hostChanged && !portChanged && !tokenChanged && !expiring) return
168
-
169
- if (!this.info.port || !this.info.launchToken) {
170
- throw new Error('未发现 dsh web 端口或 launch token')
171
- }
172
- await this.#bootstrap()
173
- }
174
-
175
- async #readHostHint() {
176
- const stateDir = this.config?.stateDir
177
- if (!stateDir) return null
178
- const hintPath = join(stateDir, 'upstream-hint.json')
179
- if (!existsSync(hintPath)) return null
180
- const hint = readJson(hintPath, null)
181
- const host = normalizeConnectHost(hint?.host)
182
- const port = Number(hint?.port)
183
- const cookie = typeof hint?.cookie === 'string' && hint.cookie.trim() ? hint.cookie.trim() : null
184
- const launchToken = typeof hint?.launchToken === 'string' && hint.launchToken.trim() ? hint.launchToken.trim() : null
185
- if (!Number.isInteger(port) || port <= 0 || (!cookie && !launchToken)) return null
186
- if (!(await probeTcp(host, port))) return null
187
- return {
188
- host,
189
- port,
190
- launchToken,
191
- cookie,
192
- fromHint: !launchToken && Boolean(cookie),
193
- mtimeMs: Number(hint?.updatedAt) || Date.now(),
194
- }
195
- }
196
-
197
- async #readLogCandidate(logPath) {
198
- if (!logPath || !existsSync(logPath)) return null
199
- try {
200
- const info = await stat(logPath)
201
- const cached = this.logCache.get(logPath)
202
- if (cached && cached.mtimeMs === info.mtimeMs && cached.size === info.size) {
203
- return cached.found ? { ...cached.found, mtimeMs: info.mtimeMs, logPath } : null
204
- }
205
- const found = parseLaunchEndpoint(await readTail(logPath))
206
- this.logCache.set(logPath, { mtimeMs: info.mtimeMs, size: info.size, found })
207
- if (found) {
208
- this.info.discoveries += 1
209
- return { ...found, mtimeMs: info.mtimeMs, logPath }
210
- }
211
- return null
212
- } catch (error) {
213
- this.logger?.warn?.('read upstream log failed', { logPath, error: String(error?.message ?? error) })
214
- return null
215
- }
216
- }
217
-
218
- async #discover() {
219
- this.info.lastDiscoverAt = Date.now()
220
- if (this.config.upstream.mode === 'fixed') {
221
- return {
222
- host: normalizeConnectHost(this.config.upstream.host),
223
- port: this.config.upstream.port,
224
- launchToken: this.config.upstream.launchToken,
225
- }
226
- }
227
- // 显式指定了单一日志文件时严格只读取该日志(兼容自定义部署与测试隔离)。
228
- if (this.config.upstream.log) {
229
- const explicit = await this.#readLogCandidate(this.config.upstream.log)
230
- if (explicit) return explicit
231
- const procs = await this.#listRunningDshWeb()
232
- if (procs.length > 0) {
233
- const newest = procs[0]
234
- return { host: newest.host, port: newest.port, launchToken: this.info.launchToken }
235
- }
236
- return {}
237
- }
238
-
239
- // 自动检索模式:扫描所有候选日志并与当前存活的 dsh web 进程匹配,绝不新开网关。
240
- const candidateLogs = Array.isArray(this.config.upstream.logs) ? this.config.upstream.logs : []
241
- const candidates = []
242
- for (const logPath of candidateLogs) {
243
- const item = await this.#readLogCandidate(logPath)
244
- if (item) candidates.push(item)
245
- }
246
- if (candidates.length === 1) {
247
- if (await probeTcp(candidates[0].host, candidates[0].port)) return candidates[0]
248
- const hint = await this.#readHostHint()
249
- return hint ?? candidates[0]
250
- }
251
- if (candidates.length > 1) {
252
- const procs = await this.#listRunningDshWeb()
253
- const scored = await Promise.all(candidates.map(async (item, index) => {
254
- const alive = await probeTcp(item.host, item.port)
255
- const exactProc = procs.some((p) => p.port === item.port && (!p.host || p.host === item.host))
256
- const hostMatch = procs.some((p) => p.host && p.host === item.host)
257
- const score = (alive ? 1000 : 0) + (exactProc ? 500 : 0) + (hostMatch ? 100 : 0) - index
258
- return { item, alive, score }
259
- }))
260
- scored.sort((a, b) => (b.score - a.score) || (b.item.mtimeMs - a.item.mtimeMs))
261
- if (scored[0].alive) return scored[0].item
262
- const hint = await this.#readHostHint()
263
- return hint ?? scored[0].item
264
- }
265
-
266
- const hint = await this.#readHostHint()
267
- if (hint) return hint
268
-
269
- const procs = await this.#listRunningDshWeb()
270
- if (procs.length > 0) {
271
- return { host: procs[0].host, port: procs[0].port, launchToken: this.info.launchToken }
272
- }
273
- return {}
274
- }
275
-
276
- /** 扫描 /proc 找出当前存活的 dsh web 进程(最新优先)。 */
277
- async #listRunningDshWeb() {
278
- let entries = []
279
- try {
280
- entries = await readdir('/proc')
281
- } catch {
282
- return []
283
- }
284
- const found = []
285
- for (const entry of entries) {
286
- if (!/^\d+$/u.test(entry)) continue
287
- let cmd
288
- try {
289
- cmd = (await readFileSyncSafe(`/proc/${entry}/cmdline`)).toString('utf8').split('\0').filter(Boolean)
290
- } catch {
291
- continue
292
- }
293
- const at = cmd.findIndex((part) => part === 'web')
294
- if (at === -1 || !cmd.some((part) => part.endsWith('/dsh') || part === 'dsh')) continue
295
- const hostAt = cmd.indexOf('--host')
296
- const host = hostAt !== -1 && cmd[hostAt + 1] ? normalizeConnectHost(cmd[hostAt + 1]) : null
297
- const portAt = cmd.indexOf('--port')
298
- const rawPort = portAt !== -1 ? Number(cmd[portAt + 1]) : null
299
- const port = Number.isInteger(rawPort) && rawPort > 0 ? rawPort : null
300
- let startedAt = 0
301
- try {
302
- startedAt = (await stat(`/proc/${entry}`)).birthtimeMs
303
- } catch {}
304
- found.push({ pid: Number(entry), host, port, startedAt })
305
- }
306
- found.sort((a, b) => (b.port ? 1 : 0) - (a.port ? 1 : 0) || b.startedAt - a.startedAt)
307
- return found
308
- }
309
-
310
- async #bootstrap() {
311
- const url = `${this.origin}/?token=${encodeURIComponent(this.info.launchToken)}`
312
- const response = await httpRequest(url, { redirect: 'manual', timeoutMs: 10_000 })
313
- if (response.status !== 303 && response.status !== 200) {
314
- throw new Error(`launch token 被拒绝: HTTP ${response.status}`)
315
- }
316
- const cookies = parseSetCookie(response.headers).filter(
317
- (cookie) => cookie.name.startsWith(COOKIE_PREFIX) || (cookie.httpOnly && cookie.maxAge),
318
- )
319
- if (cookies.length === 0) {
320
- if (response.status === 200) {
321
- // 上游可能直接接受 token(部分版本),退回 URL 注入模式
322
- this.info.cookie = null
323
- this.info.cookieExpiresAt = Date.now() + 3_600_000
324
- this.logger?.warn?.('upstream did not set a session cookie; relying on token injection')
325
- return
326
- }
327
- throw new Error('上游未返回会话 cookie')
328
- }
329
- const cookie = cookies[0]
330
- const maxAgeMs = Number.isFinite(cookie.maxAge) ? cookie.maxAge * 1000 : 30 * 86_400_000
331
- this.info.cookie = formatCookie(cookie)
332
- this.info.cookieExpiresAt = Date.now() + maxAgeMs
333
- this.info.cookieRefreshedAt = Date.now()
334
- this.info.bootstraps += 1
335
- this.info.lastError = null
336
- this.logger?.info?.('upstream cookie refreshed', {
337
- host: this.info.host,
338
- port: this.info.port,
339
- cookie: cookie.name,
340
- expiresAt: new Date(this.info.cookieExpiresAt).toISOString(),
341
- bootstraps: this.info.bootstraps,
342
- })
343
- }
344
-
345
- /** 上游 401 时调用:立刻重新换取 cookie。 */
346
- async onUnauthorized() {
347
- this.logger?.warn?.('upstream returned 401/403; re-bootstrapping')
348
- await this.ensure({ force: true })
349
- }
350
-
351
- /** 等待上游可用(用于启动顺序)。 */
352
- async waitReady({ timeoutMs = 30_000 } = {}) {
353
- const deadline = Date.now() + timeoutMs
354
- while (Date.now() < deadline) {
355
- if (this.ready) return true
356
- await this.ensure().catch(() => {})
357
- if (this.ready) return true
358
- await sleep(500)
359
- }
360
- return false
361
- }
362
-
363
- describe() {
364
- return {
365
- ...this.info,
366
- cookie: this.info.cookie ? `${this.info.cookie.split('=')[0]}=<redacted>` : null,
367
- cookieExpiresAt: this.info.cookieExpiresAt ? new Date(this.info.cookieExpiresAt).toISOString() : null,
368
- cookieRefreshedAt: this.info.cookieRefreshedAt ? new Date(this.info.cookieRefreshedAt).toISOString() : null,
369
- ready: this.ready,
370
- }
371
- }
372
- }
@@ -1,139 +0,0 @@
1
- /**
2
- * 通用工具:base64url、原子写、日志、HTTP 小工具。
3
- */
4
- import { createHash, randomBytes as nodeRandom, timingSafeEqual } from 'node:crypto'
5
- import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, 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
- renameSync(tmp, path)
59
- }
60
-
61
- export function ensureDir(path) {
62
- mkdirSync(path, { recursive: true })
63
- return path
64
- }
65
-
66
- export function createLogger({ stream = process.stdout, name = 'dsh-remote' } = {}) {
67
- const write = (level, message, fields) => {
68
- const entry = { ts: new Date().toISOString(), level, msg: message, ...(fields ?? {}) }
69
- stream.write(`${JSON.stringify(entry)}\n`)
70
- }
71
- return {
72
- info: (msg, fields) => write('info', msg, fields),
73
- warn: (msg, fields) => write('warn', msg, fields),
74
- error: (msg, fields) => write('error', msg, fields),
75
- child: (prefix, extra) => createLogger({ stream, name: `${name}/${prefix}`, ...extra }),
76
- }
77
- }
78
-
79
- export function parseDuration(text, fallbackMs) {
80
- if (typeof text === 'number' && Number.isFinite(text)) return text
81
- if (typeof text !== 'string' || text.trim() === '') return fallbackMs
82
- const match = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h|d)?$/i.exec(text.trim())
83
- if (!match) return fallbackMs
84
- const value = Number(match[1])
85
- const unit = (match[2] ?? 'ms').toLowerCase()
86
- const factor = { ms: 1, s: 1e3, m: 6e4, h: 36e5, d: 864e5 }[unit] ?? 1
87
- return Math.round(value * factor)
88
- }
89
-
90
- /** 逐条解析 Set-Cookie,返回 [{name, value, maxAge, expires, secure, httpOnly, path}]。 */
91
- export function parseSetCookie(headers) {
92
- const list = headers['set-cookie']
93
- if (!list) return []
94
- const raw = Array.isArray(list) ? list : [list]
95
- return raw.map((line) => {
96
- const parts = String(line).split(';')
97
- const [pair, ...attrs] = parts
98
- const eq = pair.indexOf('=')
99
- const name = pair.slice(0, eq).trim()
100
- const value = pair.slice(eq + 1).trim()
101
- const out = { name, value, raw: String(line) }
102
- for (const attr of attrs) {
103
- const at = attr.indexOf('=')
104
- const key = (at === -1 ? attr : attr.slice(0, at)).trim().toLowerCase()
105
- const val = at === -1 ? '' : attr.slice(at + 1).trim()
106
- if (key === 'max-age') out.maxAge = Number(val)
107
- else if (key === 'expires') out.expires = Date.parse(val)
108
- else if (key === 'secure') out.secure = true
109
- else if (key === 'httponly') out.httpOnly = true
110
- else if (key === 'path') out.path = val
111
- }
112
- return out
113
- })
114
- }
115
-
116
- export function formatCookie(cookie) {
117
- return `${cookie.name}=${cookie.value}`
118
- }
119
-
120
- /** 极简 HTTP 请求(GET/POST),返回 {status, headers, body}。 */
121
- export async function httpRequest(url, { method = 'GET', headers = {}, body, timeoutMs = 15_000, redirect = 'manual' } = {}) {
122
- const controller = new AbortController()
123
- const timer = setTimeout(() => controller.abort(), timeoutMs)
124
- try {
125
- const response = await fetch(url, { method, headers, body, redirect, signal: controller.signal })
126
- const buffer = Buffer.from(await response.arrayBuffer())
127
- const out = {}
128
- for (const [key, value] of response.headers.entries()) {
129
- if (out[key] === undefined) out[key] = value
130
- else out[key] = [].concat(out[key], value)
131
- }
132
- return { status: response.status, headers: out, body: buffer }
133
- } catch (error) {
134
- const cause = error?.cause?.message ?? error?.cause?.code
135
- throw new Error(`request ${url} failed: ${String(error?.message ?? error)}${cause ? ` (${String(cause)})` : ''}`)
136
- } finally {
137
- clearTimeout(timer)
138
- }
139
- }