{"record":{"id":"d3820275e79838c1","repo":"BigPizzaV3/CodexPlusPlus","slug":"webcrypto","errorCode":null,"errorMessage":"当前页面不是安全上下文，WebCrypto 不可用","messagePattern":"当前页面不是安全上下文，WebCrypto 不可用","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"apps/codex-plus-mobile-relay/src/main.rs","lineNumber":792,"sourceCode":"const params = new URLSearchParams(location.search);\nconst statusEl = $(\"status\");\nconst sessionsEl = $(\"sessions\");\nconst messagesEl = $(\"messages\");\nconst titleEl = $(\"threadTitle\");\nconst metaEl = $(\"threadMeta\");\nconst sessionsPane = $(\"sessionsPane\");\nconst detailPane = $(\"detailPane\");\nfunction setStatus(text, error = false) { statusEl.textContent = text; statusEl.classList.toggle(\"error\", error); }\nfunction b64url(bytes) {\n  let text = btoa(String.fromCharCode(...new Uint8Array(bytes)));\n  return text.replaceAll(\"+\", \"-\").replaceAll(\"/\", \"_\").replace(/=+$/g, \"\");\n}\nfunction b64urlDecode(text) {\n  const padded = text.replaceAll(\"-\", \"+\").replaceAll(\"_\", \"/\") + \"===\".slice((text.length + 3) % 4);\n  return Uint8Array.from(atob(padded), ch => ch.charCodeAt(0));\n}\nasync function cryptoKey() {\n  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(\"收到未加密数据包\");","sourceCodeStart":774,"sourceCodeEnd":810,"githubUrl":"https://github.com/BigPizzaV3/CodexPlusPlus/blob/b1ed92e5e4a2d74095d4b8db5af43cef7acba9c6/apps/codex-plus-mobile-relay/src/main.rs#L774-L810","documentation":"The embedded mobile relay page derives an AES-GCM key from the user-entered passphrase via crypto.subtle (SHA-256 digest + importKey). WebCrypto's SubtleCrypto is only exposed in secure contexts (HTTPS or localhost). When the page is opened over plain HTTP on a non-localhost host, `crypto?.subtle` is undefined and cryptoKey() throws this error before any encryption can happen.","triggerScenarios":"Calling cryptoKey() (directly or via encrypt()/decrypt() during a request or RPC) while `crypto.subtle` is undefined — i.e. the relay page is served over http:// from a LAN IP or hostname rather than https:// or http://localhost.","commonSituations":"Developer browses the relay page from a phone at http://192.168.x.x:port; reverse proxy terminates TLS elsewhere so the page itself is served over HTTP; browser treats the origin as insecure; mixed-content or self-signed-cert bypass leads to plain HTTP.","solutions":["Serve the relay page over HTTPS (add TLS to the relay server or put it behind an HTTPS reverse proxy).","Access via http://localhost / 127.0.0.1 where browsers still expose SubtleCrypto.","Check `window.isSecureContext` before rendering the page and show a clear setup hint instead of failing at first use.","As a last resort, fall back to a WebCrypto polyfill or refuse to run in insecure contexts explicitly."],"exampleFix":"// before\nasync function cryptoKey() {\n  if (!crypto?.subtle) throw new Error(\"当前页面不是安全上下文，WebCrypto 不可用\");\n// after\nasync function cryptoKey() {\n  if (!window.isSecureContext || !crypto?.subtle) {\n    throw new Error(\"当前页面不是安全上下文（需 HTTPS 或 localhost），WebCrypto 不可用\");\n  }","handlingStrategy":"validation","validationCode":"if (!window.isSecureContext || !crypto?.subtle) { alert(\"请通过 HTTPS 或 localhost 访问本页面\"); throw new Error(\"WebCrypto 不可用\"); }","typeGuard":"function hasWebCrypto(w = window): boolean { return typeof crypto !== \"undefined\" && !!crypto.subtle && typeof crypto.subtle.importKey === \"function\"; }","tryCatchPattern":"try { const key = await cryptoKey(); } catch (e) { if (String(e.message).includes(\"WebCrypto\")) showInsecureContextHint(); else throw e; }","preventionTips":["Always serve the relay over HTTPS or access via localhost.","Check `window.isSecureContext` at page load and disable crypto features early with a clear hint.","Add a TLS reverse proxy for LAN/phone access instead of plain HTTP."],"tags":["webcrypto","security","browser","encryption"],"backgroundTag":"insecure-context-webcrypto","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"}