mirror of
https://github.com/lWolvesl/antigravity-usage-monitor.git
synced 2026-11-26 17:09:28 +08:00
perf(panel): isolate host main.mjs startup, fix standalone CLI args, and close P0 audit bugs
This commit is contained in:
@@ -6,13 +6,12 @@
|
||||
* 2. Antigravity IDE / 2.0 后台守护桥接进程 (`mcp-entry.mjs` -> `bridge-daemon.mjs`)。
|
||||
*/
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { randomUUID } from 'node:crypto';
|
||||
import { isDeepStrictEqual } from 'node:util';
|
||||
import { handleAccountCredentialAction } from './account-switch.mjs';
|
||||
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
|
||||
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
|
||||
import {
|
||||
HERE,
|
||||
SETTINGS_FILE,
|
||||
clearRuntimeCaches,
|
||||
cloudSyncState,
|
||||
@@ -59,60 +58,7 @@ export function setStandalonePortListener(listener) {
|
||||
standalonePortListener = typeof listener === 'function' ? listener : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||
*
|
||||
* @param {string} relPath 相对路径
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export const readLocalAsync = async (relPath) => {
|
||||
const fullPath = join(HERE, relPath);
|
||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||
return fsPromises.readFile(fullPath, 'utf8');
|
||||
}
|
||||
return readFileSync(fullPath, 'utf8');
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||
*
|
||||
* @param {object} req
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLocalHostRequest(req) {
|
||||
if (!req?.headers) return true;
|
||||
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||
if (host && !hostMatch) {
|
||||
return false;
|
||||
}
|
||||
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||
return true;
|
||||
}
|
||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||
if (secFetchSite === 'cross-site') {
|
||||
return false;
|
||||
}
|
||||
if (origin) {
|
||||
const originMatch = origin.match(
|
||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||
);
|
||||
if (!originMatch) {
|
||||
return false;
|
||||
}
|
||||
if (hostMatch) {
|
||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||
const originPort = originMatch[3] || defaultPort;
|
||||
const hostPort = hostMatch[2] || defaultPort;
|
||||
if (originPort !== hostPort) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
export { isLocalHostRequest, readLocalAsync };
|
||||
|
||||
const MAX_SAFE_DATE_MS = 8_640_000_000_000_000;
|
||||
|
||||
@@ -142,7 +88,8 @@ function projectDisplayStep(st) {
|
||||
};
|
||||
}
|
||||
|
||||
let lastDisplaySteps = null;
|
||||
const MAX_DISPLAY_STEP_CACHE_ENTRIES = 8;
|
||||
const displayStepsCache = new Map();
|
||||
const displayStepFields = Object.keys(projectDisplayStep({}));
|
||||
|
||||
function haveSameDisplaySteps(previous, current) {
|
||||
@@ -165,23 +112,34 @@ function projectDisplayTelemetry(payload, requestedRevision) {
|
||||
let projected;
|
||||
let revision;
|
||||
if (typeof requestedRevision === 'string') {
|
||||
const cacheKey = active.cascadeId || '__empty__';
|
||||
const scope = [
|
||||
payload.account?.status,
|
||||
payload.account?.email || payload.account?.name || '',
|
||||
active.cascadeId,
|
||||
...agents.map((agent) => agent.agentId),
|
||||
];
|
||||
const previous = lastDisplaySteps;
|
||||
const previous = displayStepsCache.get(cacheKey);
|
||||
if (previous && isDeepStrictEqual(scope, previous.scope) &&
|
||||
sourceSteps.every((steps, index) => (steps && previous.sources[index]?.deref() === steps) ||
|
||||
haveSameDisplaySteps(previous.steps[index], steps))) {
|
||||
({ revision, steps: projected } = previous);
|
||||
previous.sources = sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined);
|
||||
displayStepsCache.delete(cacheKey);
|
||||
displayStepsCache.set(cacheKey, previous);
|
||||
} else {
|
||||
revision = randomUUID();
|
||||
projected = sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
lastDisplaySteps = { scope, steps: projected, revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined) };
|
||||
if (!displayStepsCache.has(cacheKey) && displayStepsCache.size >= MAX_DISPLAY_STEP_CACHE_ENTRIES) {
|
||||
displayStepsCache.delete(displayStepsCache.keys().next().value);
|
||||
}
|
||||
displayStepsCache.delete(cacheKey);
|
||||
displayStepsCache.set(cacheKey, {
|
||||
scope,
|
||||
steps: projected,
|
||||
revision,
|
||||
sources: sourceSteps.map((steps) => steps ? new WeakRef(steps) : undefined),
|
||||
});
|
||||
}
|
||||
}
|
||||
projected ||= sourceSteps.map((steps) => steps?.map(projectDisplayStep));
|
||||
@@ -452,6 +410,8 @@ export function executeRebuildCacheAction() {
|
||||
body: JSON.stringify({ ok: false, error: 'Failed to clear trajectory cache' }),
|
||||
};
|
||||
}
|
||||
displayStepsCache.clear();
|
||||
clearScannerRuntimeMemos();
|
||||
return {
|
||||
ok: true,
|
||||
status: 200,
|
||||
|
||||
@@ -114,7 +114,7 @@ function isSqliteBusyError(err) {
|
||||
* 以只读模式打开 SQLite 数据库执行查询并在 `finally` 中立即关闭连接,避免长连接阻塞宿主 WAL checkpoint。
|
||||
* 遇到瞬时锁竞争(`SQLITE_BUSY`)时自动重试 1 次。
|
||||
*/
|
||||
function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
export function withReadOnlySqliteDb(dbPath, queryFn) {
|
||||
const DatabaseSync = getNodeSqliteDatabaseSync();
|
||||
if (!DatabaseSync) return null;
|
||||
for (let attempt = 0; attempt < 2; attempt++) {
|
||||
@@ -729,6 +729,11 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
targets.push({ rootName: basename(root).toLowerCase(), dbPath });
|
||||
}
|
||||
|
||||
const rootsKey = roots
|
||||
.map((r) => String(r || '').trim())
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
|
||||
if (targets.length === 0) {
|
||||
if (productRoots === PRODUCT_DATA_ROOTS) {
|
||||
localSummaryMemo.sig = '';
|
||||
@@ -737,23 +742,41 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
localSummaryMemo.summariesObj = {};
|
||||
localSummaryMemo.sideQuestionParents = {};
|
||||
}
|
||||
if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||
}
|
||||
return { available: false, sig: '', byId: new Map(), summariesObj: {}, sideQuestionParents: {} };
|
||||
}
|
||||
|
||||
const sig = sigParts.join('||');
|
||||
if (
|
||||
!forceRefresh &&
|
||||
productRoots === PRODUCT_DATA_ROOTS &&
|
||||
localSummaryMemo.sig === sig &&
|
||||
localSummaryMemo.available
|
||||
) {
|
||||
return {
|
||||
available: true,
|
||||
sig,
|
||||
byId: localSummaryMemo.byId,
|
||||
summariesObj: localSummaryMemo.summariesObj || {},
|
||||
sideQuestionParents: localSummaryMemo.sideQuestionParents || {},
|
||||
};
|
||||
if (!forceRefresh) {
|
||||
if (
|
||||
productRoots === PRODUCT_DATA_ROOTS &&
|
||||
localSummaryMemo.sig === sig &&
|
||||
localSummaryMemo.available
|
||||
) {
|
||||
return {
|
||||
available: true,
|
||||
sig,
|
||||
byId: localSummaryMemo.byId,
|
||||
summariesObj: localSummaryMemo.summariesObj || {},
|
||||
sideQuestionParents: localSummaryMemo.sideQuestionParents || {},
|
||||
};
|
||||
}
|
||||
if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||
const cached = localSummaryMemo.byRootsKey.get(rootsKey);
|
||||
if (cached && cached.sig === sig && cached.available) {
|
||||
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||
localSummaryMemo.byRootsKey.set(rootsKey, cached);
|
||||
return {
|
||||
available: true,
|
||||
sig,
|
||||
byId: cached.byId,
|
||||
summariesObj: cached.summariesObj,
|
||||
sideQuestionParents: cached.sideQuestionParents,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const nextMap = new Map();
|
||||
@@ -990,6 +1013,18 @@ export function readLocalSummarySnapshot(productRoots = PRODUCT_DATA_ROOTS, { fo
|
||||
localSummaryMemo.available = true;
|
||||
localSummaryMemo.summariesObj = nextSummariesObj;
|
||||
localSummaryMemo.sideQuestionParents = nextSideQuestionParents;
|
||||
} else if (rootsKey && localSummaryMemo.byRootsKey instanceof Map) {
|
||||
if (!localSummaryMemo.byRootsKey.has(rootsKey) && localSummaryMemo.byRootsKey.size >= 8) {
|
||||
localSummaryMemo.byRootsKey.delete(localSummaryMemo.byRootsKey.keys().next().value);
|
||||
}
|
||||
localSummaryMemo.byRootsKey.delete(rootsKey);
|
||||
localSummaryMemo.byRootsKey.set(rootsKey, {
|
||||
available: true,
|
||||
sig,
|
||||
byId: nextMap,
|
||||
summariesObj: nextSummariesObj,
|
||||
sideQuestionParents: nextSideQuestionParents,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -1807,8 +1842,8 @@ function cleanShortPromptTitle(rawText, maxChars = 80) {
|
||||
.replace(/<CONTEXT_SUMMARY>[\s\S]*?<\/CONTEXT_SUMMARY>/gi, '')
|
||||
.replace(/<SYSTEM_MESSAGE>[\s\S]*$/i, '')
|
||||
.replace(/<ADDITIONAL_METADATA>[\s\S]*$/i, '');
|
||||
const reqMatch = withoutTags.match(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/i);
|
||||
const target = reqMatch ? reqMatch[1] : withoutTags;
|
||||
const reqMatches = [...withoutTags.matchAll(/<USER_REQUEST>([\s\S]*?)<\/USER_REQUEST>/gi)];
|
||||
const target = reqMatches.length > 0 ? reqMatches[reqMatches.length - 1][1] : withoutTags;
|
||||
const singleLine = target.replace(/\s+/g, ' ').trim();
|
||||
if (!singleLine) return '';
|
||||
return singleLine.length <= maxChars ? singleLine : `${singleLine.slice(0, maxChars - 1).trimEnd()}…`;
|
||||
|
||||
@@ -552,6 +552,7 @@ export const localSummaryMemo = {
|
||||
available: false,
|
||||
summariesObj: {},
|
||||
sideQuestionParents: {},
|
||||
byRootsKey: new Map(),
|
||||
};
|
||||
|
||||
/** 并发请求去重表(防止同一参数并发重复拉取)。 */
|
||||
@@ -615,6 +616,7 @@ export function clearRuntimeCaches() {
|
||||
localSummaryMemo.available = false;
|
||||
localSummaryMemo.summariesObj = {};
|
||||
localSummaryMemo.sideQuestionParents = {};
|
||||
localSummaryMemo.byRootsKey.clear();
|
||||
quotaSummaryCache.ts = 0;
|
||||
quotaSummaryCache.lastAttemptTs = 0;
|
||||
quotaSummaryCache.accountName = '';
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* @fileoverview 零业务状态依赖的静态资源读取与本机回环请求来源校验工具。
|
||||
*
|
||||
* 独立于 `./config.mjs` 与 `./api-actions.mjs`,使宿主入口 `main.mjs` 在生产环境下无需加载完整后端图谱与轨迹缓存。
|
||||
*/
|
||||
|
||||
import { readFileSync, promises as fsPromises } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
function resolveHttpHelperPanelDir() {
|
||||
const modDir = dirname(fileURLToPath(import.meta.url));
|
||||
return /[\\/]backend$/i.test(modDir) ? dirname(modDir) : modDir;
|
||||
}
|
||||
|
||||
/**
|
||||
* 异步读取 `sidecars/panel` 目录下的静态资源文件(兼容单元测试同步沙箱)。
|
||||
*
|
||||
* @param {string} relPath 相对路径
|
||||
* @returns {Promise<string>}
|
||||
*/
|
||||
export const readLocalAsync = async (relPath) => {
|
||||
const fullPath = join(resolveHttpHelperPanelDir(), relPath);
|
||||
if (typeof fsPromises !== 'undefined' && fsPromises?.readFile) {
|
||||
return fsPromises.readFile(fullPath, 'utf8');
|
||||
}
|
||||
return readFileSync(fullPath, 'utf8');
|
||||
};
|
||||
|
||||
/**
|
||||
* 校验请求是否来自本机回环同端口地址 (`127.0.0.1` / `localhost` / `[::1]`) 或受信 Webview Origin,
|
||||
* 阻止跨端口本地服务(如本地其他端口的开发服务器)或跨站 DNS Rebinding 访问 API。
|
||||
*
|
||||
* @param {object} req
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLocalHostRequest(req) {
|
||||
if (!req?.headers) return true;
|
||||
const host = String(req.headers.host || '').trim().toLowerCase();
|
||||
const hostMatch = host.match(/^(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/);
|
||||
if (host && !hostMatch) {
|
||||
return false;
|
||||
}
|
||||
const origin = String(req.headers.origin || '').trim().toLowerCase();
|
||||
if (origin && /^vscode-webview:\/\/[a-z0-9._-]+$/.test(origin)) {
|
||||
return true;
|
||||
}
|
||||
const secFetchSite = String(req.headers['sec-fetch-site'] || '').toLowerCase();
|
||||
if (secFetchSite === 'cross-site') {
|
||||
return false;
|
||||
}
|
||||
if (origin) {
|
||||
const originMatch = origin.match(
|
||||
/^(https?):\/\/(127\.0\.0\.1|localhost|\[::1\])(?::(\d+))?$/
|
||||
);
|
||||
if (!originMatch) {
|
||||
return false;
|
||||
}
|
||||
if (hostMatch) {
|
||||
const defaultPort = originMatch[1] === 'https' ? '443' : '80';
|
||||
const originPort = originMatch[3] || defaultPort;
|
||||
const hostPort = hostMatch[2] || defaultPort;
|
||||
if (originPort !== hostPort) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -354,6 +354,12 @@ const failedFetchCooldownMap = new Map();
|
||||
const liveActivityMemo = new Map();
|
||||
const transcriptTailMemo = new Map();
|
||||
|
||||
export function clearScannerRuntimeMemos() {
|
||||
failedFetchCooldownMap.clear();
|
||||
liveActivityMemo.clear();
|
||||
transcriptTailMemo.clear();
|
||||
}
|
||||
|
||||
function findTranscriptPath(cascadeId) {
|
||||
if (!cascadeId) return '';
|
||||
const normId = String(cascadeId).trim().toLowerCase();
|
||||
|
||||
@@ -513,7 +513,7 @@ export async function ensureLsEndpointDiscovered({
|
||||
if (lsRuntimeEndpoint.addr === 'test.invalid') {
|
||||
return false;
|
||||
}
|
||||
if (!force && lsRuntimeEndpoint.baseUrl && lsRuntimeEndpoint.csrfToken) {
|
||||
if (!force && lsRuntimeEndpoint.baseUrl && (lsRuntimeEndpoint.csrfToken || !lsRuntimeEndpoint.isDynamic)) {
|
||||
return true;
|
||||
}
|
||||
if (lsDiscoveryState.inFlight) {
|
||||
|
||||
@@ -356,8 +356,8 @@ export function createStandaloneWebServer(options = {}) {
|
||||
);
|
||||
}
|
||||
|
||||
if (options.lsAddr && options.csrfToken) {
|
||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken, { isDynamic: false });
|
||||
if (options.lsAddr) {
|
||||
setLsRuntimeEndpoint(options.lsAddr, options.csrfToken || '', { isDynamic: false });
|
||||
}
|
||||
|
||||
const expectedCookieVal = token ? deriveCookieValue(token) : '';
|
||||
|
||||
Reference in New Issue
Block a user