@tina_summer/codepocket 2.5.8 → 2.6.1

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 (2) hide show
  1. package/bin/codepocket.js +136 -7
  2. package/package.json +6 -5
package/bin/codepocket.js CHANGED
@@ -14,6 +14,8 @@ const fs = require('fs')
14
14
  const path = require('path')
15
15
  const os = require('os')
16
16
  const readline = require('readline')
17
+ const crypto = require('crypto')
18
+ const nacl = require('tweetnacl')
17
19
  const { HttpsProxyAgent } = require('https-proxy-agent')
18
20
  const { startMcpServer, handlePhoneActionResponse: onPhoneActionResponse } = require('../src/mcp-server')
19
21
  const { runTestCli } = require('../src/mcp-client')
@@ -254,13 +256,42 @@ function checkRunning() {
254
256
  if (args[0] === 'stop') {
255
257
  const pid = checkRunning()
256
258
  if (!pid) {
257
- console.log('[codepocket] Not running')
259
+ // Even with no recorded daemon PID, clean up orphaned hub/runner from prior runs
260
+ const orphans = killOrphans()
261
+ console.log(orphans
262
+ ? `[codepocket] 清理残留进程: ${orphans}`
263
+ : '[codepocket] Not running')
258
264
  process.exit(0)
259
265
  }
260
- try { process.kill(pid, process.platform === 'win32' ? 'SIGKILL' : 'SIGTERM') } catch {}
266
+ const sig = process.platform === 'win32' ? 'SIGKILL' : 'SIGTERM'
267
+ // Kill the whole process group (daemon is a group leader via detached:true,
268
+ // so -pid kills daemon + hub + runner together)
269
+ try { process.kill(-pid, sig) } catch {}
270
+ // Fallback: kill just the daemon if group kill failed
271
+ try { process.kill(pid, sig) } catch {}
261
272
  try { fs.unlinkSync(PID_FILE) } catch {}
262
- console.log(`[codepocket] Stopped (PID ${pid})`)
263
- process.exit(0)
273
+ // Wait briefly, then sweep up any orphans that escaped the group kill
274
+ setTimeout(() => {
275
+ const orphans = killOrphans()
276
+ const extra = orphans ? `,清理残留: ${orphans}` : ''
277
+ console.log(`[codepocket] Stopped (PID ${pid})${extra}`)
278
+ process.exit(0)
279
+ }, 300)
280
+ }
281
+
282
+ // Kill orphaned hub/runner processes by binary name (cross-platform).
283
+ // The hub binary (cpkt-hub) also runs the runner/sync modes, so matching the
284
+ // binary name catches every mode it was spawned in.
285
+ function killOrphans() {
286
+ try {
287
+ if (process.platform === 'win32') {
288
+ execSync('taskkill /F /IM cpkt-hub.exe /T', { stdio: 'ignore' })
289
+ } else {
290
+ execSync('pkill -f cpkt-hub', { stdio: 'ignore' })
291
+ }
292
+ return 'hub'
293
+ } catch {}
294
+ return ''
264
295
  }
265
296
 
266
297
  // 'logs' subcommand
@@ -489,6 +520,101 @@ async function startSSE() {
489
520
  } catch { setTimeout(startSSE, 5000) }
490
521
  }
491
522
 
