Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(media): 收紧私网授权并完善结果保存重试
liugaowei4505e76e19fc
diff --git a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.tsindex db23a3c97a..39de868bda 100644--- a/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/invocationService.test.ts@@ -685,8 +685,75 @@ describe('Cindy Core media invocation state and security boundary', () => {).resolves.toMatchObject({ ok: false, errorCode: 'ACCOUNT_CHANGED' });expect(mocks.rows.get(invocationId)?.state).toBe('pending');expect(mocks.transitionDbs.every((db) => db === originalDb)).toBe(true);+ expect(mocks.ingestMedia).toHaveBeenCalledOnce();});+ it.each([+ ['sync', 2], ['sync', 3], ['async', 2], ['async', 3],+ ] as const)('%s 入库失败 %i 次时仅重试已有字节,不再下载或审批', async (mode, failures) => {+ const media = [{ path: ['data'], encoding: 'url', kind: 'image', allowedUrlHosts: ['known.example.com'] }];+ mocks.guide.mockResolvedValue(resolvedGuide(operation(mode === 'sync'+ ? { mode, media }+ : { mode, taskIdPath: ['task_id'], poll: {+ method: 'GET', path: '/tasks/{taskId}', statusPath: ['status'],+ successValues: ['succeeded'], failureValues: ['failed'], recommendedIntervalMs: 10,+ timeoutMs: 5_000, maxResponseBytes: 1_048_576, media,+ } })));+ const payload = { status: 'succeeded', data: 'https://new.example.com/generated.png' };+ if (mode === 'async') {+ mocks.outboundFetch.mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'storage-retry' })));+ }+ mocks.outboundFetch.mockResolvedValueOnce(new Response(JSON.stringify(payload)))+ .mockResolvedValueOnce(new Response(PNG));+ for (let index = 0; index < failures; index += 1) {+ mocks.ingestMedia.mockRejectedValueOnce(new Error('temporary database failure'));+ }+ const invocationId = await prepare();+ let result = await callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } });+ if (mode === 'async') result = await callCindyMedia({ action: 'poll', invocationId });+ if (failures === 2) {+ expect(result).toMatchObject({ ok: true, status: 'complete' });+ } else {+ expect(result).toMatchObject({ ok: false, errorCode: 'MEDIA_MATERIALIZATION_FAILED', retryable: false });+ expect(mocks.rows.get(invocationId)).toMatchObject({ state: 'pending', responseJson: JSON.stringify(payload) });+ }+ expect(mocks.ingestMedia).toHaveBeenCalledTimes(3);+ const firstBytes = mocks.ingestMedia.mock.calls[0][0].buffer;+ expect(firstBytes).toEqual(PNG);+ expect(mocks.ingestMedia.mock.calls.every(([input]) => input.buffer === firstBytes)).toBe(true);+ expect(mocks.guardedOutboundFetch).toHaveBeenCalledOnce();+ expect(mocks.confirm).toHaveBeenCalledOnce();+ expect(mocks.outboundFetch.mock.calls.filter(([, init]) => init.method === 'POST')).toHaveLength(1);+ });++ it.each(['missing', 'invalid', 'expired', 'storage'])(+ '刷新结果 %s 失败时保留原成功响应', async (failure) => {+ mocks.guide.mockResolvedValue(resolvedGuide(operation({+ mode: 'async', taskIdPath: ['task_id'], poll: {+ method: 'GET', path: '/tasks/{taskId}', statusPath: ['status'],+ successValues: ['succeeded'], failureValues: ['failed'], recommendedIntervalMs: 10,+ timeoutMs: 5_000, maxResponseBytes: 1_048_576,+ media: [{ path: ['data'], encoding: 'url', kind: 'image', allowedUrlHosts: ['cdn.example.com'] }],+ },+ })));+ const original = { status: 'succeeded', data: 'https://cdn.example.com/original.png', task_id: 'preserved-task' };+ const refreshed = { status: 'succeeded', ...(failure === 'missing' ? {} : { data: 'https://cdn.example.com/refreshed.png' }) };+ mocks.outboundFetch.mockResolvedValueOnce(new Response(JSON.stringify({ task_id: 'preserved-task' })))+ .mockResolvedValueOnce(new Response(JSON.stringify(original)))+ .mockResolvedValueOnce(new Response(null, { status: 403 }))+ .mockResolvedValueOnce(new Response(JSON.stringify(refreshed)))+ .mockResolvedValueOnce(failure === 'expired' ? new Response(null, { status: 403 })+ : new Response(failure === 'invalid' ? 'not an image' : PNG));+ if (failure === 'storage') mocks.ingestMedia.mockRejectedValue(new Error('storage unavailable'));+ const invocationId = await prepare();+ await callCindyMedia({ action: 'request', invocationId, body: { prompt: 'cat' } });+ expect(await callCindyMedia({ action: 'poll', invocationId })).toMatchObject({ ok: false, retryable: false });+ expect(mocks.rows.get(invocationId)).toMatchObject({ state: 'pending', responseJson: JSON.stringify(original) });+ expect(mocks.outboundFetch.mock.calls.filter(([, init]) => init.method === 'POST')).toHaveLength(1);+ expect(mocks.outboundFetch.mock.calls.filter(([url]) => url === 'https://gateway.example.com/tasks/preserved-task')).toHaveLength(2);+ },+ );+it('Guide 缺少目标 operation 时在 prepare 返回稳定的能力不支持错误', async () => {mocks.guide.mockResolvedValue(resolvedGuide({diff --git a/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts b/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.tsindex 32832bb3c0..1402b87daa 100644--- a/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts+++ b/apps/desktop/src/main/cindy-media/__tests__/mediaDownload.test.ts@@ -114,6 +114,23 @@ describe('media download approval and network recovery', () => {expect(mocks.fetch.mock.calls[0][3]).toMatchObject({ allowHttp: true, targetUrl: 'http://known.example.com:8080/video' });});+ it.each(['/internal/admin', '/video?operation=admin'])(+ 'requires a fresh private-network decision for the same-origin target %s', async (location) => {+ const ctx = context();+ ctx.confirm.mockResolvedValueOnce(true).mockResolvedValueOnce(true).mockResolvedValueOnce(false);+ mocks.fetch.mockRejectedValueOnce(new SsrFBlockedError('private'))+ .mockResolvedValueOnce(response(null, { status: 302, headers: { location } }))+ .mockRejectedValueOnce(new SsrFBlockedError('unapproved private target'));+ await expect(download(ctx)).rejects.toMatchObject({ code: 'MEDIA_DOWNLOAD_DENIED' });+ expect(ctx.confirm.mock.calls.map(([request]) => request.reasons)).toEqual([+ ['source'], ['network'], ['network'],+ ]);+ expect(mocks.fetch.mock.calls.map((call) => call[3].allowPrivateNetwork)).toEqual([false, true, false]);+ expect(mocks.fetch.mock.calls[2][0]).toBe(new URL(location, 'https://new.example.com').href);+ expect(mocks.release).toHaveBeenCalledOnce();+ },+ );+it('does not forward URL credentials on a redirect', async () => {const ctx = context();mocks.fetch.mockResolvedValueOnce(response(null, { status: 302, headers: { location: '/next' } }));diff --git a/apps/desktop/src/main/cindy-media/invocationService.ts b/apps/desktop/src/main/cindy-media/invocationService.tsindex bf04547e7d..6a6985f63b 100644--- a/apps/desktop/src/main/cindy-media/invocationService.ts+++ b/apps/desktop/src/main/cindy-media/invocationService.ts@@ -1,5 +1,6 @@import fs from 'node:fs/promises';import { randomUUID } from 'node:crypto';+import { setTimeout as delay } from 'node:timers/promises';import type { MediaCapability } from '@cindy/model-providers';import type { CindyMediaToolRequest } from 'cindy-tools';import type {@@ -828,15 +829,28 @@ async function materializeResults(throw error;}assertAuthScope(scope);- const stored = await ingestMedia(- {- buffer: media.buffer,- mimeType: media.mimeType,- refs: [],- assertStillValid: () => assertAuthScope(scope),- },- db.drizzle,- );+ let stored: Awaited<ReturnType<typeof ingestMedia>>;+ for (let attempt = 0; ; attempt += 1) {+ assertAuthScope(scope);+ try {+ // Content-addressed writes and zero-reference ledger updates are+ // idempotent. Retry these same bytes without downloading or approving again.+ stored = await ingestMedia(+ {+ buffer: media.buffer,+ mimeType: media.mimeType,+ refs: [],+ assertStillValid: () => assertAuthScope(scope),+ },+ db.drizzle,+ );+ break;+ } catch (error) {+ assertAuthScope(scope);+ if (attempt >= 2) throw error;+ await delay(250 * 2 ** attempt, undefined, { signal: scope.downloadContext?.signal });+ }+ }assertAuthScope(scope);if (item.extractor.kind === 'image') images.push(stored.url);else if (item.extractor.kind === 'video') videos.push(stored.url);@@ -1554,6 +1568,11 @@ async function pollInvocation(const rawStatus = valuesAtPath(response, guide.statusPath)[0];const status = typeof rawStatus === 'string' ? rawStatus : '';if (guide.successValues.includes(status)) {+ if (invocation.responseJson) {+ // Keep the original durable response until refreshed media has actually+ // been ingested. Completion replaces it atomically with managed URLs.+ return materializeAsyncInvocation(invocation, response, scope, db);+ }const responseJson = JSON.stringify(response);const persisted = await transitionMediaInvocation({diff --git a/apps/desktop/src/main/cindy-media/mediaDownload.ts b/apps/desktop/src/main/cindy-media/mediaDownload.tsindex bf03d494f8..16a26b3936 100644--- a/apps/desktop/src/main/cindy-media/mediaDownload.ts+++ b/apps/desktop/src/main/cindy-media/mediaDownload.ts@@ -47,6 +47,13 @@ export async function downloadMediaResult(input: {const approved = input.context?.approvals ?? new Set<string>();const byteLimits = input.context?.byteLimits ?? new Map<string, number>();const approvalKey = (reason: MediaDownloadReason) => {+ if (reason === 'network') {+ // A private-network exception belongs to this exact HTTP target. Source+ // approval may cover an origin, but cannot authorize another internal API.+ const target = new URL(url);+ target.hash = '';+ return `network:${createHash('sha256').update(target.href).digest('hex')}`;+ }const credentials = reason === 'credentials'? createHash('sha256').update(`${url.username}:${url.password}`).digest('hex') : '';return `${url.origin}:${reason}:${credentials}`;diff --git a/docs/dev-rules/media-storage-and-protocols.md b/docs/dev-rules/media-storage-and-protocols.mdindex 26ca276b8c..10469ec8bc 100644--- a/docs/dev-rules/media-storage-and-protocols.md+++ b/docs/dev-rules/media-storage-and-protocols.md@@ -78,12 +78,16 @@变化才再次确认。不以浏览器或外部应用作为强制下载出口。- 默认经 `guardedOutboundFetch` 做 HTTPS、DNS/IP 校验及固定 IP 连接。人工例外只对当前精确 URL 的单跳生效,不自动传递到重定向目标,不改变其他网络调用的默认策略。+ 来源批准按 origin 复用;受限网络例外按不含 fragment 的完整 URL 绑定,路径或 query+ 变化后须重新确认该受限目标,不能借同源跳转访问另一内部接口。不附带生成接口凭证;地址内登录信息须单独确认,且不得沿重定向传递。- 网络时间累计最多 120 秒,连续 30 秒没有响应或数据则重试,人工审批等待另计并受 Host 操作时限约束。正常跳转逐跳重验目标与权限,循环跳转作为下载故障处理,不为次数追加审批。等待更大文件审批前取消响应体并释放连接;所有结束路径均释放 body 和 dispatcher。- 下载失败保留原调用的成功响应。异步签名地址失效时只查询原上游任务刷新地址,不重新- 付费生成。`pending` 且存在成功响应的记录不随六小时清理删除,也不占正在生成的名额;+ 付费生成;刷新结果成功入库前不覆盖原成功响应。本地入库失败由客户端对同一份已下载+ 字节最多尝试三次,期间复核账号和任务,不再次下载、生成或审批。+ `pending` 且存在成功响应的记录不随六小时清理删除,也不占正在生成的名额;不新增并行的领取状态或授权表。用户拒绝或客户端重试耗尽均返回非自动重试结果,避免模型另起一次调用而重复发起审批。- 真实 MIME 识别、账号/任务归属、受管入库规则持续有效。下载授权不包含执行文件、安装程序或覆盖用户文件的授权。旧 Guide 快照与 base64 结果保持兼容。