Files
Agent-Workbench/src/client/mobile/api.ts
T
2026-10-31 17:53:15 +08:00

25 lines
2.0 KiB
TypeScript

export class MobileError extends Error { constructor(message: string, public status = 0) { super(message); } }
export async function mobileApi<T>(route: string, value?: unknown): Promise<T> {
const controller = new AbortController(), timer = setTimeout(() => controller.abort(), route.endsWith('/stop') ? 75000 : 15000);
try {
const response = await fetch('/mobile-api' + route, { method: value === undefined ? 'GET' : 'POST', credentials: 'same-origin', cache: 'no-store', signal: controller.signal,
headers: value === undefined ? {} : { 'Content-Type': 'application/json' }, ...(value === undefined ? {} : { body: JSON.stringify(value) }) });
const body = await response.json();
if (!response.ok) throw new MobileError(body.error || '当前手机请求未完成。', response.status);
return body as T;
} catch (error) {
if (error instanceof MobileError) throw error;
throw new MobileError(value === undefined ? '连接已断开。请核对 Wi-Fi 与电脑上的手机连接。' : '没有收到完整回执,请先刷新并在电脑核对原操作。');
} finally { clearTimeout(timer); }
}
export async function verifiedText(route: string, maximum = 8 * 1024 * 1024) {
const value = await mobileApi<{ text: string; sha256: string; sourceSha256?: string; redacted?: boolean }>(route);
if (typeof value.text !== 'string' || value.text.length > maximum) throw new MobileError('报告超出手机显示范围,请在电脑查看。');
await verifyDigest(value.text, value.sha256); return value;
}
export async function verifyDigest(text: string, expected: string) {
if (!/^[a-f0-9]{64}$/.test(expected)) throw new MobileError('原结果缺少可核对的SHA-256。');
const hash = Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)))).map(value => value.toString(16).padStart(2, '0')).join('');
if (hash !== expected) throw new MobileError('结果内容校验失败,请在电脑核对原工件。');
}