dsh-relay-phone 0.13.0 → 0.14.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-relay-phone",
3
- "version": "0.13.0",
3
+ "version": "0.14.0",
4
4
  "description": "Remote-control your local DeepSeek Harness from a phone through your own zero-knowledge relay: phone-first page, QR pairing, end-to-end encryption, approvals, full desktop UI fallback.",
5
5
  "type": "module",
6
6
  "main": "src/index.js",
@@ -351,16 +351,21 @@ export function buildBootSource(id, gate) {
351
351
  }
352
352
 
353
353
  return bodyPromise.then(function (body) {
354
- if (body === null) {
355
- // GET/HEAD: response only is sealed.
354
+ var isRead = options.method === 'GET' || options.method === 'HEAD'
355
+ if (body === null && isRead) {
356
+ // GET/HEAD: there is no body, so only the response is sealed.
356
357
  return origFetch(finalUrl, Object.assign({}, options, { headers: headers }))
357
358
  .then(maybeUnwrap)
358
359
  }
360
+ // Everything else always carries an envelope - including a bodyless POST.
361
+ // The host refuses a non-GET/HEAD request without one, because an empty
362
+ // body was exactly how a ticket alone could act as the user.
363
+ var bytes = body ? body.bytes : new Uint8Array(0)
359
364
  headers.set('content-type', 'application/octet-stream')
360
- headers.set('x-relay-ct', originalType || body.type || 'text/plain;charset=UTF-8')
365
+ headers.set('x-relay-ct', originalType || (body && body.type) || 'text/plain;charset=UTF-8')
361
366
  return origFetch(finalUrl, Object.assign({}, options, {
362
367
  headers: headers,
363
- body: sealEnvelope(body.bytes),
368
+ body: sealEnvelope(bytes),
364
369
  })).then(maybeUnwrap)
365
370
  }).catch(function (error) {
366
371
  // A body-serialization failure must not silently downgrade to plaintext.
package/src/pump.js CHANGED
@@ -38,6 +38,11 @@ const PENDING_LIMIT = 1024 * 1024
38
38
  // with a phone screenshot are easily several hundred KB; the old 256KB ceiling
39
39
  // rejected them with a bare 400 before they ever reached DSH).
40
40
  const SEALED_BODY_LIMIT = 32 * 1024 * 1024
41
+ // 24-byte nonce + 16-byte secretbox overhead: nothing smaller can be an envelope.
42
+ const SEALED_BODY_MIN = 40
43
+ // The only websocket endpoints DSH's UI opens. A forged Upgrade elsewhere is not
44
+ // a handshake, it is a plaintext GET with a lie in the headers.
45
+ const SOCKET_ENDPOINTS = new Set(['/api/remote.mux'])
41
46
  const RPC_LIMIT = 32 * 1024 * 1024
42
47
  const EMPTY = Buffer.alloc(0)
43
48
  // Per-request tracing stays off unless explicitly requested: the pump sees
@@ -232,6 +237,8 @@ export class PumpManager {
232
237
  }
233
238
  case 'req-body': {
234
239
  stream.buffer = Buffer.concat([stream.buffer, this.capChunk(stream, chunk)])
240
+ // Progress resets the deadline; a stalled sender does not.
241
+ this.armIdle(sid, stream)
235
242
  this.maybeFinishSealedRequest(sid, stream)
236
243
  return
237
244
  }
@@ -433,11 +440,28 @@ export class PumpManager {
433
440
  return
434
441
  }
435
442
 
443
+ // `Upgrade: websocket` is declared by the client, so it proves nothing on its
444
+ // own: a forged header on `/api/private` used to hand the host's cookie to a
445
+ // plaintext GET. Only a complete handshake on a known socket endpoint counts.
446
+ if (sealed && isUpgrade) {
447
+ auditLog(`relayed request claimed both sealed and upgrade (${info.path})`)
448
+ this.respondInline(sid, 400, 'Bad Request')
449
+ this.closeStream(sid)
450
+ return
451
+ }
452
+ if (isUpgrade && !this.isSocketEndpoint(info)) {
453
+ auditLog(`relayed upgrade on a non-socket path refused (${info.method} ${info.path})`)
454
+ this.respondInline(sid, 403, 'Forbidden', 'dsh-relay-phone: not a websocket endpoint\n')
455
+ this.closeStream(sid)
456
+ return
457
+ }
458
+
436
459
  // Anything unsealed past this point would be forwarded to the local DSH with
437
460
  // the host's own browser cookie attached. The relay sees the ticket and the
438
461
  // gate, so it could mint the same request itself: plaintext is limited to
439
462
  // the documents and assets a browser fetches on its own.
440
- if (!this.allowDesktopPlaintext && !this.isPlaintextDocument(info, isUpgrade)) {
463
+ const plaintextOk = isUpgrade || this.isPlaintextDocument(info)
464
+ if (!this.allowDesktopPlaintext && !plaintextOk) {
441
465
  auditLog(`relayed plaintext ${info.method} ${info.path} refused (sealed only)`)
442
466
  this.respondInline(
443
467
  sid, 403, 'Forbidden',
@@ -451,19 +475,44 @@ export class PumpManager {
451
475
  this.plainForward(sid, stream, info, headText, rest, { isUpgrade, isDocument, relay: stream.relay })
452
476
  }
453
477
 
478
+ /** Every raw value for a header name, in wire order (the Map keeps only the last). */
479
+ headerValues(info, name) {
480
+ const wanted = name.toLowerCase()
481
+ const values = []
482
+ for (const line of info.rawHeaders) {
483
+ const colon = line.indexOf(':')
484
+ if (colon <= 0) continue
485
+ if (line.slice(0, colon).trim().toLowerCase() !== wanted) continue
486
+ values.push(line.slice(colon + 1).trim())
487
+ }
488
+ return values
489
+ }
490
+
454
491
  /**
455
- * True for the GET/HEAD document + asset traffic a phone browser issues by
456
- * itself, and for WebSocket handshakes.
492
+ * True for a *complete* WebSocket handshake on a path that really is a socket.
457
493
  *
458
- * A WebSocket handshake is an HTTP GET with an Upgrade header: there is no
459
- * body, so an envelope cannot ride along. Sealing happens per frame instead,
460
- * and `pumpPhoneWs` refuses any data frame that does not open — which is why
461
- * the handshake may pass while the payload stays mandatory-sealed. (DSH's own
462
- * event mux, `/api/remote.mux`, is such a WebSocket; blocking the handshake
463
- * broke the desktop UI with "Reconnecting".)
494
+ * `Upgrade: websocket` is client-declared, so a forged one on `/api/private`
495
+ * used to hand the host's cookie to a plaintext GET. The path allowlist plus
496
+ * the mandatory handshake fields are what make the header trustworthy.
497
+ */
498
+ isSocketEndpoint(info) {
499
+ if (info.method !== 'GET') return false
500
+ if (!SOCKET_ENDPOINTS.has(info.path)) return false
501
+ const connection = this.headerValues(info, 'connection').join(',').toLowerCase()
502
+ if (!connection.split(',').some((token) => token.trim() === 'upgrade')) return false
503
+ if ((info.headers.get('sec-websocket-version') ?? '').trim() !== '13') return false
504
+ // Sec-WebSocket-Key: base64 of 16 random bytes (24 chars with padding).
505
+ const key = (info.headers.get('sec-websocket-key') ?? '').trim()
506
+ if (!/^[A-Za-z0-9+/]{22}==$/.test(key)) return false
507
+ return true
508
+ }
509
+
510
+ /**
511
+ * True for the GET/HEAD document + asset traffic a phone browser issues by
512
+ * itself. Socket handshakes are decided separately by `isSocketEndpoint`; a
513
+ * sealed request is never a document.
464
514
  */
465
- isPlaintextDocument(info, isUpgrade) {
466
- if (isUpgrade) return info.method === 'GET'
515
+ isPlaintextDocument(info) {
467
516
  if (info.method !== 'GET' && info.method !== 'HEAD') return false
468
517
  if (info.path.startsWith('/api/')) return false
469
518
  return PLAINTEXT_DOCUMENT.test(info.path)
@@ -515,6 +564,9 @@ export class PumpManager {
515
564
  stream.phase = 'req-body'
516
565
  stream.reqLength = length
517
566
  stream.buffer = this.splitBody(stream, rest, length)
567
+ // Waiting for the rest of an envelope is a bounded wait: a client that sends
568
+ // half a body and stops must not hold the stream (and its slot) forever.
569
+ this.armIdle(sid, stream)
518
570
  this.maybeFinishSealedRequest(sid, stream)
519
571
  }
520
572
 
@@ -545,13 +597,57 @@ export class PumpManager {
545
597
 
546
598
  // -- sealed round trips ----------------------------------------------------------
547
599
  prepareSealedForward(sid, stream, info, headText, rest) {
548
- const length = Number(info.headers.get('content-length') ?? '0')
549
- if (!Number.isFinite(length) || length < 0 || length > SEALED_BODY_LIMIT) {
600
+ // Two legitimate shapes:
601
+ // * a body-carrying call: the envelope is at least 24+16 bytes and its
602
+ // plaintext is the request body (POST/PUT/PATCH/DELETE, or an RPC);
603
+ // * a GET/HEAD read: no body, so only the *response* is sealed. The boot
604
+ // patch sets x-relay-enc for those too, and refusing them broke every
605
+ // desktop read, so the empty body is allowed there — and only there.
606
+ const method = info.method.toUpperCase()
607
+ // `info.headers` is a Map that keeps only the last value, so a repeated
608
+ // content-length would silently win. Ask the wire instead.
609
+ const lengths = this.headerValues(info, 'content-length')
610
+ if (lengths.length > 1) {
611
+ auditLog(`sealed request with ${lengths.length} content-length headers (${info.path})`)
612
+ this.respondInline(sid, 400, 'Bad Request')
613
+ this.closeStream(sid)
614
+ return
615
+ }
616
+ const rawLength = lengths[0] ?? null
617
+ // Decimal digits only: `0x28` is 40 to Number(), which is not a length we agreed to.
618
+ if (rawLength !== null && !/^\d{1,10}$/.test(rawLength)) {
619
+ auditLog(`sealed request with a malformed content-length (${info.path}, ${JSON.stringify(rawLength).slice(0, 40)})`)
620
+ this.respondInline(sid, 400, 'Bad Request')
621
+ this.closeStream(sid)
622
+ return
623
+ }
624
+ const length = rawLength === null ? 0 : Number(rawLength)
625
+ const responseOnly = (method === 'GET' || method === 'HEAD') && length === 0
626
+ if (!Number.isSafeInteger(length) || length < 0 || length > SEALED_BODY_LIMIT) {
550
627
  if (DEBUG) console.log('[relay-dbg] 400@prepare sid=%s len=%s ct=%s', sid, length, info.headers.get('content-type'))
628
+ auditLog(`sealed request with a bad content-length (${info.path}, ${rawLength})`)
551
629
  this.respondInline(sid, 400, 'Bad Request')
552
630
  this.closeStream(sid)
553
631
  return
554
632
  }
633
+ if (!responseOnly && length < SEALED_BODY_MIN) {
634
+ // A zero/short body on anything that can change state is not an envelope.
635
+ auditLog(`sealed request without an envelope (${info.path}, content-length=${length})`)
636
+ this.respondInline(sid, 400, 'Bad Request', 'dsh-relay-phone: sealed requests need an envelope\n')
637
+ this.closeStream(sid)
638
+ return
639
+ }
640
+ if (responseOnly) {
641
+ if (rest.length > 0) {
642
+ // The client said "no body" and then sent one: refuse rather than guess.
643
+ auditLog(`sealed GET ${info.path} carried unexpected body bytes`)
644
+ this.respondInline(sid, 400, 'Bad Request')
645
+ this.closeStream(sid)
646
+ return
647
+ }
648
+ this.forwardSealed(sid, stream, Buffer.alloc(0))
649
+ return
650
+ }
555
651
  stream.phase = 'req-body'
556
652
  stream.reqLength = length
557
653
  stream.buffer = this.splitBody(stream, rest, length)
@@ -561,17 +657,22 @@ export class PumpManager {
561
657
  maybeFinishSealedRequest(sid, stream) {
562
658
  if (stream.buffer.length < stream.reqLength) return
563
659
  const sealedBody = stream.buffer.subarray(0, stream.reqLength)
564
- let plain = Buffer.alloc(0)
565
- if (stream.reqLength > 0) {
566
- plain = this.cryptoBox.open(this.cryptoBox.envelopeKey, sealedBody)
567
- if (!plain) {
568
- auditLog(`sealed request body failed to open (${stream.info.path})`)
569
- if (DEBUG) console.log('[relay-dbg] 400@open sid=%s path=%s len=%s bodyHead=%s', sid, stream.info.path, stream.reqLength, sealedBody.subarray(0, 16).toString('hex'))
570
- this.respondInline(sid, 400, 'Bad Request')
571
- this.closeStream(sid)
572
- return
573
- }
660
+ // Always decrypt. An empty *plaintext* is fine — it still arrives as a 40-byte
661
+ // envelope — but a zero-length body can never be one, so no state-changing
662
+ // request reaches the host without opening an envelope first.
663
+ const plain = this.cryptoBox.open(this.cryptoBox.envelopeKey, sealedBody)
664
+ if (!plain) {
665
+ auditLog(`sealed request body failed to open (${stream.info.path})`)
666
+ if (DEBUG) console.log('[relay-dbg] 400@open sid=%s path=%s len=%s bodyHead=%s', sid, stream.info.path, stream.reqLength, sealedBody.subarray(0, 16).toString('hex'))
667
+ this.respondInline(sid, 400, 'Bad Request')
668
+ this.closeStream(sid)
669
+ return
574
670
  }
671
+ this.forwardSealed(sid, stream, plain)
672
+ }
673
+
674
+ /** Send an opened (or bodyless) sealed request upstream and seal the response. */
675
+ forwardSealed(sid, stream, plain) {
575
676
  const info = stream.info
576
677
  // A sealed call to the mobile app's own API is answered here, not proxied
577
678
  // to DSH: the mobile bridge talks to host services directly.
@@ -645,7 +746,10 @@ export class PumpManager {
645
746
  if (stream.sealResponse) {
646
747
  out = this.cryptoBox.seal(this.cryptoBox.envelopeKey, out)
647
748
  this.respond(sid, 200, 'application/octet-stream', out, { 'x-relay-enc': '1' }, { keepAlive: stream.keepAlive })
648
- } else if (stream.injectBoot && /^HTTP\/[\d.]+\s+200/.test(out.toString('latin1').slice(0, 32))) {
749
+ } else if (stream.injectBoot && isHtmlResponse(out)) {
750
+ // Only real HTML gets the boot script. A request that merely *claimed*
751
+ // `sec-fetch-dest: document` to reach a JS asset would otherwise have the
752
+ // script prepended to JavaScript and break the bundle.
649
753
  const injected = injectBootScript(out, stream.relay, { keepAlive: stream.keepAlive })
650
754
  this.client?.sendStream(sid, injected)
651
755
  } else {
@@ -989,6 +1093,14 @@ function normalizeResponse(responseBuffer) { const split = responseBuffer.index
989
1093
  // bytes, so the message stays self-delimiting for keep-alive. The mobile
990
1094
  // enhancement (viewport meta + touch CSS + drawer JS) rides along in the same
991
1095
  // insertion. Exported for tests.
1096
+ /** A 200 whose Content-Type is really html - the only response the boot script fits. */
1097
+ function isHtmlResponse(responseBuffer) {
1098
+ const head = responseBuffer.toString('latin1', 0, Math.min(responseBuffer.length, 2048))
1099
+ if (!/^HTTP\/[\d.]+\s+200/.test(head)) return false
1100
+ const match = /\r\ncontent-type:\s*([^\r\n]*)/i.exec(head)
1101
+ return !!match && /\btext\/html\b/i.test(match[1])
1102
+ }
1103
+
992
1104
  export function injectBootScript(responseBuffer, relay, { keepAlive = false } = {}) {
993
1105
  const boot = relay
994
1106
  ? `\n<script>${buildBootSource(relay.id, relay.gate)}</script>\n`