dsh-remote-plugin 0.8.3 → 0.8.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/apk/dsh-remote.apk +0 -0
- package/approval-summary.mjs +115 -0
- package/gateway.cjs +704 -16
- package/index.mjs +12 -0
- package/insights.mjs +1 -1
- package/package.json +2 -1
- package/plugin-center.mjs +88 -17
- package/plugin-transaction.mjs +19 -3
- package/public/admin.html +30 -28
- package/public/admin.js +1 -1
- package/public/announcements.json +31 -0
- package/public/app.js +58 -47
- package/public/approval-summary.js +78 -0
- package/public/build.json +2 -2
- package/public/cache-upgrade.js +51 -0
- package/public/chat-copy.js +34 -21
- package/public/desktop/desktop.css +18 -39
- package/public/desktop/desktop.html +70 -96
- package/public/desktop/desktop.js +15 -42
- package/public/e2ee-transport.js +195 -0
- package/public/extensions.js +6 -6
- package/public/history.js +48 -1
- package/public/index.html +75 -93
- package/public/md.js +36 -18
- package/public/motion.js +1 -1
- package/public/plugin-center.css +1 -0
- package/public/plugin-center.js +92 -11
- package/public/plugin.html +25 -24
- package/public/relay-autopair.js +217 -0
- package/public/relay-devices.js +74 -0
- package/public/relay-settings.css +13 -0
- package/public/relay-settings.js +11 -4
- package/public/session-deck.css +7 -1
- package/public/session-deck.js +1 -1
- package/public/skins/blue-fish/preview.html +3 -2
- package/public/skins/bocchi/preview.html +5 -4
- package/public/skins/kita/preview.html +6 -5
- package/public/skins/nijika/preview.html +6 -5
- package/public/skins/penguin/preview.html +3 -2
- package/public/skins/ryo/preview.html +6 -5
- package/public/sponsor-entry.js +20 -21
- package/public/styles.css +24 -24
- package/public/teams.js +2 -2
- package/public/update.json +12 -12
- package/public/version.json +1 -1
- package/public/workflow.js +3 -4
- package/skills/dsh-remote-doctor/references/wiki/plugins.md +1 -1
- package/task-board.mjs +2 -2
- package/teams.mjs +7 -2
package/gateway.cjs
CHANGED
|
@@ -65,7 +65,8 @@ 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(
|
|
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]))
|
|
69
70
|
function issueInState(state, { label = '', domain, expiresAt, plan } = {}) {
|
|
70
71
|
if (state.grants.filter(g => live(g)).length >= state.maxUsers) throw fault('PILOT_FULL', 409)
|
|
71
72
|
const id = crypto.randomBytes(8).toString('hex')
|
|
@@ -266,12 +267,14 @@ function upgradeChannel(origin, ca) {
|
|
|
266
267
|
}
|
|
267
268
|
|
|
268
269
|
class RelayClient extends EventEmitter {
|
|
269
|
-
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 }) {
|
|
270
271
|
super()
|
|
271
272
|
if (!/^[a-f0-9]{16}$/.test(grantId || '') || !Number.isInteger(Number(tunnelPort)) || tunnelPort < 1 || tunnelPort > 65535 || !Number.isFinite(expiresAt)) throw fault('INVALID_CLIENT_CONFIG')
|
|
272
273
|
this.grantId = grantId; this.privateKey = crypto.createPrivateKey(privateKey)
|
|
273
274
|
if (this.privateKey.asymmetricKeyType !== 'ed25519') throw fault('INVALID_PRIVATE_KEY')
|
|
274
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')
|
|
275
278
|
this.tunnelHost = tunnelHost; this.tunnelPort = Number(tunnelPort); this.expiresAt = expiresAt; this.ca = ca
|
|
276
279
|
this.tunnelOrigin = tunnelOrigin
|
|
277
280
|
this.poolSize = Math.min(6, Math.max(1, poolSize)); this.reconnectMs = reconnectMs
|
|
@@ -285,8 +288,9 @@ class RelayClient extends EventEmitter {
|
|
|
285
288
|
try {
|
|
286
289
|
const challenge = await line(socket)
|
|
287
290
|
if (challenge.type !== 'challenge' || !/^[A-Za-z0-9_-]{43}$/.test(challenge.nonce || '')) throw fault('INVALID_CHALLENGE')
|
|
288
|
-
const
|
|
289
|
-
|
|
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 } : {}) })
|
|
290
294
|
const accepted = await line(socket)
|
|
291
295
|
if (accepted.type === 'rejected' && accepted.code === 'AUTHORIZATION_INACTIVE') throw fault('AUTHORIZATION_INACTIVE', 403)
|
|
292
296
|
if (!this.running || Date.now() >= this.expiresAt || accepted.type !== (role === 'control' ? 'accepted' : 'parked')) throw fault('CONNECTION_NOT_ACCEPTED')
|
|
@@ -304,6 +308,7 @@ class RelayClient extends EventEmitter {
|
|
|
304
308
|
if (epoch !== this.epoch) { socket.destroy(); return }
|
|
305
309
|
context = { socket, session: accepted.session, sockets: new Set([socket]), pending: 0, closing: false, retryTimer: null }
|
|
306
310
|
this.context = context; this.failures = 0
|
|
311
|
+
if (this.e2ee && accepted.e2ee !== true) throw fault('E2EE_BROKER_UNSUPPORTED')
|
|
307
312
|
if (accepted.usage) this.emit('usage', accepted.usage)
|
|
308
313
|
this.emit('status', 'online'); this.refill(context)
|
|
309
314
|
while (this.running && !context.closing) {
|
|
@@ -339,7 +344,21 @@ class RelayClient extends EventEmitter {
|
|
|
339
344
|
if (start.type !== 'start' || context.closing || this.context !== context) throw fault('STALE_WORK')
|
|
340
345
|
context.pending--; pending = false
|
|
341
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')
|
|
342
360
|
local = net.connect(this.target); context.sockets.add(local)
|
|
361
|
+
require('./gateway-sockets.cjs').track(local)
|
|
343
362
|
local.setNoDelay(true)
|
|
344
363
|
const connectTimer = setTimeout(() => local.destroy(), 5000)
|
|
345
364
|
local.once('connect', () => clearTimeout(connectTimer))
|
|
@@ -416,6 +435,507 @@ async function main() {
|
|
|
416
435
|
if (require.main === module) main().catch(error => { console.error(error.code || 'CLIENT_FAILED'); process.exitCode = 1 })
|
|
417
436
|
module.exports = { RelayClient, enroll, gatewayAddress }
|
|
418
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
|
+
},
|
|
419
939
|
"./host.cjs": function(require, module, exports) {
|
|
420
940
|
'use strict'
|
|
421
941
|
const fs = require('node:fs')
|
|
@@ -423,20 +943,26 @@ const path = require('node:path')
|
|
|
423
943
|
const crypto = require('node:crypto')
|
|
424
944
|
const { RelayClient, enroll } = require('./client.cjs')
|
|
425
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')
|
|
426
950
|
const DEFAULT_ORIGIN = 'https://relay-pilot.blankalwaysgoeson.site'
|
|
427
951
|
|
|
428
952
|
// Runs inside the gateway process: no launcher, scheduled task or runtime install.
|
|
429
953
|
class RelayHost {
|
|
430
|
-
constructor({ root, gateway, origin = DEFAULT_ORIGIN, ca }) {
|
|
954
|
+
constructor({ root, gateway, origin = DEFAULT_ORIGIN, ca, e2eeEnabled }) {
|
|
431
955
|
this.root = root; this.gateway = gateway; this.origin = origin; this.ca = ca
|
|
432
956
|
this.file = path.join(root, 'connection.json'); this.keyFile = path.join(root, 'host-private.pem')
|
|
433
957
|
this.legacyRoot = path.join(path.dirname(root), 'owner-preview')
|
|
434
958
|
this.client = null; this.phase = 'disabled'; this.daily = null; this.updatedAt = null; this.busy = false
|
|
435
959
|
this.config = null; this.error = ''
|
|
960
|
+
this.e2eeOverride = e2eeEnabled; this.endpoint = null; this.e2eeFingerprint = ''; this.devices = null
|
|
436
961
|
if (fs.existsSync(this.file)) {
|
|
437
962
|
try { this.config = JSON.parse(fs.readFileSync(this.file, 'utf8')) }
|
|
438
963
|
catch { this.phase = 'error'; this.error = 'LOCAL_STATE_INVALID' }
|
|
439
964
|
}
|
|
965
|
+
this.e2eeEnabled = e2eeEnabled ?? (this.config?.e2eeEnabled === true)
|
|
440
966
|
}
|
|
441
967
|
save(config) {
|
|
442
968
|
fs.mkdirSync(this.root, { recursive: true, mode: 0o700 })
|
|
@@ -455,6 +981,9 @@ class RelayHost {
|
|
|
455
981
|
publicUrl: config?.publicUrl || '', expiresAt: config?.expiresAt || null,
|
|
456
982
|
fingerprint: config?.fingerprint || '', daily: this.daily, usageUpdatedAt: this.updatedAt,
|
|
457
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 },
|
|
458
987
|
server: this.origin, busy: this.busy, legacyAvailable: !config && !!this.legacy() }
|
|
459
988
|
}
|
|
460
989
|
legacy() {
|
|
@@ -475,7 +1004,24 @@ class RelayHost {
|
|
|
475
1004
|
if (this.config.expiresAt <= Date.now()) { this.phase = 'expired'; return }
|
|
476
1005
|
// Only the operator-configured service is allowed, never a target supplied by a browser.
|
|
477
1006
|
if (this.config.tunnelOrigin !== this.origin) throw fault('RELAY_SERVER_MISMATCH', 409)
|
|
478
|
-
|
|
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 })
|
|
479
1025
|
this.client = client; this.phase = 'connecting'; this.error = ''
|
|
480
1026
|
client.on('status', status => { if (this.client === client) this.phase = status })
|
|
481
1027
|
client.on('usage', daily => {
|
|
@@ -484,7 +1030,44 @@ class RelayHost {
|
|
|
484
1030
|
})
|
|
485
1031
|
client.start()
|
|
486
1032
|
}
|
|
487
|
-
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
|
+
}
|
|
488
1071
|
async change(action, key) {
|
|
489
1072
|
if (this.busy) throw fault('RELAY_OPERATION_BUSY', 409)
|
|
490
1073
|
this.busy = true
|
|
@@ -520,7 +1103,8 @@ class RelayHost {
|
|
|
520
1103
|
// Construct before replacing a working configuration; a malformed response cannot disable it.
|
|
521
1104
|
new RelayClient({ ...config, gateway: this.gateway, privateKey: privateKey.export({ format: 'pem', type: 'pkcs8' }), ca: this.ca })
|
|
522
1105
|
if (config.tunnelOrigin !== this.origin || new URL(config.publicUrl).protocol !== 'https:') throw fault('INVALID_SERVER_RESPONSE', 502)
|
|
523
|
-
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) })
|
|
524
1108
|
this.daily = null; this.updatedAt = null; this.start()
|
|
525
1109
|
} else if (action === 'enable') {
|
|
526
1110
|
if (!this.config) throw fault('HOST_NOT_CONFIGURED', 409)
|
|
@@ -529,7 +1113,8 @@ class RelayHost {
|
|
|
529
1113
|
if (this.config) this.save({ ...this.config, enabled: false })
|
|
530
1114
|
// Allow the setting response to cross the tunnel before closing it.
|
|
531
1115
|
const client = this.client; this.client = null; this.phase = 'disabled'
|
|
532
|
-
const
|
|
1116
|
+
const endpoint = this.endpoint; this.endpoint = null
|
|
1117
|
+
const timer = setTimeout(() => { client?.stop(); endpoint?.close() }, 250); timer.unref?.()
|
|
533
1118
|
} else throw fault('INVALID_RELAY_ACTION', 400)
|
|
534
1119
|
return this.status()
|
|
535
1120
|
} finally { this.busy = false }
|
|
@@ -954,6 +1539,7 @@ const relayHost = new embeddedRelayHost.RelayHost({
|
|
|
954
1539
|
gateway: `http://127.0.0.1:${PORT}`,
|
|
955
1540
|
origin: process.env.DSH_REMOTE_RELAY_ORIGIN || embeddedRelayHost.DEFAULT_ORIGIN,
|
|
956
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',
|
|
957
1543
|
})
|
|
958
1544
|
|
|
959
1545
|
function durationEnv(name, fallback, min, max) {
|
|
@@ -982,6 +1568,8 @@ const DSH_HEALTH_PATH = String(process.env.DSH_HEALTH_PATH || '/').startsWith('/
|
|
|
982
1568
|
: '/' + String(process.env.DSH_HEALTH_PATH)
|
|
983
1569
|
const DSH_UPSTREAM_COOKIE_FILE = process.env.DSH_REMOTE_DSH_COOKIE_FILE || path.join(os.homedir(), '.dsh-remote', 'dsh-upstream.cookie')
|
|
984
1570
|
const TOKEN_FILE = process.env.TOKEN_FILE || path.join(os.homedir(), '.dsh-remote', 'token')
|
|
1571
|
+
const PAIRING_LOG_FILE = process.env.DSH_REMOTE_PAIR_LOG || path.join(os.homedir(), '.dsh-remote', 'pairing.log')
|
|
1572
|
+
const PAIRING_LOG_LIMIT_BYTES = 512 * 1024
|
|
985
1573
|
const DSH_CONTROL_DIR = path.join(path.dirname(TOKEN_FILE), 'lifecycle-' + PORT)
|
|
986
1574
|
const NOTES_FILE = process.env.DSH_REMOTE_NOTES || path.join(os.homedir(), '.dsh-remote', 'device-notes.json')
|
|
987
1575
|
const DEVICE_KEYS_FILE = process.env.DSH_REMOTE_DEVICE_KEYS || path.join(os.homedir(), '.dsh-remote', 'device-keys.json')
|
|
@@ -4736,7 +5324,7 @@ function serveStatic(req, res, url) {
|
|
|
4736
5324
|
res.end('403 Forbidden')
|
|
4737
5325
|
return
|
|
4738
5326
|
}
|
|
4739
|
-
fs.stat(filePath, (err, st) => {
|
|
5327
|
+
fs.stat(filePath, async (err, st) => {
|
|
4740
5328
|
if (res.destroyed || res.writableEnded) return
|
|
4741
5329
|
if (err || !st.isFile()) {
|
|
4742
5330
|
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
@@ -4749,24 +5337,32 @@ function serveStatic(req, res, url) {
|
|
|
4749
5337
|
const type = MIME[ext] || 'application/octet-stream'
|
|
4750
5338
|
const text = compressibleType(type)
|
|
4751
5339
|
const zipped = HTTP_COMPRESSION && text && st.size >= 1024 && req.method !== 'HEAD' && !req.headers.range && acceptsGzip(req)
|
|
4752
|
-
const
|
|
5340
|
+
const versioned = ['.html','.js','.css'].includes(ext) || pathname === '/build.json'
|
|
5341
|
+
let body
|
|
5342
|
+
if(versioned) {
|
|
5343
|
+
try { body = await fs.promises.readFile(filePath) }
|
|
5344
|
+
catch { if(!res.destroyed){res.writeHead(503,{'cache-control':'no-store'});res.end()}return }
|
|
5345
|
+
if(res.destroyed||res.writableEnded)return
|
|
5346
|
+
}
|
|
5347
|
+
const digest = body ? crypto.createHash('sha256').update(body).digest('hex') : st.size+'-'+st.mtimeMs
|
|
5348
|
+
const etag = `W/"${digest}-${zipped ? 'gzip' : 'identity'}"`
|
|
4753
5349
|
cors(res)
|
|
4754
5350
|
const ims = req.headers['if-modified-since']
|
|
4755
5351
|
const matched = req.headers['if-none-match']
|
|
4756
|
-
const cache =
|
|
5352
|
+
const cache = ['/harmonyos-update.json','/build.json'].includes(pathname) ? 'no-store' : versioned ? 'no-cache' : 'public, max-age=300'
|
|
4757
5353
|
const headers = { 'content-type': type, 'cache-control': cache, 'last-modified': lastModified, etag }
|
|
4758
5354
|
if (text) addEncodingVary(headers, res.getHeader('vary'))
|
|
4759
|
-
if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : ims && new Date(ims).getTime() >= mtimeSec)) {
|
|
5355
|
+
if (cache !== 'no-store' && (matched ? String(matched).split(',').some(v => v.trim() === etag || v.trim() === '*') : !versioned && ims && new Date(ims).getTime() >= mtimeSec)) {
|
|
4760
5356
|
res.writeHead(304, headers)
|
|
4761
5357
|
res.end()
|
|
4762
5358
|
return
|
|
4763
5359
|
}
|
|
4764
5360
|
if (zipped) headers['content-encoding'] = 'gzip'
|
|
4765
|
-
else headers['content-length'] = st.size
|
|
5361
|
+
else headers['content-length'] = body?.length ?? st.size
|
|
4766
5362
|
res.writeHead(200, headers)
|
|
4767
5363
|
if (req.method === 'HEAD') res.end()
|
|
4768
5364
|
else {
|
|
4769
|
-
const stream = fs.createReadStream(filePath)
|
|
5365
|
+
const stream = body ? require('node:stream').Readable.from([body]) : fs.createReadStream(filePath)
|
|
4770
5366
|
const done = error => { if (error && !res.destroyed) res.destroy() }
|
|
4771
5367
|
if (zipped) pipeline(stream, zlib.createGzip({ level: 3 }), res, done)
|
|
4772
5368
|
else pipeline(stream, res, done)
|
|
@@ -4823,6 +5419,8 @@ async function serveAdminApi(req, res, url) {
|
|
|
4823
5419
|
} catch (error) { return reply(error.status || 500, { ok: false, error: error.code || 'STARTUP_FAILED', detail: error.message }) }
|
|
4824
5420
|
}
|
|
4825
5421
|
if (sub === '/relay') return serveRelaySettings(req, res, url)
|
|
5422
|
+
if (sub === '/relay/e2ee') return serveRelayDevices(req, res, url)
|
|
5423
|
+
if (sub === '/relay/pair') return serveRelayPair(req, res, url)
|
|
4826
5424
|
if (sub === '/dsh') return serveDshControl(req, res, url)
|
|
4827
5425
|
if (sub === '/state' && req.method === 'GET') {
|
|
4828
5426
|
if (!adminAuthorized(req, url)) {
|
|
@@ -5053,7 +5651,7 @@ async function serveRelaySettings(req, res, url) {
|
|
|
5053
5651
|
if (!['GET', 'POST'].includes(req.method)) { res.setHeader('allow', 'GET, POST, OPTIONS'); return reply(405, { error: 'METHOD_NOT_ALLOWED' }) }
|
|
5054
5652
|
const canManage = adminAuthorized(req, url)
|
|
5055
5653
|
if (!canManage && !authorized(req, url)) return reply(401, { error: 'unauthorized' })
|
|
5056
|
-
if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage })
|
|
5654
|
+
if (req.method === 'GET') return reply(200, { ...relayHost.status(), canManage, canManageDevices: canManage && localRelayManagement(req), canPairLocally: localRelayPairing(req) })
|
|
5057
5655
|
if (!canManage) return reply(403, { error: 'RELAY_ADMIN_REQUIRED' })
|
|
5058
5656
|
try {
|
|
5059
5657
|
const chunks = []; let size = 0
|
|
@@ -5069,6 +5667,93 @@ async function serveRelaySettings(req, res, url) {
|
|
|
5069
5667
|
}
|
|
5070
5668
|
}
|
|
5071
5669
|
|
|
5670
|
+
function localRelayPairing(req) {
|
|
5671
|
+
// Pairing trust must come from a direct local connection, never the broker.
|
|
5672
|
+
const privateAddress = value => {
|
|
5673
|
+
const ip = String(value || '').replace(/^::ffff:/, '').replace(/^\[|\]$/g, '')
|
|
5674
|
+
if (net.isIP(ip) === 4) {
|
|
5675
|
+
const [a,b] = ip.split('.').map(Number)
|
|
5676
|
+
return a === 10 || a === 127 || a === 192 && b === 168 || a === 172 && b >= 16 && b <= 31
|
|
5677
|
+
}
|
|
5678
|
+
return net.isIP(ip) === 6 && (ip === '::1' || /^(?:fc|fd|fe[89ab])/i.test(ip))
|
|
5679
|
+
}
|
|
5680
|
+
if (!privateAddress(req.socket.remoteAddress) || relayHost.isRelayRequest(req)) return false
|
|
5681
|
+
if (['forwarded','x-forwarded-for','x-forwarded-host','x-real-ip'].some(key => req.headers[key])) return false
|
|
5682
|
+
try {
|
|
5683
|
+
const host = new URL('http://' + req.headers.host)
|
|
5684
|
+
return (host.hostname === 'localhost' || privateAddress(host.hostname)) && Number(host.port || 80) === req.socket.localPort
|
|
5685
|
+
} catch { return false }
|
|
5686
|
+
}
|
|
5687
|
+
function appendPairingLog(entry) {
|
|
5688
|
+
try {
|
|
5689
|
+
const line = JSON.stringify({ at: new Date().toISOString(), ...entry }) + '\n'
|
|
5690
|
+
fs.mkdirSync(path.dirname(PAIRING_LOG_FILE), { recursive: true, mode: 0o700 })
|
|
5691
|
+
try {
|
|
5692
|
+
if (fs.statSync(PAIRING_LOG_FILE).size + Buffer.byteLength(line) > PAIRING_LOG_LIMIT_BYTES) {
|
|
5693
|
+
try { fs.rmSync(PAIRING_LOG_FILE + '.1', { force: true }) } catch {}
|
|
5694
|
+
fs.renameSync(PAIRING_LOG_FILE, PAIRING_LOG_FILE + '.1')
|
|
5695
|
+
}
|
|
5696
|
+
} catch {}
|
|
5697
|
+
fs.appendFileSync(PAIRING_LOG_FILE, line, { mode: 0o600 })
|
|
5698
|
+
} catch {}
|
|
5699
|
+
}
|
|
5700
|
+
async function serveRelayPair(req, res, url) {
|
|
5701
|
+
cors(res)
|
|
5702
|
+
const started = Date.now(), source = String(req.socket.remoteAddress || ''), hostHeader = String(req.headers.host || '')
|
|
5703
|
+
const pairLog = (event, detail = {}) => appendPairingLog({ event, source, host: hostHeader, method: req.method, ms: Date.now() - started, ...detail })
|
|
5704
|
+
const reply = (status, value) => { res.writeHead(status, {'content-type':'application/json; charset=utf-8','cache-control':'no-store'}); res.end(JSON.stringify(value)) }
|
|
5705
|
+
if (!localRelayPairing(req)) { pairLog('pair.denied', { reason: 'local-only' }); return reply(403,{error:'LOCAL_PAIRING_REQUIRED'}) }
|
|
5706
|
+
if (req.method === 'OPTIONS') {res.writeHead(204);return res.end()}
|
|
5707
|
+
if (!/^Bearer \S+$/i.test(req.headers.authorization || '') || !adminAuthorized(req,url) && !authorized(req,url)) { pairLog('pair.denied', { reason: 'unauthorized' }); return reply(401,{error:'unauthorized'}) }
|
|
5708
|
+
if (req.method !== 'POST') { pairLog('pair.denied', { reason: 'method' }); return reply(405,{error:'METHOD_NOT_ALLOWED'}) }
|
|
5709
|
+
if (!String(req.headers['content-type'] || '').toLowerCase().startsWith('application/json')) { pairLog('pair.denied', { reason: 'content-type' }); return reply(415,{error:'JSON_REQUIRED'}) }
|
|
5710
|
+
pairLog('pair.attempt')
|
|
5711
|
+
try {
|
|
5712
|
+
const chunks=[]; let size=0
|
|
5713
|
+
for await (const chunk of req) {size+=chunk.length;if(size>1024){pairLog('pair.rejected',{code:'BODY_TOO_LARGE'});return reply(413,{error:'BODY_TOO_LARGE'})};chunks.push(chunk)}
|
|
5714
|
+
let value
|
|
5715
|
+
try {value=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{pairLog('pair.rejected',{code:'INVALID_JSON'});return reply(400,{error:'INVALID_JSON'})}
|
|
5716
|
+
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).some(key=>!['fingerprint','label'].includes(key))) { pairLog('pair.rejected',{code:'INVALID_DEVICE'}); return reply(400,{error:'INVALID_DEVICE'}) }
|
|
5717
|
+
if (!relayHost.e2eeEnabled || !relayHost.endpoint) { pairLog('pair.rejected',{code:'E2EE_NOT_CONFIGURED'}); return reply(409,{error:'E2EE_NOT_CONFIGURED'}) }
|
|
5718
|
+
if (value.fingerprint !== relayHost.e2eeFingerprint) { pairLog('pair.rejected',{code:'E2EE_PAIRING_CHANGED'}); return reply(409,{error:'E2EE_PAIRING_CHANGED'}) }
|
|
5719
|
+
const result=await relayHost.changeDevice({action:'create-device',label:value.label,days:30})
|
|
5720
|
+
pairLog('pair.created', { deviceId: String(result?.pairing?.deviceId || '').slice(0, 64), expiresAt: Number(result?.pairing?.expiresAt) || 0, label: String(value.label || '').slice(0, 80), relayPhase: String(relayHost.phase || '') })
|
|
5721
|
+
return reply(200,{pairing:result.pairing})
|
|
5722
|
+
} catch(error) {
|
|
5723
|
+
const known=new Set(['INVALID_DEVICE','E2EE_DEVICE_LIMIT','RELAY_OPERATION_BUSY','E2EE_NOT_CONFIGURED','HOST_NOT_CONFIGURED'])
|
|
5724
|
+
pairLog('pair.failed', { code: String(error?.code || 'E2EE_OPERATION_FAILED'), httpStatus: Number(error?.status) || 503 })
|
|
5725
|
+
return reply(error.status||503,{error:known.has(error.code)?error.code:'E2EE_OPERATION_FAILED'})
|
|
5726
|
+
}
|
|
5727
|
+
}
|
|
5728
|
+
function localRelayManagement(req) {
|
|
5729
|
+
if (!['127.0.0.1', '::1', '::ffff:127.0.0.1'].includes(req.socket.remoteAddress) || relayHost.isRelayRequest(req)) return false
|
|
5730
|
+
try {
|
|
5731
|
+
const host = new URL('http://' + req.headers.host)
|
|
5732
|
+
if (!['localhost','127.0.0.1','[::1]'].includes(host.hostname)) return false
|
|
5733
|
+
if (Number(host.port || 80) !== req.socket.localPort) return false
|
|
5734
|
+
if (req.headers.origin && new URL(req.headers.origin).host !== host.host) return false
|
|
5735
|
+
return true
|
|
5736
|
+
} catch { return false }
|
|
5737
|
+
}
|
|
5738
|
+
async function serveRelayDevices(req, res, url) {
|
|
5739
|
+
const reply = (status, value) => {res.writeHead(status, {'content-type':'application/json; charset=utf-8','cache-control':'no-store'});res.end(JSON.stringify(value))}
|
|
5740
|
+
if (!localRelayManagement(req)) return reply(403,{error:'LOCAL_MANAGEMENT_REQUIRED'})
|
|
5741
|
+
if (!adminAuthorized(req,url)) return reply(403,{error:'RELAY_ADMIN_REQUIRED'})
|
|
5742
|
+
if (req.method === 'GET') return reply(200,relayHost.deviceStatus())
|
|
5743
|
+
if (req.method !== 'POST') return reply(405,{error:'METHOD_NOT_ALLOWED'})
|
|
5744
|
+
try {
|
|
5745
|
+
const chunks=[];let size=0
|
|
5746
|
+
for await (const chunk of req) {size+=chunk.length;if(size>2048)return reply(413,{error:'BODY_TOO_LARGE'});chunks.push(chunk)}
|
|
5747
|
+
let value
|
|
5748
|
+
try {value=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{return reply(400,{error:'INVALID_JSON'})}
|
|
5749
|
+
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'})
|
|
5750
|
+
return reply(200,await relayHost.changeDevice(value))
|
|
5751
|
+
} catch(error) {
|
|
5752
|
+
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'])
|
|
5753
|
+
return reply(error.status||503,{error:known.has(error.code)?error.code:'E2EE_OPERATION_FAILED'})
|
|
5754
|
+
}
|
|
5755
|
+
}
|
|
5756
|
+
|
|
5072
5757
|
// ---------- /fs 文件传输: 实现 ----------
|
|
5073
5758
|
function fsJson(res, status, body, extraHeaders = {}) {
|
|
5074
5759
|
cors(res)
|
|
@@ -6677,6 +7362,7 @@ function proxyApi(req, res, url) {
|
|
|
6677
7362
|
|| (url.pathname === '/remote/api/insights/peak-reminders' && req.method === 'GET')
|
|
6678
7363
|
|| (url.pathname === '/remote/api/teams' && req.method === 'GET')
|
|
6679
7364
|
|| (url.pathname === '/remote/api/task-board' && req.method === 'GET')
|
|
7365
|
+
|| (url.pathname === '/remote/api/approval-summary' && req.method === 'POST')
|
|
6680
7366
|
|| (url.pathname === '/remote/api/doctor/target' && req.method === 'GET')
|
|
6681
7367
|
|| /^\/remote\/api\/skills\/(list|read)$/.test(url.pathname)
|
|
6682
7368
|
|| /^\/remote\/api\/plugins\/(state|details|readme|market(?:\/indexes)?|operations|preflight|recover)$/.test(url.pathname)
|
|
@@ -7021,6 +7707,8 @@ const server = http.createServer(async (req, res) => {
|
|
|
7021
7707
|
if (url.pathname === '/api/lan-pair') return await serveLanPair(req, res)
|
|
7022
7708
|
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)
|
|
7023
7709
|
if (url.pathname === '/relay') return await serveRelaySettings(req, res, url)
|
|
7710
|
+
if (url.pathname === '/relay/e2ee') return await serveRelayDevices(req, res, url)
|
|
7711
|
+
if (url.pathname === '/relay/pair') return await serveRelayPair(req, res, url)
|
|
7024
7712
|
if (url.pathname === '/fs' || url.pathname.startsWith('/fs/')) return await serveFs(req, res, url)
|
|
7025
7713
|
if (url.pathname === '/workbench' || url.pathname.startsWith('/workbench/')) return serveWorkbench(req, res, url)
|
|
7026
7714
|
if (url.pathname === '/diagnostics') return serveDiagnostics(req, res, url)
|