523
+ // ── End-to-end encryption (X25519 + XSalsa20-Poly1305) ──
524
+ // The relay only forwards e2ePubKey + opaque `enc` envelopes; it cannot decrypt.
525
+ // Nonces are counter-based with a direction tag to avoid reuse across directions
526
+ // under the same shared key: connector uses 0xFF prefix, phone uses 0x00.
527
+
528
+ let e2eKeypair = null // { publicKey, secretKey } Uint8Arrays (X25519)
529
+ let e2eSharedKey = null // Uint8Array(32), set when peer pubkey arrives
530
+ let e2eNonceCounter = 0
531
+
532
+ function ensureE2EKeypair() {
533
+ if (e2eKeypair) return e2eKeypair
534
+ // Node has crypto.randomBytes — nacl.box.keyPair auto-detects it
535
+ e2eKeypair = nacl.box.keyPair()
536
+ return e2eKeypair
537
+ }
538
+
539
+ function getE2EPubKeyB64() {
540
+ return Buffer.from(ensureE2EKeypair().publicKey).toString('base64')
541
+ }
542
+
543
+ function setPeerE2EPubKey(peerPubKeyB64) {
544
+ if (!peerPubKeyB64 || typeof peerPubKeyB64 !== 'string') return
545
+ try {
546
+ const peerPub = Buffer.from(peerPubKeyB64, 'base64')
547
+ if (peerPub.length !== 32) return
548
+ e2eSharedKey = nacl.box.before(peerPub, ensureE2EKeypair().secretKey)
549
+ e2eNonceCounter = 0
550
+ log('[codepocket] ✓ E2E 加密通道已建立')
551
+ } catch (e) {
552
+ log(`[codepocket] E2E 密钥协商失败: ${e.message}`)
553
+ }
554
+ }
555
+
556
+ function nextNonce() {
557
+ e2eNonceCounter++
558
+ const n = new Uint8Array(24)
559
+ n[0] = 0xFF // connector→phone direction tag
560
+ let c = e2eNonceCounter
561
+ for (let i = 6; i >= 1; i--) { n[i] = c & 0xff; c = Math.floor(c / 256) }
562
+ return n
563
+ }
564
+
565
+ function e2eEncrypt(obj) {
566
+ if (!e2eSharedKey) return undefined
567
+ try {
568
+ const msgBytes = Buffer.from(JSON.stringify(obj), 'utf8')
569
+ const nonce = nextNonce()
570
+ const cipher = nacl.secretbox(msgBytes, nonce, e2eSharedKey)
571
+ if (!cipher) return undefined
572
+ return { n: Buffer.from(nonce).toString('base64'), c: Buffer.from(cipher).toString('base64') }
573
+ } catch { return undefined }
574
+ }
575
+
576
+ function e2eDecrypt(envelope) {
577
+ if (!envelope || typeof envelope !== 'object') return undefined
578
+ if (typeof envelope.n !== 'string' || typeof envelope.c !== 'string') return undefined
579
+ if (!e2eSharedKey) return undefined
580
+ try {
581
+ const nonce = new Uint8Array(Buffer.from(envelope.n, 'base64'))
582
+ const cipher = new Uint8Array(Buffer.from(envelope.c, 'base64'))
583
+ const plain = nacl.secretbox.open(cipher, nonce, e2eSharedKey)
584
+ if (!plain) return undefined
585
+ return JSON.parse(Buffer.from(plain).toString('utf8'))
586
+ } catch { return undefined }
587
+ }
588
+
589
+ // Pack a message for sending: moves sensitive fields into an `enc` envelope.
590
+ // Routing fields (type, requestId, actionId, success, status, ok) stay plaintext.
591
+ function encryptMessage(msg) {
592
+ if (!e2eSharedKey) return msg
593
+ const routing = ['type', 'requestId', 'actionId', 'success', 'status', 'ok', 'reconnected']
594
+ const content = {}
595
+ for (const [k, v] of Object.entries(msg)) {
596
+ if (!routing.includes(k)) content[k] = v
597
+ }
598
+ if (Object.keys(content).length === 0) return msg
599
+ const enc = e2eEncrypt(content)
600
+ if (!enc) return msg
601
+ const out = { type: msg.type }
602
+ for (const k of routing) if (k in msg) out[k] = msg[k]
603
+ out.enc = enc
604
+ return out
605
+ }
606
+
607
+ // Unpack a received message: merges decrypted content back from `enc`.
608
+ function decryptMessage(msg) {
609
+ if (!msg || !msg.enc || !e2eSharedKey) return msg
610
+ const content = e2eDecrypt(msg.enc)
611
+ if (content) {
612
+ delete msg.enc
613
+ Object.assign(msg, content)
614
+ }
615
+ return msg
616
+ }
617
+
492
618
  // ── Relay ──
