dsh-quay-bot 1.0.2 → 1.0.6

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 (61) hide show
  1. package/README.md +28 -105
  2. package/botscreen/requirements.txt +1 -1
  3. package/client.js +123 -53
  4. package/cordis.patch.yml +1 -1
  5. package/host/api.js +4 -0
  6. package/host/remote.js +285 -8
  7. package/host/screen.js +22 -86
  8. package/package.json +34 -32
  9. package/remote/bin/dsh-remote.mjs +435 -0
  10. package/remote/package.json +27 -0
  11. package/remote/src/config.mjs +183 -0
  12. package/remote/src/crypto.mjs +220 -0
  13. package/remote/src/keys.mjs +226 -0
  14. package/remote/src/proxy.mjs +1028 -0
  15. package/remote/src/sessions.mjs +163 -0
  16. package/remote/src/shim.js +838 -0
  17. package/remote/src/supervisor.mjs +207 -0
  18. package/remote/src/tunnel.mjs +533 -0
  19. package/remote/src/upstream.mjs +403 -0
  20. package/remote/src/util.mjs +149 -0
  21. package/remote/src/ws.mjs +313 -0
  22. package/LICENSE +0 -21
  23. package/avatar/build.mjs +0 -81
  24. package/avatar/gallery/droid.json +0 -14
  25. package/avatar/gallery/ghost.json +0 -14
  26. package/avatar/gallery/grok-pod.json +0 -14
  27. package/avatar/gallery/guardian.json +0 -14
  28. package/avatar/gallery/mecha.json +0 -14
  29. package/avatar/gallery/mochi.json +0 -14
  30. package/avatar/gallery/neko.json +0 -14
  31. package/avatar/gallery/orbiter.json +0 -14
  32. package/avatar/gallery/relay.json +0 -14
  33. package/avatar/gallery/spark.json +0 -14
  34. package/avatar/src/bot/clay.ts +0 -135
  35. package/avatar/src/bot/effects.ts +0 -100
  36. package/avatar/src/bot/grok-bot.ts +0 -626
  37. package/avatar/src/bot/index.ts +0 -15
  38. package/avatar/src/bot/palettes.ts +0 -62
  39. package/avatar/src/bot/ring.ts +0 -219
  40. package/avatar/src/bot/scheduler.ts +0 -239
  41. package/avatar/src/bot/shapes.ts +0 -277
  42. package/avatar/src/bot/spring.ts +0 -196
  43. package/avatar/src/core/color.ts +0 -92
  44. package/avatar/src/core/eyes.ts +0 -297
  45. package/avatar/src/core/field.ts +0 -482
  46. package/avatar/src/core/frame.ts +0 -655
  47. package/avatar/src/core/fx.ts +0 -375
  48. package/avatar/src/core/index.ts +0 -49
  49. package/avatar/src/core/paint.ts +0 -331
  50. package/avatar/src/core/path.ts +0 -495
  51. package/avatar/src/core/pose.ts +0 -581
  52. package/avatar/src/core/svg.ts +0 -98
  53. package/avatar/src/core/types.ts +0 -153
  54. package/avatar/src/core/validate.ts +0 -296
  55. package/avatar/src/core/volume.ts +0 -681
  56. package/avatar/src/entry.ts +0 -260
  57. package/bin/doctor.mjs +0 -148
  58. package/botscreen/requirements-offline.txt +0 -11
  59. package/market/index.json +0 -41
  60. package/vendor/pip/pip-25.1.1-py3-none-any.whl +0 -0
  61. package/vendor/pip/setuptools-78.1.1-py3-none-any.whl +0 -0
