// 1.3 sleep/wake self-heal: a tiny page the gate serves at http://127.0.0.1:/app#t=&p=&b=. // // Before 1.3 the plugin frame was navigated straight to the daemon's random port. When the computer slept and the daemon was // gone afterwards (or the WebView reloaded the frame), the frame reloaded that dead address: "127.0.0.1 拒绝连接", and no // script of ours was left to recover. Now the frame stays on the gate's stable port and shows the daemon page in a child // iframe. A reload lands on the gate (alive as long as the plugin host is), and this page notices the child is not there: // - the child posts {ac_console:"alive"} every 2 s while its WebSocket is open and {ac_console:"lost",at} after 5 s without it; // - no "alive" within 12 s of loading (6 s after the child frame loaded), a "lost", or 15 s of silence (only while visible, and not counting time this page's // own timers were suspended by sleep) → go back through the Magpie plugin page (b), like 1.1's self-heal: boot.js reads the // fresh session.js and opens the gate, which restarts the daemon and sends the frame here again with the new port. // - at most 3 automatic tries in 2 minutes (counted in ?ac_try=., carried through b → boot.js → gate → here); // then a button, so a daemon that can't start doesn't loop forever. // - coming back to the page (visibilitychange → visible, or window focus) checks at once instead of waiting out the timers // that were pushed back while hidden: if the child never said alive within bootMs of loading, or its last real alive is // older than silentMs, it gets probeMs (two heartbeats) to speak up, then recover(); a child that is still alive is // never refreshed. If an end state with Reconnect is showing, coming back counts as the user clicking it (also when // the 3 automatic tries are used up), so the user never returns to a dead button. // - every disconnect / invalid-link end state shows a Reconnect button. A missing #b= is filled from sessionStorage // (last safe Magpie back URL written when this page first saw a valid b; read/write re-run safeBack). With a stored // back, recover navigates via go(false). With none: if this page is framed by Magpie (window.parent !== window), it // posts { magpie: 1, method: "error", params: { message } } so the host shows its Try-again card and rebuilds the // plugin iframe; Reconnect does the same and falls back to location.reload() after 300 ms if the frame was not // unloaded. The copy tells the user to turn the Agent Console plugin off and on again in Magpie's Plugins page if // that is still not enough (switching Magpie top-bar tabs does not rebuild the iframe within IDLE_MS). // // Security: this page holds no secret of its own. The daemon token arrives only in its # fragment (as before, never sent to a // server, not in Referer) and is handed to the child in the child's fragment; the gate key is never here. The child is always // http://127.0.0.1:/, b must pass the same Magpie-page check as everywhere else (http(s) on loopback only, // path /_magpie/plugin//(page/)?index.html, no credentials — no open redirect; never the desktop window's // wails://localhost or http://wails.localhost, which this frame can't navigate to: see gate.mjs safeBackUrl), // and only the Magpie theme protocol is relayed (theme events / hello answers down, the hello call up). The page runs inside // Magpie's sandboxed plugin frame (opaque origin) and is served with a nonce-only CSP. /** Same check as safeBackUrl in gate.mjs / web/src/api/backToMagpie.ts, as source for the page: loopback Magpie pages only * (magpie web). Never Magpie's desktop window (wails://localhost, http://wails.localhost): see gate.mjs safeBackUrl. */ const SAFE_BACK_SRC = String.raw`function safeBack(raw) { if (typeof raw !== "string" || !raw || raw.length > 2048) return null; var u; try { u = new URL(raw); } catch (e) { return null; } if (u.protocol !== "http:" && u.protocol !== "https:") return null; if (u.username || u.password) return null; var h = u.hostname.toLowerCase(); var loopback = h === "127.0.0.1" || h === "localhost" || h === "[::1]"; if (!loopback) return null; if (!/^\/_magpie\/plugin\/[A-Za-z0-9_-]{1,128}\/(?:page\/)?index\.html$/.test(u.pathname)) return null; return u.protocol + "//" + u.host + u.pathname + u.search; }`; /** ?ac_try=.: valid shape only */ export function parseTry(raw) { const m = /^(\d{10,15})\.([0-9])$/.exec(typeof raw === "string" ? raw : ""); return m ? { start: Number(m[1]), n: Number(m[2]) } : null; } export const WRAP_TIMING = { bootMs: 12000, afterLoadMs: 6000, silentMs: 15000, maxTries: 3, triesWindowMs: 120000, probeMs: 4000 }; const SCRIPT = String.raw`(function () { "use strict"; var T = __TIMING__; ${SAFE_BACK_SRC} var frag = new URLSearchParams(location.hash.slice(1)); var token = frag.get("t") || ""; var port = Number(frag.get("p")); var BACK_KEY = "ac_wrap_back"; // A stored value that no longer passes safeBack (e.g. http://wails.localhost/… kept by 1.3.5 / 1.3.6) is never followed // and is dropped. (Inside Magpie's sandboxed frame this page has an opaque origin and sessionStorage throws: null.) function readStoredBack() { try { var raw = sessionStorage.getItem(BACK_KEY); var v = safeBack(raw); if (raw && !v) sessionStorage.removeItem(BACK_KEY); return v; } catch (e) { return null; } } function writeStoredBack(v) { if (!v) return; try { sessionStorage.setItem(BACK_KEY, v); } catch (e) {} } var back = safeBack(frag.get("b")); if (back) writeStoredBack(back); var q = new URLSearchParams(location.search); var lang = (q.get("lang") || "").toLowerCase(); var zh = !lang || lang.indexOf("zh") === 0; if (q.get("theme") === "dark") document.documentElement.className = "dark"; var f = document.getElementById("f"); var box = document.getElementById("m"); var said = document.getElementById("s"); var btn = document.getElementById("r"); var RECONNECT = ["重新连接", "Reconnect"]; function onReturn(fn) { document.addEventListener("visibilitychange", function () { if (document.visibilityState === "visible") fn(); }); window.addEventListener("focus", function () { if (document.visibilityState !== "hidden") fn(); }); } function msg(zhText, enText, button) { said.textContent = zh ? zhText : enText; box.hidden = false; if (button) { btn.textContent = zh ? button[0] : button[1]; btn.hidden = false; } } // Ask Magpie's parent frame to show its native "Try again" card: pluginpages.js broke(key) → kernel.js fail() replaces // #view-'s children (this frame included) with the card at once, and Try again runs open(key) again, a fresh // " + "" + `` + "" ); } /** * Who may frame /app: the gate itself, a loopback page (Magpie's plugin page and `magpie web` on this computer) and * Magpie's desktop window, which is wails://localhost on macOS / Linux and http://wails.localhost on Windows (WebView2). * Any other site gets a blank frame. Keep in sync with the README's security section. */ export const WRAPPER_FRAME_ANCESTORS = "frame-ancestors 'self' http://127.0.0.1:* http://localhost:* http://[::1]:* http://wails.localhost:* wails:"; export function wrapperCsp(nonce) { return [ "default-src 'none'", `script-src 'nonce-${nonce}'`, `style-src 'nonce-${nonce}'`, "frame-src http://127.0.0.1:*", WRAPPER_FRAME_ANCESTORS, "base-uri 'none'", "form-action 'none'", ].join("; "); }