{"record":{"id":"506544f3ccea42d6","repo":"BigPizzaV3/CodexPlusPlus","slug":"error","errorCode":null,"errorMessage":"收到未加密数据包","messagePattern":"收到未加密数据包","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"apps/codex-plus-mobile-relay/src/main.rs","lineNumber":810,"sourceCode":"  if (!crypto?.subtle) throw new Error(\"当前页面不是安全上下文，WebCrypto 不可用\");\n  const raw = new TextEncoder().encode($(\"key\").value);\n  const digest = await crypto.subtle.digest(\"SHA-256\", raw);\n  return crypto.subtle.importKey(\"raw\", digest, \"AES-GCM\", false, [\"encrypt\", \"decrypt\"]);\n}\nasync function encrypt(payload) {\n  if (!crypto?.subtle) {\n    setStatus(\"当前浏览器禁用 WebCrypto，已使用兼容模式\", true);\n    return { type: \"plaintext\", payload };\n  }\n  const key = await cryptoKey();\n  const nonce = crypto.getRandomValues(new Uint8Array(12));\n  const plain = new TextEncoder().encode(JSON.stringify(payload));\n  const encrypted = await crypto.subtle.encrypt({ name: \"AES-GCM\", iv: nonce }, key, plain);\n  return { type: \"encrypted\", nonce: b64url(nonce), payload: b64url(encrypted) };\n}\nasync function decrypt(envelope) {\n  if (envelope?.type === \"plaintext\") return envelope.payload;\n  if (!envelope || envelope.type !== \"encrypted\") throw new Error(\"收到未加密数据包\");\n  const key = await cryptoKey();\n  const nonce = b64urlDecode(envelope.nonce);\n  const data = b64urlDecode(envelope.payload);\n  const plain = await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: nonce }, key, data);\n  return JSON.parse(new TextDecoder().decode(plain));\n}\nasync function connect() {\n  const room = encodeURIComponent($(\"room\").value.trim());\n  if (!room || !$(\"key\").value) { setStatus(\"需要房间 ID 和 Key\", true); return; }\n  const scheme = location.protocol === \"https:\" ? \"wss\" : \"ws\";\n  if (socket) try { socket.close(); } catch {}\n  socket = new WebSocket(`${scheme}://${location.host}/client?room=${room}&token=${room}`);\n  socket.onopen = async () => { setStatus(\"已连接 relay，正在读取会话...\"); try { await loadSessions(); } catch (e) { setStatus(e.message, true); } };\n  socket.onclose = () => { appServerConnected = false; setStatus(\"已断开\"); };\n  socket.onerror = () => setStatus(\"连接错误\", true);\n  socket.onmessage = async (event) => {\n    try {\n      const message = JSON.parse(event.data);","sourceCodeStart":792,"sourceCodeEnd":828,"githubUrl":"https://github.com/BigPizzaV3/CodexPlusPlus/blob/b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6/apps/codex-plus-mobile-relay/src/main.rs#L792-L828","documentation":"decrypt() expects every incoming WebSocket envelope to be either an explicit {type:\"plaintext\"} message or an {type:\"encrypted\", nonce, payload} AES-GCM envelope. Any envelope with a missing/unknown `type` (null, malformed JSON that still parsed, or an unexpected packet type) is rejected with this error to avoid silently treating attacker-controlled or corrupt data as plaintext.","triggerScenarios":"Calling decrypt(envelope) with envelope whose type is neither \"plaintext\" nor \"encrypted\": server sends a control/heartbeat frame, protocol version mismatch, JSON that decoded to a non-envelope object, or envelope === null.","commonSituations":"Relay server and page JS out of sync after an update (new message types like ping/pong not handled); proxy stripped or reshaped the message; race where socket close/error frames are fed into decrypt().","solutions":["Log the raw envelope before decrypting to see the actual `type` value.","Update page and relay server together so both speak the same envelope protocol.","Whitelist known non-encrypted message types (ping, error, ack) before calling decrypt().","Wrap decrypt() in try/catch in the WebSocket onmessage handler so a bad packet doesn't kill the session."],"exampleFix":"// before\nconst data = await decrypt(JSON.parse(event.data));\n// after\nconst envelope = JSON.parse(event.data);\nif (envelope?.type === \"ping\") return;\nconst data = await decrypt(envelope).catch(err => { setStatus(`解密失败：${err.message}`, true); });","handlingStrategy":"try-catch","validationCode":"const env = JSON.parse(event.data); if (env && (env.type === \"plaintext\" || env.type === \"encrypted\" || env.type === \"ping\")) { /* safe to decrypt */ }","typeGuard":"function isEnvelope(x) { return !!x && (x.type === \"encrypted\" || x.type === \"plaintext\"); }","tryCatchPattern":"try { const data = await decrypt(envelope); } catch (e) { if (String(e.message).includes(\"未加密\")) { logRawEnvelope(envelope); reconnect(); } else throw e; }","preventionTips":["Whitelist and short-circuit known non-data frames (ping/pong/ack) before decrypt().","Keep relay server and page JS protocol versions in lockstep.","Always wrap onmessage decryption in try/catch so one bad packet doesn't break the socket loop."],"tags":["websocket","encryption","protocol","validation"],"backgroundTag":"unexpected-response-shape","analyzedSha":"b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6","analyzedAt":"2026-09-19T23:35:21.129Z","contentChangedAt":"2026-09-19T23:35:21.129Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}