@@ -0,0 +1,220 @@
1
+ /**
2
+ * 端到端加密原语。
3
+ *
4
+ * 选型:ECDH P-256(WebCrypto 全平台可用)+ HKDF-SHA256 + AES-256-GCM。
5
+ * 每个会话派生两把单向密钥(c2s / s2c),序号即 GCM nonce(12 字节 = 4 个 0 + 8 字节大端序号),
6
+ * 密钥 + 单调序号保证 nonce 永不复用;AAD 绑定协议版本、帧类型与 sid,防止跨会话重放。
7
+ */
8
+ import {
9
+ createCipheriv,
10
+ createDecipheriv,
11
+ createHmac,
12
+ createPrivateKey,
13
+ createPublicKey,
14
+ diffieHellman,
15
+ generateKeyPairSync,
16
+ hkdfSync,
17
+ randomBytes,
18
+ timingSafeEqual,
19
+ } from 'node:crypto'
20
+ import { b64u, sha256, unb64u } from './util.mjs'
21
+
22
+ export const PROTO_VERSION = 1
23
+ export const FRAME_VERSION = 1
24
+ export const FRAME_DATA = 1
25
+ export const FRAME_CONTROL = 2
26
+ export const FRAME_CLOSE = 3
27
+ export const KEY_LEN = 32
28
+ export const SID_LEN = 16
29
+ export const HEADER_LEN = 6
30
+ export const MAX_SEQ = 0xffffffff
31
+
32
+ const BIND_CONTEXT = 'dsh-remote/v1/bind'
33
+ const KEY_INFO_PREFIX = 'dsh-remote/v1/keys'
34
+
35
+ /** 生成长期(relay 身份)ECDH 密钥对,JWK 可直接落盘。 */
36
+ export function generateRelayIdentity() {
37
+ const { publicKey, privateKey } = generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
38
+ const pub = publicKey.export({ format: 'jwk' })
39
+ const priv = privateKey.export({ format: 'jwk' })
40
+ const spki = publicKey.export({ format: 'der', type: 'spki' })
41
+ const kid = sha256(spki).toString('hex').slice(0, 16)
42
+ return { kid, publicJwk: pub, privateJwk: priv, spki: b64u(spki), createdAt: Date.now() }
43
+ }
44
+
45
+ export function importPublicDer(derB64) {
46
+ return createPublicKey({ key: unb64u(derB64), format: 'der', type: 'spki' })
47
+ }
48
+
49
+ export function publicDerFromJwk(jwk) {
50
+ const key = createPublicKey({ key: jwk, format: 'jwk' })
51
+ return b64u(key.export({ format: 'der', type: 'spki' }))
52
+ }
53
+
54
+ /** 客户端公钥 DER(base64url) → 共享密钥(P-256,32 字节)。 */
55
+ export function sharedSecret(privateJwk, clientPubDerB64) {
56
+ const privateKey = createPrivateKey({ key: privateJwk, format: 'jwk' })
57
+ const publicKey = importPublicDer(clientPubDerB64)
58
+ return diffieHellman({ privateKey, publicKey })
59
+ }
60
+
61
+ export function deriveKeys({ secret, salt, kid, spk, cpk, sessionId }) {
62
+ const info = Buffer.concat([
63
+ Buffer.from(KEY_INFO_PREFIX),
64
+ Buffer.from([0]),
65
+ Buffer.from(kid, 'utf8'),
66
+ Buffer.from(unb64u(spk)),
67
+ Buffer.from(unb64u(cpk)),
68
+ Buffer.from(sessionId),
69
+ ])
70
+ const okm = Buffer.from(hkdfSync('sha256', secret, salt, info, KEY_LEN * 2))
71
+ return { c2s: okm.subarray(0, KEY_LEN), s2c: okm.subarray(KEY_LEN, KEY_LEN * 2) }
72
+ }
73
+
74
+ /** 客户端用 PSK 证明自己:HMAC(psk, "bind"|kid|spk|cpk|nonce)。 */
75
+ export function bindProof(psk, { kid, spk, cpk, nonce }) {
76
+ return createHmac('sha256', normalizePsk(psk))
77
+ .update(BIND_CONTEXT)
78
+ .update('\0')
79
+ .update(kid)
80
+ .update('\0')
81
+ .update(spk)
82
+ .update('\0')
83
+ .update(cpk)
84
+ .update('\0')
85
+ .update(unb64u(nonce))
86
+ .digest()
87
+ }
88
+
89
+ export function verifyBindProof(psk, fields) {
90
+ const expected = bindProof(psk, fields)
91
+ const given = fields.proof
92
+ if (!Buffer.isBuffer(given) || given.length !== expected.length) return false
93
+ return timingSafeEqual(expected, given)
94
+ }
95
+
96
+ export function normalizePsk(psk) {
97
+ if (Buffer.isBuffer(psk)) return psk
98
+ if (typeof psk === 'string') return unb64u(psk)
99
+ throw new TypeError('PSK 必须是 Buffer 或 base64url 字符串')
100
+ }
101
+
102
+ export function newSessionId() {
103
+ return randomBytes(SID_LEN)
104
+ }
105
+
106
+ function nonceFor(seq) {
107
+ const nonce = Buffer.alloc(12)
108
+ nonce.writeUInt32BE(0, 0)
109
+ nonce.writeUInt32BE(Math.floor(seq / 0x100000000) >>> 0, 4)
110
+ nonce.writeUInt32BE(seq >>> 0, 8)
111
+ return nonce
112
+ }
113
+
114
+ export function sealFrame({ key, sid, seq, type = FRAME_DATA, plaintext, aadExtra = null }) {
115
+ if (!Number.isInteger(seq) || seq < 0 || seq > MAX_SEQ) throw new RangeError(`非法序号 ${seq}`)
116
+ const header = Buffer.alloc(HEADER_LEN)
117
+ header[0] = FRAME_VERSION
118
+ header[1] = type
119
+ header.writeUInt32BE(seq, 2)
120
+ const aad = aadExtra ? Buffer.concat([header, sid, aadExtra]) : Buffer.concat([header, sid])
121
+ const cipher = createCipheriv('aes-256-gcm', key, nonceFor(seq), { authTagLength: 16 })
122
+ cipher.setAAD(aad)
123
+ const body = Buffer.concat([cipher.update(plaintext), cipher.final()])
124
+ return Buffer.concat([header, body, cipher.getAuthTag()])
125
+ }
126
+
127
+ export function openFrame({ key, sid, frame, aadExtra = null }) {
128
+ if (!Buffer.isBuffer(frame) || frame.length < HEADER_LEN + 16) throw new Error('帧长度非法')
129
+ if (frame[0] !== FRAME_VERSION) throw new Error(`帧版本不支持: ${frame[0]}`)
130
+ const type = frame[1]
131
+ const seq = frame.readUInt32BE(2)
132
+ const header = frame.subarray(0, HEADER_LEN)
133
+ const aad = aadExtra ? Buffer.concat([header, sid, aadExtra]) : Buffer.concat([header, sid])
134
+ const tag = frame.subarray(frame.length - 16)
135
+ const body = frame.subarray(HEADER_LEN, frame.length - 16)
136
+ const decipher = createDecipheriv('aes-256-gcm', key, nonceFor(seq), { authTagLength: 16 })
137
+ decipher.setAAD(aad)
138
+ decipher.setAuthTag(tag)
139
+ const plaintext = Buffer.concat([decipher.update(body), decipher.final()])
140
+ return { seq, type, plaintext }
141
+ }
142
+
143
+ /** 长度前缀(u32 BE)分帧,便于流式传输与浏览器端增量解析。 */
144
+ export function encodeLengthPrefixed(frame) {
145
+ const prefix = Buffer.alloc(4)
146
+ prefix.writeUInt32BE(frame.length, 0)
147
+ return Buffer.concat([prefix, frame])
148
+ }
149
+
150
+ export class FrameDecoder {
151
+ constructor({ maxFrameBytes = 262_144 } = {}) {
152
+ this.buffer = Buffer.alloc(0)
153
+ this.maxFrameBytes = maxFrameBytes
154
+ }
155
+
156
+ push(chunk) {
157
+ this.buffer = this.buffer.length === 0 ? Buffer.from(chunk) : Buffer.concat([this.buffer, chunk])
158
+ const frames = []
159
+ while (this.buffer.length >= 4) {
160
+ const length = this.buffer.readUInt32BE(0)
161
+ if (length > this.maxFrameBytes) throw new Error(`帧过大: ${length}`)
162
+ if (this.buffer.length < 4 + length) break
163
+ frames.push(this.buffer.subarray(4, 4 + length))
164
+ this.buffer = this.buffer.subarray(4 + length)
165
+ }
166
+ return frames
167
+ }
168
+ }
169
+
170
+ /**
171
+ * 序号重放窗口:允许乱序(HTTP 并发),拒绝重复与过旧帧。
172
+ */
173
+ export class ReplayWindow {
174
+ constructor(size = 1024) {
175
+ this.size = size
176
+ this.top = -1
177
+ this.bits = new Uint8Array(size)
178
+ }
179
+
180
+ /** 返回 true 表示可以接受,并同时登记。 */
181
+ accept(seq) {
182
+ if (!Number.isInteger(seq) || seq < 0) return false
183
+ if (this.top < 0) {
184
+ this.top = seq
185
+ this.bits.fill(0)
186
+ this.bits[0] = 1
187
+ return true
188
+ }
189
+ if (seq > this.top) {
190
+ const shift = seq - this.top
191
+ if (shift >= this.size) {
192
+ this.bits.fill(0)
193
+ } else {
194
+ this.bits.copyWithin(shift, 0, this.size - shift)
195
+ this.bits.fill(0, 0, shift)
196
+ }
197
+ this.top = seq
198
+ this.bits[0] = 1
199
+ return true
200
+ }
201
+ const index = this.top - seq
202
+ if (index >= this.size) return false
203
+ if (this.bits[index] === 1) return false
204
+ this.bits[index] = 1
205
+ return true
206
+ }
207
+
208
+ /** 仅检查不登记(解密失败时不要污染窗口)。 */
209
+ allows(seq) {
210
+ if (!Number.isInteger(seq) || seq < 0) return false
211
+ if (this.top < 0 || seq > this.top) return true
212
+ const index = this.top - seq
213
+ if (index >= this.size) return false
214
+ return this.bits[index] === 0
215
+ }
216
+ }
217
+
218
+ export function keyIdForJwk(jwk) {
219
+ return sha256(Buffer.from(`${jwk.x ?? ''}.${jwk.y ?? ''}`)).toString('hex').slice(0, 16)
220
+ }
@@ -0,0 +1,226 @@
1
+ /**
2
+ * 密钥环:relay 长期身份(ECDH P-256)+ 对外访问密钥(PSK)+ 兼容用明文 token。
3
+ *
4
+ * 轮换语义:
5
+ * - active PSK 到期前 rotate() 生成新 active;旧 PSK 进入 grace 窗口继续可验证;
6
+ * - grace 结束后旧 PSK 失效,已建立会话不受影响(会话密钥独立于 PSK);
7
+ * - 新 PSK 通过已加密的会话回传(会话内 renew 帧 + 响应元数据),浏览器自动续期。
8
+ */
9
+ import { join } from 'node:path'
10
+ import { statSync } from 'node:fs'
11
+ import { b64u, randomBytes, randomToken, readJson, safeEqual, writeJsonAtomic } from './util.mjs'
12
+ import { generateRelayIdentity, normalizePsk } from './crypto.mjs'
13
+
14
+ const ROTATE_HOURS = 12
15
+ const GRACE_MINUTES = 60
16
+
17
+ export class KeyRing {
18
+ constructor({ statePath, logger, rotateHours = ROTATE_HOURS, graceMinutes = GRACE_MINUTES, relayRotateHours = 24 }) {
19
+ this.statePath = statePath
20
+ this.logger = logger
21
+ this.rotateHours = rotateHours
22
+ this.graceMinutes = graceMinutes
23
+ this.relayRotateHours = relayRotateHours
24
+ this.state = this.#load()
25
+ this.stateMtimeMs = this.#stateMtime()
26
+ }
27
+
28
+ #stateMtime() {
29
+ try {
30
+ return statSync(this.statePath).mtimeMs
31
+ } catch {
32
+ return 0
33
+ }
34
+ }
35
+
36
+ /** 外部(CLI rotate)改动后重新装载,避免长驻进程覆盖。 */
37
+ reload() {
38
+ const mtime = this.#stateMtime()
39
+ if (mtime === this.stateMtimeMs) return false
40
+ this.state = this.#load()
41
+ this.stateMtimeMs = mtime
42
+ return true
43
+ }
44
+
45
+ #load() {
46
+ const raw = readJson(this.statePath, null)
47
+ if (raw && Array.isArray(raw.psks) && Array.isArray(raw.identities) && raw.identities.length > 0) {
48
+ return raw
49
+ }
50
+ const identity = generateRelayIdentity()
51
+ const state = { version: 1, identities: [identity], psks: [], legacy: [], createdAt: Date.now() }
52
+ const psk = this.#mintPsk(Date.now())
53
+ state.psks.push(psk)
54
+ writeJsonAtomic(this.statePath, state)
55
+ return state
56
+ }
57
+
58
+ #mintPsk(now) {
59
+ return {
60
+ kid: randomBytes(6).toString('hex'),
61
+ psk: randomToken(32),
62
+ createdAt: now,
63
+ expiresAt: now + this.rotateHours * 3_600_000,
64
+ graceUntil: null,
65
+ retiredAt: null,
66
+ }
67
+ }
68
+
69
+ save() {
70
+ writeJsonAtomic(this.statePath, this.state)
71
+ this.stateMtimeMs = this.#stateMtime()
72
+ }
73
+
74
+ get identity() {
75
+ return this.state.identities[this.state.identities.length - 1]
76
+ }
77
+
78
+ identityById(kid) {
79
+ return this.state.identities.find((item) => item.kid === kid) ?? null
80
+ }
81
+
82
+ /** 已停用但仍可用于握手(旧会话续期)的身份,保留一份。 */
83
+ identitiesForHandshake() {
84
+ return this.state.identities.slice(-2)
85
+ }
86
+
87
+ rotateRelayIdentityIfDue(now = Date.now()) {
88
+ const current = this.identity
89
+ if (now - current.createdAt < this.relayRotateHours * 3_600_000) return false
90
+ const next = generateRelayIdentity()
91
+ this.state.identities = [...this.state.identities.slice(-1), next]
92
+ this.save()
93
+ this.logger?.info?.('relay identity rotated', { kid: next.kid })
94
+ return true
95
+ }
96
+
97
+ activePsk() {
98
+ const now = Date.now()
99
+ return this.state.psks.find((item) => !item.retiredAt && item.expiresAt > now) ?? null
100
+ }
101
+
102
+ /** 需要主动续期(剩余寿命不足 1/4)时返回 true。 */
103
+ rotationDue(now = Date.now()) {
104
+ const active = this.activePsk()
105
+ if (!active) return true
106
+ const lifetime = active.expiresAt - active.createdAt
107
+ return now > active.expiresAt - lifetime / 4
108
+ }
109
+
110
+ rotatePsk(now = Date.now(), { force = false } = {}) {
111
+ const active = this.activePsk()
112
+ if (active && !force && !this.rotationDue(now)) return active
113
+ if (active) {
114
+ active.retiredAt = now
115
+ active.graceUntil = now + this.graceMinutes * 60_000
116
+ }
117
+ const next = this.#mintPsk(now)
118
+ this.state.psks.push(next)
119
+ // 只保留 active + grace 内的条目
120
+ this.state.psks = this.state.psks.filter((item) => !item.graceUntil || item.graceUntil > now)
121
+ this.save()
122
+ this.logger?.info?.('psk rotated', {
123
+ kid: next.kid,
124
+ retired: active?.kid ?? null,
125
+ graceUntil: active?.graceUntil ? new Date(active.graceUntil).toISOString() : null,
126
+ })
127
+ return next
128
+ }
129
+
130
+ /** 供绑定校验:active + grace 内的所有 PSK。 */
131
+ candidates(now = Date.now()) {
132
+ return this.state.psks.filter((item) => !item.retiredAt || (item.graceUntil ?? 0) > now)
133
+ }
134
+
135
+ findPskByValue(value) {
136
+ const normalized = normalizePsk(value)
137
+ for (const item of this.state.psks) {
138
+ if (safeEqual(normalized, normalizePsk(item.psk))) return item
139
+ }
140
+ return null
141
+ }
142
+
143
+ /** App 直连令牌:长期复用,避免每次打开弹窗都轮换导致已连接设备失效。 */
144
+ appToken(now = Date.now(), ttlDays = 30) {
145
+ const existing = this.state.legacy.find((item) => item.kind === 'app' && item.expiresAt > now)
146
+ if (existing) return existing.token
147
+ const token = randomToken(32)
148
+ this.state.legacy = this.state.legacy.filter((item) => item.expiresAt > now)
149
+ this.state.legacy.push({ kind: 'app', token, createdAt: now, expiresAt: now + ttlDays * 86_400_000 })
150
+ this.save()
151
+ return token
152
+ }
153
+
154
+ /** 轮换 App 直连令牌(旧令牌立即失效,已连接客户端需要重新扫码)。 */
155
+ rotateAppToken(now = Date.now(), ttlDays = 30) {
156
+ this.state.legacy = this.state.legacy.filter((item) => item.kind !== 'app')
157
+ const token = randomToken(32)
158
+ this.state.legacy.push({ kind: 'app', token, createdAt: now, expiresAt: now + ttlDays * 86_400_000 })
159
+ this.save()
160
+ return token
161
+ }
162
+
163
+ verifyAppToken(token, now = Date.now()) {
164
+ if (typeof token !== 'string' || token.length === 0) return false
165
+ return this.state.legacy.some(
166
+ (item) => item.kind === 'app' && item.expiresAt > now && safeEqual(Buffer.from(item.token), Buffer.from(token)),
167
+ )
168
+ }
169
+
170
+ issueLegacyToken(now = Date.now(), ttlHours = 24) {
171
+ const token = randomToken(32)
172
+ this.state.legacy.push({ token, createdAt: now, expiresAt: now + ttlHours * 3_600_000 })
173
+ this.state.legacy = this.state.legacy.filter((item) => item.expiresAt > now)
174
+ this.save()
175
+ return token
176
+ }
177
+
178
+ verifyLegacyToken(token, now = Date.now()) {
179
+ if (typeof token !== 'string' || token.length === 0) return false
180
+ return this.state.legacy.some((item) => item.expiresAt > now && safeEqual(Buffer.from(item.token), Buffer.from(token)))
181
+ }
182
+
183
+ /** 对外链接:密钥放在 fragment,浏览器不会把它发给 Cloudflare。 */
184
+ link(publicUrl) {
185
+ const base = String(publicUrl ?? '').replace(/\/+$/, '')
186
+ const active = this.activePsk()
187
+ return active ? `${base}/#k=${active.psk}` : `${base}/`
188
+ }
189
+
190
+ legacyLink(publicUrl) {
191
+ const base = String(publicUrl ?? '').replace(/\/+$/, '')
192
+ const token = this.issueLegacyToken()
193
+ return `${base}/?token=${token}`
194
+ }
195
+
196
+ /** 给 Android 客户端扫码用的明文握手链接(`?token=`)。 */
197
+ appLink(publicUrl) {
198
+ const base = String(publicUrl ?? '').replace(/\/+$/, '')
199
+ return `${base}/?token=${this.appToken()}`
200
+ }
201
+
202
+ describe() {
203
+ const active = this.activePsk()
204
+ return {
205
+ path: this.statePath,
206
+ relayKid: this.identity.kid,
207
+ pskKid: active?.kid ?? null,
208
+ pskExpiresAt: active ? new Date(active.expiresAt).toISOString() : null,
209
+ psks: this.state.psks.map((item) => ({
210
+ kid: item.kid,
211
+ createdAt: new Date(item.createdAt).toISOString(),
212
+ expiresAt: new Date(item.expiresAt).toISOString(),
213
+ graceUntil: item.graceUntil ? new Date(item.graceUntil).toISOString() : null,
214
+ })),
215
+ legacyTokens: this.state.legacy.length,
216
+ }
217
+ }
218
+ }
219
+
220
+ export function keyRingPath(stateDir) {
221
+ return join(stateDir, 'keyring.json')
222
+ }
223
+
224
+ export function pskFingerprint(psk) {
225
+ return b64u(Buffer.from(psk)).slice(0, 8)
226
+ }