feat(panel): add formula-safe CSV/Markdown export, compact vertical action menus, and local file export with reveal toast

This commit is contained in:
fish
2026-11-22 11:54:20 +09:00
parent 6da4d3479c
commit a98fda8b44
25 changed files with 3817 additions and 117 deletions
+38
View File
@@ -17,6 +17,7 @@ import {
trackEndpointRequestStart,
} from './endpoint-registry.mjs';
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
import { revealLocalExportFile, writeLocalExportFile } from './file-exporter.mjs';
import { clearScannerRuntimeMemos } from './local-scanner.mjs';
import {
SETTINGS_FILE,
@@ -735,6 +736,33 @@ export function executeSessionMigrationMigrateAction(data = undefined, opts = {}
};
}
export function executeExportFileAction(data, opts = {}) {
const result = writeLocalExportFile(data || {}, {
...(opts?.exportDir ? { overrideDir: opts.exportDir } : {}),
...(opts?.homeDir ? { homeDir: opts.homeDir } : {}),
...(opts?.fallbackDataDir ? { fallbackDataDir: opts.fallbackDataDir } : {}),
});
return {
status: Number(result.status || (result.ok ? 200 : 400)),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
export function executeRevealFileAction(data, opts = {}) {
const result = revealLocalExportFile(data?.filePath, {
...(opts?.platform ? { platform: opts.platform } : {}),
...(typeof opts?.spawnFn === 'function' ? { spawnFn: opts.spawnFn } : {}),
});
return {
status: Number(result.status || (result.ok ? 200 : 400)),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
const BRIDGE_ROUTE_LOOKUP = new Map(
BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action])
);
@@ -757,6 +785,12 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
if (isPlainObject(data) && data.__sessionMigrationAction === 'migrate') {
return executeSessionMigrationMigrateAction(data.payload || data, opts);
}
if (isPlainObject(data) && data.__exportFileAction === 'save') {
return executeExportFileAction(data.payload || data, opts);
}
if (isPlainObject(data) && data.__exportFileAction === 'reveal') {
return executeRevealFileAction(data.payload || data, opts);
}
return executeSettingsAction(data);
case 'accounts_get':
return executeAccountCredentialAction(undefined, opts);
@@ -778,6 +812,10 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
return executeSessionMigrationCatalogAction(data, opts);
case 'session_migration_migrate':
return executeSessionMigrationMigrateAction(data, opts);
case 'export_file':
return executeExportFileAction(data, opts);
case 'reveal_file':
return executeRevealFileAction(data, opts);
default:
return {
status: 404,
+230
View File
@@ -0,0 +1,230 @@
/**
* @fileoverview 本机安全文本文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。
* 仅允许导出受控白名单文本扩展名(.json / .csv / .md / .txt),严格清洗文件名防止路径穿越,
* 并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。
*/
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DATA_DIR } from './config.mjs';
export const MAX_EXPORT_FILE_BYTES = 8 * 1024 * 1024;
export const ALLOWED_EXPORT_EXTENSIONS = Object.freeze(['.json', '.csv', '.md', '.txt']);
const ALLOWED_EXT_SET = new Set(ALLOWED_EXPORT_EXTENSIONS);
const MAX_RECENT_EXPORT_TRACK = 64;
const recentExportedPaths = new Set();
function recordExportedPath(absPath) {
const normalized = path.resolve(String(absPath || ''));
if (!normalized) return;
if (recentExportedPaths.has(normalized)) {
recentExportedPaths.delete(normalized);
}
recentExportedPaths.add(normalized);
while (recentExportedPaths.size > MAX_RECENT_EXPORT_TRACK) {
const oldest = recentExportedPaths.values().next().value;
if (!oldest) break;
recentExportedPaths.delete(oldest);
}
}
export function isAuthorizedExportPath(filePath) {
const normalized = path.resolve(String(filePath || ''));
return Boolean(normalized && recentExportedPaths.has(normalized));
}
function inferExtensionFromMime(mimeType) {
const lower = String(mimeType || '').toLowerCase();
if (lower.includes('csv')) return '.csv';
if (lower.includes('markdown')) return '.md';
if (lower.includes('plain')) return '.txt';
return '.json';
}
/**
* 严格净化导出文件名:剥离目录段、过滤系统非法字符,并强制收敛到允许的文本扩展名白名单。
*
* @param {string} rawFilename
* @param {string} [mimeType]
* @returns {{ fileName: string, baseName: string, ext: string }}
*/
export function sanitizeLocalExportFilename(rawFilename, mimeType = '') {
const leaf = path.basename(String(rawFilename || '').replace(/\\/g, '/')).trim();
const parsedExt = path.extname(leaf).toLowerCase();
const ext = ALLOWED_EXT_SET.has(parsedExt) ? parsedExt : inferExtensionFromMime(mimeType);
const rawBase = ALLOWED_EXT_SET.has(parsedExt) ? leaf.slice(0, -parsedExt.length) : leaf;
const cleanedBase = rawBase
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '-')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^[.\-_]+|[.\-_]+$/g, '')
.slice(0, 80);
const baseName = cleanedBase || 'export';
return {
fileName: `${baseName}${ext}`,
baseName,
ext,
};
}
/**
* 解析本机导出目录:优先使用用户系统 Downloads 目录,不存在时自动回退到插件 `.data/exports`。
*
* @param {{ overrideDir?: string, homeDir?: string, fallbackDataDir?: string }} [options]
* @returns {{ dirPath: string, source: 'override' | 'downloads' | 'data_exports' }}
*/
export function resolveExportDirectory({
overrideDir = '',
homeDir = os.homedir(),
fallbackDataDir = DATA_DIR,
} = {}) {
const custom = String(overrideDir || '').trim();
if (custom) {
const resolved = path.resolve(custom);
mkdirSync(resolved, { recursive: true });
return { dirPath: resolved, source: 'override' };
}
const downloadsDir = homeDir ? path.join(homeDir, 'Downloads') : '';
if (downloadsDir) {
try {
if (existsSync(downloadsDir) && statSync(downloadsDir).isDirectory()) {
return { dirPath: path.resolve(downloadsDir), source: 'downloads' };
}
} catch {
// ignore stat errors and fall back cleanly
}
}
const exportsDir = path.resolve(path.join(fallbackDataDir || DATA_DIR, 'exports'));
mkdirSync(exportsDir, { recursive: true });
return { dirPath: exportsDir, source: 'data_exports' };
}
/**
* 将文本导出内容安全落盘到本机目录,遇同名文件自动追加 `(1)`、`(2)` 避免覆盖已有导出。
*
* @param {{ filename?: string, content?: string, mimeType?: string }} payload
* @param {{ overrideDir?: string, homeDir?: string, fallbackDataDir?: string }} [options]
* @returns {{ ok: boolean, status: number, filePath?: string, dirPath?: string, fileName?: string, bytes?: number, source?: string, error?: string }}
*/
export function writeLocalExportFile(payload = {}, options = {}) {
if (!payload || typeof payload !== 'object') {
return { ok: false, status: 400, error: 'Invalid export payload' };
}
if (typeof payload.content !== 'string') {
return { ok: false, status: 400, error: 'Export content must be a string' };
}
const byteLen = Buffer.byteLength(payload.content, 'utf8');
if (byteLen > MAX_EXPORT_FILE_BYTES) {
return { ok: false, status: 413, error: 'Export file exceeds size limit' };
}
const { baseName, ext } = sanitizeLocalExportFilename(payload.filename, payload.mimeType);
const { dirPath, source } = resolveExportDirectory(options);
let targetPath = '';
let finalFileName = '';
for (let attempt = 0; attempt < 1000; attempt += 1) {
const candidateName = attempt === 0 ? `${baseName}${ext}` : `${baseName} (${attempt})${ext}`;
const candidatePath = path.join(dirPath, candidateName);
try {
writeFileSync(candidatePath, payload.content, { encoding: 'utf8', flag: 'wx' });
targetPath = path.resolve(candidatePath);
finalFileName = candidateName;
break;
} catch (err) {
if (err && err.code === 'EEXIST') continue;
return {
ok: false,
status: 500,
error: err?.message || 'Failed to write export file',
};
}
}
if (!targetPath) {
const fallbackName = `${baseName}-${Date.now()}${ext}`;
const fallbackPath = path.join(dirPath, fallbackName);
try {
writeFileSync(fallbackPath, payload.content, { encoding: 'utf8', flag: 'wx' });
targetPath = path.resolve(fallbackPath);
finalFileName = fallbackName;
} catch (err) {
return {
ok: false,
status: 500,
error: err?.message || 'Failed to write export file',
};
}
}
recordExportedPath(targetPath);
return {
ok: true,
status: 200,
filePath: targetPath,
dirPath,
fileName: finalFileName,
bytes: byteLen,
source,
};
}
/**
* 在系统文件管理器中定位并高亮选中由本进程刚导出的受控文件。
*
* @param {string} filePath
* @param {{ platform?: string, spawnFn?: typeof spawn }} [options]
* @returns {{ ok: boolean, status: number, filePath?: string, error?: string }}
*/
export function revealLocalExportFile(
filePath,
{ platform = process.platform, spawnFn = spawn } = {}
) {
const raw = String(filePath || '').trim();
if (!raw || /[\r\n"]/.test(raw)) {
return { ok: false, status: 400, error: 'Invalid file path' };
}
const resolved = path.resolve(raw);
if (!isAuthorizedExportPath(resolved)) {
return { ok: false, status: 403, error: 'Path is not an authorized export file' };
}
if (!existsSync(resolved)) {
return { ok: false, status: 404, error: 'Exported file no longer exists' };
}
try {
let child = null;
if (platform === 'win32') {
child = spawnFn('explorer.exe', [`/select,"${resolved}"`], {
detached: true,
stdio: 'ignore',
windowsVerbatimArguments: true,
windowsHide: false,
});
} else if (platform === 'darwin') {
child = spawnFn('open', ['-R', resolved], {
detached: true,
stdio: 'ignore',
});
} else {
child = spawnFn('xdg-open', [path.dirname(resolved)], {
detached: true,
stdio: 'ignore',
});
}
child?.on?.('error', () => {});
child?.unref?.();
return { ok: true, status: 200, filePath: resolved };
} catch (err) {
return {
ok: false,
status: 500,
error: err?.message || 'Failed to open file manager',
};
}
}
+41 -1
View File
@@ -21,6 +21,7 @@ import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
import { syncCloudCatalog } from './plugin-updater.mjs';
const MAX_JSON_BODY_BYTES = 1024 * 1024;
const MAX_EXPORT_JSON_BODY_BYTES = 8 * 1024 * 1024;
const AUTH_COOKIE_NAME = 'ag_um_token';
const NO_STORE_HEADERS = {
'Cache-Control': 'no-store, no-cache, must-revalidate',
@@ -511,12 +512,32 @@ export function createStandaloneWebServer(options = {}) {
}
if (pathname.startsWith('/api/')) {
if (
(pathname === '/api/export-file' || pathname === '/api/reveal-file') &&
!isLoopbackRemoteAddress(req.socket?.remoteAddress)
) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
fallbackBrowser: true,
error: 'Local file export is restricted to loopback clients',
})
);
return;
}
let data = undefined;
if (method === 'GET') {
data = Object.fromEntries(urlObj.searchParams.entries());
delete data.token;
} else if (method === 'POST') {
const rawBody = await readRawBody(req, MAX_JSON_BODY_BYTES);
const maxBody =
pathname === '/api/export-file' || pathname === '/api/settings'
? MAX_EXPORT_JSON_BODY_BYTES
: MAX_JSON_BODY_BYTES;
const rawBody = await readRawBody(req, maxBody);
if (rawBody.trim()) {
try {
data = JSON.parse(rawBody);
@@ -532,6 +553,25 @@ export function createStandaloneWebServer(options = {}) {
} else {
data = {};
}
if (
pathname === '/api/settings' &&
data &&
typeof data === 'object' &&
typeof data.__exportFileAction === 'string' &&
!isLoopbackRemoteAddress(req.socket?.remoteAddress)
) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
fallbackBrowser: true,
error: 'Local file export is restricted to loopback clients',
})
);
return;
}
} else {
sendResponse(
res,
+6 -1
View File
@@ -71,6 +71,7 @@ const overlayMethods = Object.fromEntries(
);
const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
const BRIDGE_MAX_EXPORT_BODY_BYTES = 8 * 1024 * 1024;
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
/**
@@ -1342,12 +1343,16 @@ export function createWindowBridgeController(options) {
return;
}
const maxBodyBytes =
parsedUrl.pathname === '/api/export-file'
? BRIDGE_MAX_EXPORT_BODY_BYTES
: BRIDGE_MAX_BODY_BYTES;
const chunks = [];
let totalBytes = 0;
let aborted = false;
req.on('data', (chunk) => {
totalBytes += chunk.length;
if (totalBytes > BRIDGE_MAX_BODY_BYTES) {
if (totalBytes > maxBodyBytes) {
aborted = true;
res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' }));