dsh-remote-plugin 0.8.2 → 0.8.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.
Files changed (122) hide show
  1. package/README.md +1 -1
  2. package/apk/dsh-remote.apk +0 -0
  3. package/approval-summary.mjs +115 -0
  4. package/gateway.cjs +708 -70
  5. package/index.mjs +12 -0
  6. package/insights.mjs +6 -4
  7. package/market.mjs +4 -1
  8. package/package.json +2 -1
  9. package/plugin-center.mjs +208 -24
  10. package/plugin-transaction.mjs +29 -6
  11. package/public/admin.html +33 -34
  12. package/public/admin.js +12 -24
  13. package/public/announcements.json +31 -0
  14. package/public/app.js +99 -80
  15. package/public/approval-summary.js +78 -0
  16. package/public/build.json +2 -2
  17. package/public/cache-upgrade.js +51 -0
  18. package/public/chat-copy.js +59 -0
  19. package/public/desktop/desktop.css +23 -34
  20. package/public/desktop/desktop.html +83 -96
  21. package/public/desktop/desktop.js +68 -51
  22. package/public/e2ee-transport.js +147 -0
  23. package/public/extensions.js +6 -6
  24. package/public/history.js +88 -6
  25. package/public/image-cache.js +141 -0
  26. package/public/image-preview.js +48 -5
  27. package/public/index.html +86 -104
  28. package/public/md.js +39 -15
  29. package/public/motion.js +1 -1
  30. package/public/plugin-center.css +1 -0
  31. package/public/plugin-center.js +93 -12
  32. package/public/plugin.html +27 -20
  33. package/public/relay-devices.js +74 -0
  34. package/public/relay-settings.css +7 -0
  35. package/public/relay-settings.js +17 -9
  36. package/public/session-deck.css +7 -1
  37. package/public/session-deck.js +1 -1
  38. package/public/skins/blue-fish/DESIGN.md +24 -0
  39. package/public/skins/blue-fish/preview.html +12 -289
  40. package/public/skins/blue-fish/skin.css +95 -585
  41. package/public/skins/blue-fish/sparkles.svg +18 -0
  42. package/public/skins/bocchi/DESIGN.md +99 -0
  43. package/public/skins/bocchi/face.png +0 -0
  44. package/public/skins/bocchi/grain.png +0 -0
  45. package/public/skins/bocchi/icon-blush.png +0 -0
  46. package/public/skins/bocchi/icon-sleep.png +0 -0
  47. package/public/skins/bocchi/icon-smile.png +0 -0
  48. package/public/skins/bocchi/icon-star.png +0 -0
  49. package/public/skins/bocchi/icon-wink.png +0 -0
  50. package/public/skins/bocchi/icon.png +0 -0
  51. package/public/skins/bocchi/pattern-soft.png +0 -0
  52. package/public/skins/bocchi/pattern.png +0 -0
  53. package/public/skins/bocchi/preview.html +55 -0
  54. package/public/skins/bocchi/skin.css +233 -0
  55. package/public/skins/bocchi/stage-bg.png +0 -0
  56. package/public/skins/bocchi/stage-soft.png +0 -0
  57. package/public/skins/bocchi/stand.png +0 -0
  58. package/public/skins/bocchi/sticker-guitar.png +0 -0
  59. package/public/skins/kessoku/DESIGN.md +38 -0
  60. package/public/skins/kessoku/grain.png +0 -0
  61. package/public/skins/kessoku/skin.css +212 -0
  62. package/public/skins/kita/SOURCES.json +51 -0
  63. package/public/skins/kita/face.png +0 -0
  64. package/public/skins/kita/icon-live.png +0 -0
  65. package/public/skins/kita/icon-reddress.png +0 -0
  66. package/public/skins/kita/icon-seifuku.png +0 -0
  67. package/public/skins/kita/pattern.png +0 -0
  68. package/public/skins/kita/preview.html +56 -0
  69. package/public/skins/kita/skin.css +26 -0
  70. package/public/skins/kita/stand.png +0 -0
  71. package/public/skins/kita/sticker-live.png +0 -0
  72. package/public/skins/nijika/SOURCES.json +51 -0
  73. package/public/skins/nijika/face.png +0 -0
  74. package/public/skins/nijika/icon-live.png +0 -0
  75. package/public/skins/nijika/icon-reddress.png +0 -0
  76. package/public/skins/nijika/icon-seifuku.png +0 -0
  77. package/public/skins/nijika/pattern.png +0 -0
  78. package/public/skins/nijika/preview.html +56 -0
  79. package/public/skins/nijika/skin.css +25 -0
  80. package/public/skins/nijika/stand.png +0 -0
  81. package/public/skins/nijika/sticker-live.png +0 -0
  82. package/public/skins/penguin/DESIGN.md +33 -0
  83. package/public/skins/penguin/SOURCES.json +22 -0
  84. package/public/skins/penguin/aic-blueprint.svg +24 -0
  85. package/public/skins/penguin/endfield-triangles.svg +4 -0
  86. package/public/skins/penguin/face.png +0 -0
  87. package/public/skins/penguin/icon-blush.png +0 -0
  88. package/public/skins/penguin/icon-dizzy.png +0 -0
  89. package/public/skins/penguin/icon-laugh.png +0 -0
  90. package/public/skins/penguin/icon-sleep.png +0 -0
  91. package/public/skins/penguin/icon-smile.png +0 -0
  92. package/public/skins/penguin/icon-star.png +0 -0
  93. package/public/skins/penguin/icon-wink.png +0 -0
  94. package/public/skins/penguin/icon.png +0 -0
  95. package/public/skins/penguin/mascot.png +0 -0
  96. package/public/skins/penguin/pattern-night.png +0 -0
  97. package/public/skins/penguin/pattern.png +0 -0
  98. package/public/skins/penguin/preview.html +12 -0
  99. package/public/skins/penguin/skin.css +212 -0
  100. package/public/skins/ryo/SOURCES.json +51 -0
  101. package/public/skins/ryo/face.png +0 -0
  102. package/public/skins/ryo/icon-live.png +0 -0
  103. package/public/skins/ryo/icon-reddress.png +0 -0
  104. package/public/skins/ryo/icon-seifuku.png +0 -0
  105. package/public/skins/ryo/pattern.png +0 -0
  106. package/public/skins/ryo/preview.html +56 -0
  107. package/public/skins/ryo/skin.css +25 -0
  108. package/public/skins/ryo/stand.png +0 -0
  109. package/public/skins/ryo/sticker-live.png +0 -0
  110. package/public/sponsor-entry.js +21 -0
  111. package/public/styles.css +29 -19
  112. package/public/teams.js +2 -2
  113. package/public/theme-picker.css +58 -0
  114. package/public/theme-vars.css +532 -5
  115. package/public/theme.js +111 -3
  116. package/public/update.json +12 -12
  117. package/public/version.json +1 -1
  118. package/public/workflow.css +2 -1
  119. package/public/workflow.js +27 -5
  120. package/skills/dsh-remote-doctor/references/wiki/plugins.md +1 -1
  121. package/task-board.mjs +2 -2
  122. package/teams.mjs +7 -2
package/gateway.cjs CHANGED
@@ -65,7 +65,19 @@ function publicKey(value) {
65
65
  }
66
66
  const digest = value => crypto.createHash('sha256').update(value).digest('hex')
67
67
  const live = (grant, now = Date.now()) => grant && !grant.revokedAt && grant.expiresAt > now
68
- const signingText = (nonce, id, role, session = '') => Buffer.from(JSON.stringify(['dsh-relay-v1', nonce, id, role, session]))
68
+ const signingText = (nonce, id, role, session = '', e2ee) => Buffer.from(JSON.stringify(
69
+ e2ee ? ['dsh-relay-e2ee-v1', nonce, id, role, session, e2ee.routeTokenHash, e2ee.policy, ...(e2ee.allowPlain === undefined ? [] : [e2ee.allowPlain]), ...(e2ee.devices === undefined ? [] : [e2ee.devices.map(d => [d.id, d.routeTokenHash, d.expiresAt])])] : ['dsh-relay-v1', nonce, id, role, session]))
70
+ function issueInState(state, { label = '', domain, expiresAt, plan } = {}) {
71
+ if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
72
+ const id = crypto.randomBytes(8).toString('hex')
73
+ const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
74
+ if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
75
+ if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
76
+ const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
77
+ const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt, createdAt: Date.now(), codeHash: digest(code), publicKey: null, revokedAt: null, ...(plan ? { plan } : {}) }
78
+ state.grants.push(grant)
79
+ return { code, grant }
80
+ }
69
81
 
70
82
  class Registry {
71
83
  constructor(file) { this.file = path.resolve(file) }
@@ -83,8 +95,10 @@ class Registry {
83
95
  const result = fn(state)
84
96
  const temp = this.file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp'
85
97
  try {
86
- fs.writeFileSync(temp, JSON.stringify(state, null, 2) + '\n', { mode: 0o600, flag: 'wx' })
98
+ const output = fs.openSync(temp, 'wx', 0o600)
99
+ try { fs.writeFileSync(output, JSON.stringify(state, null, 2) + '\n'); fs.fsyncSync(output) } finally { fs.closeSync(output) }
87
100
  fs.renameSync(temp, this.file)
101
+ if (process.platform !== 'win32') { const dir = fs.openSync(path.dirname(this.file), 'r'); try { fs.fsyncSync(dir) } finally { fs.closeSync(dir) } }
88
102
  } finally { try { fs.unlinkSync(temp) } catch {} }
89
103
  return result
90
104
  } finally { fs.closeSync(fd); fs.unlinkSync(lock) }
@@ -105,14 +119,9 @@ class Registry {
105
119
  const expires = Number(expiresAt)
106
120
  if (!Number.isFinite(expires) || expires <= Date.now() || expires > Date.now() + 90 * 86400000) throw fault('INVALID_EXPIRY')
107
121
  return this.change(state => {
108
- if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
109
- const id = crypto.randomBytes(8).toString('hex')
110
- const assigned = hostname(domain || `r-${id}.${state.baseDomain}`)
111
- if (!assigned.endsWith('.' + state.baseDomain) || assigned === new URL(state.origin).hostname || assigned === state.tunnelHost) throw fault('INVALID_TENANT_DOMAIN')
112
- if (state.grants.some(g => g.domain === assigned)) throw fault('DOMAIN_ALREADY_ASSIGNED', 409)
113
- const code = `dsrp_${id}.${crypto.randomBytes(32).toString('base64url')}`
114
- const grant = { id, label: String(label).slice(0, 80), domain: assigned, expiresAt: expires, createdAt: Date.now(), codeHash: digest(code), publicKey: null, revokedAt: null }
115
- state.grants.push(grant)
122
+ const reserved = (state.sponsorship?.applications || []).filter(a => a.status === 'submitted' || a.status === 'draft' && a.reservedUntil > Date.now()).length
123
+ if (state.grants.filter(g => live(g)).length + reserved >= state.maxUsers) throw fault('PILOT_FULL', 409)
124
+ const { code, grant } = issueInState(state, { label, domain, expiresAt: expires })
116
125
  return { code, grant: this.view(grant) }
117
126
  })
118
127
  }
@@ -135,13 +144,13 @@ class Registry {
135
144
  if (!live(grant) || !crypto.timingSafeEqual(Buffer.from(grant.codeHash, 'hex'), Buffer.from(digest(code), 'hex'))) throw fault('INVALID_AUTHORIZATION', 403)
136
145
  if (grant.publicKey && grant.publicKey !== normalized) throw fault('HOST_ALREADY_BOUND', 409)
137
146
  grant.publicKey = normalized
138
- return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, dailyLimitBytes: 5_000_000_000, timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
147
+ return { grantId: grant.id, domain: grant.domain, expiresAt: grant.expiresAt, publicUrl: `https://${grant.domain}`, ...(grant.plan === 'sponsor-basic' ? { quotaPeriod: 'month', monthlyLimitBytes: 5_000_000_000, fileTransfer: false } : { dailyLimitBytes: 5_000_000_000 }), timezone: 'Asia/Shanghai', transport: 'https-upgrade', tunnelOrigin: state.origin, tunnelHost: state.tunnelHost, tunnelPort: state.tunnelPort }
139
148
  })
