Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(client): 避免解析异常日志夹带响应正文

liugaoweia4ca1aedc0cb
diff --git a/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts b/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts
index a3e631c7ce..a720d8fc23 100644
--- a/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts
+++ b/apps/desktop/src/main/__tests__/ossPublicUpload.test.ts
@@ -46,6 +46,15 @@ describe('uploadPublicAsset', () => {
expect(JSON.stringify(onError.mock.calls)).not.toContain('private-signature');
});
+ it('does not log response excerpts when presign returns malformed JSON', async () => {
+ const onError = vi.fn();
+ const result = await uploadPublicAsset({
+ ...makeDeps(async () => new Response('private display name')), onError,
+ }, { scene: 'avatar', contentType: 'image/png', body: BODY });
+ expect(result).toEqual({ ok: false, stage: 'presign', status: 0 });
+ expect(onError).toHaveBeenCalledExactlyOnceWith('presign', 'SyntaxError');
+ });
+
it('成功链路:presign 带 Bearer/scene/size,PUT 原样携带返回 headers', async () => {
const calls: Array<{ url: string; init: RequestInit | undefined }> = [];
const fetchImpl = vi.fn(async (url: string, init?: RequestInit) => {
diff --git a/apps/desktop/src/main/__tests__/serverApiClient.test.ts b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
index d7619b38a0..dcfba34366 100644
--- a/apps/desktop/src/main/__tests__/serverApiClient.test.ts
+++ b/apps/desktop/src/main/__tests__/serverApiClient.test.ts
@@ -51,14 +51,19 @@ describe('serverApiFetch', () => {
expect(logged).not.toContain('private-token');
});
- it('logs the original response parse failure without changing the existing empty-response error', async () => {
- mocks.netFetch.mockResolvedValueOnce({ ok: true, status: 200,
- json: async () => { throw new SyntaxError('Unexpected end of JSON input'); } });
+ // Native JSON errors can quote the response body; transport read failures must stay diagnosable.
+ it.each([
+ { response: new Response('private display name'), logged: 'SyntaxError' },
+ { response: { ok: true, status: 200,
+ json: async () => { throw new TypeError('response stream closed'); } }, logged: 'response stream closed' },
+ ])('logs a response failure without exposing its body or changing EMPTY_RESPONSE: $logged', async ({ response, logged }) => {
+ mocks.netFetch.mockResolvedValueOnce(response);
await expect(serverApiFetch('/api/resource', { baseUrl: 'https://api.example.invalid' }))
.rejects.toMatchObject({ code: 'EMPTY_RESPONSE', statusCode: 200 });
expect(mocks.logger.warn).toHaveBeenCalledWith(
- 'response read failed', '/api/resource', { status: 200 }, 'Unexpected end of JSON input',
+ 'response read failed', '/api/resource', { status: 200 }, logged,
);
+ expect(JSON.stringify(mocks.logger.warn.mock.calls)).not.toContain('private display name');
});
it('TOKEN_EXPIRED refresh 后用新 token 和重新生成的 body 重试', async () => {
diff --git a/apps/desktop/src/main/requestErrorMessage.ts b/apps/desktop/src/main/requestErrorMessage.ts
index 332f62ec2c..6429a815ab 100644
--- a/apps/desktop/src/main/requestErrorMessage.ts
+++ b/apps/desktop/src/main/requestErrorMessage.ts
@@ -9,7 +9,12 @@ export function requestErrorMessage(error: unknown): string {
messages.push(String(error));
break;
}
- const value = error as { message?: unknown; code?: unknown; cause?: unknown };
+ const value = error as { name?: unknown; message?: unknown; code?: unknown; cause?: unknown };
+ // JSON parsers can quote response contents in both the message and stack.
+ if (value.name === 'SyntaxError') {
+ messages.push('SyntaxError');
+ break;
+ }
const message = typeof value.message === 'string' ? value.message : 'Unknown error';
messages.push(typeof value.code === 'string' ? `${message} (${value.code})` : message);
error = value.cause;
diff --git a/apps/mobile/src/__tests__/apiClient.test.ts b/apps/mobile/src/__tests__/apiClient.test.ts
index 151764c574..6538c26c92 100644
--- a/apps/mobile/src/__tests__/apiClient.test.ts
+++ b/apps/mobile/src/__tests__/apiClient.test.ts
@@ -20,15 +20,19 @@ describe('apiFetchRaw', () => {
setMobileDebugSink(undefined);
});
- it.each([new SyntaxError('Unexpected end of JSON input'), new TypeError('response stream closed')])(
- 'rejects a failed successful-response body and logs its original message: %s', async (error) => {
+ it.each([
+ { response: new Response('private response body'), logged: 'SyntaxError' },
+ { response: { ok: true, status: 200,
+ json: async () => { throw new TypeError('response stream closed'); } }, logged: 'response stream closed' },
+ ])(
+ 'rejects a failed successful-response body and logs its cause without body excerpts: $logged', async ({ response, logged }) => {
const logs: string[] = [];
setMobileDebugSink((level, scope, args) => { logs.push(serializeMobileDebugRecord(level, scope, args)); });
- vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, status: 200,
- json: async () => { throw error; } }));
+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response));
await expect(apiFetchRaw('/api/resource', { baseUrl: 'https://api.example.invalid' }))
.rejects.toMatchObject({ code: 'INVALID_RESPONSE', status: 200 });
- expect(logs.join('')).toContain(error.message);
+ expect(logs.join('')).toContain(logged);
+ expect(logs.join('')).not.toContain('private response body');
},
);
diff --git a/apps/mobile/src/api/client.ts b/apps/mobile/src/api/client.ts
index d9cdba84bc..c981812f5e 100644
--- a/apps/mobile/src/api/client.ts
+++ b/apps/mobile/src/api/client.ts
@@ -80,7 +80,9 @@ export async function apiFetchRaw<T>(
if (nextResponse.status === 204 || nextResponse.status === 205) {
return { response: nextResponse, data: null };
}
- mobileDebugLog('warn', 'network', 'response read failed', { status: nextResponse.status }, error);
+ // JSON SyntaxError messages/stacks can include response contents.
+ mobileDebugLog('warn', 'network', 'response read failed', { status: nextResponse.status },
+ error instanceof SyntaxError ? 'SyntaxError' : error);
if (nextResponse.ok) {
throw new ApiError('INVALID_RESPONSE', nextResponse.status, i18n.t('apiErrors.requestFailed'));
}
diff --git a/docs/dev-rules/log-upload-and-redaction.md b/docs/dev-rules/log-upload-and-redaction.md
index 406f1b3de1..8f47eca125 100644
--- a/docs/dev-rules/log-upload-and-redaction.md
+++ b/docs/dev-rules/log-upload-and-redaction.md
@@ -274,6 +274,7 @@ Mobile 的设置 → 调试 / 开发者提供 Debug 开关、导出与手动上
`mobileDebugRecord.ts` 在落盘前过滤敏感字段、凭证、地址参数等;禁止传入消息正文、请求体或完整鉴权信息,
不接管全局 console,不重复保存被控端任务记录。
`auth` / `network` 在错误转换前记录原始异常及原因,仍走上述落盘脱敏;不记录成功认证响应,
+ JSON 语法异常只记录 `SyntaxError` 与响应状态,避免消息或堆栈夹带响应正文;
不扩展上传摘要白名单,也不改变 Debug 开关。
- 详细日志在 `Paths.document/cindy-debug/`,NDJSON 文件每份最多 1 MiB、最多 8 份、保留最近 7 天。
每 2 秒及前后台切换时批量落盘;内存待写最多 512 KiB,溢出或写失败在后续记录中标明丢失,不能无限重试堆积。
diff --git a/packages/auth-client/src/__tests__/client.test.ts b/packages/auth-client/src/__tests__/client.test.ts
index 015aacb0c4..5e035dd998 100644
--- a/packages/auth-client/src/__tests__/client.test.ts
+++ b/packages/auth-client/src/__tests__/client.test.ts
@@ -81,6 +81,22 @@ describe("CindyAuthClient", () => {
expect(onRequestError).not.toHaveBeenCalled();
});
+ // Native SyntaxError.message includes body excerpts even when no response object is logged.
+ it.each([200, 400])("logs only the JSON error type for a malformed %s response", async (status) => {
+ const onRequestError = vi.fn();
+ const instance = new CindyAuthClient({
+ baseUrl: "https://auth.example.com", region: "cn", deviceId: "device-1", clientType: "desktop",
+ fetch: async () => new Response("private display name", { status }),
+ onRequestError,
+ });
+ await expect(instance.refresh("unused-token")).rejects.toMatchObject({
+ code: "INVALID_RESPONSE", statusCode: status,
+ });
+ expect(onRequestError).toHaveBeenCalledExactlyOnceWith(
+ "/api/auth/refresh", status, "SyntaxError",
+ );
+ });
+
it.each([
["120", 120_000],
["Wed, 07 Oct 2026 06:02:00 GMT", 120_000],
diff --git a/packages/auth-client/src/client.ts b/packages/auth-client/src/client.ts
index 0e77883e5c..317b3d1a32 100644
--- a/packages/auth-client/src/client.ts
+++ b/packages/auth-client/src/client.ts
@@ -57,7 +57,7 @@ export interface AuthClientOptions {
locale?: string;
fetch: AuthFetch;
timeoutMs?: number;
- /** Original failure before UI error mapping; platform adapters handle log redaction. */
+ /** Original failure before UI mapping; JSON syntax errors omit body excerpts. Adapters redact logs. */
onRequestError?: (path: string, status: number, error: unknown) => void;
}
@@ -600,7 +600,11 @@ export class CindyAuthClient {
private logRequestError(path: string, status: number, error: unknown): void {
try {
- this.options.onRequestError?.(path, status, error);
+ // JSON SyntaxError messages/stacks can include the response body.
+ const detail = error && typeof error === "object" && "name" in error && error.name === "SyntaxError"
+ ? "SyntaxError"
+ : error;
+ this.options.onRequestError?.(path, status, detail);
} catch {
// A logging failure cannot affect auth, retries or rotated credentials.
}