'use strict'; /** * Remote SSH Integration Engine for 哈基米.app * - Adaptive Linux ELF64 (x86-64 & arm64) Region Unlock (ValidateAndOnboardAccount) * - Bootstrap script decorator for dist/remote/bootstrapScript.js (auto-patches remote language_server) * - In-memory SSH remote session registry & Electron session-routed Connect RPC transport * * Strictly read-only toward official Antigravity.app; zero System Prompt modifications. */ const fs = require('fs'); const path = require('path'); const { sha256Buffer, readCString, scanGopclntabBySuffix, analyzeArm64RegionInRange, } = require('./binary-utils'); const TARGET_REGION_FUNC = 'authclient.ValidateAndOnboardAccount'; const FREE_TIE_BYTES = Buffer.from('667265652d746965', 'hex'); // "free-tie" LE // ============================================================================ // 1. Pure Node.js Linux ELF64 (x86-64 & arm64) Adaptive Region Analyzer & Patcher // ============================================================================ function parseElf64(buf) { if (!Buffer.isBuffer(buf) || buf.length < 64) { throw new Error('目标文件过小,非有效 ELF64 可执行文件'); } if (buf[0] !== 0x7f || buf[1] !== 0x45 || buf[2] !== 0x4c || buf[3] !== 0x46) { throw new Error('非 ELF 二进制文件'); } if (buf[4] !== 2 || buf[5] !== 1) { throw new Error(`仅支持 64-bit 小端 ELF (class=${buf[4]}, data=${buf[5]})`); } const eMachine = buf.readUInt16LE(18); const arch = eMachine === 62 ? 'x86-64' : eMachine === 183 ? 'arm64' : null; if (!arch) { throw new Error(`不支持的 ELF 架构 e_machine=${eMachine}`); } const eShoff = Number(buf.readBigUInt64LE(40)); const eShentsize = buf.readUInt16LE(58); const eShnum = buf.readUInt16LE(60); const eShstrndx = buf.readUInt16LE(62); if (!eShoff || eShentsize < 64 || eShnum === 0 || eShstrndx >= eShnum) { throw new Error('ELF 缺少有效的 Section Header 表'); } const shstrEntryOff = eShoff + eShstrndx * eShentsize; if (shstrEntryOff + 64 > buf.length) { throw new Error('ELF shstrtab 表项越界'); } const shstrOff = Number(buf.readBigUInt64LE(shstrEntryOff + 24)); const sections = []; const byName = Object.create(null); for (let i = 0; i < eShnum; i++) { const off = eShoff + i * eShentsize; if (off + 64 > buf.length) break; const shName = buf.readUInt32LE(off); const shType = buf.readUInt32LE(off + 4); const shAddr = Number(buf.readBigUInt64LE(off + 16)); const shOffset = Number(buf.readBigUInt64LE(off + 24)); const shSize = Number(buf.readBigUInt64LE(off + 32)); const name = readCString(buf, shstrOff + shName, 256); const sec = { name, type: shType, addr: shAddr, offset: shOffset, size: shSize }; sections.push(sec); if (name && !byName[name]) byName[name] = sec; } const textSec = byName['.text']; if (!textSec || textSec.size <= 0) { throw new Error('ELF 中未找到 .text 段'); } return { format: 'ELF64', arch, textVA: textSec.addr, textOff: textSec.offset, textSize: textSec.size, relaDyn: byName['.rela.dyn'] || null, sections, byName, }; } function fileOffToVA(elf, fileOff) { for (const sec of elf.sections) { if (sec.size > 0 && sec.addr > 0 && fileOff >= sec.offset && fileOff < sec.offset + sec.size) { return sec.addr + (fileOff - sec.offset); } } return fileOff; } function resolveElfGoTextBase(buf, elf, pclnOff, textStartFromHeader) { const { textVA, textOff, textSize } = elf; if ( Number.isFinite(textStartFromHeader) && textStartFromHeader >= textVA && textStartFromHeader < textVA + textSize ) { return { goTextVA: textStartFromHeader, goTextOff: textOff + (textStartFromHeader - textVA), source: 'pclntab_header', }; } // PIE Go ELF binaries leave pcHeader.textStart == 0 and store runtime.text via .rela.dyn in firstmoduledata if (elf.relaDyn && elf.relaDyn.size >= 24) { const pclnVA = fileOffToVA(elf, pclnOff); const needle = Buffer.alloc(8); needle.writeBigUInt64LE(BigInt(pclnVA), 0); const rOff = elf.relaDyn.offset; const rEnd = Math.min(buf.length, rOff + elf.relaDyn.size); let pos = rOff; while (pos < rEnd) { const hit = buf.indexOf(needle, pos); if (hit < 0 || hit >= rEnd) break; pos = hit + 8; if ((hit - rOff) % 24 !== 16) continue; const moddataVA = Number(buf.readBigUInt64LE(hit - 16)); const candidates = new Map(); const scanRange = (start, end) => { for (let p = start; p + 24 <= end; p += 24) { const ro = Number(buf.readBigUInt64LE(p)); if (ro >= moddataVA && ro < moddataVA + 0x160) { const ra = Number(buf.readBigInt64LE(p + 16)); if (ra >= textVA && ra < textVA + textSize) { candidates.set(ra, (candidates.get(ra) || 0) + 1); } } } }; const winStart = Math.max(rOff, hit - 16 - 24 * 64); const winEnd = Math.min(rEnd, hit - 16 + 24 * 128); scanRange(winStart, winEnd); if (candidates.size === 0) { scanRange(rOff, rEnd); } if (candidates.size > 0) { let bestVA = null; let bestCount = -1; for (const [va, cnt] of candidates.entries()) { if (cnt > bestCount || (cnt === bestCount && va < bestVA)) { bestVA = va; bestCount = cnt; } } return { goTextVA: bestVA, goTextOff: textOff + (bestVA - textVA), source: 'rela_firstmoduledata', }; } } } return { goTextVA: textVA, goTextOff: textOff, source: 'text_section_start', }; } function findElfGoFunctions(buf, elf, targetSuffixes, options = {}) { const minLC = elf.arch === 'arm64' ? 0x04 : 0x01; return scanGopclntabBySuffix(buf, targetSuffixes, { minLC, maxNfunc: options.maxNfunc ?? 5000000, resolveBase: (pclnOff, textStart) => resolveElfGoTextBase(buf, elf, pclnOff, textStart), }); } function decodeX64JneOrJmp(buf, off, fnEnd) { if (off + 2 > fnEnd) return null; const b0 = buf[off]; const b1 = buf[off + 1]; if (b0 === 0x0f && b1 === 0x85 && off + 6 <= fnEnd) { const rel32 = buf.readInt32LE(off + 2); const patched = Buffer.alloc(6); patched[0] = 0x90; patched[1] = 0xe9; patched.writeInt32LE(rel32, 2); return { len: 6, state: 'unpatched', target: off + 6 + rel32, patched }; } if (b0 === 0x90 && b1 === 0xe9 && off + 6 <= fnEnd) { const rel32 = buf.readInt32LE(off + 2); return { len: 6, state: 'patched', target: off + 6 + rel32, patched: Buffer.from(buf.subarray(off, off + 6)) }; } if (b0 === 0xe9 && off + 6 <= fnEnd && buf[off + 5] === 0x90) { const rel32 = buf.readInt32LE(off + 1); return { len: 6, state: 'patched', target: off + 5 + rel32, patched: Buffer.from(buf.subarray(off, off + 6)) }; } if (b0 === 0x75) { const rel8 = buf.readInt8(off + 1); const patched = Buffer.from([0xeb, buf[off + 1]]); return { len: 2, state: 'unpatched', target: off + 2 + rel8, patched }; } if (b0 === 0xeb) { const rel8 = buf.readInt8(off + 1); return { len: 2, state: 'patched', target: off + 2 + rel8, patched: Buffer.from(buf.subarray(off, off + 2)) }; } return null; } function analyzeX64RegionInRange(buf, fnStart, fnEnd, fnName) { const hasFreeTieConst = buf.indexOf(FREE_TIE_BYTES, fnStart) >= fnStart && buf.indexOf(FREE_TIE_BYTES, fnStart) < fnEnd; const candidates = []; const seenJOff = new Set(); for (let p = fnStart; p < fnEnd - 24; p++) { let cmpLen = 0; if ((buf[p] === 0x48 || buf[p] === 0x49) && buf[p + 1] === 0x83 && (buf[p + 2] & 0xf8) === 0xf8 && buf[p + 3] === 0x09) { cmpLen = 4; } else if ( buf[p] === 0x83 && (buf[p + 1] & 0xf8) === 0xf8 && buf[p + 2] === 0x09 && !(p > fnStart && (buf[p - 1] === 0x48 || buf[p - 1] === 0x49)) ) { cmpLen = 3; } else { continue; } const jOff = p + cmpLen; if (seenJOff.has(jOff)) continue; const br = decodeX64JneOrJmp(buf, jOff, fnEnd); if (!br) continue; const afterBr = jOff + br.len; const freeIdx = buf.indexOf(FREE_TIE_BYTES, afterBr); if (freeIdx < 0 || freeIdx > afterBr + 16) continue; let tailEnd = null; let loopTop = null; const tailScanEnd = Math.min(fnEnd - 6, freeIdx + 0x30); for (let q = freeIdx + 8; q < tailScanEnd; q++) { let nextQ = -1; if (buf[q] === 0x80 && (buf[q + 1] & 0xf8) === 0x78 && buf[q + 2] === 0x08 && buf[q + 3] === 0x72) { nextQ = q + 4; } else if (buf[q] === 0x80 && buf[q + 1] === 0x7c && buf[q + 3] === 0x08 && buf[q + 4] === 0x72) { nextQ = q + 5; } if (nextQ < 0 || nextQ + 2 > fnEnd) continue; let tTarget = null; let tEnd = null; if (buf[nextQ] === 0x0f && buf[nextQ + 1] === 0x85 && nextQ + 6 <= fnEnd) { tTarget = nextQ + 6 + buf.readInt32LE(nextQ + 2); tEnd = nextQ + 6; } else if (buf[nextQ] === 0x75) { tTarget = nextQ + 2 + buf.readInt8(nextQ + 1); tEnd = nextQ + 2; } if (tTarget !== null && tTarget >= fnStart && tTarget < p) { loopTop = tTarget; tailEnd = tEnd; break; } } if (tailEnd === null || loopTop === null) continue; const loopExits = []; const loopScanEnd = Math.min(p, loopTop + 0x48); for (let r = loopTop; r < loopScanEnd - 2; r++) { let dest = null; if (buf[r] === 0x0f && buf[r + 1] >= 0x80 && buf[r + 1] <= 0x8f && r + 6 <= fnEnd) { dest = r + 6 + buf.readInt32LE(r + 2); } else if (buf[r] >= 0x70 && buf[r] <= 0x7f) { dest = r + 2 + buf.readInt8(r + 1); } if (dest !== null && dest >= tailEnd && dest < fnEnd) { loopExits.push({ offset: r, dest }); } } if (loopExits.length === 0) continue; let immediateBreakTarget = null; if (tailEnd + 2 <= fnEnd && buf[tailEnd] === 0xeb) { immediateBreakTarget = tailEnd + 2 + buf.readInt8(tailEnd + 1); } else if (tailEnd + 5 <= fnEnd && buf[tailEnd] === 0xe9) { immediateBreakTarget = tailEnd + 5 + buf.readInt32LE(tailEnd + 1); } const isBreakOnly = immediateBreakTarget !== null && loopExits.some((e) => e.dest === immediateBreakTarget); const hasMatchBody = !isBreakOnly && br.target === loopTop && loopExits.some((e) => e.dest > tailEnd + 0x10); seenJOff.add(jOff); candidates.push({ p, jOff, jLen: br.len, state: br.state, target: br.target, patched: br.patched, loopTop, tailEnd, hasMatchBody, isBreakOnly, }); } const ineligible = candidates.filter((c) => c.hasMatchBody); const allowed = candidates.filter((c) => c.isBreakOnly && !c.hasMatchBody); if (ineligible.length === 0) { return { ok: false, status: 'pattern_missing', code: 'PATTERN_NOT_FOUND', fnName, hasFreeTieConst, allowedTiersCount: allowed.length, error: '未找到 x86-64 free-tier 地区限制分支' }; } if (ineligible.length > 1) { return { ok: false, status: 'ambiguous', code: 'AMBIGUOUS_MATCH', fnName, error: `在 ValidateAndOnboardAccount 中命中 ${ineligible.length} 处 x86-64 候选分支` }; } if (allowed.some((c) => c.state !== 'unpatched')) { return { ok: false, status: 'corrupted_allowed_tiers', code: 'ALLOWED_TIERS_MODIFIED', fnName, error: '检测到 allowedTiers 循环被意外修改' }; } const hit = ineligible[0]; return { ok: true, arch: 'x86-64', status: hit.state, fnName, fnStart, fnEnd, cmpOffset: hit.p, branchOffset: hit.jOff, branchLength: hit.jLen, targetOffset: hit.target, currentBytes: Buffer.from(buf.subarray(hit.jOff, hit.jOff + hit.jLen)), patchedBytes: hit.patched, allowedTiersCount: allowed.length, hasFreeTieConst, }; } function analyzeElfRegionUnlock(filePathOrBuf) { const buf = Buffer.isBuffer(filePathOrBuf) ? filePathOrBuf : fs.readFileSync(String(filePathOrBuf)); const sha256 = sha256Buffer(buf); let elf; try { elf = parseElf64(buf); } catch (e) { return { ok: false, status: 'unsupported', code: 'INVALID_ELF', sha256, error: e.message }; } const goInfo = findElfGoFunctions(buf, elf, [TARGET_REGION_FUNC]); if (!goInfo.foundPcln) { return { ok: false, status: 'pclntab_missing', code: 'PCLNTAB_NOT_FOUND', sha256, error: '找不到 Go .gopclntab 符号表' }; } const fn = goInfo.funcs[TARGET_REGION_FUNC]; if (!fn) { return { ok: false, status: 'symbol_missing', code: 'SYMBOL_NOT_FOUND', sha256, error: `找不到 ${TARGET_REGION_FUNC}` }; } const fnStart = Math.max(elf.textOff, fn.fnStart); const fnEnd = Math.min(buf.length, fn.fnEnd); if (fnEnd <= fnStart + 24) { return { ok: false, status: 'pattern_missing', code: 'FUNCTION_TOO_SMALL', fnName: fn.name, sha256, error: '函数体过短' }; } const res = elf.arch === 'arm64' ? analyzeArm64RegionInRange(buf, fnStart, fnEnd, fn.name) : analyzeX64RegionInRange(buf, fnStart, fnEnd, fn.name); return { ...res, format: 'ELF64', goTextSource: goInfo.goTextSource, sha256 }; } function patchElfBuffer(inputBuf) { const buf = Buffer.from(inputBuf); const reg = analyzeElfRegionUnlock(buf); let regionResult = reg; let modified = false; if (reg.ok && reg.status === 'unpatched') { reg.patchedBytes.copy(buf, reg.branchOffset); regionResult = { ...reg, status: 'patched', changed: true }; modified = true; } else if (reg.ok) { regionResult = { ...reg, changed: false }; } return { ok: Boolean(regionResult?.ok), modified, buffer: buf, region: regionResult, }; } function patchElfBinaryFile(filePath) { const target = path.resolve(String(filePath || '')); if (!target || !fs.existsSync(target)) { return { ok: false, error: `找不到目标 ELF 文件: ${filePath}` }; } const input = fs.readFileSync(target); const res = patchElfBuffer(input); if (res.modified) { const tmpPath = `${target}.hakimi_tmp.${process.pid}`; fs.writeFileSync(tmpPath, res.buffer); fs.chmodSync(tmpPath, 0o755); fs.renameSync(tmpPath, target); } return { ok: res.ok, modified: res.modified, region: res.region, }; } // ============================================================================ // 2. Embedded Self-Contained Python3 Remote ELF64 Region Patcher & Bootstrap Decorator // ============================================================================ function getRemotePythonPatcherSource() { return `import json, os, struct, sys FREE_TIE = bytes.fromhex("667265652d746965") def sxt(v, bits): m = 1 << (bits - 1) return (v & (m - 1)) - (v & m) def cstr(b, off, lim=2048): if off < 0 or off >= len(b): return "" e = b.find(b"\\x00", off, min(len(b), off + lim)) if e < 0: e = min(len(b), off + lim) return b[off:e].decode("utf-8", "replace") def parse_elf64(b): if len(b) < 64 or b[:4] != b"\\x7fELF" or b[4] != 2 or b[5] != 1: raise RuntimeError("not ELF64 LE") em = struct.unpack_from(" len(b): break sn, st, sf, sa, so, ss = struct.unpack_from(" len(b): continue nfunc = struct.unpack_from(" len(b) or fnm >= len(b): continue go_tva = tva if tva <= tstart < tva + tsz: go_tva = tstart elif rela_sec and rela_sec[3] >= 24: pcln_va = i for _, sa, so, ss in secs: if ss > 0 and sa > 0 and so <= i < so + ss: pcln_va = sa + (i - so) break _, _, roff, rsz = rela_sec rend = min(len(b), roff + rsz) ndl = struct.pack(" len(b): continue no = struct.unpack_from("= len(b): continue nm = cstr(b, fnm + no) for suf in targets: if suf not in found and (nm == suf or nm.endswith("/" + suf) or nm.endswith("." + suf)): neo = struct.unpack_from(" fn_s and b[p-1] in (0x48, 0x49)): clen = 3 else: continue jo = p + clen if jo in seen or jo + 2 > fn_e: continue b0, b1 = b[jo], b[jo+1] if b0 == 0x0f and b1 == 0x85 and jo + 6 <= fn_e: r32 = struct.unpack_from(" fn_e: continue tt, te = None, None if b[nq] == 0x0f and b[nq+1] == 0x85 and nq + 6 <= fn_e: tt = nq + 6 + struct.unpack_from(" tail_end + 0x10 for d in exits) seen.add(jo) cands.append((jo, st, pbytes, has_body, is_brk)) inel = [c for c in cands if c[3]] alw = [c for c in cands if c[4] and not c[3]] if len(inel) != 1 or any(c[1] != "unpatched" for c in alw): return None return inel[0][0], inel[0][1], inel[0][2] def analyze_region_a64(b, fn_s, fn_e): def dec_bne(w, o): return o + sxt((w >> 5) & 0x7ffff, 19) * 4 if (w & 0xff00001f) == 0x54000001 else None def dec_cb(w, o): return o + sxt((w >> 5) & 0x7ffff, 19) * 4 if (w & 0xff000010) == 0x54000000 else None def dec_b(w, o): return o + sxt(w & 0x03ffffff, 26) * 4 if (w & 0xfc000000) == 0x14000000 else None cands = [] for p in range(fn_s, fn_e - 20, 4): w0, w1 = struct.unpack_from("= te: exits.append(d) if not exits: continue has_body = any(d > te for d in exits) is_brk = all(d == te for d in exits) cands.append((p + 4, st, T, has_body, is_brk)) inel = [c for c in cands if c[3]] alw = [c for c in cands if c[4] and not c[3]] if len(inel) != 1 or any(c[1] != "unpatched" for c in alw): return None bo, st, T = inel[0][0], inel[0][1], inel[0][2] off26 = (T - bo) // 4 pbytes = struct.pack("/dev/null 2>&1 } hakimi_stamp_matches() { hakimi_stf="$1.hakimi_stamp" [ -f "$hakimi_stf" ] || return 1 hakimi_cur=$(cat "$hakimi_stf" 2>/dev/null) || return 1 [ "$hakimi_cur" = "$hakimi_want_spec" ] } hakimi_skip_matches() { hakimi_skf="$1.hakimi_skip" [ -f "$hakimi_skf" ] || return 1 hakimi_sk=$(cat "$hakimi_skf" 2>/dev/null) || return 1 hakimi_sz=$(wc -c <"$1" 2>/dev/null | tr -d ' ') || hakimi_sz=0 [ "$hakimi_sk" = "$hakimi_want_spec|$hakimi_sz" ] } hakimi_patch_bin() { hakimi_target=$1 [ -z "\${agy_serverpath:-}" ] || return 0 [ -f "$hakimi_target" ] || return 0 if hakimi_stamp_matches "$hakimi_target"; then return 0 fi if hakimi_skip_matches "$hakimi_target"; then return 0 fi hakimi_log="\${agy_datadir:-/tmp}/hakimi-patch.log" mkdir -p "\${agy_datadir:-/tmp}" 2>/dev/null || true if ! hakimi_can_patch; then printf '[hakimi] python3 not found; skipping remote patch for %s\\n' "$hakimi_target" >>"$hakimi_log" 2>&1 return 0 fi hakimi_py_file="\${agy_bindir:-/tmp}/.hakimi_patch.$$.py" if printf '%s' "$hakimi_py_b64" | base64 -d >"$hakimi_py_file" 2>>"$hakimi_log" || python3 -c 'import base64,sys; open(sys.argv[1],"wb").write(base64.b64decode(sys.argv[2]))' "$hakimi_py_file" "$hakimi_py_b64" 2>>"$hakimi_log"; then if python3 "$hakimi_py_file" "$hakimi_target" >>"$hakimi_log" 2>&1; then printf '%s\\n' "$hakimi_want_spec" >"$hakimi_target.hakimi_stamp" 2>/dev/null || true rm -f "$hakimi_target.hakimi_skip" 2>/dev/null || true else hakimi_sz=$(wc -c <"$hakimi_target" 2>/dev/null | tr -d ' ') || hakimi_sz=0 printf '%s|%s\\n' "$hakimi_want_spec" "$hakimi_sz" >"$hakimi_target.hakimi_skip" 2>/dev/null || true printf '[hakimi] patch failed (non-fatal) for %s\\n' "$hakimi_target" >>"$hakimi_log" 2>&1 fi fi rm -f "$hakimi_py_file" 2>/dev/null || true return 0 } hakimi_maybe_replace_unpatched() { [ -z "\${agy_serverpath:-}" ] || return 0 [ -z "\${agy_rep_pid:-}" ] || return 0 [ "\${agy_attach_only:-0}" != 1 ] || return 0 hakimi_can_patch || return 0 agy_read_disc || return 0 agy_is_ls_pid "$agy_dpid" || return 0 hakimi_exe=$(readlink "/proc/$agy_dpid/exe" 2>/dev/null) || hakimi_exe= if [ "$hakimi_exe" = "$agy_bin" ] && hakimi_stamp_matches "$agy_bin"; then return 0 fi if [ "$hakimi_exe" = "$agy_bin" ] && hakimi_skip_matches "$agy_bin"; then return 0 fi # Running server is unpatched or uses an outdated Hakimi spec: trigger Antigravity's native locked replace flow agy_rep_pid=$agy_dpid agy_rep_ver=$agy_dver } agy_check_paths() { set -- "$agy_root" "$agy_root/bin" "$agy_datadir" "$agy_daemon" "$agy_disc" [ -n "$agy_serverpath" ] || set -- "$@" "$agy_bindir" "$agy_bin" for agy_f do [ -e "$agy_f" ] || continue [ -O "$agy_f" ] || agy_fail INSTALL_FAILED "$agy_f is not owned by you" done hakimi_maybe_replace_unpatched || true } agy_prepare() { if [ -n "$agy_serverpath" ]; then agy_check_server_path else mkdir -p "$agy_bindir" 2>/dev/null || agy_fail INSTALL_FAILED "cannot create $agy_bindir" agy_install hakimi_patch_bin "$agy_bin" || true fi } `; } function decorateBootstrapScript(script) { if (typeof script !== 'string' || !script) return script; if (script.includes('hakimi_patch_bin()')) return script; const hookShell = buildRemoteBootstrapHookShell(); const anchor = '\nagy_main; exit $?'; const idx = script.lastIndexOf(anchor); if (idx >= 0) { return `${script.slice(0, idx)}\n${hookShell}${script.slice(idx)}`; } return `${script}\n${hookShell}`; } // ============================================================================ // 3. Runtime SSH Session Registry & Electron Session-Routed Connect RPC // ============================================================================ const remoteSessions = new Map(); function normalizeHttpsLoopbackOrigin(rawUrl) { if (!rawUrl || typeof rawUrl !== 'string') return null; try { const u = new URL(rawUrl); if ((u.protocol !== 'https:' && u.protocol !== 'http:') || (u.hostname !== '127.0.0.1' && u.hostname !== 'localhost')) { return null; } return u.origin; } catch { return null; } } function recordRemoteSession(entry, sshSession) { try { const hostId = entry?.hostId; if (!hostId || !sshSession) return null; const origin = normalizeHttpsLoopbackOrigin(sshSession.url); const csrfToken = String(sshSession?.discovery?.csrfToken || '').trim(); const info = { hostId: String(hostId), label: String(entry?.label || hostId), origin, csrfToken, pid: Number(sshSession?.discovery?.pid || 0) || null, lsVersion: String(sshSession?.discovery?.lsVersion || ''), socksPort: Number(sshSession?.socksPort || 0) || null, updatedAt: Date.now(), }; remoteSessions.set(String(hostId), info); return info; } catch { return null; } } function forgetRemoteSession(hostId) { if (!hostId) return false; return remoteSessions.delete(String(hostId)); } function getRemoteSession(hostId) { if (!hostId) return null; return remoteSessions.get(String(hostId)) || null; } function getRemoteBackendForSender(sender) { if (!sender) return null; try { const wb = require('./remote/windowBackends'); if (wb && typeof wb.remoteBackendOf === 'function') { const info = wb.remoteBackendOf(sender); if (info && info.kind === 'ssh' && info.hostId) return info; } } catch {} return null; } function getRemoteBackendForWindow(win) { if (!win) return null; try { const wb = require('./remote/windowBackends'); if (wb && typeof wb.remoteBackendOfWindow === 'function') { const info = wb.remoteBackendOfWindow(win); if (info && info.kind === 'ssh' && info.hostId) return info; } } catch {} return null; } function createRemoteSessionRequester(sender, sessionInfo, expectedOrigin = null) { const ses = sender?.session; const origin = normalizeHttpsLoopbackOrigin(expectedOrigin || sessionInfo?.origin); const csrfToken = String(sessionInfo?.csrfToken || '').trim(); if (!ses || typeof ses.fetch !== 'function') { throw new Error('SSH 窗口 Electron session 不可用,无法通过代理访问远端语言服务'); } if (!origin) { throw new Error('SSH 远端语言服务地址无效'); } if (!csrfToken) { throw new Error('SSH 远端 CSRF Token 尚未就绪,请等待连接完成或重连'); } return { origin, hostId: sessionInfo?.hostId || null, label: sessionInfo?.label || null, csrfToken, call: async (method, body = {}) => { const url = `${origin}/exa.language_server_pb.LanguageServerService/${method}`; const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), 20000); try { const res = await ses.fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Connect-Protocol-Version': '1', 'x-codeium-csrf-token': csrfToken, }, body: JSON.stringify(body || {}), signal: controller.signal, redirect: 'manual', }); const text = await res.text(); if (!res.ok) { throw new Error(`SSH Remote API HTTP ${res.status}: ${text.slice(0, 200)}`); } return JSON.parse(text); } finally { clearTimeout(timer); } }, }; } module.exports = { TARGET_REGION_FUNC, parseElf64, fileOffToVA, findElfGoFunctions, analyzeElfRegionUnlock, patchElfBuffer, patchElfBinaryFile, getRemotePythonPatcherSource, buildRemoteBootstrapHookShell, decorateBootstrapScript, recordRemoteSession, forgetRemoteSession, getRemoteSession, getRemoteBackendForSender, getRemoteBackendForWindow, createRemoteSessionRequester, };