140
149
  }
141
150
  get(id) { return this.read().grants.find(g => g.id === id) }
142
151
  }
143
152
 
144
- module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText }
153
+ module.exports = { Registry, fault, hostname, publicKey, digest, live, signingText, issueInState }
145
154
  },
146
155
  "./wire.cjs": function(require, module, exports) {
147
156
  'use strict'
@@ -258,12 +267,14 @@ function upgradeChannel(origin, ca) {
258
267
  }
259
268
 
260
269
  class RelayClient extends EventEmitter {
261
- constructor({ grantId, privateKey, tunnelHost, tunnelPort, tunnelOrigin, expiresAt, gateway = 'http://127.0.0.1:8787', ca, poolSize = 4, reconnectMs = 1500 }) {
270
+ constructor({ grantId, privateKey, tunnelHost, tunnelPort, tunnelOrigin, expiresAt, gateway = 'http://127.0.0.1:8787', ca, poolSize = 4, reconnectMs = 1500, e2ee }) {
262
271
  super()
263
272
  if (!/^[a-f0-9]{16}$/.test(grantId || '') || !Number.isInteger(Number(tunnelPort)) || tunnelPort < 1 || tunnelPort > 65535 || !Number.isFinite(expiresAt)) throw fault('INVALID_CLIENT_CONFIG')
264
273
  this.grantId = grantId; this.privateKey = crypto.createPrivateKey(privateKey)
265
274
  if (this.privateKey.asymmetricKeyType !== 'ed25519') throw fault('INVALID_PRIVATE_KEY')
266
275
  this.target = gatewayAddress(gateway)
276
+ this.e2ee = e2ee
277
+ if (e2ee && (!/^[a-f0-9]{64}$/.test(e2ee.routeTokenHash || '') || !['standard', 'sponsor-basic'].includes(e2ee.policy) || typeof e2ee.accept !== 'function')) throw fault('INVALID_E2EE_CONFIG')
267
278
  this.tunnelHost = tunnelHost; this.tunnelPort = Number(tunnelPort); this.expiresAt = expiresAt; this.ca = ca
268
279
  this.tunnelOrigin = tunnelOrigin
269
280
  this.poolSize = Math.min(6, Math.max(1, poolSize)); this.reconnectMs = reconnectMs
@@ -277,8 +288,9 @@ class RelayClient extends EventEmitter {
277
288
  try {
278
289
  const challenge = await line(socket)
279
290
  if (challenge.type !== 'challenge' || !/^[A-Za-z0-9_-]{43}$/.test(challenge.nonce || '')) throw fault('INVALID_CHALLENGE')
280
- const signature = crypto.sign(null, signingText(challenge.nonce, this.grantId, role, session), this.privateKey).toString('base64url')
281
- send(socket, { grantId: this.grantId, role, session, signature })
291
+ const capability = role === 'control' && this.e2ee ? { routeTokenHash: this.e2ee.routeTokenHash, policy: this.e2ee.policy, ...(this.e2ee.allowPlain === true ? { allowPlain: true } : {}), ...(this.e2ee.devices ? { devices: this.e2ee.devices } : {}) } : undefined
292
+ const signature = crypto.sign(null, signingText(challenge.nonce, this.grantId, role, session, capability), this.privateKey).toString('base64url')
293
+ send(socket, { grantId: this.grantId, role, session, signature, ...(capability ? { e2ee: capability } : {}) })
282
294
  const accepted = await line(socket)
283
295
  if (accepted.type === 'rejected' && accepted.code === 'AUTHORIZATION_INACTIVE') throw fault('AUTHORIZATION_INACTIVE', 403)
284
296
  if (!this.running || Date.now() >= this.expiresAt || accepted.type !== (role === 'control' ? 'accepted' : 'parked')) throw fault('CONNECTION_NOT_ACCEPTED')
@@ -296,6 +308,7 @@ class RelayClient extends EventEmitter {
296
308
  if (epoch !== this.epoch) { socket.destroy(); return }
297
309
  context = { socket, session: accepted.session, sockets: new Set([socket]), pending: 0, closing: false, retryTimer: null }
298
310
  this.context = context; this.failures = 0
311
+ if (this.e2ee && accepted.e2ee !== true) throw fault('E2EE_BROKER_UNSUPPORTED')
299
312
  if (accepted.usage) this.emit('usage', accepted.usage)
300
313
  this.emit('status', 'online'); this.refill(context)
301
314
  while (this.running && !context.closing) {
@@ -331,7 +344,21 @@ class RelayClient extends EventEmitter {
331
344
  if (start.type !== 'start' || context.closing || this.context !== context) throw fault('STALE_WORK')
332
345
  context.pending--; pending = false
333
346
  this.refill(context)
347
+ if (start.transport === 'relay-plain-v1') {
348
+ if (!this.e2ee?.allowPlain || typeof this.e2ee.acceptPlain !== 'function') throw fault('PLAIN_RELAY_NOT_SUPPORTED')
349
+ this.e2ee.acceptPlain(remote)
350
+ await new Promise(resolve => remote.once('close', resolve))
351
+ return
352
+ }
353
+ if (start.transport === 'e2ee-v1') {
354
+ if (!this.e2ee) throw fault('E2EE_NOT_CONFIGURED')
355
+ this.e2ee.accept(remote)
356
+ await new Promise(resolve => remote.once('close', resolve))
357
+ return
358
+ }
359
+ if (start.transport !== undefined || this.e2ee) throw fault('E2EE_TRANSPORT_REQUIRED')
334
360
  local = net.connect(this.target); context.sockets.add(local)
361
+ require('./gateway-sockets.cjs').track(local)
335
362
  local.setNoDelay(true)
336
363
  const connectTimer = setTimeout(() => local.destroy(), 5000)
337
364
  local.once('connect', () => clearTimeout(connectTimer))
@@ -408,6 +435,507 @@ async function main() {
408
435
  if (require.main === module) main().catch(error => { console.error(error.code || 'CLIENT_FAILED'); process.exitCode = 1 })
409
436
  module.exports = { RelayClient, enroll, gatewayAddress }
410
437
  },
438
+ "./e2ee-channel.cjs": function(require, module, exports) {
439
+ 'use strict'
440
+
441
+ // Native-client inner TLS. Never send application bytes before connectPinned resolves.
442
+ // TLS implements key agreement, AEAD records and sequence numbers (RFC 8446).
443
+ const tls = require('node:tls')
444
+ const { Duplex } = require('node:stream')
445
+ const { X509Certificate, createHash, timingSafeEqual } = require('node:crypto')
446
+
447
+ const PROTOCOL = 'dsh-remote-native-tls13-prototype-v1'
448
+ const DEVICE_PROTOCOL = 'dsh-remote-native-tls13-v2'
449
+ const fingerprint = raw => createHash('sha256').update(raw).digest('hex')
450
+ const fault = code => Object.assign(new Error(code), { code })
451
+
452
+ // Call ONLY with a certificate obtained directly from the owner's host through
453
+ // a trusted local pairing step. Fetching it from the relay defeats pinning.
454
+ function createPairing(certificate, hostname) {
455
+ if (typeof certificate !== 'string' || certificate.length > 8192
456
+ || (certificate.match(/-----BEGIN CERTIFICATE-----/g) || []).length !== 1
457
+ || typeof hostname !== 'string' || !/^[a-z0-9](?:[a-z0-9.-]{0,251}[a-z0-9])?$/i.test(hostname)) {
458
+ throw fault('INVALID_E2EE_PAIRING')
459
+ }
460
+ let cert
461
+ try { cert = new X509Certificate(certificate) } catch { throw fault('INVALID_E2EE_CERTIFICATE') }
462
+ if (tls.checkServerIdentity(hostname, cert.toLegacyObject())) throw fault('E2EE_HOSTNAME_MISMATCH')
463
+ return Object.freeze({ protocol: PROTOCOL, hostname, certificate: cert.toString(), fingerprint: fingerprint(cert.raw) })
464
+ }
465
+
466
+ function validatePairing(value) {
467
+ if (!value || ![PROTOCOL,DEVICE_PROTOCOL].includes(value.protocol) || typeof value.fingerprint !== 'string'
468
+ || !/^[a-f0-9]{64}$/.test(value.fingerprint)) throw fault('INVALID_E2EE_PAIRING')
469
+ // Snapshot inputs before opening a connection. No trust-on-first-use or pin refresh.
470
+ const pair = createPairing(value.certificate, value.hostname)
471
+ if (!timingSafeEqual(Buffer.from(pair.fingerprint, 'hex'), Buffer.from(value.fingerprint, 'hex'))) {
472
+ throw fault('E2EE_PIN_MISMATCH')
473
+ }
474
+ if(value.protocol===DEVICE_PROTOCOL){
475
+ if(!/^[a-f0-9]{32}$/.test(value.deviceId||'')||!/^[A-Za-z0-9_-]{43}$/.test(value.deviceSecret||'')||!Number.isFinite(value.expiresAt)||value.expiresAt<=Date.now())throw fault('INVALID_E2EE_DEVICE_PAIRING')
476
+ return Object.freeze({...pair,protocol:DEVICE_PROTOCOL,deviceId:value.deviceId,deviceSecret:value.deviceSecret,expiresAt:value.expiresAt})
477
+ }
478
+ return pair
479
+ }
480
+
481
+ // The supplied Duplex carries ONLY inner TLS records. For example, it may be an
482
+ // already authenticated outer HTTPS Upgrade tunnel; no token is sent outside it.
483
+ // Resolve only after CA, name, version and exact certificate checks succeed.
484
+ function connectPinned({ socket, pairing, timeoutMs = 10000 }) {
485
+ return new Promise((resolve, reject) => {
486
+ let pair
487
+ try {
488
+ pair = validatePairing(pairing)
489
+ if (!(socket instanceof Duplex)
490
+ || socket.destroyed || !Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 30000) {
491
+ throw fault('INVALID_E2EE_TRANSPORT')
492
+ }
493
+ } catch (error) { socket?.destroy?.(); reject(error); return }
494
+
495
+ let channel, settled = false
496
+ const fail = error => {
497
+ if (!settled) { settled = true; clearTimeout(timer); reject(error) }
498
+ channel?.destroy()
499
+ socket.destroy()
500
+ }
501
+ const closed = () => { if (!settled) fail(fault('E2EE_CHANNEL_CLOSED')); else channel?.destroy() }
502
+ const transportError = error => { if (!settled) fail(error); else channel?.destroy(error) }
503
+ const timer = setTimeout(() => fail(fault('E2EE_HANDSHAKE_TIMEOUT')), timeoutMs)
504
+ socket.on('error', transportError)
505
+ socket.once('close', closed)
506
+ try {
507
+ channel = tls.connect({
508
+ socket, servername: pair.hostname, ca: pair.certificate,
509
+ rejectUnauthorized: true, minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3',
510
+ ALPNProtocols: ['http/1.1'],
511
+ // Never supply a cached session or early data. Each connect reauthenticates.
512
+ checkServerIdentity(host, cert) {
513
+ const error = tls.checkServerIdentity(host, cert)
514
+ if (error) return error
515
+ if (!cert.raw || fingerprint(cert.raw) !== pair.fingerprint) return fault('E2EE_PIN_MISMATCH')
516
+ },
517
+ })
518
+ channel.on('error', error => { if (!settled) fail(error) })
519
+ channel.once('close', () => {
520
+ if (!settled) fail(fault('E2EE_CHANNEL_CLOSED'))
521
+ clearTimeout(timer)
522
+ socket.off('error', transportError)
523
+ socket.off('close', closed)
524
+ socket.destroy()
525
+ })
526
+ channel.once('secureConnect', () => {
527
+ if (settled) return
528
+ const cert = channel.getPeerCertificate()
529
+ if (!channel.authorized || channel.getProtocol() !== 'TLSv1.3' || channel.isSessionReused()
530
+ || !cert.raw || fingerprint(cert.raw) !== pair.fingerprint) return fail(fault('E2EE_PEER_REJECTED'))
531
+ clearTimeout(timer); settled = true; resolve(channel)
532
+ })
533
+ } catch (error) { fail(error) }
534
+ })
535
+ }
536
+
537
+ module.exports = { createPairing, validatePairing, connectPinned, DEVICE_PROTOCOL }
538
+ },
539
+ "./e2ee-identity.cjs": function(require, module, exports) {
540
+ 'use strict'
541
+ const crypto = require('node:crypto')
542
+ const fs = require('node:fs')
543
+ const path = require('node:path')
544
+ const { spawnSync } = require('node:child_process')
545
+ const { createPairing } = require('./e2ee-channel.cjs')
546
+ const { fault } = require('./registry.cjs')
547
+ const HOSTNAME = 'dsh-remote-e2ee.local'
548
+
549
+ // DER for one self-signed X.509 v3 identity. Signing and verification use native
550
+ // node:crypto. This implements a certificate encoding, not a cipher/protocol.
551
+ function der(tag, ...parts) {
552
+ const value = Buffer.concat(parts), length = value.length
553
+ const size = length < 128 ? Buffer.from([length]) : length < 256 ? Buffer.from([0x81, length]) : Buffer.from([0x82, length >> 8, length & 255])
554
+ return Buffer.concat([Buffer.from([tag]), size, value])
555
+ }
556
+ const seq = (...parts) => der(0x30, ...parts)
557
+ const oid = hex => der(6, Buffer.from(hex, 'hex'))
558
+ const bit = bytes => der(3, Buffer.from([0]), bytes)
559
+ const extension = (id, value, critical = false) => seq(oid(id), ...(critical ? [Buffer.from([1, 1, 255])] : []), der(4, value))
560
+ function generateIdentity(now = Date.now()) {
561
+ const pair = crypto.generateKeyPairSync('ec', { namedCurve: 'prime256v1' })
562
+ const algorithm = seq(oid('2a8648ce3d040302')) // ecdsa-with-SHA256
563
+ const name = seq(der(0x31, seq(oid('550403'), der(12, Buffer.from(HOSTNAME)))))
564
+ const time = value => {
565
+ const date = new Date(value), stamp = date.toISOString().replace(/[-:T]/g, '').replace(/\.\d{3}Z$/, 'Z')
566
+ return date.getUTCFullYear() >= 1950 && date.getUTCFullYear() < 2050 ? der(23, Buffer.from(stamp.slice(2))) : der(24, Buffer.from(stamp))
567
+ }
568
+ const serial = crypto.randomBytes(16); serial[0] &= 0x7f; serial[0] ||= 1
569
+ const tbs = seq(der(0xa0, der(2, Buffer.from([2]))), der(2, serial), algorithm, name,
570
+ seq(time(now - 300000), time(now + 365 * 86400000)), name,
571
+ pair.publicKey.export({ format: 'der', type: 'spki' }),
572
+ der(0xa3, seq(extension('551d13', seq(), true),
573
+ extension('551d0f', der(3, Buffer.from([7, 0x80])), true),
574
+ extension('551d25', seq(oid('2b06010505070301'))),
575
+ extension('551d11', seq(der(0x82, Buffer.from(HOSTNAME)))))))
576
+ const bytes = seq(tbs, algorithm, bit(crypto.sign('sha256', tbs, pair.privateKey)))
577
+ const certificate = '-----BEGIN CERTIFICATE-----\n' + bytes.toString('base64').match(/.{1,64}/g).join('\n') + '\n-----END CERTIFICATE-----\n'
578
+ const parsed = new crypto.X509Certificate(certificate)
579
+ if (!parsed.verify(pair.publicKey)) throw fault('E2EE_IDENTITY_INVALID')
580
+ return { certificate, privateKey: pair.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString(), routeToken: crypto.randomBytes(32).toString('base64url') }
581
+ }
582
+ function validateIdentity(value) {
583
+ if (!value || !/^[A-Za-z0-9_-]{43}$/.test(value.routeToken || '')) throw fault('E2EE_IDENTITY_INVALID')
584
+ const cert = new crypto.X509Certificate(value.certificate), key = crypto.createPrivateKey(value.privateKey)
585
+ const now = Date.now(), from = Date.parse(cert.validFrom), to = Date.parse(cert.validTo)
586
+ if (!Number.isFinite(from) || !Number.isFinite(to) || !cert.checkPrivateKey(key) || !cert.verify(cert.publicKey) || now < from || now >= to) throw fault('E2EE_IDENTITY_INVALID')
587
+ createPairing(value.certificate, HOSTNAME)
588
+ return value
589
+ }
590
+ function privateDirectory(root) {
591
+ const dir = path.join(root, 'e2ee'), file = path.join(dir, 'identity.json')
592
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
593
+ if (fs.lstatSync(dir).isSymbolicLink() || fs.existsSync(file) && fs.lstatSync(file).isSymbolicLink()) throw fault('E2EE_IDENTITY_INVALID')
594
+ if (process.platform === 'win32') {
595
+ // Apply before writing secrets. An ACL failure is fatal, never a warning.
596
+ const script = "$ErrorActionPreference='Stop'; $acl=New-Object System.Security.AccessControl.DirectorySecurity; $acl.SetAccessRuleProtection($true,$false); $owner=[System.Security.Principal.WindowsIdentity]::GetCurrent().User; $acl.SetOwner($owner); foreach($sid in @($owner,(New-Object System.Security.Principal.SecurityIdentifier('S-1-5-18')))) { $rule=New-Object System.Security.AccessControl.FileSystemAccessRule($sid,'FullControl','ContainerInherit,ObjectInherit','None','Allow'); $acl.AddAccessRule($rule) }; [System.IO.Directory]::SetAccessControl($env:DSH_E2EE_PRIVATE_DIRECTORY,$acl)"
597
+ const result = spawnSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-EncodedCommand', Buffer.from(script, 'utf16le').toString('base64')], {
598
+ env: { ...process.env, DSH_E2EE_PRIVATE_DIRECTORY: dir }, windowsHide: true, stdio: 'pipe', timeout: 10000,
599
+ })
600
+ if (result.status !== 0) throw fault('E2EE_PRIVATE_DIRECTORY_UNAVAILABLE', 503)
601
+ } else fs.chmodSync(dir, 0o700)
602
+ return {dir, file}
603
+ }
604
+ function rotateIdentity(root) {
605
+ const {file,dir} = privateDirectory(root), value = generateIdentity()
606
+ const temp = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp'
607
+ try { fs.writeFileSync(temp, JSON.stringify(value) + '\n', {flag:'wx',mode:0o600}); fs.renameSync(temp,file) }
608
+ finally { fs.rmSync(temp,{force:true}) }
609
+ // An interruption before this reset makes the mismatched store fail closed.
610
+ const pairing = createPairing(value.certificate, HOSTNAME)
611
+ const store = path.join(dir,'devices.json'), pending = store + '.reset.tmp'
612
+ try { fs.writeFileSync(pending, JSON.stringify({schema:1,fingerprint:pairing.fingerprint,devices:[]})+'\n',{flag:'wx',mode:0o600}); fs.renameSync(pending,store) }
613
+ finally { fs.rmSync(pending,{force:true}) }
614
+ fs.rmSync(path.join(dir,'pairing.json'),{force:true})
615
+ return value
616
+ }
617
+ function loadIdentity(root) {
618
+ const {file} = privateDirectory(root)
619
+ if (fs.existsSync(file)) return validateIdentity(JSON.parse(fs.readFileSync(file, 'utf8')))
620
+ const value = generateIdentity(), temp = file + '.' + crypto.randomBytes(8).toString('hex') + '.tmp'
621
+ try {
622
+ fs.writeFileSync(temp, JSON.stringify(value) + '\n', { flag: 'wx', mode: 0o600 })
623
+ // Exclusive link avoids replacing an identity generated by another process.
624
+ try { fs.linkSync(temp, file) } catch (error) { if (error.code !== 'EEXIST') throw error }
625
+ } finally { fs.rmSync(temp, { force: true }) }
626
+ return validateIdentity(JSON.parse(fs.readFileSync(file, 'utf8')))
627
+ }
628
+ module.exports = { HOSTNAME, generateIdentity, validateIdentity, loadIdentity, rotateIdentity }
629
+ },
630
+ "./e2ee-devices.cjs": function(require, module, exports) {
631
+ 'use strict'
632
+ const fs=require('node:fs'),path=require('node:path'),crypto=require('node:crypto')
633
+ const {fault}=require('./registry.cjs')
634
+ const {createPairing,DEVICE_PROTOCOL}=require('./e2ee-channel.cjs')
635
+ const {HOSTNAME}=require('./e2ee-identity.cjs')
636
+ const hash=value=>crypto.createHash('sha256').update(value).digest('hex')
637
+ const ID=/^[a-f0-9]{32}$/,HASH=/^[a-f0-9]{64}$/
638
+ class DeviceStore{
639
+ constructor(root,identity){
640
+ this.file=path.join(root,'e2ee','devices.json')
641
+ this.identity=identity;this.fingerprint=createPairing(identity.certificate,HOSTNAME).fingerprint
642
+ if(fs.existsSync(this.file)){
643
+ const stat=fs.lstatSync(this.file)
644
+ if(stat.isSymbolicLink()||!stat.isFile()||stat.size>256*1024)throw fault('E2EE_DEVICE_STATE_INVALID')
645
+ try{this.state=JSON.parse(fs.readFileSync(this.file,'utf8'))}catch{throw fault('E2EE_DEVICE_STATE_INVALID')}
646
+ if(this.state?.schema!==1||this.state.fingerprint!==this.fingerprint||!Array.isArray(this.state.devices)
647
+ ||this.state.devices.length>64||this.state.devices.some(d=>!ID.test(d?.id||'')||!HASH.test(d?.routeTokenHash||'')||!HASH.test(d?.secretHash||'')||!Number.isFinite(d.expiresAt)||!Number.isFinite(d.createdAt)||d.revokedAt!==null&&!Number.isFinite(d.revokedAt)||typeof d.label!=='string'||!d.label.trim()||d.label.length>80||/[\x00-\x1f]/.test(d.label))
648
+ ||new Set(this.state.devices.map(d=>d.id)).size!==this.state.devices.length)throw fault('E2EE_DEVICE_STATE_INVALID')
649
+ }else this.save({schema:1,fingerprint:this.fingerprint,devices:[]})
650
+ }
651
+ save(state){
652
+ const temp=this.file+'.'+crypto.randomBytes(8).toString('hex')+'.tmp'
653
+ try{fs.writeFileSync(temp,JSON.stringify(state)+'\n',{mode:0o600,flag:'wx'});fs.renameSync(temp,this.file);this.state=state}
654
+ finally{fs.rmSync(temp,{force:true})}
655
+ }
656
+ active(id){const d=this.state.devices.find(d=>d.id===id);return d&&!d.revokedAt&&d.expiresAt>Date.now()?d:null}
657
+ list(){return this.state.devices.map(({id,label,createdAt,expiresAt,revokedAt})=>({id,label,createdAt,expiresAt,revokedAt:revokedAt||null,active:!!this.active(id)}))}
658
+ routes(){return this.state.devices.filter(d=>this.active(d.id)).map(({id,routeTokenHash,expiresAt})=>({id,routeTokenHash,expiresAt})).sort((a,b)=>a.id.localeCompare(b.id))}
659
+ create({label,expiresAt,publicUrl}){
660
+ if(typeof label!=='string'||!label.trim()||label.length>80||/[\x00-\x1f]/.test(label)||!Number.isFinite(expiresAt)||expiresAt<=Date.now()||expiresAt>Date.now()+366*86400000)throw fault('INVALID_DEVICE')
661
+ if(this.routes().length>=32)throw fault('E2EE_DEVICE_LIMIT',409)
662
+ const origin=new URL(publicUrl);if(origin.protocol!=='https:'||origin.username||origin.password)throw fault('INVALID_DEVICE')
663
+ const id=crypto.randomBytes(16).toString('hex'),routeToken=crypto.randomBytes(32).toString('base64url'),deviceSecret=crypto.randomBytes(32).toString('base64url')
664
+ const record={id,label:label.trim(),routeTokenHash:hash(routeToken),secretHash:hash(deviceSecret),createdAt:Date.now(),expiresAt,revokedAt:null}
665
+ const retained=this.state.devices.filter(d=>this.active(d.id)).concat(this.state.devices.filter(d=>!this.active(d.id)).slice(-31))
666
+ this.save({...this.state,devices:[...retained,record]})
667
+ const certificate=new crypto.X509Certificate(this.identity.certificate)
668
+ return {device:{id,label:record.label,expiresAt},pairing:{...createPairing(this.identity.certificate,HOSTNAME),protocol:DEVICE_PROTOCOL,
669
+ relayUrl:new URL('/relay/v1/e2ee',origin).href,routeToken,deviceId:id,deviceSecret,expiresAt,
670
+ publicKeyHash:hash(certificate.publicKey.export({type:'spki',format:'der'})),label:record.label}}
671
+ }
672
+ revoke(id){
673
+ if(!ID.test(id||'')||!this.state.devices.some(d=>d.id===id))throw fault('DEVICE_NOT_FOUND',404)
674
+ this.save({...this.state,devices:this.state.devices.map(d=>d.id===id?{...d,revokedAt:d.revokedAt||Date.now()}:d)})
675
+ }
676
+ authorize(value){
677
+ const match=/^([a-f0-9]{32})\.([A-Za-z0-9_-]{43})$/.exec(String(value||''))
678
+ const device=match&&this.active(match[1])
679
+ if(!device||!crypto.timingSafeEqual(Buffer.from(hash(match[2]),'hex'),Buffer.from(device.secretHash,'hex')))throw fault('RELAY_DEVICE_UNAUTHORIZED',403)
680
+ return device.id
681
+ }
682
+ }
683
+ module.exports={DeviceStore}
684
+ },
685
+ "./gateway-sockets.cjs": function(require, module, exports) {
686
+ 'use strict'
687
+ // Record actual TCP provenance, rather than trusting forwarded headers or Host.
688
+ const ports = new Set()
689
+ function track(socket) {
690
+ const register = () => {
691
+ const port = socket.localPort
692
+ if (!port || socket.destroyed) return
693
+ ports.add(port); socket.once('close', () => ports.delete(port))
694
+ }
695
+ if (socket.connecting) socket.once('connect', register); else register()
696
+ }
697
+ function contains(req) { return ports.has(req.socket.remotePort) }
698
+ module.exports = { track, contains }
699
+ },
700
+ "./e2ee-endpoint.cjs": function(require, module, exports) {
701
+ 'use strict'
702
+ const http = require('node:http')
703
+ const https = require('node:https')
704
+ const { headersOf } = require('./http-headers.cjs')
705
+ const { basicPolicy, basicBody, imageResponse } = require('./basic-policy.cjs')
706
+ const { link } = require('./wire.cjs')
707
+ const { fault } = require('./registry.cjs')
708
+ const { FileRate } = require('./file-rate.cjs')
709
+
710
+ // Attached only to authenticated reverse work streams, never a listening port.
711
+ // Access authentication remains owned by the real local gateway.
712
+ class E2eeEndpoint {
713
+ constructor({ identity, target, policy, expiresAt, devices }) {
714
+ if (!['standard', 'sponsor-basic'].includes(policy) || !Number.isFinite(expiresAt)) throw fault('E2EE_POLICY_REQUIRED')
715
+ this.policy = policy; this.expiresAt = expiresAt; this.sockets = new Set(); this.active = 0; this.buffered = 0; this.files = 0
716
+ this.devices = devices
717
+ this.expiryTimer = setInterval(() => {
718
+ for (const socket of this.sockets) if (Date.now() >= this.expiresAt || socket.deviceId && !this.devices?.active(socket.deviceId)) socket.destroy()
719
+ }, 1000); this.expiryTimer.unref()
720
+ this.server = https.createServer({ cert: identity.certificate, key: identity.privateKey,
721
+ minVersion: 'TLSv1.3', maxVersion: 'TLSv1.3', handshakeTimeout: 10000,
722
+ ALPNProtocols: ['http/1.1'] }, (req, res) => this.proxy(req, res))
723
+ this.target = target
724
+ this.server.headersTimeout = 15000; this.server.requestTimeout = 120000
725
+ this.server.maxHeadersCount = 100
726
+ this.server.on('secureConnection', socket => this.track(socket))
727
+ this.server.on('tlsClientError', (_, socket) => socket.destroy())
728
+ this.server.on('upgrade', (req, socket, head) => this.upgrade(req, socket, head))
729
+ this.plainServer = http.createServer((req, res) => this.proxy(req, res))
730
+ this.plainServer.headersTimeout = 15000; this.plainServer.requestTimeout = 120000; this.plainServer.maxHeadersCount = 100
731
+ this.plainServer.on('upgrade', (req, socket, head) => this.upgrade(req, socket, head))
732
+ }
733
+ track(socket) { this.sockets.add(socket); socket.on('error', () => {}); socket.once('close', () => this.sockets.delete(socket)) }
734
+ accept(socket) {
735
+ if (Date.now() >= this.expiresAt || this.sockets.size >= 64) return socket.destroy()
736
+ this.track(socket); this.server.emit('connection', socket); socket.resume()
737
+ }
738
+ acceptPlain(socket) {
739
+ if (Date.now() >= this.expiresAt || this.sockets.size >= 64) return socket.destroy()
740
+ this.track(socket); this.plainServer.emit('connection', socket); socket.resume()
741
+ }
742
+ check(req, upgrade = false) {
743
+ if (!req.url.startsWith('/') || req.url.startsWith('//')) throw fault('INVALID_REQUEST_TARGET')
744
+ if (Date.now() >= this.expiresAt) throw fault('AUTHORIZATION_INACTIVE', 403)
745
+ if (this.devices) req.socket.deviceId = this.devices.authorize(req.headers['x-dsh-relay-device'])
746
+ if (this.active >= 16) throw fault('HOST_BUSY', 503)
747
+ if (this.policy !== 'sponsor-basic') return null
748
+ const mode = basicPolicy(req)
749
+ if (upgrade && (mode || req.method !== 'GET' || !/^\/api\/events\.(?:mux|host)(?:\?|$)/.test(req.url))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
750
+ return mode
751
+ }
752
+ request(req, upgrade) {
753
+ // target is parsed once by gatewayAddress(), never chosen by the request.
754
+ const headers = headersOf(req.headers, upgrade)
755
+ delete headers['x-dsh-relay-device']
756
+ const request = http.request({ ...this.target, method: req.method, path: req.url, headers, agent: false })
757
+ request.on('socket', socket => require('./gateway-sockets.cjs').track(socket))
758
+ request.setTimeout(120000, () => request.destroy())
759
+ return request
760
+ }
761
+ async proxy(req, res) {
762
+ let request, counted = false, buffered = false, file = false, upload, download
763
+ const release = () => {
764
+ if (counted) { counted = false; this.active-- }; if (buffered) { buffered = false; this.buffered-- }
765
+ if (file) { file = false; this.files-- }; upload?.destroy(); download?.destroy()
766
+ }
767
+ const fail = error => {
768
+ release()
769
+ if (res.headersSent) return res.destroy()
770
+ res.writeHead(error.status || 503, { 'content-type': 'application/json', 'cache-control': 'no-store' })
771
+ res.end(JSON.stringify({ error: error.code || 'HOST_CONNECTION_LOST' }))
772
+ }
773
+ try {
774
+ const mode = this.check(req)
775
+ const pathname = new URL(req.url, 'http://relay.invalid').pathname
776
+ if (!mode && (pathname === '/fs' || pathname.startsWith('/fs/'))) {
777
+ if (this.files >= 2) throw fault('FILE_TRANSFER_BUSY', 429)
778
+ this.files++; file = true
779
+ }
780
+ if (this.policy === 'sponsor-basic' && (mode || req.method === 'POST' && req.url.startsWith('/api/'))) {
781
+ if (this.buffered >= 4) throw fault('HOST_BUSY', 503)
782
+ this.buffered++; buffered = true
783
+ }
784
+ this.active++; counted = true
785
+ res.once('close', release); res.once('finish', release)
786
+ const body = this.policy === 'sponsor-basic' ? await basicBody(req) : null
787
+ if (res.destroyed || req.aborted) { release(); return }
788
+ request = this.request(req, false)
789
+ req.once('aborted', () => request.destroy()); res.once('close', () => request.destroy())
790
+ request.on('error', fail)
791
+ request.on('response', response => {
792
+ if (res.destroyed) return response.destroy()
793
+ if (mode) { void imageResponse(response, res, mode); return }
794
+ res.writeHead(response.statusCode, headersOf(response.headers))
795
+ response.on('error', () => res.destroy())
796
+ if (file) {
797
+ download = new FileRate(102400); download.on('error', () => res.destroy()); response.pipe(download).pipe(res)
798
+ } else response.pipe(res)
799
+ })
800
+ if (body) request.end(body)
801
+ else if (file) {
802
+ upload = new FileRate(102400); upload.on('error', () => request.destroy()); req.pipe(upload).pipe(request)
803
+ } else req.pipe(request)
804
+ } catch (error) { request?.destroy(); fail(error) }
805
+ }
806
+ upgrade(req, socket, head) {
807
+ let request, counted = false
808
+ const release = () => { if (counted) { counted = false; this.active-- } }
809
+ const fail = error => {
810
+ request?.destroy(); release()
811
+ if (!socket.destroyed) socket.end(`HTTP/1.1 ${error.status || 503} Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`)
812
+ }
813
+ try {
814
+ if (String(req.headers.upgrade).toLowerCase() !== 'websocket' || req.method !== 'GET') throw fault('INVALID_UPGRADE')
815
+ this.check(req, true); this.active++; counted = true
816
+ socket.once('close', () => { release(); request?.destroy() })
817
+ request = this.request(req, true); request.on('error', fail)
818
+ request.on('response', response => {
819
+ socket.write(`HTTP/1.1 ${response.statusCode} Rejected\r\n` + Object.entries(headersOf(response.headers)).map(([k,v]) => `${k}: ${v}\r\n`).join('') + '\r\n')
820
+ response.on('error', () => socket.destroy()); response.pipe(socket)
821
+ })
822
+ request.on('upgrade', (response, remote, remoteHead) => {
823
+ if (socket.destroyed) return remote.destroy()
824
+ socket.write('HTTP/1.1 101 Switching Protocols\r\n' + Object.entries(headersOf(response.headers, true)).map(([k,v]) => `${k}: ${v}\r\n`).join('') + '\r\n')
825
+ if (head.length) remote.write(head)
826
+ if (remoteHead.length) socket.write(remoteHead)
827
+ link(socket, remote)
828
+ })
829
+ request.end()
830
+ } catch (error) { fail(error) }
831
+ }
832
+ close() { clearInterval(this.expiryTimer); for (const socket of this.sockets) socket.destroy(); this.server.close(); this.plainServer.close() }
833
+ }
834
+ module.exports = { E2eeEndpoint }
835
+ },
836
+ "./http-headers.cjs": function(require, module, exports) {
837
+ 'use strict'
838
+ const HOP = new Set(['connection', 'keep-alive', 'proxy-authenticate', 'proxy-authorization', 'te', 'trailer', 'transfer-encoding', 'upgrade'])
839
+ function headersOf(input, upgrade = false) {
840
+ const denied = new Set([...HOP, ...String(input.connection || '').toLowerCase().split(',').map(s => s.trim())])
841
+ const out = {}
842
+ for (const [key, value] of Object.entries(input)) if (!denied.has(key.toLowerCase()) && value !== undefined) out[key] = value
843
+ if (upgrade) { out.connection = 'Upgrade'; out.upgrade = 'websocket' }
844
+ else out.connection = 'close'
845
+ return out
846
+ }
847
+ module.exports = { headersOf }
848
+ },
849
+ "./file-rate.cjs": function(require, module, exports) {
850
+ 'use strict'
851
+ const { Transform } = require('node:stream')
852
+ class FileRate extends Transform {
853
+ constructor(rate) {
854
+ super(); this.rate = rate; this.nextAt = 0; this.timer = null
855
+ this.once('close', () => clearTimeout(this.timer))
856
+ }
857
+ _transform(chunk, encoding, done) {
858
+ let offset = 0
859
+ const step = () => {
860
+ if (this.destroyed) return
861
+ const wait = this.nextAt - performance.now()
862
+ if (wait > 1) { this.timer = setTimeout(step, wait); return }
863
+ const end = Math.min(offset + 16384, chunk.length)
864
+ this.push(chunk.subarray(offset, end))
865
+ this.nextAt = Math.max(performance.now(), this.nextAt) + (end - offset) / this.rate * 1000
866
+ offset = end
867
+ if (offset === chunk.length) done()
868
+ else step()
869
+ }
870
+ step()
871
+ }
872
+ }
873
+
874
+ module.exports = { FileRate }
875
+ },
876
+ "./basic-policy.cjs": function(require, module, exports) {
877
+ 'use strict'
878
+ const { fault } = require('./registry.cjs')
879
+ const IMAGE = /^image\/(?:png|jpeg|gif|webp)$/
880
+ const IMAGE_MAX = 12 * 1024 * 1024
881
+ function basicPolicy(req) {
882
+ const url = new URL(req.url, 'http://relay.invalid')
883
+ let route
884
+ try { route = decodeURIComponent(url.pathname).replace(/\/+$/, '') } catch { throw fault('INVALID_PATH') }
885
+ if (/[\\%]/.test(route)) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
886
+ if (route === '/fs/file' && ['GET', 'HEAD'].includes(req.method)
887
+ && url.searchParams.getAll('path').length === 1 && /\.(?:png|jpe?g|gif|webp)$/i.test(url.searchParams.get('path')) && !req.headers.range) return 'image'
888
+ if (route === '/fs' || route.startsWith('/fs/') || /^\/(?:remote\/)?(?:admin\/)?api\/(?:session-file|file-inbox)(?:\/|$)/.test(route)
889
+ || /^\/api\/(?:session[./]export|attachments?(?:[./]|$)|files?(?:[./]|$))/.test(route)) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
890
+ if (route === '/api/session.attachment') return 'attachment'
891
+ return null
892
+ }
893
+ async function imageResponse(response, res, mode) {
894
+ const deny = () => {
895
+ response.destroy()
896
+ if (res.headersSent) return res.destroy()
897
+ res.writeHead(403, { 'content-type': 'application/json', 'cache-control': 'no-store' })
898
+ res.end(JSON.stringify({ error: 'FILE_TRANSFER_NOT_ALLOWED', message: '基础中转不支持文件传输,仅允许对话图片预览。' }))
899
+ }
900
+ // Buffer only bounded image responses. No arbitrary file bytes reach the browser first.
901
+ try {
902
+ const parts = []; let size = 0
903
+ const max = mode === 'attachment' ? Math.ceil(IMAGE_MAX / 3) * 4 + 16384 : IMAGE_MAX
904
+ if (Number(response.headers['content-length']) > max || response.headers['content-encoding']) return deny()
905
+ if (response.statusCode === 304) { res.writeHead(304, { 'cache-control': 'no-cache' }); res.end(); return }
906
+ if (mode === 'image' && !IMAGE.test(String(response.headers['content-type'] || '').split(';')[0])) return deny()
907
+ for await (const chunk of response) { size += chunk.length; if (size > max) return deny(); parts.push(chunk) }
908
+ const data = Buffer.concat(parts)
909
+ if (mode === 'attachment') {
910
+ const envelope = JSON.parse(data.toString('utf8')), value = envelope?.result?.value
911
+ if (envelope?.result?.ok !== true || !IMAGE.test(value?.attachment?.mediaType || '') || typeof value?.data !== 'string' || !/^[A-Za-z0-9+/]+={0,2}$/.test(value.data)) return deny()
912
+ if (!imageMagic(Buffer.from(value.data, 'base64'), value.attachment.mediaType)) return deny()
913
+ } else if (!imageMagic(data, String(response.headers['content-type']).split(';')[0]) && data.length) return deny()
914
+ res.writeHead(response.statusCode, { 'content-type': mode === 'attachment' ? 'application/json' : response.headers['content-type'], 'cache-control': 'private, no-cache', 'x-content-type-options': 'nosniff', ...(response.headers.etag ? { etag: response.headers.etag } : {}) })
915
+ res.end(data)
916
+ } catch { deny() }
917
+ }
918
+ function imageMagic(bytes, type) {
919
+ if (type === 'image/png') return bytes.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))
920
+ if (type === 'image/jpeg') return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255
921
+ if (type === 'image/gif') return /^GIF8[79]a$/.test(bytes.subarray(0, 6).toString())
922
+ return type === 'image/webp' && bytes.subarray(0, 4).toString() === 'RIFF' && bytes.subarray(8, 12).toString() === 'WEBP'
923
+ }
924
+ async function basicBody(req) {
925
+ const url = new URL(req.url, 'http://relay.invalid')
926
+ if (req.method !== 'POST' || !url.pathname.startsWith('/api/')) return null
927
+ const parts = []; let size = 0
928
+ for await (const chunk of req) { size += chunk.length; if (size > 16 * 1024 * 1024) throw fault('BODY_TOO_LARGE', 413); parts.push(chunk) }
929
+ const raw = Buffer.concat(parts)
930
+ let value
931
+ try { value = JSON.parse(raw.toString('utf8')) } catch { throw fault('INVALID_JSON') }
932
+ if (value?.type === 'client-request' && value.method !== decodeURIComponent(url.pathname.slice(5))) throw fault('RPC_ROUTE_MISMATCH', 403)
933
+ // The operations endpoint must not be used to tunnel a file/attachment request.
934
+ if (url.pathname === '/api/operations' && /^(?:session[./](?:attachment|export)|files?[./])/.test(String(value?.method))) throw fault('FILE_TRANSFER_NOT_ALLOWED', 403)
935
+ return raw
936
+ }
937
+ module.exports = { basicPolicy, imageResponse, basicBody }
938
+ },
411
939
  "./host.cjs": function(require, module, exports) {
412
940
  'use strict'
413
941
  const fs = require('node:fs')
@@ -415,20 +943,26 @@ const path = require('node:path')
415
943
  const crypto = require('node:crypto')
416
944
  const { RelayClient, enroll } = require('./client.cjs')
417
945
  const { fault } = require('./registry.cjs')
946
+ const { loadIdentity, HOSTNAME } = require('./e2ee-identity.cjs')
947
+ const { createPairing } = require('./e2ee-channel.cjs')
948
+ const { E2eeEndpoint } = require('./e2ee-endpoint.cjs')
949
+ const { DeviceStore } = require('./e2ee-devices.cjs')
418
950
  const DEFAULT_ORIGIN = 'https://relay-pilot.blankalwaysgoeson.site'
419
951
 
420
952
  // Runs inside the gateway process: no launcher, scheduled task or runtime install.
421
953
  class RelayHost {
422
- constructor({ root, gateway, origin = DEFAULT_ORIGIN, ca }) {
954
+ constructor({ root, gateway, origin = DEFAULT_ORIGIN, ca, e2eeEnabled }) {
423
955
  this.root = root; this.gateway = gateway; this.origin = origin; this.ca = ca
424
956
  this.file = path.join(root, 'connection.json'); this.keyFile = path.join(root, 'host-private.pem')
425
957
  this.legacyRoot = path.join(path.dirname(root), 'owner-preview')
426
958
  this.client = null; this.phase = 'disabled'; this.daily = null; this.updatedAt = null; this.busy = false
427
959
  this.config = null; this.error = ''
960
+ this.e2eeOverride = e2eeEnabled; this.endpoint = null; this.e2eeFingerprint = ''; this.devices = null
428
961
  if (fs.existsSync(this.file)) {
429
962
  try { this.config = JSON.parse(fs.readFileSync(this.file, 'utf8')) }
430
963
  catch { this.phase = 'error'; this.error = 'LOCAL_STATE_INVALID' }
431
964
  }
965
+ this.e2eeEnabled = e2eeEnabled ?? (this.config?.e2eeEnabled === true)
432
966
  }
433
967
  save(config) {
434
968
  fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
@@ -447,6 +981,9 @@ class RelayHost {
447
981
  publicUrl: config?.publicUrl || '', expiresAt: config?.expiresAt || null,
448
982
  fingerprint: config?.fingerprint || '', daily: this.daily, usageUpdatedAt: this.updatedAt,
449
983
  quotaPending: !!config?.enabled && !this.daily, error: this.error,
984
+ quotaPeriod: config?.quotaPeriod || 'day', fileTransfer: config?.fileTransfer !== false,
985
+ monthlyLimitBytes: config?.monthlyLimitBytes || null,
986
+ e2ee: { enabled: this.e2eeEnabled, configured: !!this.endpoint, fingerprint: this.e2eeFingerprint, deviceCount: this.devices?.routes().length || 0 },
450
987
  server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy() }
451
988
  }
452
989
  legacy() {
@@ -467,7 +1004,24 @@ class RelayHost {
467
1004
  if (this.config.expiresAt <= Date.now()) { this.phase = 'expired'; return }
468
1005
  // Only the operator-configured service is allowed, never a target supplied by a browser.
469
1006
  if (this.config.tunnelOrigin !== this.origin) throw fault('RELAY_SERVER_MISMATCH', 409)
470
- const client = new RelayClient({ ...this.config, gateway: this.gateway, privateKey: fs.readFileSync(this.keyFile), ca: this.ca })
1007
+ this.e2eeEnabled = this.e2eeOverride ?? (this.config.e2eeEnabled === true)
1008
+ let e2ee
1009
+ if (this.e2eeEnabled) {
1010
+ const identity = loadIdentity(this.root)
1011
+ this.devices = new DeviceStore(this.root, identity)
1012
+ const policy = this.config.quotaPeriod === 'month' && this.config.fileTransfer === false ? 'sponsor-basic'
1013
+ : this.config.quotaPeriod !== 'month' && Number(this.config.dailyLimitBytes) > 0 ? 'standard' : null
1014
+ if (!policy) throw fault('E2EE_POLICY_REQUIRED')
1015
+ const { gatewayAddress } = require('./client.cjs')
1016
+ this.endpoint = new E2eeEndpoint({ identity, target: gatewayAddress(this.gateway), policy, expiresAt: this.config.expiresAt, devices: this.devices })
1017
+ const endpoint = this.endpoint
1018
+ e2ee = { routeTokenHash: crypto.createHash('sha256').update(identity.routeToken).digest('hex'), devices: this.devices.routes(), policy, allowPlain: true, accept: socket => endpoint.accept(socket), acceptPlain: socket => endpoint.acceptPlain(socket) }
1019
+ const pairing = createPairing(identity.certificate, HOSTNAME)
1020
+ this.e2eeFingerprint = pairing.fingerprint
1021
+ // Shared prototype credentials are no longer usable or exported.
1022
+ fs.rmSync(path.join(this.root, 'e2ee', 'pairing.json'), {force:true})
1023
+ }
1024
+ const client = new RelayClient({ ...this.config, gateway: this.gateway, privateKey: fs.readFileSync(this.keyFile), ca: this.ca, e2ee })
471
1025
  this.client = client; this.phase = 'connecting'; this.error = ''
472
1026
  client.on('status', status => { if (this.client === client) this.phase = status })
473
1027
  client.on('usage', daily => {
@@ -476,7 +1030,44 @@ class RelayHost {
476
1030
  })
477
1031
  client.start()
478
1032
  }
479
- stop() { const client = this.client; this.client = null; client?.stop(); this.phase = 'disabled' }
1033
+ stop() { const client = this.client; this.client = null; client?.stop(); this.endpoint?.close(); this.endpoint = null; this.phase = 'disabled' }
1034
+ isRelayRequest(req) { return require('./gateway-sockets.cjs').contains(req) }
1035
+ deviceStatus() { return { ...this.status(), devices: this.devices?.list() || [] } }
1036
+ async changeDevice(value) {
1037
+ if (this.busy) throw fault('RELAY_OPERATION_BUSY',409)
1038
+ if (!this.config) throw fault('HOST_NOT_CONFIGURED',409)
1039
+ if (this.e2eeOverride === false && ['enable-encryption','rotate-identity'].includes(value.action)) throw fault('E2EE_DISABLED_BY_POLICY',409)
1040
+ this.busy = true
1041
+ try {
1042
+ if (value.action === 'enable-encryption') {
1043
+ this.e2eeOverride = undefined
1044
+ this.save({...this.config,e2eeEnabled:true})
1045
+ } else if (value.action === 'rotate-identity') {
1046
+ if (value.confirm !== 'REPAIR_ALL_DEVICES') throw fault('E2EE_CONFIRMATION_REQUIRED')
1047
+ this.stop(); require('./e2ee-identity.cjs').rotateIdentity(this.root)
1048
+ this.devices = null; this.e2eeFingerprint = ''; this.e2eeOverride = undefined
1049
+ this.save({...this.config,e2eeEnabled:true})
1050
+ } else {
1051
+ if (!this.e2eeEnabled || !this.devices) throw fault('E2EE_NOT_CONFIGURED',409)
1052
+ if (value.action === 'create-device') {
1053
+ const days = Number(value.days)
1054
+ if (!Number.isInteger(days) || days < 1 || days > 30) throw fault('INVALID_DEVICE')
1055
+ const identity = loadIdentity(this.root)
1056
+ const expiresAt = Math.min(this.config.expiresAt, Date.parse(new crypto.X509Certificate(identity.certificate).validTo), Date.now()+days*86400000)
1057
+ const result = this.devices.create({label:value.label,expiresAt,publicUrl:this.config.publicUrl})
1058
+ if (this.config.enabled) this.start()
1059
+ return {...this.deviceStatus(),...result}
1060
+ } else if (value.action === 'revoke-device') this.devices.revoke(value.id)
1061
+ else throw fault('INVALID_RELAY_ACTION')
1062
+ }
1063
+ if (this.config.enabled) this.start()
1064
+ else if (this.config.e2eeEnabled) {
1065
+ const identity=loadIdentity(this.root);this.devices=new DeviceStore(this.root,identity)
1066
+ this.e2eeEnabled=true;this.e2eeFingerprint=createPairing(identity.certificate,HOSTNAME).fingerprint
1067
+ }
1068
+ return this.deviceStatus()
1069
+ } finally {this.busy=false}
1070
+ }
480
1071
  async change(action, key) {
481
1072
  if (this.busy) throw fault('RELAY_OPERATION_BUSY', 409)
482
1073
  this.busy = true
@@ -512,7 +1103,8 @@ class RelayHost {
512
1103
  // Construct before replacing a working configuration; a malformed response cannot disable it.
513
1104
  new RelayClient({ ...config, gateway: this.gateway, privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }), ca: this.ca })
514
1105
  if (config.tunnelOrigin !== this.origin || new URL(config.publicUrl).protocol !== 'https:') throw fault('INVALID_SERVER_RESPONSE', 502)
515
- this.save({ ...config, fingerprint: crypto.createHash('sha256').update(publicKey).digest('hex'), enabled: true })
1106
+ this.save({ ...config, fingerprint: crypto.createHash('sha256').update(publicKey).digest('hex'), enabled: true,
1107
+ e2eeEnabled: this.e2eeOverride ?? (this.config ? this.e2eeEnabled : true) })
516
1108
  this.daily = null; this.updatedAt = null; this.start()
517
1109
  } else if (action === 'enable') {
518
1110
  if (!this.config) throw fault('HOST_NOT_CONFIGURED', 409)
@@ -521,7 +1113,8 @@ class RelayHost {
521
1113
  if (this.config) this.save({ ...this.config, enabled: false })
522
1114
  // Allow the setting response to cross the tunnel before closing it.
523
1115
  const client = this.client; this.client = null; this.phase = 'disabled'
524
- const timer = setTimeout(() => client?.stop(), 250); timer.unref?.()
1116
+ const endpoint = this.endpoint; this.endpoint = null
1117
+ const timer = setTimeout(() => { client?.stop(); endpoint?.close() }, 250); timer.unref?.()
525
1118
  } else throw fault('INVALID_RELAY_ACTION', 400)
526
1119
  return this.status()
527
1120
  } finally { this.busy = false }
@@ -946,6 +1539,7 @@ const relayHost = new embeddedRelayHost.RelayHost({
946
1539
  gateway: `http://127.0.0.1:${PORT}`,
947
1540
  origin: process.env.DSH_REMOTE_RELAY_ORIGIN || embeddedRelayHost.DEFAULT_ORIGIN,
948
1541
  ca: process.env.DSH_REMOTE_RELAY_CA_FILE ? fs.readFileSync(process.env.DSH_REMOTE_RELAY_CA_FILE) : undefined,
1542
+ e2eeEnabled: process.env.DSH_REMOTE_RELAY_E2EE === undefined ? undefined : process.env.DSH_REMOTE_RELAY_E2EE === '1',
949
1543
  })
950
1544
 
951
1545
  function durationEnv(name, fallback, min, max) {
@@ -1985,7 +2579,8 @@ function cors(res, req = res.req) {
1985
2579
  }
1986
2580
  if (allowed) res.setHeader('access-control-allow-origin', origin || '*')
1987
2581
  res.setHeader('vary', 'Origin')
1988
- res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id, x-dsh-remote-inbox-key')
2582
+ res.setHeader('access-control-allow-headers', 'authorization, content-type, x-dsh-remote-client, x-dsh-remote-client-id, x-dsh-remote-inbox-key, if-none-match, if-modified-since')
2583
+ res.setHeader('access-control-expose-headers', 'etag, last-modified')
1989
2584
  res.setHeader('access-control-allow-methods', 'GET, POST, OPTIONS')
1990
2585
  res.setHeader('access-control-max-age', '600')
1991
2586
  }
@@ -2032,6 +2627,16 @@ function withRequestBody(req, res, limit, callback) {
2032
2627
  })
2033
2628
  }
2034
2629
 
2630
+ async function readResponseText(response, maxBytes) {
2631
+ const chunks = []; let bytes = 0
2632
+ for await (const chunk of response.body) {
2633
+ bytes += chunk.length
2634
+ if (bytes > maxBytes) throw Object.assign(new Error('response too large'), { status: 413 })
2635
+ chunks.push(chunk)
2636
+ }
2637
+ return Buffer.concat(chunks).toString('utf8')
2638
+ }
2639
+
2035
2640
  function execFileResult(file, args, timeout = 5000) {
2036
2641
  return new Promise((resolvePromise) => {
2037
2642
  execFile(file, args, { timeout, windowsHide: true }, (error, stdout, stderr) => {
@@ -2862,7 +3467,7 @@ async function serveDshControl(req, res, url) {
2862
3467
  // 阻断时改走 GET /api/events.poll 增量拉取。
2863
3468
  const EVENT_BUFFER_MAX = durationEnv('GATEWAY_EVENT_BUFFER_MAX', 1000, 100, 10000)
2864
3469
  const EVENT_POLL_WAIT_MAX = durationEnv('GATEWAY_EVENT_POLL_WAIT_MS', 25000, 0, 60000)
2865
- const EVENT_MAX_STRING = 16 * 1024
3470
+ const EVENT_BUFFER_MAX_BYTES = durationEnv('GATEWAY_EVENT_BUFFER_MAX_BYTES', 8 * 1024 * 1024, 65536, 64 * 1024 * 1024)
2866
3471
  const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
2867
3472
  const eventBuffers = { mux: [], host: [] }
2868
3473
  const eventNextSeq = { mux: 1, host: 1 }
@@ -3294,21 +3899,6 @@ async function translateModernRpc(method, payload, rpcId, strictReceipt = false)
3294
3899
  return legacyEnvelope(rpcId, { ok: true, value: transform(response.body.result.value) })
3295
3900
  }
3296
3901
 
3297
- /** 递归截断超大字段,避免单条超大事件撑爆环形缓冲。 */
3298
- function truncateEventValue(v, depth = 0) {
3299
- if (typeof v === 'string') return v.length > EVENT_MAX_STRING ? v.slice(0, EVENT_MAX_STRING) + '…[truncated]' : v
3300
- if (Array.isArray(v)) {
3301
- if (depth > 3 || v.length > 200) return v.slice(0, 200)
3302
- return v.map(x => truncateEventValue(x, depth + 1))
3303
- }
3304
- if (v && typeof v === 'object' && depth <= 3) {
3305
- const out = {}
3306
- for (const k of Object.keys(v)) out[k] = truncateEventValue(v[k], depth + 1)
3307
- return out
3308
- }
3309
- return v
3310
- }
3311
-
3312
3902
  function wsAccept(key) {
3313
3903
  return crypto.createHash('sha1').update(String(key || '') + WS_GUID).digest('base64')
3314
3904
  }
@@ -3382,8 +3972,12 @@ function pushEvent(kind, full, raw = JSON.stringify(full)) {
3382
3972
  }
3383
3973
  if (eventCollectorState[kind]) eventCollectorState[kind].lastEventAt = Date.now()
3384
3974
  const buf = eventBuffers[kind]
3385
- buf.push({ seq: eventNextSeq[kind]++, ts: Date.now(), event: truncateEventValue(full) })
3386
- if (buf.length > EVENT_BUFFER_MAX) buf.shift()
3975
+ const size = Buffer.byteLength(raw), record = { seq: eventNextSeq[kind]++, ts: Date.now(), event: JSON.parse(raw) }
3976
+ Object.defineProperty(record, 'bytes', { value: size })
3977
+ buf.push(record); buf.retainedBytes = (buf.retainedBytes || 0) + size
3978
+ // Evict whole records, never alter message content. Keep the newest complete
3979
+ // event even if it alone exceeds the target budget; cursor gaps trigger reset.
3980
+ while (buf.length > 1 && (buf.length > EVENT_BUFFER_MAX || buf.retainedBytes > EVENT_BUFFER_MAX_BYTES)) buf.retainedBytes -= buf.shift().bytes
3387
3981
  rememberCollectorReplay(kind, full, raw)
3388
3982
  broadcastCollectorFrame(kind, raw)
3389
3983
  flushEventPollWaiters(kind)
@@ -4188,6 +4782,9 @@ function serveStats(req, res, url) {
4188
4782
  // ---------- 反馈提交 ----------
4189
4783
  const feedbackThrottle = new Map() // ip -> 上次受理时间戳
4190
4784
  const FEEDBACK_WINDOW_MS = 60 * 1000
4785
+ // A full diagnostic upload can outlast the former eight-second budget on Funnel.
4786
+ // Share one deadline with the explicit legacy-size fallback; never retry timeouts.
4787
+ const FEEDBACK_FORWARD_TIMEOUT_MS = 30 * 1000
4191
4788
  // 反馈收集器: 环境变量可覆盖, 默认使用 Tailscale Funnel 提供的公网 HTTPS
4192
4789
  // 入口。这里是公开的 ts.net 域名,不要求提交反馈的用户加入 tailnet。
4193
4790
  const FEEDBACK_URL = process.env.DSH_REMOTE_FEEDBACK_URL || 'https://vm-0-2-ubuntu.tail1f6fc4.ts.net/submit'
@@ -4259,8 +4856,8 @@ async function loadCentralAnnouncements(force = false) {
4259
4856
  }
4260
4857
  if (!res.ok) throw new Error(`central announcements HTTP ${res.status}`)
4261
4858
  const declared = Number(res.headers.get('content-length') || 0)
4262
- if (declared > ANNOUNCEMENTS_MAX_BYTES) throw new Error('announcements too large')
4263
- const raw = await res.text()
4859
+ if (declared > ANNOUNCEMENTS_MAX_BYTES) { await res.body?.cancel(); throw new Error('announcements too large') }
4860
+ const raw = await readResponseText(res, ANNOUNCEMENTS_MAX_BYTES)
4264
4861
  const parsed = parseAnnouncements(raw)
4265
4862
  announcementsCache = {
4266
4863
  ...parsed,
@@ -4554,7 +5151,7 @@ function serveFeedback(req, res, url) {
4554
5151
  }
4555
5152
  touchDevice(req)
4556
5153
 
4557
- withRequestBody(req, res, 96 * 1024, async body => {
5154
+ withRequestBody(req, res, 256 * 1024, async body => {
4558
5155
  let payload
4559
5156
  try {
4560
5157
  payload = JSON.parse(body || '{}')
@@ -4602,9 +5199,10 @@ function serveFeedback(req, res, url) {
4602
5199
  res.end(JSON.stringify({ error: 'message required' }))
4603
5200
  return
4604
5201
  }
4605
- if (message.length > 2000) {
5202
+ const messageLimit = type === 'poll' ? 2000 : 20000
5203
+ if (message.length > messageLimit) {
4606
5204
  res.writeHead(400, { 'content-type': 'application/json; charset=utf-8' })
4607
- res.end(JSON.stringify({ error: 'message too long', max: 2000 }))
5205
+ res.end(JSON.stringify({ error: 'message too long', max: messageLimit }))
4608
5206
  return
4609
5207
  }
4610
5208
  if (contact.length > 200) {
@@ -4637,7 +5235,8 @@ function serveFeedback(req, res, url) {
4637
5235
  ...(includeDiagnostics ? {serverInfo:feedbackDiagnosticSummary(clientDiagnostics,gatewayDiagnostics,crashes)} : crashes?{serverInfo:JSON.stringify(crashes)}:{}),
4638
5236
  ...(pollVote || {})
4639
5237
  }
4640
- const send=body=>fetch(FEEDBACK_URL,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(8000)})
5238
+ const deadline = Date.now() + FEEDBACK_FORWARD_TIMEOUT_MS
5239
+ const send=body=>fetch(FEEDBACK_URL,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body),signal:AbortSignal.timeout(Math.max(1, deadline - Date.now()))})
4641
5240
  send(outbound).then(async (r) => {
4642
5241
  let data = await r.json().catch(() => ({}))
4643
5242
  // A size rejection happens before acceptance. Retry only this explicit
@@ -4649,6 +5248,15 @@ function serveFeedback(req, res, url) {
4649
5248
  if (r.status === 429) {
4650
5249
  res.writeHead(429, { 'content-type': 'application/json; charset=utf-8' })
4651
5250
  res.end(JSON.stringify({ error: 'rate_limited' }))
5251
+ } else if (r.status === 413 || r.status === 400 && data.error === 'bad body size') {
5252
+ res.writeHead(413, { 'content-type': 'application/json; charset=utf-8' })
5253
+ res.end(JSON.stringify({ error: 'collector-body-limit' }))
5254
+ } else if (r.status === 400 && (/message.*(?:<=|≤)\s*2000/i.test(String(data.error || '')) || Number.isSafeInteger(data.max) && data.max > 0 && data.max < message.length)) {
5255
+ res.writeHead(413, { 'content-type': 'application/json; charset=utf-8' })
5256
+ res.end(JSON.stringify({ error: 'collector-message-limit', max: Number.isSafeInteger(data.max) ? data.max : 2000 }))
5257
+ } else if (r.ok && data.ok && data.messageSha256 && data.messageSha256 !== crypto.createHash('sha256').update(message).digest('hex')) {
5258
+ res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
5259
+ res.end(JSON.stringify({ error: 'feedback-content-unconfirmed' }))
4652
5260
  } else if (r.ok && data.ok) {
4653
5261
  feedbackThrottle.set(ip, now)
4654
5262
  res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' })
@@ -4659,7 +5267,7 @@ function serveFeedback(req, res, url) {
4659
5267
  }
4660
5268
  }).catch(() => {
4661
5269
  res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
4662
- res.end(JSON.stringify({ error: 'feedback_service_unavailable' }))
5270
+ res.end(JSON.stringify({ error: 'feedback_service_unavailable', uncertain: true }))
4663
5271
  })
4664
5272
  })
4665
5273
  }
@@ -4714,7 +5322,7 @@ function serveStatic(req, res, url) {
4714
5322
  res.end('403 Forbidden')
4715
5323
  return
4716
5324
  }
4717
- fs.stat(filePath, (err, st) => {
5325
+ fs.stat(filePath, async (err, st) => {
4718
5326
  if (res.destroyed || res.writableEnded) return
4719
5327
  if (err || !st.isFile()) {
4720
5328
  res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
@@ -4727,24 +5335,32 @@ function serveStatic(req, res, url) {
4727
5335
  const type = MIME[ext] || 'application/octet-stream'
4728
5336
  const text = compressibleType(type)
4729
5337
  const zipped = HTTP_COMPRESSION && text && st.size >= 1024 && req.method !== 'HEAD' && !req.headers.range && acceptsGzip(req)
4730
- const etag = `W/"${st.size}-${st.mtimeMs}-${zipped ? 'gzip' : 'identity'}"`
5338
+ const versioned = ['.html','.js','.css'].includes(ext) || pathname === '/build.json'
5339
+ let body
5340
+ if(versioned) {
5341
+ try { body = await fs.promises.readFile(filePath) }
5342
+ catch { if(!res.destroyed){res.writeHead(503,{'cache-control':'no-store'});res.end()}return }
5343
+ if(res.destroyed||res.writableEnded)return
5344
+ }
5345
+ const digest = body ? crypto.createHash('sha256').update(body).digest('hex') : st.size+'-'+st.mtimeMs
5346
+ const etag = `W/"${digest}-${zipped ? 'gzip' : 'identity'}"`
4731
5347
  cors(res)
4732
5348
  const ims = req.headers['if-modified-since']
4733
5349
  const matched = req.headers['if-none-match']
4734
- const cache = pathname === '/harmonyos-update.json' ? 'no-store' : ext === '.html' || ext === '.js' || ext === '.css' ? 'no-cache' : 'public, max-age=300'
5350
+ const cache = ['/harmonyos-update.json','/build.json'].includes(pathname) ? 'no-store' : versioned ? 'no-cache' : 'public, max-age=300'
4735
5351
  const headers = { 'content-type': type, 'cache-control': cache, 'last-modified': lastModified, etag }
4736
5352
  if (text) addEncodingVary(headers, res.getHeader('vary'))
4737
- if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : ims && new Date(ims).getTime() >= mtimeSec)) {
5353
+ if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : !versioned && ims && new Date(ims).getTime() >= mtimeSec)) {
4738
5354
  res.writeHead(304, headers)
4739
5355
  res.end()
4740
5356
  return
4741
5357
  }
4742
5358
  if (zipped) headers['content-encoding'] = 'gzip'
4743
- else headers['content-length'] = st.size
5359
+ else headers['content-length'] = body?.length ?? st.size
4744
5360
  res.writeHead(200, headers)
4745
5361
  if (req.method === 'HEAD') res.end()
4746
5362
  else {
4747
- const stream = fs.createReadStream(filePath)
5363
+ const stream = body ? require('node:stream').Readable.from([body]) : fs.createReadStream(filePath)
4748
5364
  const done = error => { if (error && !res.destroyed) res.destroy() }
4749
5365
  if (zipped) pipeline(stream, zlib.createGzip({ level: 3 }), res, done)
4750
5366
  else pipeline(stream, res, done)
@@ -4801,6 +5417,7 @@ async function serveAdminApi(req, res, url) {
4801
5417
  } catch (error) { return reply(error.status || 500, { ok: false, error: error.code || 'STARTUP_FAILED', detail: error.message }) }
4802
5418
  }
4803
5419
  if (sub === '/relay') return serveRelaySettings(req, res, url)
5420
+ if (sub === '/relay/e2ee') return serveRelayDevices(req, res, url)
4804
5421
  if (sub === '/dsh') return serveDshControl(req, res, url)
4805
5422
  if (sub === '/state' && req.method === 'GET') {
4806
5423
  if (!adminAuthorized(req, url)) {
@@ -5031,7 +5648,7 @@ async function serveRelaySettings(req, res, url) {
5031
5648
  if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST, OPTIONS'); return reply(405, { error: 'METHOD_NOT_ALLOWED' }) }
5032
5649
  const canManage = adminAuthorized(req, url)
5033
5650
  if (!canManage && !authorized(req, url)) return reply(401, { error: 'unauthorized' })
5034
- if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage })
5651
+ if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage, canManageDevices: canManage && localRelayManagement(req) })
5035
5652
  if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
5036
5653
  try {
5037
5654
  const chunks = []; let size = 0
@@ -5047,6 +5664,35 @@ async function serveRelaySettings(req, res, url) {
5047
5664
  }
5048
5665
  }
5049
5666
 
5667
+ function localRelayManagement(req) {
5668
+ if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress) || relayHost.isRelayRequest(req)) return false
5669
+ try {
5670
+ const host = new URL('http://' + req.headers.host)
5671
+ if (!['localhost','127.0.0.1','[::1]'].includes(host.hostname)) return false
5672
+ if (Number(host.port || 80) !== req.socket.localPort) return false
5673
+ if (req.headers.origin && new URL(req.headers.origin).host !== host.host) return false
5674
+ return true
5675
+ } catch { return false }
5676
+ }
5677
+ async function serveRelayDevices(req, res, url) {
5678
+ const reply = (status, value) => {res.writeHead(status, {'content-type':'application/json; charset=utf-8','cache-control':'no-store'});res.end(JSON.stringify(value))}
5679
+ if (!localRelayManagement(req)) return reply(403,{error:'LOCAL_MANAGEMENT_REQUIRED'})
5680
+ if (!adminAuthorized(req,url)) return reply(403,{error:'RELAY_ADMIN_REQUIRED'})
5681
+ if (req.method === 'GET') return reply(200,relayHost.deviceStatus())
5682
+ if (req.method !== 'POST') return reply(405,{error:'METHOD_NOT_ALLOWED'})
5683
+ try {
5684
+ const chunks=[];let size=0
5685
+ for await (const chunk of req) {size+=chunk.length;if(size>2048)return reply(413,{error:'BODY_TOO_LARGE'});chunks.push(chunk)}
5686
+ let value
5687
+ try {value=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{return reply(400,{error:'INVALID_JSON'})}
5688
+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(k=>!['action','id','label','days','confirm'].includes(k))) return reply(400,{error:'INVALID_RELAY_ACTION'})
5689
+ return reply(200,await relayHost.changeDevice(value))
5690
+ } catch(error) {
5691
+ const known = new Set(['RELAY_OPERATION_BUSY','HOST_NOT_CONFIGURED','E2EE_CONFIRMATION_REQUIRED','E2EE_NOT_CONFIGURED','INVALID_DEVICE','DEVICE_NOT_FOUND','E2EE_DEVICE_LIMIT','INVALID_RELAY_ACTION','E2EE_IDENTITY_INVALID','E2EE_DEVICE_STATE_INVALID','E2EE_DISABLED_BY_POLICY'])
5692
+ return reply(error.status||503,{error:known.has(error.code)?error.code:'E2EE_OPERATION_FAILED'})
5693
+ }
5694
+ }
5695
+
5050
5696
  // ---------- /fs 文件传输: 实现 ----------
5051
5697
  function fsJson(res, status, body, extraHeaders = {}) {
5052
5698
  cors(res)
@@ -6237,17 +6883,7 @@ const ADAPTIVE_RPC_METHODS = new Set([
6237
6883
  ])
6238
6884
 
6239
6885
  function readApiRequest(req, maxBytes = 4 * 1024 * 1024) {
6240
- return new Promise((resolve, reject) => {
6241
- let raw = ''
6242
- req.setEncoding('utf8')
6243
- req.on('data', chunk => {
6244
- raw += chunk
6245
- if (Buffer.byteLength(raw) > maxBytes) reject(new Error('request body too large'))
6246
- })
6247
- req.once('end', () => resolve(raw))
6248
- req.once('error', reject)
6249
- req.once('aborted', () => reject(new Error('request aborted')))
6250
- })
6886
+ return readBody(req, maxBytes)
6251
6887
  }
6252
6888
 
6253
6889
  // Only the explicit pre-admission image rejection is safe to retry. Never retry
@@ -6463,7 +7099,7 @@ async function serveOperations(req, res, url) {
6463
7099
  let old = loadOperation(key)
6464
7100
  if (req.method === 'GET') return old ? reply(200, operationSnapshot(old)) : reply(404, { error: 'operation-not-found' })
6465
7101
  let body
6466
- try { body = JSON.parse(await readApiRequest(req)) } catch { return reply(400, { error: 'bad-operation' }) }
7102
+ try { body = JSON.parse(await readApiRequest(req)) } catch (error) { return reply(error.status === 413 ? 413 : 400, { error: error.status === 413 ? 'body-too-large' : 'bad-operation' }) }
6467
7103
  if (!OPERATION_METHODS.has(body?.method) || !body.payload || typeof body.payload !== 'object' || Array.isArray(body.payload)) {
6468
7104
  return reply(400, { error: 'unsupported-operation' })
6469
7105
  }
@@ -6579,9 +7215,9 @@ async function proxyModernApi(req, res, url) {
6579
7215
  } catch (error) {
6580
7216
  if (!res.headersSent) {
6581
7217
  cors(res)
6582
- res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
7218
+ res.writeHead(error.status === 413 ? 413 : 502, { 'content-type': 'application/json; charset=utf-8' })
6583
7219
  }
6584
- if (!res.writableEnded) res.end(JSON.stringify({ error: 'upstream-incompatible', detail: String(error?.message || error) }))
7220
+ if (!res.writableEnded) res.end(JSON.stringify(error.status === 413 ? { error: 'body-too-large', max: 4 * 1024 * 1024 } : { error: 'upstream-incompatible', detail: String(error?.message || error) }))
6585
7221
  return true
6586
7222
  }
6587
7223
  }
@@ -6629,7 +7265,7 @@ async function proxyLegacyApi(req, res, url) {
6629
7265
  upstreamRes.pipe(res)
6630
7266
  })
6631
7267
 
6632
- const requestTimeout = ['/api/session.export', '/remote/api/command'].includes(url.pathname)
7268
+ const requestTimeout = ['/api/session.export', '/remote/api/command', '/remote/api/plugins/preflight'].includes(url.pathname)
6633
7269
  ? Math.max(UPSTREAM_REQUEST_TIMEOUT_MS, 130000) : UPSTREAM_REQUEST_TIMEOUT_MS
6634
7270
  upstreamReq.setTimeout(requestTimeout, () => {
6635
7271
  upstreamReq.destroy(new Error('upstream request timeout'))
@@ -6665,6 +7301,7 @@ function proxyApi(req, res, url) {
6665
7301
  || (url.pathname === '/remote/api/insights/peak-reminders' && req.method === 'GET')
6666
7302
  || (url.pathname === '/remote/api/teams' && req.method === 'GET')
6667
7303
  || (url.pathname === '/remote/api/task-board' && req.method === 'GET')
7304
+ || (url.pathname === '/remote/api/approval-summary' && req.method === 'POST')
6668
7305
  || (url.pathname === '/remote/api/doctor/target' && req.method === 'GET')
6669
7306
  || /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
6670
7307
  || /^\/remote\/api\/plugins\/(state|details|readme|market(?:\/indexes)?|operations|preflight|recover)$/.test(url.pathname)
@@ -6682,8 +7319,8 @@ function proxyApi(req, res, url) {
6682
7319
  if (!handled) return proxyLegacyApi(req, res, url)
6683
7320
  }).catch(error => {
6684
7321
  cors(res)
6685
- if (!res.headersSent) res.writeHead(502, { 'content-type': 'application/json; charset=utf-8' })
6686
- if (!res.writableEnded) res.end(JSON.stringify({ error: 'upstream-unreachable', detail: String(error?.message || error) }))
7322
+ if (!res.headersSent) res.writeHead(error.status === 413 ? 413 : 502, { 'content-type': 'application/json; charset=utf-8' })
7323
+ if (!res.writableEnded) res.end(JSON.stringify(error.status === 413 ? { error: 'body-too-large', max: 4 * 1024 * 1024 } : { error: 'upstream-unreachable', detail: String(error?.message || error) }))
6687
7324
  })
6688
7325
  }
6689
7326
 
@@ -7009,6 +7646,7 @@ const server = http.createServer(async (req, res) => {
7009
7646
  if (url.pathname === '/api/lan-pair') return await serveLanPair(req, res)
7010
7647
  if (url.pathname === '/api/file-inbox' || url.pathname.startsWith('/api/file-inbox/') || url.pathname === '/fs/inbox-file' || url.pathname === '/admin/api/file-inbox') return await serveFileInbox(req, res, url)
7011
7648
  if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
7649
+ if (url.pathname === '/relay/e2ee') return await serveRelayDevices(req, res, url)
7012
7650
  if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
7013
7651
  if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
7014
7652
  if (url.pathname === '/diagnostics') return serveDiagnostics(req, res, url)