493
619
 
494
620
  function connectRelay() {
@@ -518,6 +644,7 @@ function connectRelay() {
518
644
  type: 'register',
519
645
  key: relayKey,
520
646
  sessionToken: savedSession?.sessionToken || undefined,
647
+ e2ePubKey: getE2EPubKeyB64(),
521
648
  }))
522
649
  relayPingInterval = setInterval(() => {
523
650
  if (relayWs?.readyState === WebSocket.OPEN) {
@@ -529,6 +656,7 @@ function connectRelay() {
529
656
  relayWs.on('message', (raw) => {
530
657
  let msg
531
658
  try { msg = JSON.parse(raw.toString()) } catch { return }
659
+ msg = decryptMessage(msg)
532
660
  switch (msg.type) {
533
661
  case 'registered': {
534
662
  try {
@@ -543,6 +671,7 @@ function connectRelay() {
543
671
  break
544
672
  }
545
673
  case 'client-connected': {
674
+ if (msg.clientE2EPubKey) setPeerE2EPubKey(msg.clientE2EPubKey)
546
675
  log('[codepocket] ✓ 小程序已连接')
547
676
  break
548
677
  }
@@ -604,7 +733,7 @@ function connectRelay() {
604
733
  }
605
734
 
606
735
  function sendToRelay(msg) {
607
- if (relayWs?.readyState === WebSocket.OPEN) relayWs.send(JSON.stringify(msg))
736
+ if (relayWs?.readyState === WebSocket.OPEN) relayWs.send(JSON.stringify(encryptMessage(msg)))
608
737
  }
609
738
 
610
739
  function sendSpawnResult(requestId, sessionId, error) {
@@ -613,12 +742,12 @@ function sendSpawnResult(requestId, sessionId, error) {
613
742
  : { type: 'spawn-session-result', requestId, success: true, sessionId }
614
743
  // Retry sending if relay connection is temporarily down
615
744
  if (relayWs?.readyState === WebSocket.OPEN) {
616
- relayWs.send(JSON.stringify(msg))
745
+ relayWs.send(JSON.stringify(encryptMessage(msg)))
617
746
  } else {
618
747
  log(`[codepocket] Relay not open, retrying spawn result in 2s...`)
619
748
  setTimeout(() => {
620
749
  if (relayWs?.readyState === WebSocket.OPEN) {
621
- relayWs.send(JSON.stringify(msg))
750
+ relayWs.send(JSON.stringify(encryptMessage(msg)))
622
751
  } else {
623
752
  log(`[codepocket] Failed to send spawn result, relay still down`)
624
753
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.5.8",
3
+ "version": "2.6.1",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",
@@ -16,13 +16,14 @@
16
16
  "dependencies": {
17
17
  "https-proxy-agent": "^7.0.0",
18
18
  "qrcode-terminal": "^0.12.0",
19
+ "tweetnacl": "^1.0.3",
19
20
  "ws": "^8.18.0"
20
21
  },
21
22
  "optionalDependencies": {
22
- "@tina_summer/codepocket-darwin-arm64": "2.5.8",
23
- "@tina_summer/codepocket-darwin-x64": "2.5.8",
24
- "@tina_summer/codepocket-linux-x64": "2.5.8",
25
- "@tina_summer/codepocket-win32-x64": "2.5.8"
23
+ "@tina_summer/codepocket-darwin-arm64": "2.6.1",
24
+ "@tina_summer/codepocket-darwin-x64": "2.6.1",
25
+ "@tina_summer/codepocket-linux-x64": "2.6.1",
26
+ "@tina_summer/codepocket-win32-x64": "2.6.1"
26
27
  },
27
28
  "engines": {
28
29
  "node": ">=18"